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