1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ***************************************************************************/
22
23 /*
24 * Source file for all NSS-specific code for the TLS/SSL layer. No code
25 * but vtls.c should ever call or use these functions.
26 */
27
28 #include "curl_setup.h"
29
30 #ifdef USE_NSS
31
32 #include "urldata.h"
33 #include "sendf.h"
34 #include "formdata.h" /* for the boundary function */
35 #include "url.h" /* for the ssl config check function */
36 #include "connect.h"
37 #include "strcase.h"
38 #include "select.h"
39 #include "vtls.h"
40 #include "llist.h"
41 #include "multiif.h"
42 #include "curl_printf.h"
43 #include "nssg.h"
44 #include <nspr.h>
45 #include <nss.h>
46 #include <ssl.h>
47 #include <sslerr.h>
48 #include <secerr.h>
49 #include <secmod.h>
50 #include <sslproto.h>
51 #include <prtypes.h>
52 #include <pk11pub.h>
53 #include <prio.h>
54 #include <secitem.h>
55 #include <secport.h>
56 #include <certdb.h>
57 #include <base64.h>
58 #include <cert.h>
59 #include <prerror.h>
60 #include <keyhi.h> /* for SECKEY_DestroyPublicKey() */
61 #include <private/pprio.h> /* for PR_ImportTCPSocket */
62
63 #define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH)
64
65 #if NSSVERNUM >= 0x030f00 /* 3.15.0 */
66 #include <ocsp.h>
67 #endif
68
69 #include "strcase.h"
70 #include "warnless.h"
71 #include "x509asn1.h"
72
73 /* The last #include files should be: */
74 #include "curl_memory.h"
75 #include "memdebug.h"
76
77 #define SSL_DIR "/etc/pki/nssdb"
78
79 /* enough to fit the string "PEM Token #[0|1]" */
80 #define SLOTSIZE 13
81
82 struct ssl_backend_data {
83 PRFileDesc *handle;
84 char *client_nickname;
85 struct Curl_easy *data;
86 struct Curl_llist obj_list;
87 PK11GenericObject *obj_clicert;
88 };
89
90 static PRLock *nss_initlock = NULL;
91 static PRLock *nss_crllock = NULL;
92 static PRLock *nss_findslot_lock = NULL;
93 static PRLock *nss_trustload_lock = NULL;
94 static struct Curl_llist nss_crl_list;
95 static NSSInitContext *nss_context = NULL;
96 static volatile int initialized = 0;
97
98 /* type used to wrap pointers as list nodes */
99 struct ptr_list_wrap {
100 void *ptr;
101 struct Curl_llist_element node;
102 };
103
104 struct cipher_s {
105 const char *name;
106 int num;
107 };
108
109 #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
110 CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
111 ptr->type = (_type); \
112 ptr->pValue = (_val); \
113 ptr->ulValueLen = (_len); \
114 } while(0)
115
116 #define CERT_NewTempCertificate __CERT_NewTempCertificate
117
118 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
119 static const struct cipher_s cipherlist[] = {
120 /* SSL2 cipher suites */
121 {"rc4", SSL_EN_RC4_128_WITH_MD5},
122 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
123 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
124 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
125 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
126 {"des", SSL_EN_DES_64_CBC_WITH_MD5},
127 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
128 /* SSL3/TLS cipher suites */
129 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
130 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
131 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
132 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
133 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
134 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
135 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
136 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
137 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
138 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
139 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
140 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
141 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
142 /* TLS 1.0: Exportable 56-bit Cipher Suites. */
143 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
144 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
145 /* AES ciphers. */
146 {"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
147 {"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
148 {"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
149 {"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
150 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
151 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
152 /* ECC ciphers. */
153 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
154 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
155 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
156 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
157 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
158 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
159 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
160 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
161 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
162 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
163 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
164 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
165 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
166 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
167 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
168 {"ecdhe_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
169 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
170 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
171 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
172 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
173 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
174 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
175 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
176 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
177 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
178 #ifdef TLS_RSA_WITH_NULL_SHA256
179 /* new HMAC-SHA256 cipher suites specified in RFC */
180 {"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
181 {"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
182 {"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
183 {"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
184 {"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
185 {"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
186 {"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
187 #endif
188 #ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
189 /* AES GCM cipher suites in RFC 5288 and RFC 5289 */
190 {"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
191 {"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
192 {"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
193 {"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
194 {"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
195 {"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
196 {"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
197 #endif
198 #ifdef TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
199 /* cipher suites using SHA384 */
200 {"rsa_aes_256_gcm_sha_384", TLS_RSA_WITH_AES_256_GCM_SHA384},
201 {"dhe_rsa_aes_256_gcm_sha_384", TLS_DHE_RSA_WITH_AES_256_GCM_SHA384},
202 {"dhe_dss_aes_256_gcm_sha_384", TLS_DHE_DSS_WITH_AES_256_GCM_SHA384},
203 {"ecdhe_ecdsa_aes_256_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384},
204 {"ecdhe_rsa_aes_256_sha_384", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384},
205 {"ecdhe_ecdsa_aes_256_gcm_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
206 {"ecdhe_rsa_aes_256_gcm_sha_384", TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
207 #endif
208 #ifdef TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
209 /* chacha20-poly1305 cipher suites */
210 {"ecdhe_rsa_chacha20_poly1305_sha_256",
211 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
212 {"ecdhe_ecdsa_chacha20_poly1305_sha_256",
213 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256},
214 {"dhe_rsa_chacha20_poly1305_sha_256",
215 TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
216 #endif
217 #ifdef TLS_AES_256_GCM_SHA384
218 {"aes_128_gcm_sha_256", TLS_AES_128_GCM_SHA256},
219 {"aes_256_gcm_sha_384", TLS_AES_256_GCM_SHA384},
220 {"chacha20_poly1305_sha_256", TLS_CHACHA20_POLY1305_SHA256},
221 #endif
222 };
223
224 #if defined(WIN32)
225 static const char *pem_library = "nsspem.dll";
226 static const char *trust_library = "nssckbi.dll";
227 #elif defined(__APPLE__)
228 static const char *pem_library = "libnsspem.dylib";
229 static const char *trust_library = "libnssckbi.dylib";
230 #else
231 static const char *pem_library = "libnsspem.so";
232 static const char *trust_library = "libnssckbi.so";
233 #endif
234
235 static SECMODModule *pem_module = NULL;
236 static SECMODModule *trust_module = NULL;
237
238 /* NSPR I/O layer we use to detect blocking direction during SSL handshake */
239 static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
240 static PRIOMethods nspr_io_methods;
241
nss_error_to_name(PRErrorCode code)242 static const char *nss_error_to_name(PRErrorCode code)
243 {
244 const char *name = PR_ErrorToName(code);
245 if(name)
246 return name;
247
248 return "unknown error";
249 }
250
nss_print_error_message(struct Curl_easy * data,PRUint32 err)251 static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
252 {
253 failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
254 }
255
nss_sslver_to_name(PRUint16 nssver)256 static char *nss_sslver_to_name(PRUint16 nssver)
257 {
258 switch(nssver) {
259 case SSL_LIBRARY_VERSION_2:
260 return strdup("SSLv2");
261 case SSL_LIBRARY_VERSION_3_0:
262 return strdup("SSLv3");
263 case SSL_LIBRARY_VERSION_TLS_1_0:
264 return strdup("TLSv1.0");
265 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
266 case SSL_LIBRARY_VERSION_TLS_1_1:
267 return strdup("TLSv1.1");
268 #endif
269 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
270 case SSL_LIBRARY_VERSION_TLS_1_2:
271 return strdup("TLSv1.2");
272 #endif
273 #ifdef SSL_LIBRARY_VERSION_TLS_1_3
274 case SSL_LIBRARY_VERSION_TLS_1_3:
275 return strdup("TLSv1.3");
276 #endif
277 default:
278 return curl_maprintf("0x%04x", nssver);
279 }
280 }
281
set_ciphers(struct Curl_easy * data,PRFileDesc * model,char * cipher_list)282 static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
283 char *cipher_list)
284 {
285 unsigned int i;
286 PRBool cipher_state[NUM_OF_CIPHERS];
287 PRBool found;
288 char *cipher;
289
290 /* use accessors to avoid dynamic linking issues after an update of NSS */
291 const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
292 const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
293 if(!implemented_ciphers)
294 return SECFailure;
295
296 /* First disable all ciphers. This uses a different max value in case
297 * NSS adds more ciphers later we don't want them available by
298 * accident
299 */
300 for(i = 0; i < num_implemented_ciphers; i++) {
301 SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
302 }
303
304 /* Set every entry in our list to false */
305 for(i = 0; i < NUM_OF_CIPHERS; i++) {
306 cipher_state[i] = PR_FALSE;
307 }
308
309 cipher = cipher_list;
310
311 while(cipher_list && (cipher_list[0])) {
312 while((*cipher) && (ISSPACE(*cipher)))
313 ++cipher;
314
315 cipher_list = strchr(cipher, ',');
316 if(cipher_list) {
317 *cipher_list++ = '\0';
318 }
319
320 found = PR_FALSE;
321
322 for(i = 0; i<NUM_OF_CIPHERS; i++) {
323 if(strcasecompare(cipher, cipherlist[i].name)) {
324 cipher_state[i] = PR_TRUE;
325 found = PR_TRUE;
326 break;
327 }
328 }
329
330 if(found == PR_FALSE) {
331 failf(data, "Unknown cipher in list: %s", cipher);
332 return SECFailure;
333 }
334
335 if(cipher_list) {
336 cipher = cipher_list;
337 }
338 }
339
340 /* Finally actually enable the selected ciphers */
341 for(i = 0; i<NUM_OF_CIPHERS; i++) {
342 if(!cipher_state[i])
343 continue;
344
345 if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
346 failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
347 return SECFailure;
348 }
349 }
350
351 return SECSuccess;
352 }
353
354 /*
355 * Return true if at least one cipher-suite is enabled. Used to determine
356 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
357 */
any_cipher_enabled(void)358 static bool any_cipher_enabled(void)
359 {
360 unsigned int i;
361
362 for(i = 0; i<NUM_OF_CIPHERS; i++) {
363 PRInt32 policy = 0;
364 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
365 if(policy)
366 return TRUE;
367 }
368
369 return FALSE;
370 }
371
372 /*
373 * Determine whether the nickname passed in is a filename that needs to
374 * be loaded as a PEM or a regular NSS nickname.
375 *
376 * returns 1 for a file
377 * returns 0 for not a file (NSS nickname)
378 */
is_file(const char * filename)379 static int is_file(const char *filename)
380 {
381 struct_stat st;
382
383 if(filename == NULL)
384 return 0;
385
386 if(stat(filename, &st) == 0)
387 if(S_ISREG(st.st_mode) || S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
388 return 1;
389
390 return 0;
391 }
392
393 /* Check if the given string is filename or nickname of a certificate. If the
394 * given string is recognized as filename, return NULL. If the given string is
395 * recognized as nickname, return a duplicated string. The returned string
396 * should be later deallocated using free(). If the OOM failure occurs, we
397 * return NULL, too.
398 */
dup_nickname(struct Curl_easy * data,const char * str)399 static char *dup_nickname(struct Curl_easy *data, const char *str)
400 {
401 const char *n;
402
403 if(!is_file(str))
404 /* no such file exists, use the string as nickname */
405 return strdup(str);
406
407 /* search the first slash; we require at least one slash in a file name */
408 n = strchr(str, '/');
409 if(!n) {
410 infof(data, "warning: certificate file name \"%s\" handled as nickname; "
411 "please use \"./%s\" to force file name\n", str, str);
412 return strdup(str);
413 }
414
415 /* we'll use the PEM reader to read the certificate from file */
416 return NULL;
417 }
418
419 /* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition
420 * in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN. For more
421 * details, go to <https://bugzilla.mozilla.org/1297397>.
422 */
nss_find_slot_by_name(const char * slot_name)423 static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name)
424 {
425 PK11SlotInfo *slot;
426 PR_Lock(nss_findslot_lock);
427 slot = PK11_FindSlotByName(slot_name);
428 PR_Unlock(nss_findslot_lock);
429 return slot;
430 }
431
432 /* wrap 'ptr' as list node and tail-insert into 'list' */
insert_wrapped_ptr(struct Curl_llist * list,void * ptr)433 static CURLcode insert_wrapped_ptr(struct Curl_llist *list, void *ptr)
434 {
435 struct ptr_list_wrap *wrap = malloc(sizeof(*wrap));
436 if(!wrap)
437 return CURLE_OUT_OF_MEMORY;
438
439 wrap->ptr = ptr;
440 Curl_llist_insert_next(list, list->tail, wrap, &wrap->node);
441 return CURLE_OK;
442 }
443
444 /* Call PK11_CreateGenericObject() with the given obj_class and filename. If
445 * the call succeeds, append the object handle to the list of objects so that
446 * the object can be destroyed in Curl_nss_close(). */
nss_create_object(struct ssl_connect_data * connssl,CK_OBJECT_CLASS obj_class,const char * filename,bool cacert)447 static CURLcode nss_create_object(struct ssl_connect_data *connssl,
448 CK_OBJECT_CLASS obj_class,
449 const char *filename, bool cacert)
450 {
451 PK11SlotInfo *slot;
452 PK11GenericObject *obj;
453 CK_BBOOL cktrue = CK_TRUE;
454 CK_BBOOL ckfalse = CK_FALSE;
455 CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
456 int attr_cnt = 0;
457 CURLcode result = (cacert)
458 ? CURLE_SSL_CACERT_BADFILE
459 : CURLE_SSL_CERTPROBLEM;
460
461 const int slot_id = (cacert) ? 0 : 1;
462 char *slot_name = aprintf("PEM Token #%d", slot_id);
463 struct ssl_backend_data *backend = connssl->backend;
464 if(!slot_name)
465 return CURLE_OUT_OF_MEMORY;
466
467 slot = nss_find_slot_by_name(slot_name);
468 free(slot_name);
469 if(!slot)
470 return result;
471
472 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
473 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
474 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
475 (CK_ULONG)strlen(filename) + 1);
476
477 if(CKO_CERTIFICATE == obj_class) {
478 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
479 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
480 }
481
482 /* PK11_CreateManagedGenericObject() was introduced in NSS 3.34 because
483 * PK11_DestroyGenericObject() does not release resources allocated by
484 * PK11_CreateGenericObject() early enough. */
485 obj =
486 #ifdef HAVE_PK11_CREATEMANAGEDGENERICOBJECT
487 PK11_CreateManagedGenericObject
488 #else
489 PK11_CreateGenericObject
490 #endif
491 (slot, attrs, attr_cnt, PR_FALSE);
492
493 PK11_FreeSlot(slot);
494 if(!obj)
495 return result;
496
497 if(insert_wrapped_ptr(&backend->obj_list, obj) != CURLE_OK) {
498 PK11_DestroyGenericObject(obj);
499 return CURLE_OUT_OF_MEMORY;
500 }
501
502 if(!cacert && CKO_CERTIFICATE == obj_class)
503 /* store reference to a client certificate */
504 backend->obj_clicert = obj;
505
506 return CURLE_OK;
507 }
508
509 /* Destroy the NSS object whose handle is given by ptr. This function is
510 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
511 * NSS objects in Curl_nss_close() */
nss_destroy_object(void * user,void * ptr)512 static void nss_destroy_object(void *user, void *ptr)
513 {
514 struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr;
515 PK11GenericObject *obj = (PK11GenericObject *) wrap->ptr;
516 (void) user;
517 PK11_DestroyGenericObject(obj);
518 free(wrap);
519 }
520
521 /* same as nss_destroy_object() but for CRL items */
nss_destroy_crl_item(void * user,void * ptr)522 static void nss_destroy_crl_item(void *user, void *ptr)
523 {
524 struct ptr_list_wrap *wrap = (struct ptr_list_wrap *) ptr;
525 SECItem *crl_der = (SECItem *) wrap->ptr;
526 (void) user;
527 SECITEM_FreeItem(crl_der, PR_TRUE);
528 free(wrap);
529 }
530
nss_load_cert(struct ssl_connect_data * ssl,const char * filename,PRBool cacert)531 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
532 const char *filename, PRBool cacert)
533 {
534 CURLcode result = (cacert)
535 ? CURLE_SSL_CACERT_BADFILE
536 : CURLE_SSL_CERTPROBLEM;
537
538 /* libnsspem.so leaks memory if the requested file does not exist. For more
539 * details, go to <https://bugzilla.redhat.com/734760>. */
540 if(is_file(filename))
541 result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
542
543 if(!result && !cacert) {
544 /* we have successfully loaded a client certificate */
545 CERTCertificate *cert;
546 char *nickname = NULL;
547 char *n = strrchr(filename, '/');
548 if(n)
549 n++;
550
551 /* The following undocumented magic helps to avoid a SIGSEGV on call
552 * of PK11_ReadRawAttribute() from SelectClientCert() when using an
553 * immature version of libnsspem.so. For more details, go to
554 * <https://bugzilla.redhat.com/733685>. */
555 nickname = aprintf("PEM Token #1:%s", n);
556 if(nickname) {
557 cert = PK11_FindCertFromNickname(nickname, NULL);
558 if(cert)
559 CERT_DestroyCertificate(cert);
560
561 free(nickname);
562 }
563 }
564
565 return result;
566 }
567
568 /* add given CRL to cache if it is not already there */
nss_cache_crl(SECItem * crl_der)569 static CURLcode nss_cache_crl(SECItem *crl_der)
570 {
571 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
572 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
573 if(crl) {
574 /* CRL already cached */
575 SEC_DestroyCrl(crl);
576 SECITEM_FreeItem(crl_der, PR_TRUE);
577 return CURLE_OK;
578 }
579
580 /* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
581 PR_Lock(nss_crllock);
582
583 if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
584 /* unable to cache CRL */
585 SECITEM_FreeItem(crl_der, PR_TRUE);
586 PR_Unlock(nss_crllock);
587 return CURLE_SSL_CRL_BADFILE;
588 }
589
590 /* store the CRL item so that we can free it in Curl_nss_cleanup() */
591 if(insert_wrapped_ptr(&nss_crl_list, crl_der) != CURLE_OK) {
592 if(SECSuccess == CERT_UncacheCRL(db, crl_der))
593 SECITEM_FreeItem(crl_der, PR_TRUE);
594 PR_Unlock(nss_crllock);
595 return CURLE_OUT_OF_MEMORY;
596 }
597
598 /* we need to clear session cache, so that the CRL could take effect */
599 SSL_ClearSessionCache();
600 PR_Unlock(nss_crllock);
601 return CURLE_OK;
602 }
603
nss_load_crl(const char * crlfilename)604 static CURLcode nss_load_crl(const char *crlfilename)
605 {
606 PRFileDesc *infile;
607 PRFileInfo info;
608 SECItem filedata = { 0, NULL, 0 };
609 SECItem *crl_der = NULL;
610 char *body;
611
612 infile = PR_Open(crlfilename, PR_RDONLY, 0);
613 if(!infile)
614 return CURLE_SSL_CRL_BADFILE;
615
616 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
617 goto fail;
618
619 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
620 goto fail;
621
622 if(info.size != PR_Read(infile, filedata.data, info.size))
623 goto fail;
624
625 crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
626 if(!crl_der)
627 goto fail;
628
629 /* place a trailing zero right after the visible data */
630 body = (char *)filedata.data;
631 body[--filedata.len] = '\0';
632
633 body = strstr(body, "-----BEGIN");
634 if(body) {
635 /* assume ASCII */
636 char *trailer;
637 char *begin = PORT_Strchr(body, '\n');
638 if(!begin)
639 begin = PORT_Strchr(body, '\r');
640 if(!begin)
641 goto fail;
642
643 trailer = strstr(++begin, "-----END");
644 if(!trailer)
645 goto fail;
646
647 /* retrieve DER from ASCII */
648 *trailer = '\0';
649 if(ATOB_ConvertAsciiToItem(crl_der, begin))
650 goto fail;
651
652 SECITEM_FreeItem(&filedata, PR_FALSE);
653 }
654 else
655 /* assume DER */
656 *crl_der = filedata;
657
658 PR_Close(infile);
659 return nss_cache_crl(crl_der);
660
661 fail:
662 PR_Close(infile);
663 SECITEM_FreeItem(crl_der, PR_TRUE);
664 SECITEM_FreeItem(&filedata, PR_FALSE);
665 return CURLE_SSL_CRL_BADFILE;
666 }
667
nss_load_key(struct connectdata * conn,int sockindex,char * key_file)668 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
669 char *key_file)
670 {
671 PK11SlotInfo *slot, *tmp;
672 SECStatus status;
673 CURLcode result;
674 struct ssl_connect_data *ssl = conn->ssl;
675 struct Curl_easy *data = conn->data;
676
677 (void)sockindex; /* unused */
678
679 result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
680 if(result) {
681 PR_SetError(SEC_ERROR_BAD_KEY, 0);
682 return result;
683 }
684
685 slot = nss_find_slot_by_name("PEM Token #1");
686 if(!slot)
687 return CURLE_SSL_CERTPROBLEM;
688
689 /* This will force the token to be seen as re-inserted */
690 tmp = SECMOD_WaitForAnyTokenEvent(pem_module, 0, 0);
691 if(tmp)
692 PK11_FreeSlot(tmp);
693 if(!PK11_IsPresent(slot)) {
694 PK11_FreeSlot(slot);
695 return CURLE_SSL_CERTPROBLEM;
696 }
697
698 status = PK11_Authenticate(slot, PR_TRUE, SSL_SET_OPTION(key_passwd));
699 PK11_FreeSlot(slot);
700
701 return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
702 }
703
display_error(struct connectdata * conn,PRInt32 err,const char * filename)704 static int display_error(struct connectdata *conn, PRInt32 err,
705 const char *filename)
706 {
707 switch(err) {
708 case SEC_ERROR_BAD_PASSWORD:
709 failf(conn->data, "Unable to load client key: Incorrect password");
710 return 1;
711 case SEC_ERROR_UNKNOWN_CERT:
712 failf(conn->data, "Unable to load certificate %s", filename);
713 return 1;
714 default:
715 break;
716 }
717 return 0; /* The caller will print a generic error */
718 }
719
cert_stuff(struct connectdata * conn,int sockindex,char * cert_file,char * key_file)720 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
721 char *cert_file, char *key_file)
722 {
723 struct Curl_easy *data = conn->data;
724 CURLcode result;
725
726 if(cert_file) {
727 result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
728 if(result) {
729 const PRErrorCode err = PR_GetError();
730 if(!display_error(conn, err, cert_file)) {
731 const char *err_name = nss_error_to_name(err);
732 failf(data, "unable to load client cert: %d (%s)", err, err_name);
733 }
734
735 return result;
736 }
737 }
738
739 if(key_file || (is_file(cert_file))) {
740 if(key_file)
741 result = nss_load_key(conn, sockindex, key_file);
742 else
743 /* In case the cert file also has the key */
744 result = nss_load_key(conn, sockindex, cert_file);
745 if(result) {
746 const PRErrorCode err = PR_GetError();
747 if(!display_error(conn, err, key_file)) {
748 const char *err_name = nss_error_to_name(err);
749 failf(data, "unable to load client key: %d (%s)", err, err_name);
750 }
751
752 return result;
753 }
754 }
755
756 return CURLE_OK;
757 }
758
nss_get_password(PK11SlotInfo * slot,PRBool retry,void * arg)759 static char *nss_get_password(PK11SlotInfo *slot, PRBool retry, void *arg)
760 {
761 (void)slot; /* unused */
762
763 if(retry || NULL == arg)
764 return NULL;
765 else
766 return (char *)PORT_Strdup((char *)arg);
767 }
768
769 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
770 * verify peer */
nss_auth_cert_hook(void * arg,PRFileDesc * fd,PRBool checksig,PRBool isServer)771 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
772 PRBool isServer)
773 {
774 struct connectdata *conn = (struct connectdata *)arg;
775
776 #ifdef SSL_ENABLE_OCSP_STAPLING
777 if(SSL_CONN_CONFIG(verifystatus)) {
778 SECStatus cacheResult;
779
780 const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
781 if(!csa) {
782 failf(conn->data, "Invalid OCSP response");
783 return SECFailure;
784 }
785
786 if(csa->len == 0) {
787 failf(conn->data, "No OCSP response received");
788 return SECFailure;
789 }
790
791 cacheResult = CERT_CacheOCSPResponseFromSideChannel(
792 CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
793 PR_Now(), &csa->items[0], arg
794 );
795
796 if(cacheResult != SECSuccess) {
797 failf(conn->data, "Invalid OCSP response");
798 return cacheResult;
799 }
800 }
801 #endif
802
803 if(!SSL_CONN_CONFIG(verifypeer)) {
804 infof(conn->data, "skipping SSL peer certificate verification\n");
805 return SECSuccess;
806 }
807
808 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
809 }
810
811 /**
812 * Inform the application that the handshake is complete.
813 */
HandshakeCallback(PRFileDesc * sock,void * arg)814 static void HandshakeCallback(PRFileDesc *sock, void *arg)
815 {
816 struct connectdata *conn = (struct connectdata*) arg;
817 unsigned int buflenmax = 50;
818 unsigned char buf[50];
819 unsigned int buflen;
820 SSLNextProtoState state;
821
822 if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
823 return;
824 }
825
826 if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
827
828 switch(state) {
829 #if NSSVERNUM >= 0x031a00 /* 3.26.0 */
830 /* used by NSS internally to implement 0-RTT */
831 case SSL_NEXT_PROTO_EARLY_VALUE:
832 /* fall through! */
833 #endif
834 case SSL_NEXT_PROTO_NO_SUPPORT:
835 case SSL_NEXT_PROTO_NO_OVERLAP:
836 infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
837 return;
838 #ifdef SSL_ENABLE_ALPN
839 case SSL_NEXT_PROTO_SELECTED:
840 infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
841 break;
842 #endif
843 case SSL_NEXT_PROTO_NEGOTIATED:
844 infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
845 break;
846 }
847
848 #ifdef USE_NGHTTP2
849 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
850 !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
851 conn->negnpn = CURL_HTTP_VERSION_2;
852 }
853 else
854 #endif
855 if(buflen == ALPN_HTTP_1_1_LENGTH &&
856 !memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
857 conn->negnpn = CURL_HTTP_VERSION_1_1;
858 }
859 Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
860 BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
861 }
862 }
863
864 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
CanFalseStartCallback(PRFileDesc * sock,void * client_data,PRBool * canFalseStart)865 static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
866 PRBool *canFalseStart)
867 {
868 struct connectdata *conn = client_data;
869 struct Curl_easy *data = conn->data;
870
871 SSLChannelInfo channelInfo;
872 SSLCipherSuiteInfo cipherInfo;
873
874 SECStatus rv;
875 PRBool negotiatedExtension;
876
877 *canFalseStart = PR_FALSE;
878
879 if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
880 return SECFailure;
881
882 if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
883 sizeof(cipherInfo)) != SECSuccess)
884 return SECFailure;
885
886 /* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
887 * TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
888 */
889 if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
890 goto end;
891
892 /* Only allow ECDHE key exchange algorithm.
893 * See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
894 if(cipherInfo.keaType != ssl_kea_ecdh)
895 goto end;
896
897 /* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
898 * mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
899 * design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
900 if(cipherInfo.symCipher != ssl_calg_aes_gcm)
901 goto end;
902
903 /* Enforce ALPN or NPN to do False Start, as an indicator of server
904 * compatibility. */
905 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
906 &negotiatedExtension);
907 if(rv != SECSuccess || !negotiatedExtension) {
908 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
909 &negotiatedExtension);
910 }
911
912 if(rv != SECSuccess || !negotiatedExtension)
913 goto end;
914
915 *canFalseStart = PR_TRUE;
916
917 infof(data, "Trying TLS False Start\n");
918
919 end:
920 return SECSuccess;
921 }
922 #endif
923
display_cert_info(struct Curl_easy * data,CERTCertificate * cert)924 static void display_cert_info(struct Curl_easy *data,
925 CERTCertificate *cert)
926 {
927 char *subject, *issuer, *common_name;
928 PRExplodedTime printableTime;
929 char timeString[256];
930 PRTime notBefore, notAfter;
931
932 subject = CERT_NameToAscii(&cert->subject);
933 issuer = CERT_NameToAscii(&cert->issuer);
934 common_name = CERT_GetCommonName(&cert->subject);
935 infof(data, "\tsubject: %s\n", subject);
936
937 CERT_GetCertTimes(cert, ¬Before, ¬After);
938 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
939 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
940 infof(data, "\tstart date: %s\n", timeString);
941 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
942 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
943 infof(data, "\texpire date: %s\n", timeString);
944 infof(data, "\tcommon name: %s\n", common_name);
945 infof(data, "\tissuer: %s\n", issuer);
946
947 PR_Free(subject);
948 PR_Free(issuer);
949 PR_Free(common_name);
950 }
951
display_conn_info(struct connectdata * conn,PRFileDesc * sock)952 static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
953 {
954 CURLcode result = CURLE_OK;
955 SSLChannelInfo channel;
956 SSLCipherSuiteInfo suite;
957 CERTCertificate *cert;
958 CERTCertificate *cert2;
959 CERTCertificate *cert3;
960 PRTime now;
961 int i;
962
963 if(SSL_GetChannelInfo(sock, &channel, sizeof(channel)) ==
964 SECSuccess && channel.length == sizeof(channel) &&
965 channel.cipherSuite) {
966 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
967 &suite, sizeof(suite)) == SECSuccess) {
968 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
969 }
970 }
971
972 cert = SSL_PeerCertificate(sock);
973 if(cert) {
974 infof(conn->data, "Server certificate:\n");
975
976 if(!conn->data->set.ssl.certinfo) {
977 display_cert_info(conn->data, cert);
978 CERT_DestroyCertificate(cert);
979 }
980 else {
981 /* Count certificates in chain. */
982 now = PR_Now();
983 i = 1;
984 if(!cert->isRoot) {
985 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
986 while(cert2) {
987 i++;
988 if(cert2->isRoot) {
989 CERT_DestroyCertificate(cert2);
990 break;
991 }
992 cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
993 CERT_DestroyCertificate(cert2);
994 cert2 = cert3;
995 }
996 }
997
998 result = Curl_ssl_init_certinfo(conn->data, i);
999 if(!result) {
1000 for(i = 0; cert; cert = cert2) {
1001 result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
1002 (char *)cert->derCert.data +
1003 cert->derCert.len);
1004 if(result)
1005 break;
1006
1007 if(cert->isRoot) {
1008 CERT_DestroyCertificate(cert);
1009 break;
1010 }
1011
1012 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
1013 CERT_DestroyCertificate(cert);
1014 }
1015 }
1016 }
1017 }
1018
1019 return result;
1020 }
1021
BadCertHandler(void * arg,PRFileDesc * sock)1022 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
1023 {
1024 struct connectdata *conn = (struct connectdata *)arg;
1025 struct Curl_easy *data = conn->data;
1026 PRErrorCode err = PR_GetError();
1027 CERTCertificate *cert;
1028
1029 /* remember the cert verification result */
1030 SSL_SET_OPTION_LVALUE(certverifyresult) = err;
1031
1032 if(err == SSL_ERROR_BAD_CERT_DOMAIN && !SSL_CONN_CONFIG(verifyhost))
1033 /* we are asked not to verify the host name */
1034 return SECSuccess;
1035
1036 /* print only info about the cert, the error is printed off the callback */
1037 cert = SSL_PeerCertificate(sock);
1038 if(cert) {
1039 infof(data, "Server certificate:\n");
1040 display_cert_info(data, cert);
1041 CERT_DestroyCertificate(cert);
1042 }
1043
1044 return SECFailure;
1045 }
1046
1047 /**
1048 *
1049 * Check that the Peer certificate's issuer certificate matches the one found
1050 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
1051 * issuer check, so we provide comments that mimic the OpenSSL
1052 * X509_check_issued function (in x509v3/v3_purp.c)
1053 */
check_issuer_cert(PRFileDesc * sock,char * issuer_nickname)1054 static SECStatus check_issuer_cert(PRFileDesc *sock,
1055 char *issuer_nickname)
1056 {
1057 CERTCertificate *cert, *cert_issuer, *issuer;
1058 SECStatus res = SECSuccess;
1059 void *proto_win = NULL;
1060
1061 cert = SSL_PeerCertificate(sock);
1062 cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
1063
1064 proto_win = SSL_RevealPinArg(sock);
1065 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
1066
1067 if((!cert_issuer) || (!issuer))
1068 res = SECFailure;
1069 else if(SECITEM_CompareItem(&cert_issuer->derCert,
1070 &issuer->derCert) != SECEqual)
1071 res = SECFailure;
1072
1073 CERT_DestroyCertificate(cert);
1074 CERT_DestroyCertificate(issuer);
1075 CERT_DestroyCertificate(cert_issuer);
1076 return res;
1077 }
1078
cmp_peer_pubkey(struct ssl_connect_data * connssl,const char * pinnedpubkey)1079 static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
1080 const char *pinnedpubkey)
1081 {
1082 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1083 struct ssl_backend_data *backend = connssl->backend;
1084 struct Curl_easy *data = backend->data;
1085 CERTCertificate *cert;
1086
1087 if(!pinnedpubkey)
1088 /* no pinned public key specified */
1089 return CURLE_OK;
1090
1091 /* get peer certificate */
1092 cert = SSL_PeerCertificate(backend->handle);
1093 if(cert) {
1094 /* extract public key from peer certificate */
1095 SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
1096 if(pubkey) {
1097 /* encode the public key as DER */
1098 SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
1099 if(cert_der) {
1100 /* compare the public key with the pinned public key */
1101 result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data,
1102 cert_der->len);
1103 SECITEM_FreeItem(cert_der, PR_TRUE);
1104 }
1105 SECKEY_DestroyPublicKey(pubkey);
1106 }
1107 CERT_DestroyCertificate(cert);
1108 }
1109
1110 /* report the resulting status */
1111 switch(result) {
1112 case CURLE_OK:
1113 infof(data, "pinned public key verified successfully!\n");
1114 break;
1115 case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
1116 failf(data, "failed to verify pinned public key");
1117 break;
1118 default:
1119 /* OOM, etc. */
1120 break;
1121 }
1122
1123 return result;
1124 }
1125
1126 /**
1127 *
1128 * Callback to pick the SSL client certificate.
1129 */
SelectClientCert(void * arg,PRFileDesc * sock,struct CERTDistNamesStr * caNames,struct CERTCertificateStr ** pRetCert,struct SECKEYPrivateKeyStr ** pRetKey)1130 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
1131 struct CERTDistNamesStr *caNames,
1132 struct CERTCertificateStr **pRetCert,
1133 struct SECKEYPrivateKeyStr **pRetKey)
1134 {
1135 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
1136 struct ssl_backend_data *backend = connssl->backend;
1137 struct Curl_easy *data = backend->data;
1138 const char *nickname = backend->client_nickname;
1139 static const char pem_slotname[] = "PEM Token #1";
1140
1141 if(backend->obj_clicert) {
1142 /* use the cert/key provided by PEM reader */
1143 SECItem cert_der = { 0, NULL, 0 };
1144 void *proto_win = SSL_RevealPinArg(sock);
1145 struct CERTCertificateStr *cert;
1146 struct SECKEYPrivateKeyStr *key;
1147
1148 PK11SlotInfo *slot = nss_find_slot_by_name(pem_slotname);
1149 if(NULL == slot) {
1150 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
1151 return SECFailure;
1152 }
1153
1154 if(PK11_ReadRawAttribute(PK11_TypeGeneric, backend->obj_clicert, CKA_VALUE,
1155 &cert_der) != SECSuccess) {
1156 failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
1157 PK11_FreeSlot(slot);
1158 return SECFailure;
1159 }
1160
1161 cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
1162 SECITEM_FreeItem(&cert_der, PR_FALSE);
1163 if(NULL == cert) {
1164 failf(data, "NSS: client certificate from file not found");
1165 PK11_FreeSlot(slot);
1166 return SECFailure;
1167 }
1168
1169 key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
1170 PK11_FreeSlot(slot);
1171 if(NULL == key) {
1172 failf(data, "NSS: private key from file not found");
1173 CERT_DestroyCertificate(cert);
1174 return SECFailure;
1175 }
1176
1177 infof(data, "NSS: client certificate from file\n");
1178 display_cert_info(data, cert);
1179
1180 *pRetCert = cert;
1181 *pRetKey = key;
1182 return SECSuccess;
1183 }
1184
1185 /* use the default NSS hook */
1186 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
1187 pRetCert, pRetKey)
1188 || NULL == *pRetCert) {
1189
1190 if(NULL == nickname)
1191 failf(data, "NSS: client certificate not found (nickname not "
1192 "specified)");
1193 else
1194 failf(data, "NSS: client certificate not found: %s", nickname);
1195
1196 return SECFailure;
1197 }
1198
1199 /* get certificate nickname if any */
1200 nickname = (*pRetCert)->nickname;
1201 if(NULL == nickname)
1202 nickname = "[unknown]";
1203
1204 if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) {
1205 failf(data, "NSS: refusing previously loaded certificate from file: %s",
1206 nickname);
1207 return SECFailure;
1208 }
1209
1210 if(NULL == *pRetKey) {
1211 failf(data, "NSS: private key not found for certificate: %s", nickname);
1212 return SECFailure;
1213 }
1214
1215 infof(data, "NSS: using client certificate: %s\n", nickname);
1216 display_cert_info(data, *pRetCert);
1217 return SECSuccess;
1218 }
1219
1220 /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
nss_update_connecting_state(ssl_connect_state state,void * secret)1221 static void nss_update_connecting_state(ssl_connect_state state, void *secret)
1222 {
1223 struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
1224 if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
1225 /* an unrelated error is passing by */
1226 return;
1227
1228 switch(connssl->connecting_state) {
1229 case ssl_connect_2:
1230 case ssl_connect_2_reading:
1231 case ssl_connect_2_writing:
1232 break;
1233 default:
1234 /* we are not called from an SSL handshake */
1235 return;
1236 }
1237
1238 /* update the state accordingly */
1239 connssl->connecting_state = state;
1240 }
1241
1242 /* recv() wrapper we use to detect blocking direction during SSL handshake */
nspr_io_recv(PRFileDesc * fd,void * buf,PRInt32 amount,PRIntn flags,PRIntervalTime timeout)1243 static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
1244 PRIntn flags, PRIntervalTime timeout)
1245 {
1246 const PRRecvFN recv_fn = fd->lower->methods->recv;
1247 const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
1248 if(rv < 0)
1249 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1250 nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
1251 return rv;
1252 }
1253
1254 /* send() wrapper we use to detect blocking direction during SSL handshake */
nspr_io_send(PRFileDesc * fd,const void * buf,PRInt32 amount,PRIntn flags,PRIntervalTime timeout)1255 static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
1256 PRIntn flags, PRIntervalTime timeout)
1257 {
1258 const PRSendFN send_fn = fd->lower->methods->send;
1259 const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
1260 if(rv < 0)
1261 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1262 nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
1263 return rv;
1264 }
1265
1266 /* close() wrapper to avoid assertion failure due to fd->secret != NULL */
nspr_io_close(PRFileDesc * fd)1267 static PRStatus nspr_io_close(PRFileDesc *fd)
1268 {
1269 const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
1270 fd->secret = NULL;
1271 return close_fn(fd);
1272 }
1273
1274 /* load a PKCS #11 module */
nss_load_module(SECMODModule ** pmod,const char * library,const char * name)1275 static CURLcode nss_load_module(SECMODModule **pmod, const char *library,
1276 const char *name)
1277 {
1278 char *config_string;
1279 SECMODModule *module = *pmod;
1280 if(module)
1281 /* already loaded */
1282 return CURLE_OK;
1283
1284 config_string = aprintf("library=%s name=%s", library, name);
1285 if(!config_string)
1286 return CURLE_OUT_OF_MEMORY;
1287
1288 module = SECMOD_LoadUserModule(config_string, NULL, PR_FALSE);
1289 free(config_string);
1290
1291 if(module && module->loaded) {
1292 /* loaded successfully */
1293 *pmod = module;
1294 return CURLE_OK;
1295 }
1296
1297 if(module)
1298 SECMOD_DestroyModule(module);
1299 return CURLE_FAILED_INIT;
1300 }
1301
1302 /* unload a PKCS #11 module */
nss_unload_module(SECMODModule ** pmod)1303 static void nss_unload_module(SECMODModule **pmod)
1304 {
1305 SECMODModule *module = *pmod;
1306 if(!module)
1307 /* not loaded */
1308 return;
1309
1310 if(SECMOD_UnloadUserModule(module) != SECSuccess)
1311 /* unload failed */
1312 return;
1313
1314 SECMOD_DestroyModule(module);
1315 *pmod = NULL;
1316 }
1317
1318 /* data might be NULL */
nss_init_core(struct Curl_easy * data,const char * cert_dir)1319 static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
1320 {
1321 NSSInitParameters initparams;
1322 PRErrorCode err;
1323 const char *err_name;
1324
1325 if(nss_context != NULL)
1326 return CURLE_OK;
1327
1328 memset((void *) &initparams, '\0', sizeof(initparams));
1329 initparams.length = sizeof(initparams);
1330
1331 if(cert_dir) {
1332 char *certpath = aprintf("sql:%s", cert_dir);
1333 if(!certpath)
1334 return CURLE_OUT_OF_MEMORY;
1335
1336 infof(data, "Initializing NSS with certpath: %s\n", certpath);
1337 nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
1338 NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
1339 free(certpath);
1340
1341 if(nss_context != NULL)
1342 return CURLE_OK;
1343
1344 err = PR_GetError();
1345 err_name = nss_error_to_name(err);
1346 infof(data, "Unable to initialize NSS database: %d (%s)\n", err, err_name);
1347 }
1348
1349 infof(data, "Initializing NSS with certpath: none\n");
1350 nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
1351 | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
1352 | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
1353 if(nss_context != NULL)
1354 return CURLE_OK;
1355
1356 err = PR_GetError();
1357 err_name = nss_error_to_name(err);
1358 failf(data, "Unable to initialize NSS: %d (%s)", err, err_name);
1359 return CURLE_SSL_CACERT_BADFILE;
1360 }
1361
1362 /* data might be NULL */
nss_init(struct Curl_easy * data)1363 static CURLcode nss_init(struct Curl_easy *data)
1364 {
1365 char *cert_dir;
1366 struct_stat st;
1367 CURLcode result;
1368
1369 if(initialized)
1370 return CURLE_OK;
1371
1372 /* list of all CRL items we need to destroy in Curl_nss_cleanup() */
1373 Curl_llist_init(&nss_crl_list, nss_destroy_crl_item);
1374
1375 /* First we check if $SSL_DIR points to a valid dir */
1376 cert_dir = getenv("SSL_DIR");
1377 if(cert_dir) {
1378 if((stat(cert_dir, &st) != 0) ||
1379 (!S_ISDIR(st.st_mode))) {
1380 cert_dir = NULL;
1381 }
1382 }
1383
1384 /* Now we check if the default location is a valid dir */
1385 if(!cert_dir) {
1386 if((stat(SSL_DIR, &st) == 0) &&
1387 (S_ISDIR(st.st_mode))) {
1388 cert_dir = (char *)SSL_DIR;
1389 }
1390 }
1391
1392 if(nspr_io_identity == PR_INVALID_IO_LAYER) {
1393 /* allocate an identity for our own NSPR I/O layer */
1394 nspr_io_identity = PR_GetUniqueIdentity("libcurl");
1395 if(nspr_io_identity == PR_INVALID_IO_LAYER)
1396 return CURLE_OUT_OF_MEMORY;
1397
1398 /* the default methods just call down to the lower I/O layer */
1399 memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(),
1400 sizeof(nspr_io_methods));
1401
1402 /* override certain methods in the table by our wrappers */
1403 nspr_io_methods.recv = nspr_io_recv;
1404 nspr_io_methods.send = nspr_io_send;
1405 nspr_io_methods.close = nspr_io_close;
1406 }
1407
1408 result = nss_init_core(data, cert_dir);
1409 if(result)
1410 return result;
1411
1412 if(!any_cipher_enabled())
1413 NSS_SetDomesticPolicy();
1414
1415 initialized = 1;
1416
1417 return CURLE_OK;
1418 }
1419
1420 /**
1421 * Global SSL init
1422 *
1423 * @retval 0 error initializing SSL
1424 * @retval 1 SSL initialized successfully
1425 */
Curl_nss_init(void)1426 static int Curl_nss_init(void)
1427 {
1428 /* curl_global_init() is not thread-safe so this test is ok */
1429 if(nss_initlock == NULL) {
1430 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
1431 nss_initlock = PR_NewLock();
1432 nss_crllock = PR_NewLock();
1433 nss_findslot_lock = PR_NewLock();
1434 nss_trustload_lock = PR_NewLock();
1435 }
1436
1437 /* We will actually initialize NSS later */
1438
1439 return 1;
1440 }
1441
1442 /* data might be NULL */
Curl_nss_force_init(struct Curl_easy * data)1443 CURLcode Curl_nss_force_init(struct Curl_easy *data)
1444 {
1445 CURLcode result;
1446 if(!nss_initlock) {
1447 if(data)
1448 failf(data, "unable to initialize NSS, curl_global_init() should have "
1449 "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1450 return CURLE_FAILED_INIT;
1451 }
1452
1453 PR_Lock(nss_initlock);
1454 result = nss_init(data);
1455 PR_Unlock(nss_initlock);
1456
1457 return result;
1458 }
1459
1460 /* Global cleanup */
Curl_nss_cleanup(void)1461 static void Curl_nss_cleanup(void)
1462 {
1463 /* This function isn't required to be threadsafe and this is only done
1464 * as a safety feature.
1465 */
1466 PR_Lock(nss_initlock);
1467 if(initialized) {
1468 /* Free references to client certificates held in the SSL session cache.
1469 * Omitting this hampers destruction of the security module owning
1470 * the certificates. */
1471 SSL_ClearSessionCache();
1472
1473 nss_unload_module(&pem_module);
1474 nss_unload_module(&trust_module);
1475 NSS_ShutdownContext(nss_context);
1476 nss_context = NULL;
1477 }
1478
1479 /* destroy all CRL items */
1480 Curl_llist_destroy(&nss_crl_list, NULL);
1481
1482 PR_Unlock(nss_initlock);
1483
1484 PR_DestroyLock(nss_initlock);
1485 PR_DestroyLock(nss_crllock);
1486 PR_DestroyLock(nss_findslot_lock);
1487 PR_DestroyLock(nss_trustload_lock);
1488 nss_initlock = NULL;
1489
1490 initialized = 0;
1491 }
1492
1493 /*
1494 * This function uses SSL_peek to determine connection status.
1495 *
1496 * Return codes:
1497 * 1 means the connection is still in place
1498 * 0 means the connection has been closed
1499 * -1 means the connection status is unknown
1500 */
Curl_nss_check_cxn(struct connectdata * conn)1501 static int Curl_nss_check_cxn(struct connectdata *conn)
1502 {
1503 struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
1504 struct ssl_backend_data *backend = connssl->backend;
1505 int rc;
1506 char buf;
1507
1508 rc =
1509 PR_Recv(backend->handle, (void *)&buf, 1, PR_MSG_PEEK,
1510 PR_SecondsToInterval(1));
1511 if(rc > 0)
1512 return 1; /* connection still in place */
1513
1514 if(rc == 0)
1515 return 0; /* connection has been closed */
1516
1517 return -1; /* connection status unknown */
1518 }
1519
nss_close(struct ssl_connect_data * connssl)1520 static void nss_close(struct ssl_connect_data *connssl)
1521 {
1522 /* before the cleanup, check whether we are using a client certificate */
1523 struct ssl_backend_data *backend = connssl->backend;
1524 const bool client_cert = (backend->client_nickname != NULL)
1525 || (backend->obj_clicert != NULL);
1526
1527 free(backend->client_nickname);
1528 backend->client_nickname = NULL;
1529
1530 /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1531 Curl_llist_destroy(&backend->obj_list, NULL);
1532 backend->obj_clicert = NULL;
1533
1534 if(backend->handle) {
1535 if(client_cert)
1536 /* A server might require different authentication based on the
1537 * particular path being requested by the client. To support this
1538 * scenario, we must ensure that a connection will never reuse the
1539 * authentication data from a previous connection. */
1540 SSL_InvalidateSession(backend->handle);
1541
1542 PR_Close(backend->handle);
1543 backend->handle = NULL;
1544 }
1545 }
1546
1547 /*
1548 * This function is called when an SSL connection is closed.
1549 */
Curl_nss_close(struct connectdata * conn,int sockindex)1550 static void Curl_nss_close(struct connectdata *conn, int sockindex)
1551 {
1552 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1553 #ifndef CURL_DISABLE_PROXY
1554 struct ssl_connect_data *connssl_proxy = &conn->proxy_ssl[sockindex];
1555 #endif
1556 struct ssl_backend_data *backend = connssl->backend;
1557
1558 if(backend->handle
1559 #ifndef CURL_DISABLE_PROXY
1560 || connssl_proxy->backend->handle
1561 #endif
1562 ) {
1563 /* NSS closes the socket we previously handed to it, so we must mark it
1564 as closed to avoid double close */
1565 fake_sclose(conn->sock[sockindex]);
1566 conn->sock[sockindex] = CURL_SOCKET_BAD;
1567 }
1568
1569 #ifndef CURL_DISABLE_PROXY
1570 if(backend->handle)
1571 /* nss_close(connssl) will transitively close also
1572 connssl_proxy->backend->handle if both are used. Clear it to avoid
1573 a double close leading to crash. */
1574 connssl_proxy->backend->handle = NULL;
1575
1576 nss_close(connssl_proxy);
1577 #endif
1578 nss_close(connssl);
1579 }
1580
1581 /* return true if NSS can provide error code (and possibly msg) for the
1582 error */
is_nss_error(CURLcode err)1583 static bool is_nss_error(CURLcode err)
1584 {
1585 switch(err) {
1586 case CURLE_PEER_FAILED_VERIFICATION:
1587 case CURLE_SSL_CERTPROBLEM:
1588 case CURLE_SSL_CONNECT_ERROR:
1589 case CURLE_SSL_ISSUER_ERROR:
1590 return true;
1591
1592 default:
1593 return false;
1594 }
1595 }
1596
1597 /* return true if the given error code is related to a client certificate */
is_cc_error(PRInt32 err)1598 static bool is_cc_error(PRInt32 err)
1599 {
1600 switch(err) {
1601 case SSL_ERROR_BAD_CERT_ALERT:
1602 case SSL_ERROR_EXPIRED_CERT_ALERT:
1603 case SSL_ERROR_REVOKED_CERT_ALERT:
1604 return true;
1605
1606 default:
1607 return false;
1608 }
1609 }
1610
1611 static Curl_recv nss_recv;
1612 static Curl_send nss_send;
1613
nss_load_ca_certificates(struct connectdata * conn,int sockindex)1614 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1615 int sockindex)
1616 {
1617 struct Curl_easy *data = conn->data;
1618 const char *cafile = SSL_CONN_CONFIG(CAfile);
1619 const char *capath = SSL_CONN_CONFIG(CApath);
1620 bool use_trust_module;
1621 CURLcode result = CURLE_OK;
1622
1623 /* treat empty string as unset */
1624 if(cafile && !cafile[0])
1625 cafile = NULL;
1626 if(capath && !capath[0])
1627 capath = NULL;
1628
1629 infof(data, " CAfile: %s\n", cafile ? cafile : "none");
1630 infof(data, " CApath: %s\n", capath ? capath : "none");
1631
1632 /* load libnssckbi.so if no other trust roots were specified */
1633 use_trust_module = !cafile && !capath;
1634
1635 PR_Lock(nss_trustload_lock);
1636 if(use_trust_module && !trust_module) {
1637 /* libnssckbi.so needed but not yet loaded --> load it! */
1638 result = nss_load_module(&trust_module, trust_library, "trust");
1639 infof(data, "%s %s\n", (result) ? "failed to load" : "loaded",
1640 trust_library);
1641 if(result == CURLE_FAILED_INIT)
1642 /* If libnssckbi.so is not available (or fails to load), one can still
1643 use CA certificates stored in NSS database. Ignore the failure. */
1644 result = CURLE_OK;
1645 }
1646 else if(!use_trust_module && trust_module) {
1647 /* libnssckbi.so not needed but already loaded --> unload it! */
1648 infof(data, "unloading %s\n", trust_library);
1649 nss_unload_module(&trust_module);
1650 }
1651 PR_Unlock(nss_trustload_lock);
1652
1653 if(cafile)
1654 result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1655
1656 if(result)
1657 return result;
1658
1659 if(capath) {
1660 struct_stat st;
1661 if(stat(capath, &st) == -1)
1662 return CURLE_SSL_CACERT_BADFILE;
1663
1664 if(S_ISDIR(st.st_mode)) {
1665 PRDirEntry *entry;
1666 PRDir *dir = PR_OpenDir(capath);
1667 if(!dir)
1668 return CURLE_SSL_CACERT_BADFILE;
1669
1670 while((entry =
1671 PR_ReadDir(dir, (PRDirFlags)(PR_SKIP_BOTH | PR_SKIP_HIDDEN)))) {
1672 char *fullpath = aprintf("%s/%s", capath, entry->name);
1673 if(!fullpath) {
1674 PR_CloseDir(dir);
1675 return CURLE_OUT_OF_MEMORY;
1676 }
1677
1678 if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1679 /* This is purposefully tolerant of errors so non-PEM files can
1680 * be in the same directory */
1681 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1682
1683 free(fullpath);
1684 }
1685
1686 PR_CloseDir(dir);
1687 }
1688 else
1689 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1690 }
1691
1692 return CURLE_OK;
1693 }
1694
nss_sslver_from_curl(PRUint16 * nssver,long version)1695 static CURLcode nss_sslver_from_curl(PRUint16 *nssver, long version)
1696 {
1697 switch(version) {
1698 case CURL_SSLVERSION_SSLv2:
1699 *nssver = SSL_LIBRARY_VERSION_2;
1700 return CURLE_OK;
1701
1702 case CURL_SSLVERSION_SSLv3:
1703 *nssver = SSL_LIBRARY_VERSION_3_0;
1704 return CURLE_OK;
1705
1706 case CURL_SSLVERSION_TLSv1_0:
1707 *nssver = SSL_LIBRARY_VERSION_TLS_1_0;
1708 return CURLE_OK;
1709
1710 case CURL_SSLVERSION_TLSv1_1:
1711 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1712 *nssver = SSL_LIBRARY_VERSION_TLS_1_1;
1713 return CURLE_OK;
1714 #else
1715 return CURLE_SSL_CONNECT_ERROR;
1716 #endif
1717
1718 case CURL_SSLVERSION_TLSv1_2:
1719 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1720 *nssver = SSL_LIBRARY_VERSION_TLS_1_2;
1721 return CURLE_OK;
1722 #else
1723 return CURLE_SSL_CONNECT_ERROR;
1724 #endif
1725
1726 case CURL_SSLVERSION_TLSv1_3:
1727 #ifdef SSL_LIBRARY_VERSION_TLS_1_3
1728 *nssver = SSL_LIBRARY_VERSION_TLS_1_3;
1729 return CURLE_OK;
1730 #else
1731 return CURLE_SSL_CONNECT_ERROR;
1732 #endif
1733
1734 default:
1735 return CURLE_SSL_CONNECT_ERROR;
1736 }
1737 }
1738
nss_init_sslver(SSLVersionRange * sslver,struct Curl_easy * data,struct connectdata * conn)1739 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1740 struct Curl_easy *data,
1741 struct connectdata *conn)
1742 {
1743 CURLcode result;
1744 const long min = SSL_CONN_CONFIG(version);
1745 const long max = SSL_CONN_CONFIG(version_max);
1746 SSLVersionRange vrange;
1747
1748 switch(min) {
1749 case CURL_SSLVERSION_TLSv1:
1750 case CURL_SSLVERSION_DEFAULT:
1751 /* Bump our minimum TLS version if NSS has stricter requirements. */
1752 if(SSL_VersionRangeGetDefault(ssl_variant_stream, &vrange) != SECSuccess)
1753 return CURLE_SSL_CONNECT_ERROR;
1754 if(sslver->min < vrange.min)
1755 sslver->min = vrange.min;
1756 break;
1757 default:
1758 result = nss_sslver_from_curl(&sslver->min, min);
1759 if(result) {
1760 failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
1761 return result;
1762 }
1763 }
1764
1765 switch(max) {
1766 case CURL_SSLVERSION_MAX_NONE:
1767 case CURL_SSLVERSION_MAX_DEFAULT:
1768 break;
1769 default:
1770 result = nss_sslver_from_curl(&sslver->max, max >> 16);
1771 if(result) {
1772 failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
1773 return result;
1774 }
1775 }
1776
1777 return CURLE_OK;
1778 }
1779
nss_fail_connect(struct ssl_connect_data * connssl,struct Curl_easy * data,CURLcode curlerr)1780 static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
1781 struct Curl_easy *data,
1782 CURLcode curlerr)
1783 {
1784 PRErrorCode err = 0;
1785 struct ssl_backend_data *backend = connssl->backend;
1786
1787 if(is_nss_error(curlerr)) {
1788 /* read NSPR error code */
1789 err = PR_GetError();
1790 if(is_cc_error(err))
1791 curlerr = CURLE_SSL_CERTPROBLEM;
1792
1793 /* print the error number and error string */
1794 infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1795
1796 /* print a human-readable message describing the error if available */
1797 nss_print_error_message(data, err);
1798 }
1799
1800 /* cleanup on connection failure */
1801 Curl_llist_destroy(&backend->obj_list, NULL);
1802
1803 return curlerr;
1804 }
1805
1806 /* Switch the SSL socket into blocking or non-blocking mode. */
nss_set_blocking(struct ssl_connect_data * connssl,struct Curl_easy * data,bool blocking)1807 static CURLcode nss_set_blocking(struct ssl_connect_data *connssl,
1808 struct Curl_easy *data,
1809 bool blocking)
1810 {
1811 static PRSocketOptionData sock_opt;
1812 struct ssl_backend_data *backend = connssl->backend;
1813 sock_opt.option = PR_SockOpt_Nonblocking;
1814 sock_opt.value.non_blocking = !blocking;
1815
1816 if(PR_SetSocketOption(backend->handle, &sock_opt) != PR_SUCCESS)
1817 return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
1818
1819 return CURLE_OK;
1820 }
1821
nss_setup_connect(struct connectdata * conn,int sockindex)1822 static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
1823 {
1824 PRFileDesc *model = NULL;
1825 PRFileDesc *nspr_io = NULL;
1826 PRFileDesc *nspr_io_stub = NULL;
1827 PRBool ssl_no_cache;
1828 PRBool ssl_cbc_random_iv;
1829 struct Curl_easy *data = conn->data;
1830 curl_socket_t sockfd = conn->sock[sockindex];
1831 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1832 struct ssl_backend_data *backend = connssl->backend;
1833 CURLcode result;
1834 bool second_layer = FALSE;
1835 SSLVersionRange sslver_supported;
1836
1837 SSLVersionRange sslver = {
1838 SSL_LIBRARY_VERSION_TLS_1_0, /* min */
1839 #ifdef SSL_LIBRARY_VERSION_TLS_1_3
1840 SSL_LIBRARY_VERSION_TLS_1_3 /* max */
1841 #elif defined SSL_LIBRARY_VERSION_TLS_1_2
1842 SSL_LIBRARY_VERSION_TLS_1_2
1843 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1844 SSL_LIBRARY_VERSION_TLS_1_1
1845 #else
1846 SSL_LIBRARY_VERSION_TLS_1_0
1847 #endif
1848 };
1849
1850 backend->data = data;
1851
1852 /* list of all NSS objects we need to destroy in Curl_nss_close() */
1853 Curl_llist_init(&backend->obj_list, nss_destroy_object);
1854
1855 PR_Lock(nss_initlock);
1856 result = nss_init(conn->data);
1857 if(result) {
1858 PR_Unlock(nss_initlock);
1859 goto error;
1860 }
1861
1862 PK11_SetPasswordFunc(nss_get_password);
1863
1864 result = nss_load_module(&pem_module, pem_library, "PEM");
1865 PR_Unlock(nss_initlock);
1866 if(result == CURLE_FAILED_INIT)
1867 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1868 "OpenSSL PEM certificates will not work.\n", pem_library);
1869 else if(result)
1870 goto error;
1871
1872 result = CURLE_SSL_CONNECT_ERROR;
1873
1874 model = PR_NewTCPSocket();
1875 if(!model)
1876 goto error;
1877 model = SSL_ImportFD(NULL, model);
1878
1879 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1880 goto error;
1881 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1882 goto error;
1883 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1884 goto error;
1885
1886 /* do not use SSL cache if disabled or we are not going to verify peer */
1887 ssl_no_cache = (SSL_SET_OPTION(primary.sessionid)
1888 && SSL_CONN_CONFIG(verifypeer)) ? PR_FALSE : PR_TRUE;
1889 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1890 goto error;
1891
1892 /* enable/disable the requested SSL version(s) */
1893 if(nss_init_sslver(&sslver, data, conn) != CURLE_OK)
1894 goto error;
1895 if(SSL_VersionRangeGetSupported(ssl_variant_stream,
1896 &sslver_supported) != SECSuccess)
1897 goto error;
1898 if(sslver_supported.max < sslver.max && sslver_supported.max >= sslver.min) {
1899 char *sslver_req_str, *sslver_supp_str;
1900 sslver_req_str = nss_sslver_to_name(sslver.max);
1901 sslver_supp_str = nss_sslver_to_name(sslver_supported.max);
1902 if(sslver_req_str && sslver_supp_str)
1903 infof(data, "Falling back from %s to max supported SSL version (%s)\n",
1904 sslver_req_str, sslver_supp_str);
1905 free(sslver_req_str);
1906 free(sslver_supp_str);
1907 sslver.max = sslver_supported.max;
1908 }
1909 if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1910 goto error;
1911
1912 ssl_cbc_random_iv = !SSL_SET_OPTION(enable_beast);
1913 #ifdef SSL_CBC_RANDOM_IV
1914 /* unless the user explicitly asks to allow the protocol vulnerability, we
1915 use the work-around */
1916 if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1917 infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1918 ssl_cbc_random_iv);
1919 #else
1920 if(ssl_cbc_random_iv)
1921 infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1922 #endif
1923
1924 if(SSL_CONN_CONFIG(cipher_list)) {
1925 if(set_ciphers(data, model, SSL_CONN_CONFIG(cipher_list)) != SECSuccess) {
1926 result = CURLE_SSL_CIPHER;
1927 goto error;
1928 }
1929 }
1930
1931 if(!SSL_CONN_CONFIG(verifypeer) && SSL_CONN_CONFIG(verifyhost))
1932 infof(data, "warning: ignoring value of ssl.verifyhost\n");
1933
1934 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1935 * verify peer */
1936 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1937 goto error;
1938
1939 /* not checked yet */
1940 SSL_SET_OPTION_LVALUE(certverifyresult) = 0;
1941
1942 if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1943 goto error;
1944
1945 if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
1946 goto error;
1947
1948 {
1949 const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1950 if((rv == CURLE_SSL_CACERT_BADFILE) && !SSL_CONN_CONFIG(verifypeer))
1951 /* not a fatal error because we are not going to verify the peer */
1952 infof(data, "warning: CA certificates failed to load\n");
1953 else if(rv) {
1954 result = rv;
1955 goto error;
1956 }
1957 }
1958
1959 if(SSL_SET_OPTION(CRLfile)) {
1960 const CURLcode rv = nss_load_crl(SSL_SET_OPTION(CRLfile));
1961 if(rv) {
1962 result = rv;
1963 goto error;
1964 }
1965 infof(data, " CRLfile: %s\n", SSL_SET_OPTION(CRLfile));
1966 }
1967
1968 if(SSL_SET_OPTION(primary.clientcert)) {
1969 char *nickname = dup_nickname(data, SSL_SET_OPTION(primary.clientcert));
1970 if(nickname) {
1971 /* we are not going to use libnsspem.so to read the client cert */
1972 backend->obj_clicert = NULL;
1973 }
1974 else {
1975 CURLcode rv = cert_stuff(conn, sockindex,
1976 SSL_SET_OPTION(primary.clientcert),
1977 SSL_SET_OPTION(key));
1978 if(rv) {
1979 /* failf() is already done in cert_stuff() */
1980 result = rv;
1981 goto error;
1982 }
1983 }
1984
1985 /* store the nickname for SelectClientCert() called during handshake */
1986 backend->client_nickname = nickname;
1987 }
1988 else
1989 backend->client_nickname = NULL;
1990
1991 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1992 (void *)connssl) != SECSuccess) {
1993 result = CURLE_SSL_CERTPROBLEM;
1994 goto error;
1995 }
1996
1997 #ifndef CURL_DISABLE_PROXY
1998 if(conn->proxy_ssl[sockindex].use) {
1999 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
2000 DEBUGASSERT(conn->proxy_ssl[sockindex].backend->handle != NULL);
2001 nspr_io = conn->proxy_ssl[sockindex].backend->handle;
2002 second_layer = TRUE;
2003 }
2004 #endif
2005 else {
2006 /* wrap OS file descriptor by NSPR's file descriptor abstraction */
2007 nspr_io = PR_ImportTCPSocket(sockfd);
2008 if(!nspr_io)
2009 goto error;
2010 }
2011
2012 /* create our own NSPR I/O layer */
2013 nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
2014 if(!nspr_io_stub) {
2015 if(!second_layer)
2016 PR_Close(nspr_io);
2017 goto error;
2018 }
2019
2020 /* make the per-connection data accessible from NSPR I/O callbacks */
2021 nspr_io_stub->secret = (void *)connssl;
2022
2023 /* push our new layer to the NSPR I/O stack */
2024 if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
2025 if(!second_layer)
2026 PR_Close(nspr_io);
2027 PR_Close(nspr_io_stub);
2028 goto error;
2029 }
2030
2031 /* import our model socket onto the current I/O stack */
2032 backend->handle = SSL_ImportFD(model, nspr_io);
2033 if(!backend->handle) {
2034 if(!second_layer)
2035 PR_Close(nspr_io);
2036 goto error;
2037 }
2038
2039 PR_Close(model); /* We don't need this any more */
2040 model = NULL;
2041
2042 /* This is the password associated with the cert that we're using */
2043 if(SSL_SET_OPTION(key_passwd)) {
2044 SSL_SetPKCS11PinArg(backend->handle, SSL_SET_OPTION(key_passwd));
2045 }
2046
2047 #ifdef SSL_ENABLE_OCSP_STAPLING
2048 if(SSL_CONN_CONFIG(verifystatus)) {
2049 if(SSL_OptionSet(backend->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
2050 != SECSuccess)
2051 goto error;
2052 }
2053 #endif
2054
2055 #ifdef SSL_ENABLE_NPN
2056 if(SSL_OptionSet(backend->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
2057 ? PR_TRUE : PR_FALSE) != SECSuccess)
2058 goto error;
2059 #endif
2060
2061 #ifdef SSL_ENABLE_ALPN
2062 if(SSL_OptionSet(backend->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
2063 ? PR_TRUE : PR_FALSE) != SECSuccess)
2064 goto error;
2065 #endif
2066
2067 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
2068 if(data->set.ssl.falsestart) {
2069 if(SSL_OptionSet(backend->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
2070 != SECSuccess)
2071 goto error;
2072
2073 if(SSL_SetCanFalseStartCallback(backend->handle, CanFalseStartCallback,
2074 conn) != SECSuccess)
2075 goto error;
2076 }
2077 #endif
2078
2079 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
2080 if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
2081 int cur = 0;
2082 unsigned char protocols[128];
2083
2084 #ifdef USE_NGHTTP2
2085 if(data->set.httpversion >= CURL_HTTP_VERSION_2
2086 #ifndef CURL_DISABLE_PROXY
2087 && (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)
2088 #endif
2089 ) {
2090 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
2091 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
2092 NGHTTP2_PROTO_VERSION_ID_LEN);
2093 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
2094 }
2095 #endif
2096 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
2097 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
2098 cur += ALPN_HTTP_1_1_LENGTH;
2099
2100 if(SSL_SetNextProtoNego(backend->handle, protocols, cur) != SECSuccess)
2101 goto error;
2102 }
2103 #endif
2104
2105
2106 /* Force handshake on next I/O */
2107 if(SSL_ResetHandshake(backend->handle, /* asServer */ PR_FALSE)
2108 != SECSuccess)
2109 goto error;
2110
2111 /* propagate hostname to the TLS layer */
2112 if(SSL_SetURL(backend->handle, SSL_HOST_NAME()) != SECSuccess)
2113 goto error;
2114
2115 /* prevent NSS from re-using the session for a different hostname */
2116 if(SSL_SetSockPeerID(backend->handle, SSL_HOST_NAME()) != SECSuccess)
2117 goto error;
2118
2119 return CURLE_OK;
2120
2121 error:
2122 if(model)
2123 PR_Close(model);
2124
2125 return nss_fail_connect(connssl, data, result);
2126 }
2127
nss_do_connect(struct connectdata * conn,int sockindex)2128 static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
2129 {
2130 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2131 struct ssl_backend_data *backend = connssl->backend;
2132 struct Curl_easy *data = conn->data;
2133 CURLcode result = CURLE_SSL_CONNECT_ERROR;
2134 PRUint32 timeout;
2135
2136 /* check timeout situation */
2137 const timediff_t time_left = Curl_timeleft(data, NULL, TRUE);
2138 if(time_left < 0) {
2139 failf(data, "timed out before SSL handshake");
2140 result = CURLE_OPERATION_TIMEDOUT;
2141 goto error;
2142 }
2143
2144 /* Force the handshake now */
2145 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
2146 if(SSL_ForceHandshakeWithTimeout(backend->handle, timeout) != SECSuccess) {
2147 if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
2148 /* blocking direction is updated by nss_update_connecting_state() */
2149 return CURLE_AGAIN;
2150 else if(SSL_SET_OPTION(certverifyresult) == SSL_ERROR_BAD_CERT_DOMAIN)
2151 result = CURLE_PEER_FAILED_VERIFICATION;
2152 else if(SSL_SET_OPTION(certverifyresult) != 0)
2153 result = CURLE_PEER_FAILED_VERIFICATION;
2154 goto error;
2155 }
2156
2157 result = display_conn_info(conn, backend->handle);
2158 if(result)
2159 goto error;
2160
2161 if(SSL_SET_OPTION(issuercert)) {
2162 SECStatus ret = SECFailure;
2163 char *nickname = dup_nickname(data, SSL_SET_OPTION(issuercert));
2164 if(nickname) {
2165 /* we support only nicknames in case of issuercert for now */
2166 ret = check_issuer_cert(backend->handle, nickname);
2167 free(nickname);
2168 }
2169
2170 if(SECFailure == ret) {
2171 infof(data, "SSL certificate issuer check failed\n");
2172 result = CURLE_SSL_ISSUER_ERROR;
2173 goto error;
2174 }
2175 else {
2176 infof(data, "SSL certificate issuer check ok\n");
2177 }
2178 }
2179
2180 result = cmp_peer_pubkey(connssl, SSL_PINNED_PUB_KEY());
2181 if(result)
2182 /* status already printed */
2183 goto error;
2184
2185 return CURLE_OK;
2186
2187 error:
2188 return nss_fail_connect(connssl, data, result);
2189 }
2190
nss_connect_common(struct connectdata * conn,int sockindex,bool * done)2191 static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
2192 bool *done)
2193 {
2194 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2195 struct Curl_easy *data = conn->data;
2196 const bool blocking = (done == NULL);
2197 CURLcode result;
2198
2199 if(connssl->state == ssl_connection_complete) {
2200 if(!blocking)
2201 *done = TRUE;
2202 return CURLE_OK;
2203 }
2204
2205 if(connssl->connecting_state == ssl_connect_1) {
2206 result = nss_setup_connect(conn, sockindex);
2207 if(result)
2208 /* we do not expect CURLE_AGAIN from nss_setup_connect() */
2209 return result;
2210
2211 connssl->connecting_state = ssl_connect_2;
2212 }
2213
2214 /* enable/disable blocking mode before handshake */
2215 result = nss_set_blocking(connssl, data, blocking);
2216 if(result)
2217 return result;
2218
2219 result = nss_do_connect(conn, sockindex);
2220 switch(result) {
2221 case CURLE_OK:
2222 break;
2223 case CURLE_AGAIN:
2224 if(!blocking)
2225 /* CURLE_AGAIN in non-blocking mode is not an error */
2226 return CURLE_OK;
2227 /* FALLTHROUGH */
2228 default:
2229 return result;
2230 }
2231
2232 if(blocking) {
2233 /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
2234 result = nss_set_blocking(connssl, data, /* blocking */ FALSE);
2235 if(result)
2236 return result;
2237 }
2238 else
2239 /* signal completed SSL handshake */
2240 *done = TRUE;
2241
2242 connssl->state = ssl_connection_complete;
2243 conn->recv[sockindex] = nss_recv;
2244 conn->send[sockindex] = nss_send;
2245
2246 /* ssl_connect_done is never used outside, go back to the initial state */
2247 connssl->connecting_state = ssl_connect_1;
2248
2249 return CURLE_OK;
2250 }
2251
Curl_nss_connect(struct connectdata * conn,int sockindex)2252 static CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
2253 {
2254 return nss_connect_common(conn, sockindex, /* blocking */ NULL);
2255 }
2256
Curl_nss_connect_nonblocking(struct connectdata * conn,int sockindex,bool * done)2257 static CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
2258 int sockindex, bool *done)
2259 {
2260 return nss_connect_common(conn, sockindex, done);
2261 }
2262
nss_send(struct connectdata * conn,int sockindex,const void * mem,size_t len,CURLcode * curlcode)2263 static ssize_t nss_send(struct connectdata *conn, /* connection data */
2264 int sockindex, /* socketindex */
2265 const void *mem, /* send this data */
2266 size_t len, /* amount to write */
2267 CURLcode *curlcode)
2268 {
2269 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2270 struct ssl_backend_data *backend = connssl->backend;
2271 ssize_t rc;
2272
2273 /* The SelectClientCert() hook uses this for infof() and failf() but the
2274 handle stored in nss_setup_connect() could have already been freed. */
2275 backend->data = conn->data;
2276
2277 rc = PR_Send(backend->handle, mem, (int)len, 0, PR_INTERVAL_NO_WAIT);
2278 if(rc < 0) {
2279 PRInt32 err = PR_GetError();
2280 if(err == PR_WOULD_BLOCK_ERROR)
2281 *curlcode = CURLE_AGAIN;
2282 else {
2283 /* print the error number and error string */
2284 const char *err_name = nss_error_to_name(err);
2285 infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
2286
2287 /* print a human-readable message describing the error if available */
2288 nss_print_error_message(conn->data, err);
2289
2290 *curlcode = (is_cc_error(err))
2291 ? CURLE_SSL_CERTPROBLEM
2292 : CURLE_SEND_ERROR;
2293 }
2294
2295 return -1;
2296 }
2297
2298 return rc; /* number of bytes */
2299 }
2300
nss_recv(struct connectdata * conn,int sockindex,char * buf,size_t buffersize,CURLcode * curlcode)2301 static ssize_t nss_recv(struct connectdata *conn, /* connection data */
2302 int sockindex, /* socketindex */
2303 char *buf, /* store read data here */
2304 size_t buffersize, /* max amount to read */
2305 CURLcode *curlcode)
2306 {
2307 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
2308 struct ssl_backend_data *backend = connssl->backend;
2309 ssize_t nread;
2310
2311 /* The SelectClientCert() hook uses this for infof() and failf() but the
2312 handle stored in nss_setup_connect() could have already been freed. */
2313 backend->data = conn->data;
2314
2315 nread = PR_Recv(backend->handle, buf, (int)buffersize, 0,
2316 PR_INTERVAL_NO_WAIT);
2317 if(nread < 0) {
2318 /* failed SSL read */
2319 PRInt32 err = PR_GetError();
2320
2321 if(err == PR_WOULD_BLOCK_ERROR)
2322 *curlcode = CURLE_AGAIN;
2323 else {
2324 /* print the error number and error string */
2325 const char *err_name = nss_error_to_name(err);
2326 infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
2327
2328 /* print a human-readable message describing the error if available */
2329 nss_print_error_message(conn->data, err);
2330
2331 *curlcode = (is_cc_error(err))
2332 ? CURLE_SSL_CERTPROBLEM
2333 : CURLE_RECV_ERROR;
2334 }
2335
2336 return -1;
2337 }
2338
2339 return nread;
2340 }
2341
Curl_nss_version(char * buffer,size_t size)2342 static size_t Curl_nss_version(char *buffer, size_t size)
2343 {
2344 return msnprintf(buffer, size, "NSS/%s", NSS_VERSION);
2345 }
2346
2347 /* data might be NULL */
Curl_nss_seed(struct Curl_easy * data)2348 static int Curl_nss_seed(struct Curl_easy *data)
2349 {
2350 /* make sure that NSS is initialized */
2351 return !!Curl_nss_force_init(data);
2352 }
2353
2354 /* data might be NULL */
Curl_nss_random(struct Curl_easy * data,unsigned char * entropy,size_t length)2355 static CURLcode Curl_nss_random(struct Curl_easy *data,
2356 unsigned char *entropy,
2357 size_t length)
2358 {
2359 Curl_nss_seed(data); /* Initiate the seed if not already done */
2360
2361 if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
2362 /* signal a failure */
2363 return CURLE_FAILED_INIT;
2364
2365 return CURLE_OK;
2366 }
2367
Curl_nss_md5sum(unsigned char * tmp,size_t tmplen,unsigned char * md5sum,size_t md5len)2368 static CURLcode Curl_nss_md5sum(unsigned char *tmp, /* input */
2369 size_t tmplen,
2370 unsigned char *md5sum, /* output */
2371 size_t md5len)
2372 {
2373 PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
2374 unsigned int MD5out;
2375
2376 if(!MD5pw)
2377 return CURLE_NOT_BUILT_IN;
2378
2379 PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
2380 PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
2381 PK11_DestroyContext(MD5pw, PR_TRUE);
2382
2383 return CURLE_OK;
2384 }
2385
Curl_nss_sha256sum(const unsigned char * tmp,size_t tmplen,unsigned char * sha256sum,size_t sha256len)2386 static CURLcode Curl_nss_sha256sum(const unsigned char *tmp, /* input */
2387 size_t tmplen,
2388 unsigned char *sha256sum, /* output */
2389 size_t sha256len)
2390 {
2391 PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
2392 unsigned int SHA256out;
2393
2394 if(!SHA256pw)
2395 return CURLE_NOT_BUILT_IN;
2396
2397 PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
2398 PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
2399 PK11_DestroyContext(SHA256pw, PR_TRUE);
2400
2401 return CURLE_OK;
2402 }
2403
Curl_nss_cert_status_request(void)2404 static bool Curl_nss_cert_status_request(void)
2405 {
2406 #ifdef SSL_ENABLE_OCSP_STAPLING
2407 return TRUE;
2408 #else
2409 return FALSE;
2410 #endif
2411 }
2412
Curl_nss_false_start(void)2413 static bool Curl_nss_false_start(void)
2414 {
2415 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
2416 return TRUE;
2417 #else
2418 return FALSE;
2419 #endif
2420 }
2421
Curl_nss_get_internals(struct ssl_connect_data * connssl,CURLINFO info UNUSED_PARAM)2422 static void *Curl_nss_get_internals(struct ssl_connect_data *connssl,
2423 CURLINFO info UNUSED_PARAM)
2424 {
2425 struct ssl_backend_data *backend = connssl->backend;
2426 (void)info;
2427 return backend->handle;
2428 }
2429
2430 const struct Curl_ssl Curl_ssl_nss = {
2431 { CURLSSLBACKEND_NSS, "nss" }, /* info */
2432
2433 SSLSUPP_CA_PATH |
2434 SSLSUPP_CERTINFO |
2435 SSLSUPP_PINNEDPUBKEY |
2436 SSLSUPP_HTTPS_PROXY,
2437
2438 sizeof(struct ssl_backend_data),
2439
2440 Curl_nss_init, /* init */
2441 Curl_nss_cleanup, /* cleanup */
2442 Curl_nss_version, /* version */
2443 Curl_nss_check_cxn, /* check_cxn */
2444 /* NSS has no shutdown function provided and thus always fail */
2445 Curl_none_shutdown, /* shutdown */
2446 Curl_none_data_pending, /* data_pending */
2447 Curl_nss_random, /* random */
2448 Curl_nss_cert_status_request, /* cert_status_request */
2449 Curl_nss_connect, /* connect */
2450 Curl_nss_connect_nonblocking, /* connect_nonblocking */
2451 Curl_nss_get_internals, /* get_internals */
2452 Curl_nss_close, /* close_one */
2453 Curl_none_close_all, /* close_all */
2454 /* NSS has its own session ID cache */
2455 Curl_none_session_free, /* session_free */
2456 Curl_none_set_engine, /* set_engine */
2457 Curl_none_set_engine_default, /* set_engine_default */
2458 Curl_none_engines_list, /* engines_list */
2459 Curl_nss_false_start, /* false_start */
2460 Curl_nss_md5sum, /* md5sum */
2461 Curl_nss_sha256sum /* sha256sum */
2462 };
2463
2464 #endif /* USE_NSS */
2465