-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnss.c
2392 lines (2016 loc) · 70.5 KB
/
nss.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Source file for all NSS-specific code for the TLS/SSL layer. No code
* but vtls.c should ever call or use these functions.
*/
#include "curl_setup.h"
#ifdef USE_NSS
#include "urldata.h"
#include "sendf.h"
#include "formdata.h" /* for the boundary function */
#include "url.h" /* for the ssl config check function */
#include "connect.h"
#include "strcase.h"
#include "select.h"
#include "vtls.h"
#include "llist.h"
#include "curl_printf.h"
#include "nssg.h"
#include <nspr.h>
#include <nss.h>
#include <ssl.h>
#include <sslerr.h>
#include <secerr.h>
#include <secmod.h>
#include <sslproto.h>
#include <prtypes.h>
#include <pk11pub.h>
#include <prio.h>
#include <secitem.h>
#include <secport.h>
#include <certdb.h>
#include <base64.h>
#include <cert.h>
#include <prerror.h>
#include <keyhi.h> /* for SECKEY_DestroyPublicKey() */
#include <private/pprio.h> /* for PR_ImportTCPSocket */
#define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH)
#if NSSVERNUM >= 0x030f00 /* 3.15.0 */
#include <ocsp.h>
#endif
#include "strcase.h"
#include "warnless.h"
#include "x509asn1.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
#define SSL_DIR "/etc/pki/nssdb"
/* enough to fit the string "PEM Token #[0|1]" */
#define SLOTSIZE 13
struct ssl_backend_data {
PRFileDesc *handle;
char *client_nickname;
struct Curl_easy *data;
struct curl_llist obj_list;
PK11GenericObject *obj_clicert;
};
#define BACKEND connssl->backend
static PRLock *nss_initlock = NULL;
static PRLock *nss_crllock = NULL;
static PRLock *nss_findslot_lock = NULL;
static PRLock *nss_trustload_lock = NULL;
static struct curl_llist nss_crl_list;
static NSSInitContext *nss_context = NULL;
static volatile int initialized = 0;
/* type used to wrap pointers as list nodes */
struct ptr_list_wrap {
void *ptr;
struct curl_llist_element node;
};
typedef struct {
const char *name;
int num;
} cipher_s;
#define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
ptr->type = (_type); \
ptr->pValue = (_val); \
ptr->ulValueLen = (_len); \
} WHILE_FALSE
#define CERT_NewTempCertificate __CERT_NewTempCertificate
#define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
static const cipher_s cipherlist[] = {
/* SSL2 cipher suites */
{"rc4", SSL_EN_RC4_128_WITH_MD5},
{"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
{"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
{"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
{"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
{"des", SSL_EN_DES_64_CBC_WITH_MD5},
{"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
/* SSL3/TLS cipher suites */
{"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
{"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
{"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
{"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
{"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
{"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
{"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
{"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
{"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
{"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
{"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
{"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
{"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
/* TLS 1.0: Exportable 56-bit Cipher Suites. */
{"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
{"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
/* AES ciphers. */
{"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
{"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
{"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
{"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
{"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
{"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
/* ECC ciphers. */
{"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
{"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
{"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
{"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
{"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
{"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
{"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
{"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
{"ecdhe_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
{"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
{"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
{"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
{"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
{"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
{"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
{"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
{"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
#ifdef TLS_RSA_WITH_NULL_SHA256
/* new HMAC-SHA256 cipher suites specified in RFC */
{"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
{"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
{"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
{"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
{"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
{"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
{"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
#endif
#ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
/* AES GCM cipher suites in RFC 5288 and RFC 5289 */
{"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
{"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
{"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
#endif
#ifdef TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
/* cipher suites using SHA384 */
{"rsa_aes_256_gcm_sha_384", TLS_RSA_WITH_AES_256_GCM_SHA384},
{"dhe_rsa_aes_256_gcm_sha_384", TLS_DHE_RSA_WITH_AES_256_GCM_SHA384},
{"dhe_dss_aes_256_gcm_sha_384", TLS_DHE_DSS_WITH_AES_256_GCM_SHA384},
{"ecdhe_ecdsa_aes_256_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384},
{"ecdhe_rsa_aes_256_sha_384", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384},
{"ecdhe_ecdsa_aes_256_gcm_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
{"ecdhe_rsa_aes_256_gcm_sha_384", TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
#endif
#ifdef TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
/* chacha20-poly1305 cipher suites */
{"ecdhe_rsa_chacha20_poly1305_sha_256",
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
{"ecdhe_ecdsa_chacha20_poly1305_sha_256",
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256},
{"dhe_rsa_chacha20_poly1305_sha_256",
TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
#endif
};
static const char *pem_library = "libnsspem.so";
static SECMODModule *pem_module = NULL;
static const char *trust_library = "libnssckbi.so";
static SECMODModule *trust_module = NULL;
/* NSPR I/O layer we use to detect blocking direction during SSL handshake */
static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
static PRIOMethods nspr_io_methods;
static const char *nss_error_to_name(PRErrorCode code)
{
const char *name = PR_ErrorToName(code);
if(name)
return name;
return "unknown error";
}
static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
{
failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
}
static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
char *cipher_list)
{
unsigned int i;
PRBool cipher_state[NUM_OF_CIPHERS];
PRBool found;
char *cipher;
/* use accessors to avoid dynamic linking issues after an update of NSS */
const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
if(!implemented_ciphers)
return SECFailure;
/* First disable all ciphers. This uses a different max value in case
* NSS adds more ciphers later we don't want them available by
* accident
*/
for(i = 0; i < num_implemented_ciphers; i++) {
SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
}
/* Set every entry in our list to false */
for(i = 0; i < NUM_OF_CIPHERS; i++) {
cipher_state[i] = PR_FALSE;
}
cipher = cipher_list;
while(cipher_list && (cipher_list[0])) {
while((*cipher) && (ISSPACE(*cipher)))
++cipher;
cipher_list = strchr(cipher, ',');
if(cipher_list) {
*cipher_list++ = '\0';
}
found = PR_FALSE;
for(i = 0; i<NUM_OF_CIPHERS; i++) {
if(strcasecompare(cipher, cipherlist[i].name)) {
cipher_state[i] = PR_TRUE;
found = PR_TRUE;
break;
}
}
if(found == PR_FALSE) {
failf(data, "Unknown cipher in list: %s", cipher);
return SECFailure;
}
if(cipher_list) {
cipher = cipher_list;
}
}
/* Finally actually enable the selected ciphers */
for(i = 0; i<NUM_OF_CIPHERS; i++) {
if(!cipher_state[i])
continue;
if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
return SECFailure;
}
}
return SECSuccess;
}
/*
* Return true if at least one cipher-suite is enabled. Used to determine
* if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
*/
static bool any_cipher_enabled(void)
{
unsigned int i;
for(i = 0; i<NUM_OF_CIPHERS; i++) {
PRInt32 policy = 0;
SSL_CipherPolicyGet(cipherlist[i].num, &policy);
if(policy)
return TRUE;
}
return FALSE;
}
/*
* Determine whether the nickname passed in is a filename that needs to
* be loaded as a PEM or a regular NSS nickname.
*
* returns 1 for a file
* returns 0 for not a file (NSS nickname)
*/
static int is_file(const char *filename)
{
struct_stat st;
if(filename == NULL)
return 0;
if(stat(filename, &st) == 0)
if(S_ISREG(st.st_mode))
return 1;
return 0;
}
/* Check if the given string is filename or nickname of a certificate. If the
* given string is recognized as filename, return NULL. If the given string is
* recognized as nickname, return a duplicated string. The returned string
* should be later deallocated using free(). If the OOM failure occurs, we
* return NULL, too.
*/
static char *dup_nickname(struct Curl_easy *data, const char *str)
{
const char *n;
if(!is_file(str))
/* no such file exists, use the string as nickname */
return strdup(str);
/* search the first slash; we require at least one slash in a file name */
n = strchr(str, '/');
if(!n) {
infof(data, "warning: certificate file name \"%s\" handled as nickname; "
"please use \"./%s\" to force file name\n", str, str);
return strdup(str);
}
/* we'll use the PEM reader to read the certificate from file */
return NULL;
}
/* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition
* in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN. For more
* details, go to <https://bugzilla.mozilla.org/1297397>.
*/
static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name)
{
PK11SlotInfo *slot;
PR_Lock(nss_findslot_lock);
slot = PK11_FindSlotByName(slot_name);
PR_Unlock(nss_findslot_lock);
return slot;
}
/* wrap 'ptr' as list node and tail-insert into 'list' */
static CURLcode insert_wrapped_ptr(struct curl_llist *list, void *ptr)
{
struct ptr_list_wrap *wrap = malloc(sizeof(*wrap));
if(!wrap)
return CURLE_OUT_OF_MEMORY;
wrap->ptr = ptr;
Curl_llist_insert_next(list, list->tail, wrap, &wrap->node);
return CURLE_OK;
}
/* Call PK11_CreateGenericObject() with the given obj_class and filename. If
* the call succeeds, append the object handle to the list of objects so that
* the object can be destroyed in Curl_nss_close(). */
static CURLcode nss_create_object(struct ssl_connect_data *connssl,
CK_OBJECT_CLASS obj_class,
const char *filename, bool cacert)
{
PK11SlotInfo *slot;
PK11GenericObject *obj;
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
int attr_cnt = 0;
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
const int slot_id = (cacert) ? 0 : 1;
char *slot_name = aprintf("PEM Token #%d", slot_id);
if(!slot_name)
return CURLE_OUT_OF_MEMORY;
slot = nss_find_slot_by_name(slot_name);
free(slot_name);
if(!slot)
return result;
PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
(CK_ULONG)strlen(filename) + 1);
if(CKO_CERTIFICATE == obj_class) {
CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
}
/* PK11_CreateManagedGenericObject() was introduced in NSS 3.34 because
* PK11_DestroyGenericObject() does not release resources allocated by
* PK11_CreateGenericObject() early enough. */
obj =
#ifdef HAVE_PK11_CREATEMANAGEDGENERICOBJECT
PK11_CreateManagedGenericObject
#else
PK11_CreateGenericObject
#endif
(slot, attrs, attr_cnt, PR_FALSE);
PK11_FreeSlot(slot);
if(!obj)
return result;
if(insert_wrapped_ptr(&BACKEND->obj_list, obj) != CURLE_OK) {
PK11_DestroyGenericObject(obj);
return CURLE_OUT_OF_MEMORY;
}
if(!cacert && CKO_CERTIFICATE == obj_class)
/* store reference to a client certificate */
BACKEND->obj_clicert = obj;
return CURLE_OK;
}
/* Destroy the NSS object whose handle is given by ptr. This function is
* a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
* NSS objects in Curl_nss_close() */
static void nss_destroy_object(void *user, void *ptr)
{
struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr;
PK11GenericObject *obj = (PK11GenericObject *) wrap->ptr;
(void) user;
PK11_DestroyGenericObject(obj);
free(wrap);
}
/* same as nss_destroy_object() but for CRL items */
static void nss_destroy_crl_item(void *user, void *ptr)
{
struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr;
SECItem *crl_der = (SECItem *) wrap->ptr;
(void) user;
SECITEM_FreeItem(crl_der, PR_TRUE);
free(wrap);
}
static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
const char *filename, PRBool cacert)
{
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
/* libnsspem.so leaks memory if the requested file does not exist. For more
* details, go to <https://bugzilla.redhat.com/734760>. */
if(is_file(filename))
result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
if(!result && !cacert) {
/* we have successfully loaded a client certificate */
CERTCertificate *cert;
char *nickname = NULL;
char *n = strrchr(filename, '/');
if(n)
n++;
/* The following undocumented magic helps to avoid a SIGSEGV on call
* of PK11_ReadRawAttribute() from SelectClientCert() when using an
* immature version of libnsspem.so. For more details, go to
* <https://bugzilla.redhat.com/733685>. */
nickname = aprintf("PEM Token #1:%s", n);
if(nickname) {
cert = PK11_FindCertFromNickname(nickname, NULL);
if(cert)
CERT_DestroyCertificate(cert);
free(nickname);
}
}
return result;
}
/* add given CRL to cache if it is not already there */
static CURLcode nss_cache_crl(SECItem *crl_der)
{
CERTCertDBHandle *db = CERT_GetDefaultCertDB();
CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
if(crl) {
/* CRL already cached */
SEC_DestroyCrl(crl);
SECITEM_FreeItem(crl_der, PR_TRUE);
return CURLE_OK;
}
/* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
PR_Lock(nss_crllock);
/* store the CRL item so that we can free it in Curl_nss_cleanup() */
if(insert_wrapped_ptr(&nss_crl_list, crl_der) != CURLE_OK) {
SECITEM_FreeItem(crl_der, PR_TRUE);
PR_Unlock(nss_crllock);
return CURLE_OUT_OF_MEMORY;
}
if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
/* unable to cache CRL */
PR_Unlock(nss_crllock);
return CURLE_SSL_CRL_BADFILE;
}
/* we need to clear session cache, so that the CRL could take effect */
SSL_ClearSessionCache();
PR_Unlock(nss_crllock);
return CURLE_OK;
}
static CURLcode nss_load_crl(const char *crlfilename)
{
PRFileDesc *infile;
PRFileInfo info;
SECItem filedata = { 0, NULL, 0 };
SECItem *crl_der = NULL;
char *body;
infile = PR_Open(crlfilename, PR_RDONLY, 0);
if(!infile)
return CURLE_SSL_CRL_BADFILE;
if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
goto fail;
if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
goto fail;
if(info.size != PR_Read(infile, filedata.data, info.size))
goto fail;
crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
if(!crl_der)
goto fail;
/* place a trailing zero right after the visible data */
body = (char *)filedata.data;
body[--filedata.len] = '\0';
body = strstr(body, "-----BEGIN");
if(body) {
/* assume ASCII */
char *trailer;
char *begin = PORT_Strchr(body, '\n');
if(!begin)
begin = PORT_Strchr(body, '\r');
if(!begin)
goto fail;
trailer = strstr(++begin, "-----END");
if(!trailer)
goto fail;
/* retrieve DER from ASCII */
*trailer = '\0';
if(ATOB_ConvertAsciiToItem(crl_der, begin))
goto fail;
SECITEM_FreeItem(&filedata, PR_FALSE);
}
else
/* assume DER */
*crl_der = filedata;
PR_Close(infile);
return nss_cache_crl(crl_der);
fail:
PR_Close(infile);
SECITEM_FreeItem(crl_der, PR_TRUE);
SECITEM_FreeItem(&filedata, PR_FALSE);
return CURLE_SSL_CRL_BADFILE;
}
static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
char *key_file)
{
PK11SlotInfo *slot, *tmp;
SECStatus status;
CURLcode result;
struct ssl_connect_data *ssl = conn->ssl;
struct Curl_easy *data = conn->data;
(void)sockindex; /* unused */
result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
if(result) {
PR_SetError(SEC_ERROR_BAD_KEY, 0);
return result;
}
slot = nss_find_slot_by_name("PEM Token #1");
if(!slot)
return CURLE_SSL_CERTPROBLEM;
/* This will force the token to be seen as re-inserted */
tmp = SECMOD_WaitForAnyTokenEvent(pem_module, 0, 0);
if(tmp)
PK11_FreeSlot(tmp);
PK11_IsPresent(slot);
status = PK11_Authenticate(slot, PR_TRUE, SSL_SET_OPTION(key_passwd));
PK11_FreeSlot(slot);
return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
}
static int display_error(struct connectdata *conn, PRInt32 err,
const char *filename)
{
switch(err) {
case SEC_ERROR_BAD_PASSWORD:
failf(conn->data, "Unable to load client key: Incorrect password");
return 1;
case SEC_ERROR_UNKNOWN_CERT:
failf(conn->data, "Unable to load certificate %s", filename);
return 1;
default:
break;
}
return 0; /* The caller will print a generic error */
}
static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
char *cert_file, char *key_file)
{
struct Curl_easy *data = conn->data;
CURLcode result;
if(cert_file) {
result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, cert_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client cert: %d (%s)", err, err_name);
}
return result;
}
}
if(key_file || (is_file(cert_file))) {
if(key_file)
result = nss_load_key(conn, sockindex, key_file);
else
/* In case the cert file also has the key */
result = nss_load_key(conn, sockindex, cert_file);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, key_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client key: %d (%s)", err, err_name);
}
return result;
}
}
return CURLE_OK;
}
static char *nss_get_password(PK11SlotInfo *slot, PRBool retry, void *arg)
{
(void)slot; /* unused */
if(retry || NULL == arg)
return NULL;
else
return (char *)PORT_Strdup((char *)arg);
}
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
PRBool isServer)
{
struct connectdata *conn = (struct connectdata *)arg;
#ifdef SSL_ENABLE_OCSP_STAPLING
if(SSL_CONN_CONFIG(verifystatus)) {
SECStatus cacheResult;
const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
if(!csa) {
failf(conn->data, "Invalid OCSP response");
return SECFailure;
}
if(csa->len == 0) {
failf(conn->data, "No OCSP response received");
return SECFailure;
}
cacheResult = CERT_CacheOCSPResponseFromSideChannel(
CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
PR_Now(), &csa->items[0], arg
);
if(cacheResult != SECSuccess) {
failf(conn->data, "Invalid OCSP response");
return cacheResult;
}
}
#endif
if(!SSL_CONN_CONFIG(verifypeer)) {
infof(conn->data, "skipping SSL peer certificate verification\n");
return SECSuccess;
}
return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
}
/**
* Inform the application that the handshake is complete.
*/
static void HandshakeCallback(PRFileDesc *sock, void *arg)
{
struct connectdata *conn = (struct connectdata*) arg;
unsigned int buflenmax = 50;
unsigned char buf[50];
unsigned int buflen;
SSLNextProtoState state;
if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
return;
}
if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
switch(state) {
#if NSSVERNUM >= 0x031a00 /* 3.26.0 */
/* used by NSS internally to implement 0-RTT */
case SSL_NEXT_PROTO_EARLY_VALUE:
/* fall through! */
#endif
case SSL_NEXT_PROTO_NO_SUPPORT:
case SSL_NEXT_PROTO_NO_OVERLAP:
infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
return;
#ifdef SSL_ENABLE_ALPN
case SSL_NEXT_PROTO_SELECTED:
infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
break;
#endif
case SSL_NEXT_PROTO_NEGOTIATED:
infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
break;
}
#ifdef USE_NGHTTP2
if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
!memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
conn->negnpn = CURL_HTTP_VERSION_2;
}
else
#endif
if(buflen == ALPN_HTTP_1_1_LENGTH &&
!memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
conn->negnpn = CURL_HTTP_VERSION_1_1;
}
}
}
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
PRBool *canFalseStart)
{
struct connectdata *conn = client_data;
struct Curl_easy *data = conn->data;
SSLChannelInfo channelInfo;
SSLCipherSuiteInfo cipherInfo;
SECStatus rv;
PRBool negotiatedExtension;
*canFalseStart = PR_FALSE;
if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
return SECFailure;
if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
sizeof(cipherInfo)) != SECSuccess)
return SECFailure;
/* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
* TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
*/
if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
goto end;
/* Only allow ECDHE key exchange algorithm.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
if(cipherInfo.keaType != ssl_kea_ecdh)
goto end;
/* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
* mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
* design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
if(cipherInfo.symCipher != ssl_calg_aes_gcm)
goto end;
/* Enforce ALPN or NPN to do False Start, as an indicator of server
* compatibility. */
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
&negotiatedExtension);
if(rv != SECSuccess || !negotiatedExtension) {
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
&negotiatedExtension);
}
if(rv != SECSuccess || !negotiatedExtension)
goto end;
*canFalseStart = PR_TRUE;
infof(data, "Trying TLS False Start\n");
end:
return SECSuccess;
}
#endif
static void display_cert_info(struct Curl_easy *data,
CERTCertificate *cert)
{
char *subject, *issuer, *common_name;
PRExplodedTime printableTime;
char timeString[256];
PRTime notBefore, notAfter;
subject = CERT_NameToAscii(&cert->subject);
issuer = CERT_NameToAscii(&cert->issuer);
common_name = CERT_GetCommonName(&cert->subject);
infof(data, "\tsubject: %s\n", subject);
CERT_GetCertTimes(cert, ¬Before, ¬After);
PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\tstart date: %s\n", timeString);
PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\texpire date: %s\n", timeString);
infof(data, "\tcommon name: %s\n", common_name);
infof(data, "\tissuer: %s\n", issuer);
PR_Free(subject);
PR_Free(issuer);
PR_Free(common_name);
}
static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
{
CURLcode result = CURLE_OK;
SSLChannelInfo channel;
SSLCipherSuiteInfo suite;
CERTCertificate *cert;
CERTCertificate *cert2;
CERTCertificate *cert3;
PRTime now;
int i;
if(SSL_GetChannelInfo(sock, &channel, sizeof(channel)) ==
SECSuccess && channel.length == sizeof(channel) &&
channel.cipherSuite) {
if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
&suite, sizeof(suite)) == SECSuccess) {
infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
}
}
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(conn->data, "Server certificate:\n");
if(!conn->data->set.ssl.certinfo) {
display_cert_info(conn->data, cert);
CERT_DestroyCertificate(cert);
}
else {
/* Count certificates in chain. */
now = PR_Now();
i = 1;
if(!cert->isRoot) {
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
while(cert2) {
i++;
if(cert2->isRoot) {
CERT_DestroyCertificate(cert2);
break;
}
cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
CERT_DestroyCertificate(cert2);
cert2 = cert3;
}
}
result = Curl_ssl_init_certinfo(conn->data, i);
if(!result) {
for(i = 0; cert; cert = cert2) {
result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
(char *)cert->derCert.data +
cert->derCert.len);
if(result)
break;
if(cert->isRoot) {
CERT_DestroyCertificate(cert);
break;
}
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
CERT_DestroyCertificate(cert);
}
}
}
}
return result;
}
static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
{
struct connectdata *conn = (struct connectdata *)arg;
struct Curl_easy *data = conn->data;
PRErrorCode err = PR_GetError();
CERTCertificate *cert;
/* remember the cert verification result */
if(SSL_IS_PROXY())
data->set.proxy_ssl.certverifyresult = err;
else
data->set.ssl.certverifyresult = err;
if(err == SSL_ERROR_BAD_CERT_DOMAIN && !SSL_CONN_CONFIG(verifyhost))
/* we are asked not to verify the host name */
return SECSuccess;
/* print only info about the cert, the error is printed off the callback */
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(data, "Server certificate:\n");
display_cert_info(data, cert);
CERT_DestroyCertificate(cert);
}