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