nss: ALPN and NPN support
[platform/upstream/curl.git] / lib / vtls / nss.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2014, 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 http://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 "strequal.h"
38 #include "select.h"
39 #include "vtls.h"
40 #include "llist.h"
41
42 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
43 #include <curl/mprintf.h>
44
45 #include "nssg.h"
46 #include <nspr.h>
47 #include <nss.h>
48 #include <ssl.h>
49 #include <sslerr.h>
50 #include <secerr.h>
51 #include <secmod.h>
52 #include <sslproto.h>
53 #include <prtypes.h>
54 #include <pk11pub.h>
55 #include <prio.h>
56 #include <secitem.h>
57 #include <secport.h>
58 #include <certdb.h>
59 #include <base64.h>
60 #include <cert.h>
61 #include <prerror.h>
62
63 #include "curl_memory.h"
64 #include "rawstr.h"
65 #include "warnless.h"
66 #include "x509asn1.h"
67
68 /* The last #include file should be: */
69 #include "memdebug.h"
70
71 #define SSL_DIR "/etc/pki/nssdb"
72
73 /* enough to fit the string "PEM Token #[0|1]" */
74 #define SLOTSIZE 13
75
76 PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
77
78 PRLock * nss_initlock = NULL;
79 PRLock * nss_crllock = NULL;
80 NSSInitContext * nss_context = NULL;
81
82 volatile int initialized = 0;
83
84 typedef struct {
85   const char *name;
86   int num;
87 } cipher_s;
88
89 #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do {  \
90   CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++);                 \
91   ptr->type = (_type);                                      \
92   ptr->pValue = (_val);                                     \
93   ptr->ulValueLen = (_len);                                 \
94 } WHILE_FALSE
95
96 #define CERT_NewTempCertificate __CERT_NewTempCertificate
97
98 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
99 static const cipher_s cipherlist[] = {
100   /* SSL2 cipher suites */
101   {"rc4",                        SSL_EN_RC4_128_WITH_MD5},
102   {"rc4-md5",                    SSL_EN_RC4_128_WITH_MD5},
103   {"rc4export",                  SSL_EN_RC4_128_EXPORT40_WITH_MD5},
104   {"rc2",                        SSL_EN_RC2_128_CBC_WITH_MD5},
105   {"rc2export",                  SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
106   {"des",                        SSL_EN_DES_64_CBC_WITH_MD5},
107   {"desede3",                    SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
108   /* SSL3/TLS cipher suites */
109   {"rsa_rc4_128_md5",            SSL_RSA_WITH_RC4_128_MD5},
110   {"rsa_rc4_128_sha",            SSL_RSA_WITH_RC4_128_SHA},
111   {"rsa_3des_sha",               SSL_RSA_WITH_3DES_EDE_CBC_SHA},
112   {"rsa_des_sha",                SSL_RSA_WITH_DES_CBC_SHA},
113   {"rsa_rc4_40_md5",             SSL_RSA_EXPORT_WITH_RC4_40_MD5},
114   {"rsa_rc2_40_md5",             SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
115   {"rsa_null_md5",               SSL_RSA_WITH_NULL_MD5},
116   {"rsa_null_sha",               SSL_RSA_WITH_NULL_SHA},
117   {"fips_3des_sha",              SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
118   {"fips_des_sha",               SSL_RSA_FIPS_WITH_DES_CBC_SHA},
119   {"fortezza",                   SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
120   {"fortezza_rc4_128_sha",       SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
121   {"fortezza_null",              SSL_FORTEZZA_DMS_WITH_NULL_SHA},
122   /* TLS 1.0: Exportable 56-bit Cipher Suites. */
123   {"rsa_des_56_sha",             TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
124   {"rsa_rc4_56_sha",             TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
125   /* AES ciphers. */
126   {"rsa_aes_128_sha",            TLS_RSA_WITH_AES_128_CBC_SHA},
127   {"rsa_aes_256_sha",            TLS_RSA_WITH_AES_256_CBC_SHA},
128   /* ECC ciphers. */
129   {"ecdh_ecdsa_null_sha",        TLS_ECDH_ECDSA_WITH_NULL_SHA},
130   {"ecdh_ecdsa_rc4_128_sha",     TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
131   {"ecdh_ecdsa_3des_sha",        TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
132   {"ecdh_ecdsa_aes_128_sha",     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
133   {"ecdh_ecdsa_aes_256_sha",     TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
134   {"ecdhe_ecdsa_null_sha",       TLS_ECDHE_ECDSA_WITH_NULL_SHA},
135   {"ecdhe_ecdsa_rc4_128_sha",    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
136   {"ecdhe_ecdsa_3des_sha",       TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
137   {"ecdhe_ecdsa_aes_128_sha",    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
138   {"ecdhe_ecdsa_aes_256_sha",    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
139   {"ecdh_rsa_null_sha",          TLS_ECDH_RSA_WITH_NULL_SHA},
140   {"ecdh_rsa_128_sha",           TLS_ECDH_RSA_WITH_RC4_128_SHA},
141   {"ecdh_rsa_3des_sha",          TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
142   {"ecdh_rsa_aes_128_sha",       TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
143   {"ecdh_rsa_aes_256_sha",       TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
144   {"echde_rsa_null",             TLS_ECDHE_RSA_WITH_NULL_SHA},
145   {"ecdhe_rsa_rc4_128_sha",      TLS_ECDHE_RSA_WITH_RC4_128_SHA},
146   {"ecdhe_rsa_3des_sha",         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
147   {"ecdhe_rsa_aes_128_sha",      TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
148   {"ecdhe_rsa_aes_256_sha",      TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
149   {"ecdh_anon_null_sha",         TLS_ECDH_anon_WITH_NULL_SHA},
150   {"ecdh_anon_rc4_128sha",       TLS_ECDH_anon_WITH_RC4_128_SHA},
151   {"ecdh_anon_3des_sha",         TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
152   {"ecdh_anon_aes_128_sha",      TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
153   {"ecdh_anon_aes_256_sha",      TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
154 };
155
156 /* following ciphers are new in NSS 3.4 and not enabled by default, therefore
157    they are enabled explicitly */
158 static const int enable_ciphers_by_default[] = {
159   TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
160   TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
161   TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
162   TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
163   TLS_RSA_WITH_AES_128_CBC_SHA,
164   TLS_RSA_WITH_AES_256_CBC_SHA,
165   SSL_NULL_WITH_NULL_NULL
166 };
167
168 static const char* pem_library = "libnsspem.so";
169 SECMODModule* mod = NULL;
170
171 static const char* nss_error_to_name(PRErrorCode code)
172 {
173   const char *name = PR_ErrorToName(code);
174   if(name)
175     return name;
176
177   return "unknown error";
178 }
179
180 static void nss_print_error_message(struct SessionHandle *data, PRUint32 err)
181 {
182   failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
183 }
184
185 static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
186                              char *cipher_list)
187 {
188   unsigned int i;
189   PRBool cipher_state[NUM_OF_CIPHERS];
190   PRBool found;
191   char *cipher;
192
193   /* First disable all ciphers. This uses a different max value in case
194    * NSS adds more ciphers later we don't want them available by
195    * accident
196    */
197   for(i=0; i<SSL_NumImplementedCiphers; i++) {
198     SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], PR_FALSE);
199   }
200
201   /* Set every entry in our list to false */
202   for(i=0; i<NUM_OF_CIPHERS; i++) {
203     cipher_state[i] = PR_FALSE;
204   }
205
206   cipher = cipher_list;
207
208   while(cipher_list && (cipher_list[0])) {
209     while((*cipher) && (ISSPACE(*cipher)))
210       ++cipher;
211
212     if((cipher_list = strchr(cipher, ','))) {
213       *cipher_list++ = '\0';
214     }
215
216     found = PR_FALSE;
217
218     for(i=0; i<NUM_OF_CIPHERS; i++) {
219       if(Curl_raw_equal(cipher, cipherlist[i].name)) {
220         cipher_state[i] = PR_TRUE;
221         found = PR_TRUE;
222         break;
223       }
224     }
225
226     if(found == PR_FALSE) {
227       failf(data, "Unknown cipher in list: %s", cipher);
228       return SECFailure;
229     }
230
231     if(cipher_list) {
232       cipher = cipher_list;
233     }
234   }
235
236   /* Finally actually enable the selected ciphers */
237   for(i=0; i<NUM_OF_CIPHERS; i++) {
238     if(!cipher_state[i])
239       continue;
240
241     if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
242       failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
243       return SECFailure;
244     }
245   }
246
247   return SECSuccess;
248 }
249
250 /*
251  * Get the number of ciphers that are enabled. We use this to determine
252  * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
253  */
254 static int num_enabled_ciphers(void)
255 {
256   PRInt32 policy = 0;
257   int count = 0;
258   unsigned int i;
259
260   for(i=0; i<NUM_OF_CIPHERS; i++) {
261     SSL_CipherPolicyGet(cipherlist[i].num, &policy);
262     if(policy)
263       count++;
264   }
265   return count;
266 }
267
268 /*
269  * Determine whether the nickname passed in is a filename that needs to
270  * be loaded as a PEM or a regular NSS nickname.
271  *
272  * returns 1 for a file
273  * returns 0 for not a file (NSS nickname)
274  */
275 static int is_file(const char *filename)
276 {
277   struct_stat st;
278
279   if(filename == NULL)
280     return 0;
281
282   if(stat(filename, &st) == 0)
283     if(S_ISREG(st.st_mode))
284       return 1;
285
286   return 0;
287 }
288
289 /* Check if the given string is filename or nickname of a certificate.  If the
290  * given string is recognized as filename, return NULL.  If the given string is
291  * recognized as nickname, return a duplicated string.  The returned string
292  * should be later deallocated using free().  If the OOM failure occurs, we
293  * return NULL, too.
294  */
295 static char* dup_nickname(struct SessionHandle *data, enum dupstring cert_kind)
296 {
297   const char *str = data->set.str[cert_kind];
298   const char *n;
299
300   if(!is_file(str))
301     /* no such file exists, use the string as nickname */
302     return strdup(str);
303
304   /* search the last slash; we require at least one slash in a file name */
305   n = strrchr(str, '/');
306   if(!n) {
307     infof(data, "warning: certificate file name \"%s\" handled as nickname; "
308           "please use \"./%s\" to force file name\n", str, str);
309     return strdup(str);
310   }
311
312   /* we'll use the PEM reader to read the certificate from file */
313   return NULL;
314 }
315
316 /* Call PK11_CreateGenericObject() with the given obj_class and filename.  If
317  * the call succeeds, append the object handle to the list of objects so that
318  * the object can be destroyed in Curl_nss_close(). */
319 static CURLcode nss_create_object(struct ssl_connect_data *ssl,
320                                   CK_OBJECT_CLASS obj_class,
321                                   const char *filename, bool cacert)
322 {
323   PK11SlotInfo *slot;
324   PK11GenericObject *obj;
325   CK_BBOOL cktrue = CK_TRUE;
326   CK_BBOOL ckfalse = CK_FALSE;
327   CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
328   int attr_cnt = 0;
329   CURLcode err = (cacert)
330     ? CURLE_SSL_CACERT_BADFILE
331     : CURLE_SSL_CERTPROBLEM;
332
333   const int slot_id = (cacert) ? 0 : 1;
334   char *slot_name = aprintf("PEM Token #%d", slot_id);
335   if(!slot_name)
336     return CURLE_OUT_OF_MEMORY;
337
338   slot = PK11_FindSlotByName(slot_name);
339   free(slot_name);
340   if(!slot)
341     return err;
342
343   PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
344   PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
345   PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
346                 strlen(filename) + 1);
347
348   if(CKO_CERTIFICATE == obj_class) {
349     CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
350     PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
351   }
352
353   obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
354   PK11_FreeSlot(slot);
355   if(!obj)
356     return err;
357
358   if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
359     PK11_DestroyGenericObject(obj);
360     return CURLE_OUT_OF_MEMORY;
361   }
362
363   if(!cacert && CKO_CERTIFICATE == obj_class)
364     /* store reference to a client certificate */
365     ssl->obj_clicert = obj;
366
367   return CURLE_OK;
368 }
369
370 /* Destroy the NSS object whose handle is given by ptr.  This function is
371  * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
372  * NSS objects in Curl_nss_close() */
373 static void nss_destroy_object(void *user, void *ptr)
374 {
375   PK11GenericObject *obj = (PK11GenericObject *)ptr;
376   (void) user;
377   PK11_DestroyGenericObject(obj);
378 }
379
380 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
381                               const char *filename, PRBool cacert)
382 {
383   CURLcode err = (cacert)
384     ? CURLE_SSL_CACERT_BADFILE
385     : CURLE_SSL_CERTPROBLEM;
386
387   /* libnsspem.so leaks memory if the requested file does not exist.  For more
388    * details, go to <https://bugzilla.redhat.com/734760>. */
389   if(is_file(filename))
390     err = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
391
392   if(CURLE_OK == err && !cacert) {
393     /* we have successfully loaded a client certificate */
394     CERTCertificate *cert;
395     char *nickname = NULL;
396     char *n = strrchr(filename, '/');
397     if(n)
398       n++;
399
400     /* The following undocumented magic helps to avoid a SIGSEGV on call
401      * of PK11_ReadRawAttribute() from SelectClientCert() when using an
402      * immature version of libnsspem.so.  For more details, go to
403      * <https://bugzilla.redhat.com/733685>. */
404     nickname = aprintf("PEM Token #1:%s", n);
405     if(nickname) {
406       cert = PK11_FindCertFromNickname(nickname, NULL);
407       if(cert)
408         CERT_DestroyCertificate(cert);
409
410       free(nickname);
411     }
412   }
413
414   return err;
415 }
416
417 /* add given CRL to cache if it is not already there */
418 static SECStatus nss_cache_crl(SECItem *crlDER)
419 {
420   CERTCertDBHandle *db = CERT_GetDefaultCertDB();
421   CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0);
422   if(crl) {
423     /* CRL already cached */
424     SEC_DestroyCrl(crl);
425     SECITEM_FreeItem(crlDER, PR_FALSE);
426     return SECSuccess;
427   }
428
429   /* acquire lock before call of CERT_CacheCRL() */
430   PR_Lock(nss_crllock);
431   if(SECSuccess != CERT_CacheCRL(db, crlDER)) {
432     /* unable to cache CRL */
433     PR_Unlock(nss_crllock);
434     SECITEM_FreeItem(crlDER, PR_FALSE);
435     return SECFailure;
436   }
437
438   /* we need to clear session cache, so that the CRL could take effect */
439   SSL_ClearSessionCache();
440   PR_Unlock(nss_crllock);
441   return SECSuccess;
442 }
443
444 static SECStatus nss_load_crl(const char* crlfilename)
445 {
446   PRFileDesc *infile;
447   PRFileInfo  info;
448   SECItem filedata = { 0, NULL, 0 };
449   SECItem crlDER = { 0, NULL, 0 };
450   char *body;
451
452   infile = PR_Open(crlfilename, PR_RDONLY, 0);
453   if(!infile)
454     return SECFailure;
455
456   if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
457     goto fail;
458
459   if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
460     goto fail;
461
462   if(info.size != PR_Read(infile, filedata.data, info.size))
463     goto fail;
464
465   /* place a trailing zero right after the visible data */
466   body = (char*)filedata.data;
467   body[--filedata.len] = '\0';
468
469   body = strstr(body, "-----BEGIN");
470   if(body) {
471     /* assume ASCII */
472     char *trailer;
473     char *begin = PORT_Strchr(body, '\n');
474     if(!begin)
475       begin = PORT_Strchr(body, '\r');
476     if(!begin)
477       goto fail;
478
479     trailer = strstr(++begin, "-----END");
480     if(!trailer)
481       goto fail;
482
483     /* retrieve DER from ASCII */
484     *trailer = '\0';
485     if(ATOB_ConvertAsciiToItem(&crlDER, begin))
486       goto fail;
487
488     SECITEM_FreeItem(&filedata, PR_FALSE);
489   }
490   else
491     /* assume DER */
492     crlDER = filedata;
493
494   PR_Close(infile);
495   return nss_cache_crl(&crlDER);
496
497 fail:
498   PR_Close(infile);
499   SECITEM_FreeItem(&filedata, PR_FALSE);
500   return SECFailure;
501 }
502
503 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
504                              char *key_file)
505 {
506   PK11SlotInfo *slot;
507   SECStatus status;
508   CURLcode rv;
509   struct ssl_connect_data *ssl = conn->ssl;
510   (void)sockindex; /* unused */
511
512   rv = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
513   if(CURLE_OK != rv) {
514     PR_SetError(SEC_ERROR_BAD_KEY, 0);
515     return rv;
516   }
517
518   slot = PK11_FindSlotByName("PEM Token #1");
519   if(!slot)
520     return CURLE_SSL_CERTPROBLEM;
521
522   /* This will force the token to be seen as re-inserted */
523   SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
524   PK11_IsPresent(slot);
525
526   status = PK11_Authenticate(slot, PR_TRUE,
527                              conn->data->set.str[STRING_KEY_PASSWD]);
528   PK11_FreeSlot(slot);
529   return (SECSuccess == status)
530     ? CURLE_OK
531     : CURLE_SSL_CERTPROBLEM;
532 }
533
534 static int display_error(struct connectdata *conn, PRInt32 err,
535                          const char *filename)
536 {
537   switch(err) {
538   case SEC_ERROR_BAD_PASSWORD:
539     failf(conn->data, "Unable to load client key: Incorrect password");
540     return 1;
541   case SEC_ERROR_UNKNOWN_CERT:
542     failf(conn->data, "Unable to load certificate %s", filename);
543     return 1;
544   default:
545     break;
546   }
547   return 0; /* The caller will print a generic error */
548 }
549
550 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
551                            char *cert_file, char *key_file)
552 {
553   struct SessionHandle *data = conn->data;
554   CURLcode rv;
555
556   if(cert_file) {
557     rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
558     if(CURLE_OK != rv) {
559       const PRErrorCode err = PR_GetError();
560       if(!display_error(conn, err, cert_file)) {
561         const char *err_name = nss_error_to_name(err);
562         failf(data, "unable to load client cert: %d (%s)", err, err_name);
563       }
564
565       return rv;
566     }
567   }
568
569   if(key_file || (is_file(cert_file))) {
570     if(key_file)
571       rv = nss_load_key(conn, sockindex, key_file);
572     else
573       /* In case the cert file also has the key */
574       rv = nss_load_key(conn, sockindex, cert_file);
575     if(CURLE_OK != rv) {
576       const PRErrorCode err = PR_GetError();
577       if(!display_error(conn, err, key_file)) {
578         const char *err_name = nss_error_to_name(err);
579         failf(data, "unable to load client key: %d (%s)", err, err_name);
580       }
581
582       return rv;
583     }
584   }
585
586   return CURLE_OK;
587 }
588
589 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
590 {
591   (void)slot; /* unused */
592   if(retry || NULL == arg)
593     return NULL;
594   else
595     return (char *)PORT_Strdup((char *)arg);
596 }
597
598 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
599  * verify peer */
600 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
601                                     PRBool isServer)
602 {
603   struct connectdata *conn = (struct connectdata *)arg;
604   if(!conn->data->set.ssl.verifypeer) {
605     infof(conn->data, "skipping SSL peer certificate verification\n");
606     return SECSuccess;
607   }
608
609   return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
610 }
611
612 /**
613  * Inform the application that the handshake is complete.
614  */
615 static void HandshakeCallback(PRFileDesc *sock, void *arg)
616 {
617   struct connectdata *conn = (struct connectdata*) arg;
618
619 #ifndef USE_NGHTTP2
620   (void)sock;
621   (void)conn;
622 #else
623   unsigned int buflenmax = 50;
624   unsigned char buf[50];
625   unsigned int buflen;
626   SSLNextProtoState state;
627
628   if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
629
630     switch(state) {
631       case SSL_NEXT_PROTO_NO_SUPPORT:
632       case SSL_NEXT_PROTO_NO_OVERLAP:
633         infof(conn->data, "TLS, neither ALPN nor NPN succeeded\n");
634         return;
635       case SSL_NEXT_PROTO_SELECTED:
636         infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
637         break;
638       case SSL_NEXT_PROTO_NEGOTIATED:
639         infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
640         break;
641     }
642
643     if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
644         memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)
645         == 0) {
646       conn->negnpn = NPN_HTTP2_DRAFT09;
647     }
648     else if(buflen == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1, buf,
649         ALPN_HTTP_1_1_LENGTH)) {
650       conn->negnpn = NPN_HTTP1_1;
651     }
652   }
653 #endif
654 }
655
656 static void display_cert_info(struct SessionHandle *data,
657                               CERTCertificate *cert)
658 {
659   char *subject, *issuer, *common_name;
660   PRExplodedTime printableTime;
661   char timeString[256];
662   PRTime notBefore, notAfter;
663
664   subject = CERT_NameToAscii(&cert->subject);
665   issuer = CERT_NameToAscii(&cert->issuer);
666   common_name = CERT_GetCommonName(&cert->subject);
667   infof(data, "\tsubject: %s\n", subject);
668
669   CERT_GetCertTimes(cert, &notBefore, &notAfter);
670   PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
671   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
672   infof(data, "\tstart date: %s\n", timeString);
673   PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
674   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
675   infof(data, "\texpire date: %s\n", timeString);
676   infof(data, "\tcommon name: %s\n", common_name);
677   infof(data, "\tissuer: %s\n", issuer);
678
679   PR_Free(subject);
680   PR_Free(issuer);
681   PR_Free(common_name);
682 }
683
684 static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
685 {
686   SSLChannelInfo channel;
687   SSLCipherSuiteInfo suite;
688   CERTCertificate *cert;
689   CERTCertificate *cert2;
690   CERTCertificate *cert3;
691   PRTime now;
692   int i;
693
694   if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
695      SECSuccess && channel.length == sizeof channel &&
696      channel.cipherSuite) {
697     if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
698                               &suite, sizeof suite) == SECSuccess) {
699       infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
700     }
701   }
702
703   cert = SSL_PeerCertificate(sock);
704
705   if(cert) {
706     infof(conn->data, "Server certificate:\n");
707
708     if(!conn->data->set.ssl.certinfo) {
709       display_cert_info(conn->data, cert);
710       CERT_DestroyCertificate(cert);
711     }
712     else {
713       /* Count certificates in chain. */
714       now = PR_Now();
715       i = 1;
716       if(!cert->isRoot) {
717         cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
718         while(cert2) {
719           i++;
720           if(cert2->isRoot) {
721             CERT_DestroyCertificate(cert2);
722             break;
723           }
724           cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
725           CERT_DestroyCertificate(cert2);
726           cert2 = cert3;
727         }
728       }
729       Curl_ssl_init_certinfo(conn->data, i);
730       for(i = 0; cert; cert = cert2) {
731         Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
732                               (char *)cert->derCert.data + cert->derCert.len);
733         if(cert->isRoot) {
734           CERT_DestroyCertificate(cert);
735           break;
736         }
737         cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
738         CERT_DestroyCertificate(cert);
739       }
740     }
741   }
742
743   return;
744 }
745
746 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
747 {
748   struct connectdata *conn = (struct connectdata *)arg;
749   struct SessionHandle *data = conn->data;
750   PRErrorCode err = PR_GetError();
751   CERTCertificate *cert;
752
753   /* remember the cert verification result */
754   data->set.ssl.certverifyresult = err;
755
756   if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
757     /* we are asked not to verify the host name */
758     return SECSuccess;
759
760   /* print only info about the cert, the error is printed off the callback */
761   cert = SSL_PeerCertificate(sock);
762   if(cert) {
763     infof(data, "Server certificate:\n");
764     display_cert_info(data, cert);
765     CERT_DestroyCertificate(cert);
766   }
767
768   return SECFailure;
769 }
770
771 /**
772  *
773  * Check that the Peer certificate's issuer certificate matches the one found
774  * by issuer_nickname.  This is not exactly the way OpenSSL and GNU TLS do the
775  * issuer check, so we provide comments that mimic the OpenSSL
776  * X509_check_issued function (in x509v3/v3_purp.c)
777  */
778 static SECStatus check_issuer_cert(PRFileDesc *sock,
779                                    char *issuer_nickname)
780 {
781   CERTCertificate *cert,*cert_issuer,*issuer;
782   SECStatus res=SECSuccess;
783   void *proto_win = NULL;
784
785   /*
786     PRArenaPool   *tmpArena = NULL;
787     CERTAuthKeyID *authorityKeyID = NULL;
788     SECITEM       *caname = NULL;
789   */
790
791   cert = SSL_PeerCertificate(sock);
792   cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
793
794   proto_win = SSL_RevealPinArg(sock);
795   issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
796
797   if((!cert_issuer) || (!issuer))
798     res = SECFailure;
799   else if(SECITEM_CompareItem(&cert_issuer->derCert,
800                               &issuer->derCert)!=SECEqual)
801     res = SECFailure;
802
803   CERT_DestroyCertificate(cert);
804   CERT_DestroyCertificate(issuer);
805   CERT_DestroyCertificate(cert_issuer);
806   return res;
807 }
808
809 /**
810  *
811  * Callback to pick the SSL client certificate.
812  */
813 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
814                                   struct CERTDistNamesStr *caNames,
815                                   struct CERTCertificateStr **pRetCert,
816                                   struct SECKEYPrivateKeyStr **pRetKey)
817 {
818   struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
819   struct SessionHandle *data = connssl->data;
820   const char *nickname = connssl->client_nickname;
821
822   if(connssl->obj_clicert) {
823     /* use the cert/key provided by PEM reader */
824     static const char pem_slotname[] = "PEM Token #1";
825     SECItem cert_der = { 0, NULL, 0 };
826     void *proto_win = SSL_RevealPinArg(sock);
827     struct CERTCertificateStr *cert;
828     struct SECKEYPrivateKeyStr *key;
829
830     PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
831     if(NULL == slot) {
832       failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
833       return SECFailure;
834     }
835
836     if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
837                              &cert_der) != SECSuccess) {
838       failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
839       PK11_FreeSlot(slot);
840       return SECFailure;
841     }
842
843     cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
844     SECITEM_FreeItem(&cert_der, PR_FALSE);
845     if(NULL == cert) {
846       failf(data, "NSS: client certificate from file not found");
847       PK11_FreeSlot(slot);
848       return SECFailure;
849     }
850
851     key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
852     PK11_FreeSlot(slot);
853     if(NULL == key) {
854       failf(data, "NSS: private key from file not found");
855       CERT_DestroyCertificate(cert);
856       return SECFailure;
857     }
858
859     infof(data, "NSS: client certificate from file\n");
860     display_cert_info(data, cert);
861
862     *pRetCert = cert;
863     *pRetKey = key;
864     return SECSuccess;
865   }
866
867   /* use the default NSS hook */
868   if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
869                                           pRetCert, pRetKey)
870       || NULL == *pRetCert) {
871
872     if(NULL == nickname)
873       failf(data, "NSS: client certificate not found (nickname not "
874             "specified)");
875     else
876       failf(data, "NSS: client certificate not found: %s", nickname);
877
878     return SECFailure;
879   }
880
881   /* get certificate nickname if any */
882   nickname = (*pRetCert)->nickname;
883   if(NULL == nickname)
884     nickname = "[unknown]";
885
886   if(NULL == *pRetKey) {
887     failf(data, "NSS: private key not found for certificate: %s", nickname);
888     return SECFailure;
889   }
890
891   infof(data, "NSS: using client certificate: %s\n", nickname);
892   display_cert_info(data, *pRetCert);
893   return SECSuccess;
894 }
895
896 /* This function is supposed to decide, which error codes should be used
897  * to conclude server is TLS intolerant.
898  *
899  * taken from xulrunner - nsNSSIOLayer.cpp
900  */
901 static PRBool
902 isTLSIntoleranceError(PRInt32 err)
903 {
904   switch (err) {
905   case SSL_ERROR_BAD_MAC_ALERT:
906   case SSL_ERROR_BAD_MAC_READ:
907   case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
908   case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
909   case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE:
910   case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
911   case SSL_ERROR_NO_CYPHER_OVERLAP:
912   case SSL_ERROR_BAD_SERVER:
913   case SSL_ERROR_BAD_BLOCK_PADDING:
914   case SSL_ERROR_UNSUPPORTED_VERSION:
915   case SSL_ERROR_PROTOCOL_VERSION_ALERT:
916   case SSL_ERROR_RX_MALFORMED_FINISHED:
917   case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE:
918   case SSL_ERROR_DECODE_ERROR_ALERT:
919   case SSL_ERROR_RX_UNKNOWN_ALERT:
920     return PR_TRUE;
921   default:
922     return PR_FALSE;
923   }
924 }
925
926 static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir)
927 {
928   NSSInitParameters initparams;
929
930   if(nss_context != NULL)
931     return CURLE_OK;
932
933   memset((void *) &initparams, '\0', sizeof(initparams));
934   initparams.length = sizeof(initparams);
935
936   if(cert_dir) {
937     const bool use_sql = NSS_VersionCheck("3.12.0");
938     char *certpath = aprintf("%s%s", use_sql ? "sql:" : "", cert_dir);
939     if(!certpath)
940       return CURLE_OUT_OF_MEMORY;
941
942     infof(data, "Initializing NSS with certpath: %s\n", certpath);
943     nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
944             NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
945     free(certpath);
946
947     if(nss_context != NULL)
948       return CURLE_OK;
949
950     infof(data, "Unable to initialize NSS database\n");
951   }
952
953   infof(data, "Initializing NSS with certpath: none\n");
954   nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
955          | NSS_INIT_NOCERTDB   | NSS_INIT_NOMODDB       | NSS_INIT_FORCEOPEN
956          | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
957   if(nss_context != NULL)
958     return CURLE_OK;
959
960   infof(data, "Unable to initialize NSS\n");
961   return CURLE_SSL_CACERT_BADFILE;
962 }
963
964 static CURLcode nss_init(struct SessionHandle *data)
965 {
966   char *cert_dir;
967   struct_stat st;
968   CURLcode rv;
969
970   if(initialized)
971     return CURLE_OK;
972
973   /* First we check if $SSL_DIR points to a valid dir */
974   cert_dir = getenv("SSL_DIR");
975   if(cert_dir) {
976     if((stat(cert_dir, &st) != 0) ||
977         (!S_ISDIR(st.st_mode))) {
978       cert_dir = NULL;
979     }
980   }
981
982   /* Now we check if the default location is a valid dir */
983   if(!cert_dir) {
984     if((stat(SSL_DIR, &st) == 0) &&
985         (S_ISDIR(st.st_mode))) {
986       cert_dir = (char *)SSL_DIR;
987     }
988   }
989
990   rv = nss_init_core(data, cert_dir);
991   if(rv)
992     return rv;
993
994   if(num_enabled_ciphers() == 0)
995     NSS_SetDomesticPolicy();
996
997   initialized = 1;
998   return CURLE_OK;
999 }
1000
1001 /**
1002  * Global SSL init
1003  *
1004  * @retval 0 error initializing SSL
1005  * @retval 1 SSL initialized successfully
1006  */
1007 int Curl_nss_init(void)
1008 {
1009   /* curl_global_init() is not thread-safe so this test is ok */
1010   if(nss_initlock == NULL) {
1011     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
1012     nss_initlock = PR_NewLock();
1013     nss_crllock = PR_NewLock();
1014   }
1015
1016   /* We will actually initialize NSS later */
1017
1018   return 1;
1019 }
1020
1021 CURLcode Curl_nss_force_init(struct SessionHandle *data)
1022 {
1023   CURLcode rv;
1024   if(!nss_initlock) {
1025     failf(data,
1026           "unable to initialize NSS, curl_global_init() should have been "
1027           "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1028     return CURLE_FAILED_INIT;
1029   }
1030
1031   PR_Lock(nss_initlock);
1032   rv = nss_init(data);
1033   PR_Unlock(nss_initlock);
1034   return rv;
1035 }
1036
1037 /* Global cleanup */
1038 void Curl_nss_cleanup(void)
1039 {
1040   /* This function isn't required to be threadsafe and this is only done
1041    * as a safety feature.
1042    */
1043   PR_Lock(nss_initlock);
1044   if(initialized) {
1045     /* Free references to client certificates held in the SSL session cache.
1046      * Omitting this hampers destruction of the security module owning
1047      * the certificates. */
1048     SSL_ClearSessionCache();
1049
1050     if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1051       SECMOD_DestroyModule(mod);
1052       mod = NULL;
1053     }
1054     NSS_ShutdownContext(nss_context);
1055     nss_context = NULL;
1056   }
1057   PR_Unlock(nss_initlock);
1058
1059   PR_DestroyLock(nss_initlock);
1060   PR_DestroyLock(nss_crllock);
1061   nss_initlock = NULL;
1062
1063   initialized = 0;
1064 }
1065
1066 /*
1067  * This function uses SSL_peek to determine connection status.
1068  *
1069  * Return codes:
1070  *     1 means the connection is still in place
1071  *     0 means the connection has been closed
1072  *    -1 means the connection status is unknown
1073  */
1074 int
1075 Curl_nss_check_cxn(struct connectdata *conn)
1076 {
1077   int rc;
1078   char buf;
1079
1080   rc =
1081     PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1082             PR_SecondsToInterval(1));
1083   if(rc > 0)
1084     return 1; /* connection still in place */
1085
1086   if(rc == 0)
1087     return 0; /* connection has been closed */
1088
1089   return -1;  /* connection status unknown */
1090 }
1091
1092 /*
1093  * This function is called when an SSL connection is closed.
1094  */
1095 void Curl_nss_close(struct connectdata *conn, int sockindex)
1096 {
1097   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1098
1099   if(connssl->handle) {
1100     /* NSS closes the socket we previously handed to it, so we must mark it
1101        as closed to avoid double close */
1102     fake_sclose(conn->sock[sockindex]);
1103     conn->sock[sockindex] = CURL_SOCKET_BAD;
1104
1105     if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
1106       /* A server might require different authentication based on the
1107        * particular path being requested by the client.  To support this
1108        * scenario, we must ensure that a connection will never reuse the
1109        * authentication data from a previous connection. */
1110       SSL_InvalidateSession(connssl->handle);
1111
1112     if(connssl->client_nickname != NULL) {
1113       free(connssl->client_nickname);
1114       connssl->client_nickname = NULL;
1115     }
1116     /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1117     Curl_llist_destroy(connssl->obj_list, NULL);
1118     connssl->obj_list = NULL;
1119     connssl->obj_clicert = NULL;
1120
1121     PR_Close(connssl->handle);
1122     connssl->handle = NULL;
1123   }
1124 }
1125
1126 /*
1127  * This function is called when the 'data' struct is going away. Close
1128  * down everything and free all resources!
1129  */
1130 int Curl_nss_close_all(struct SessionHandle *data)
1131 {
1132   (void)data;
1133   return 0;
1134 }
1135
1136 /* return true if NSS can provide error code (and possibly msg) for the
1137    error */
1138 static bool is_nss_error(CURLcode err)
1139 {
1140   switch(err) {
1141   case CURLE_PEER_FAILED_VERIFICATION:
1142   case CURLE_SSL_CACERT:
1143   case CURLE_SSL_CERTPROBLEM:
1144   case CURLE_SSL_CONNECT_ERROR:
1145   case CURLE_SSL_ISSUER_ERROR:
1146     return true;
1147
1148   default:
1149     return false;
1150   }
1151 }
1152
1153 /* return true if the given error code is related to a client certificate */
1154 static bool is_cc_error(PRInt32 err)
1155 {
1156   switch(err) {
1157   case SSL_ERROR_BAD_CERT_ALERT:
1158   case SSL_ERROR_EXPIRED_CERT_ALERT:
1159   case SSL_ERROR_REVOKED_CERT_ALERT:
1160     return true;
1161
1162   default:
1163     return false;
1164   }
1165 }
1166
1167 static Curl_recv nss_recv;
1168 static Curl_send nss_send;
1169
1170 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1171                                          int sockindex)
1172 {
1173   struct SessionHandle *data = conn->data;
1174   const char *cafile = data->set.ssl.CAfile;
1175   const char *capath = data->set.ssl.CApath;
1176
1177   if(cafile) {
1178     CURLcode rv = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1179     if(CURLE_OK != rv)
1180       return rv;
1181   }
1182
1183   if(capath) {
1184     struct_stat st;
1185     if(stat(capath, &st) == -1)
1186       return CURLE_SSL_CACERT_BADFILE;
1187
1188     if(S_ISDIR(st.st_mode)) {
1189       PRDirEntry *entry;
1190       PRDir *dir = PR_OpenDir(capath);
1191       if(!dir)
1192         return CURLE_SSL_CACERT_BADFILE;
1193
1194       while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1195         char *fullpath = aprintf("%s/%s", capath, entry->name);
1196         if(!fullpath) {
1197           PR_CloseDir(dir);
1198           return CURLE_OUT_OF_MEMORY;
1199         }
1200
1201         if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1202           /* This is purposefully tolerant of errors so non-PEM files can
1203            * be in the same directory */
1204           infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1205
1206         free(fullpath);
1207       }
1208
1209       PR_CloseDir(dir);
1210     }
1211     else
1212       infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1213   }
1214
1215   infof(data, "  CAfile: %s\n  CApath: %s\n",
1216       cafile ? cafile : "none",
1217       capath ? capath : "none");
1218
1219   return CURLE_OK;
1220 }
1221
1222 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1223                                 struct SessionHandle *data)
1224 {
1225   switch (data->set.ssl.version) {
1226   default:
1227   case CURL_SSLVERSION_DEFAULT:
1228     if(data->state.ssl_connect_retry) {
1229       infof(data, "TLS disabled due to previous handshake failure\n");
1230       sslver->max = SSL_LIBRARY_VERSION_3_0;
1231       return CURLE_OK;
1232     }
1233   /* intentional fall-through to default to highest TLS version if possible */
1234
1235   case CURL_SSLVERSION_TLSv1:
1236     sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1237 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1238     sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1239 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1240     sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1241 #else
1242     sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1243 #endif
1244     return CURLE_OK;
1245
1246   case CURL_SSLVERSION_SSLv2:
1247     sslver->min = SSL_LIBRARY_VERSION_2;
1248     sslver->max = SSL_LIBRARY_VERSION_2;
1249     return CURLE_OK;
1250
1251   case CURL_SSLVERSION_SSLv3:
1252     sslver->min = SSL_LIBRARY_VERSION_3_0;
1253     sslver->max = SSL_LIBRARY_VERSION_3_0;
1254     return CURLE_OK;
1255
1256   case CURL_SSLVERSION_TLSv1_0:
1257     sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1258     sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1259     return CURLE_OK;
1260
1261   case CURL_SSLVERSION_TLSv1_1:
1262 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1263     sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1264     sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1265     return CURLE_OK;
1266 #endif
1267     break;
1268
1269   case CURL_SSLVERSION_TLSv1_2:
1270 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1271     sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1272     sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1273     return CURLE_OK;
1274 #endif
1275     break;
1276   }
1277
1278   failf(data, "TLS minor version cannot be set");
1279   return CURLE_SSL_CONNECT_ERROR;
1280 }
1281
1282 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1283 {
1284   PRErrorCode err = 0;
1285   PRFileDesc *model = NULL;
1286   PRBool ssl_no_cache;
1287   PRBool ssl_cbc_random_iv;
1288   struct SessionHandle *data = conn->data;
1289   curl_socket_t sockfd = conn->sock[sockindex];
1290   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1291   CURLcode curlerr;
1292   const int *cipher_to_enable;
1293   PRSocketOptionData sock_opt;
1294   long time_left;
1295   PRUint32 timeout;
1296
1297   SSLVersionRange sslver = {
1298     SSL_LIBRARY_VERSION_3_0,      /* min */
1299     SSL_LIBRARY_VERSION_TLS_1_0   /* max */
1300   };
1301
1302 #ifdef USE_NGHTTP2
1303 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
1304   unsigned int alpn_protos_len = NGHTTP2_PROTO_VERSION_ID_LEN +
1305       ALPN_HTTP_1_1_LENGTH + 2;
1306   unsigned char alpn_protos[NGHTTP2_PROTO_VERSION_ID_LEN + ALPN_HTTP_1_1_LENGTH
1307       + 2];
1308   int cur = 0;
1309 #endif
1310 #endif
1311
1312   if(connssl->state == ssl_connection_complete)
1313     return CURLE_OK;
1314
1315   connssl->data = data;
1316
1317   /* list of all NSS objects we need to destroy in Curl_nss_close() */
1318   connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1319   if(!connssl->obj_list)
1320     return CURLE_OUT_OF_MEMORY;
1321
1322   /* FIXME. NSS doesn't support multiple databases open at the same time. */
1323   PR_Lock(nss_initlock);
1324   curlerr = nss_init(conn->data);
1325   if(CURLE_OK != curlerr) {
1326     PR_Unlock(nss_initlock);
1327     goto error;
1328   }
1329
1330   curlerr = CURLE_SSL_CONNECT_ERROR;
1331
1332   if(!mod) {
1333     char *configstring = aprintf("library=%s name=PEM", pem_library);
1334     if(!configstring) {
1335       PR_Unlock(nss_initlock);
1336       goto error;
1337     }
1338     mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1339     free(configstring);
1340
1341     if(!mod || !mod->loaded) {
1342       if(mod) {
1343         SECMOD_DestroyModule(mod);
1344         mod = NULL;
1345       }
1346       infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1347             "OpenSSL PEM certificates will not work.\n", pem_library);
1348     }
1349   }
1350
1351   PK11_SetPasswordFunc(nss_get_password);
1352   PR_Unlock(nss_initlock);
1353
1354   model = PR_NewTCPSocket();
1355   if(!model)
1356     goto error;
1357   model = SSL_ImportFD(NULL, model);
1358
1359   if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1360     goto error;
1361   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1362     goto error;
1363   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1364     goto error;
1365
1366   /* do not use SSL cache if disabled or we are not going to verify peer */
1367   ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
1368     PR_FALSE : PR_TRUE;
1369   if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1370     goto error;
1371
1372   /* enable/disable the requested SSL version(s) */
1373   if(nss_init_sslver(&sslver, data) != CURLE_OK)
1374     goto error;
1375   if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1376     goto error;
1377
1378   ssl_cbc_random_iv = !data->set.ssl_enable_beast;
1379 #ifdef SSL_CBC_RANDOM_IV
1380   /* unless the user explicitly asks to allow the protocol vulnerability, we
1381      use the work-around */
1382   if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1383     infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1384           ssl_cbc_random_iv);
1385 #else
1386   if(ssl_cbc_random_iv)
1387     infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1388 #endif
1389
1390   /* reset the flag to avoid an infinite loop */
1391   data->state.ssl_connect_retry = FALSE;
1392
1393   /* enable all ciphers from enable_ciphers_by_default */
1394   cipher_to_enable = enable_ciphers_by_default;
1395   while(SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
1396     if(SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
1397       curlerr = CURLE_SSL_CIPHER;
1398       goto error;
1399     }
1400     cipher_to_enable++;
1401   }
1402
1403   if(data->set.ssl.cipher_list) {
1404     if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1405       curlerr = CURLE_SSL_CIPHER;
1406       goto error;
1407     }
1408   }
1409
1410   if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
1411     infof(data, "warning: ignoring value of ssl.verifyhost\n");
1412
1413   /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1414    * verify peer */
1415   if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1416     goto error;
1417
1418   data->set.ssl.certverifyresult=0; /* not checked yet */
1419   if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1420     goto error;
1421
1422   if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
1423     goto error;
1424
1425   if(data->set.ssl.verifypeer) {
1426     const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1427     if(CURLE_OK != rv) {
1428       curlerr = rv;
1429       goto error;
1430     }
1431   }
1432
1433   if(data->set.ssl.CRLfile) {
1434     if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) {
1435       curlerr = CURLE_SSL_CRL_BADFILE;
1436       goto error;
1437     }
1438     infof(data,
1439           "  CRLfile: %s\n",
1440           data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
1441   }
1442
1443   if(data->set.str[STRING_CERT]) {
1444     char *nickname = dup_nickname(data, STRING_CERT);
1445     if(nickname) {
1446       /* we are not going to use libnsspem.so to read the client cert */
1447       connssl->obj_clicert = NULL;
1448     }
1449     else {
1450       CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1451                                data->set.str[STRING_KEY]);
1452       if(CURLE_OK != rv) {
1453         /* failf() is already done in cert_stuff() */
1454         curlerr = rv;
1455         goto error;
1456       }
1457     }
1458
1459     /* store the nickname for SelectClientCert() called during handshake */
1460     connssl->client_nickname = nickname;
1461   }
1462   else
1463     connssl->client_nickname = NULL;
1464
1465   if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1466                                (void *)connssl) != SECSuccess) {
1467     curlerr = CURLE_SSL_CERTPROBLEM;
1468     goto error;
1469   }
1470
1471   /* Import our model socket  onto the existing file descriptor */
1472   connssl->handle = PR_ImportTCPSocket(sockfd);
1473   connssl->handle = SSL_ImportFD(model, connssl->handle);
1474   if(!connssl->handle)
1475     goto error;
1476
1477   PR_Close(model); /* We don't need this any more */
1478   model = NULL;
1479
1480   /* This is the password associated with the cert that we're using */
1481   if(data->set.str[STRING_KEY_PASSWD]) {
1482     SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1483   }
1484
1485 #ifdef USE_NGHTTP2
1486 #ifdef SSL_ENABLE_NPN
1487   if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, PR_TRUE) != SECSuccess)
1488     goto error;
1489 #endif
1490
1491 #ifdef SSL_ENABLE_ALPN
1492   if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, PR_TRUE) != SECSuccess)
1493     goto error;
1494 #endif
1495
1496 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
1497   alpn_protos[cur] = NGHTTP2_PROTO_VERSION_ID_LEN;
1498   cur++;
1499   memcpy(&alpn_protos[cur], NGHTTP2_PROTO_VERSION_ID,
1500       NGHTTP2_PROTO_VERSION_ID_LEN);
1501   cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1502   alpn_protos[cur] = ALPN_HTTP_1_1_LENGTH;
1503   cur++;
1504   memcpy(&alpn_protos[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1505
1506   if(SSL_SetNextProtoNego(connssl->handle, alpn_protos, alpn_protos_len)
1507       != SECSuccess)
1508     goto error;
1509 #endif
1510 #endif
1511
1512   /* Force handshake on next I/O */
1513   SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1514
1515   SSL_SetURL(connssl->handle, conn->host.name);
1516
1517   /* check timeout situation */
1518   time_left = Curl_timeleft(data, NULL, TRUE);
1519   if(time_left < 0L) {
1520     failf(data, "timed out before SSL handshake");
1521     curlerr = CURLE_OPERATION_TIMEDOUT;
1522     goto error;
1523   }
1524   timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1525
1526   /* Force the handshake now */
1527   if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1528     if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1529       curlerr = CURLE_PEER_FAILED_VERIFICATION;
1530     else if(conn->data->set.ssl.certverifyresult!=0)
1531       curlerr = CURLE_SSL_CACERT;
1532     goto error;
1533   }
1534
1535   /* switch the SSL socket into non-blocking mode */
1536   sock_opt.option = PR_SockOpt_Nonblocking;
1537   sock_opt.value.non_blocking = PR_TRUE;
1538   if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1539     goto error;
1540
1541   connssl->state = ssl_connection_complete;
1542   conn->recv[sockindex] = nss_recv;
1543   conn->send[sockindex] = nss_send;
1544
1545   display_conn_info(conn, connssl->handle);
1546
1547   if(data->set.str[STRING_SSL_ISSUERCERT]) {
1548     SECStatus ret = SECFailure;
1549     char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
1550     if(nickname) {
1551       /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
1552       ret = check_issuer_cert(connssl->handle, nickname);
1553       free(nickname);
1554     }
1555
1556     if(SECFailure == ret) {
1557       infof(data,"SSL certificate issuer check failed\n");
1558       curlerr = CURLE_SSL_ISSUER_ERROR;
1559       goto error;
1560     }
1561     else {
1562       infof(data, "SSL certificate issuer check ok\n");
1563     }
1564   }
1565
1566   return CURLE_OK;
1567
1568   error:
1569   /* reset the flag to avoid an infinite loop */
1570   data->state.ssl_connect_retry = FALSE;
1571
1572   if(is_nss_error(curlerr)) {
1573     /* read NSPR error code */
1574     err = PR_GetError();
1575     if(is_cc_error(err))
1576       curlerr = CURLE_SSL_CERTPROBLEM;
1577
1578     /* print the error number and error string */
1579     infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1580
1581     /* print a human-readable message describing the error if available */
1582     nss_print_error_message(data, err);
1583   }
1584
1585   if(model)
1586     PR_Close(model);
1587
1588   /* cleanup on connection failure */
1589   Curl_llist_destroy(connssl->obj_list, NULL);
1590   connssl->obj_list = NULL;
1591
1592   if((sslver.min == SSL_LIBRARY_VERSION_3_0)
1593       && (sslver.max == SSL_LIBRARY_VERSION_TLS_1_0)
1594       && isTLSIntoleranceError(err)) {
1595     /* schedule reconnect through Curl_retry_request() */
1596     data->state.ssl_connect_retry = TRUE;
1597     infof(data, "Error in TLS handshake, trying SSLv3...\n");
1598     return CURLE_OK;
1599   }
1600
1601   return curlerr;
1602 }
1603
1604 static ssize_t nss_send(struct connectdata *conn,  /* connection data */
1605                         int sockindex,             /* socketindex */
1606                         const void *mem,           /* send this data */
1607                         size_t len,                /* amount to write */
1608                         CURLcode *curlcode)
1609 {
1610   ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
1611                        PR_INTERVAL_NO_WAIT);
1612   if(rc < 0) {
1613     PRInt32 err = PR_GetError();
1614     if(err == PR_WOULD_BLOCK_ERROR)
1615       *curlcode = CURLE_AGAIN;
1616     else {
1617       /* print the error number and error string */
1618       const char *err_name = nss_error_to_name(err);
1619       infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
1620
1621       /* print a human-readable message describing the error if available */
1622       nss_print_error_message(conn->data, err);
1623
1624       *curlcode = (is_cc_error(err))
1625         ? CURLE_SSL_CERTPROBLEM
1626         : CURLE_SEND_ERROR;
1627     }
1628     return -1;
1629   }
1630   return rc; /* number of bytes */
1631 }
1632
1633 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1634                         int num,                   /* socketindex */
1635                         char *buf,                 /* store read data here */
1636                         size_t buffersize,         /* max amount to read */
1637                         CURLcode *curlcode)
1638 {
1639   ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
1640                           PR_INTERVAL_NO_WAIT);
1641   if(nread < 0) {
1642     /* failed SSL read */
1643     PRInt32 err = PR_GetError();
1644
1645     if(err == PR_WOULD_BLOCK_ERROR)
1646       *curlcode = CURLE_AGAIN;
1647     else {
1648       /* print the error number and error string */
1649       const char *err_name = nss_error_to_name(err);
1650       infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
1651
1652       /* print a human-readable message describing the error if available */
1653       nss_print_error_message(conn->data, err);
1654
1655       *curlcode = (is_cc_error(err))
1656         ? CURLE_SSL_CERTPROBLEM
1657         : CURLE_RECV_ERROR;
1658     }
1659     return -1;
1660   }
1661   return nread;
1662 }
1663
1664 size_t Curl_nss_version(char *buffer, size_t size)
1665 {
1666   return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
1667 }
1668
1669 int Curl_nss_seed(struct SessionHandle *data)
1670 {
1671   /* make sure that NSS is initialized */
1672   return !!Curl_nss_force_init(data);
1673 }
1674
1675 void Curl_nss_random(struct SessionHandle *data,
1676                      unsigned char *entropy,
1677                      size_t length)
1678 {
1679   Curl_nss_seed(data);  /* Initiate the seed if not already done */
1680   if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length))) {
1681     /* no way to signal a failure from here, we have to abort */
1682     failf(data, "PK11_GenerateRandom() failed, calling abort()...");
1683     abort();
1684   }
1685 }
1686
1687 void Curl_nss_md5sum(unsigned char *tmp, /* input */
1688                      size_t tmplen,
1689                      unsigned char *md5sum, /* output */
1690                      size_t md5len)
1691 {
1692   PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
1693   unsigned int MD5out;
1694   PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
1695   PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
1696   PK11_DestroyContext(MD5pw, PR_TRUE);
1697 }
1698
1699 #endif /* USE_NSS */