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