nss: do not use the NSS_ENABLE_ECC define
[platform/upstream/curl.git] / lib / vtls / 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 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   (void)sock;
618   (void)arg;
619 }
620
621 static void display_cert_info(struct SessionHandle *data,
622                               CERTCertificate *cert)
623 {
624   char *subject, *issuer, *common_name;
625   PRExplodedTime printableTime;
626   char timeString[256];
627   PRTime notBefore, notAfter;
628
629   subject = CERT_NameToAscii(&cert->subject);
630   issuer = CERT_NameToAscii(&cert->issuer);
631   common_name = CERT_GetCommonName(&cert->subject);
632   infof(data, "\tsubject: %s\n", subject);
633
634   CERT_GetCertTimes(cert, &notBefore, &notAfter);
635   PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
636   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
637   infof(data, "\tstart date: %s\n", timeString);
638   PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
639   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
640   infof(data, "\texpire date: %s\n", timeString);
641   infof(data, "\tcommon name: %s\n", common_name);
642   infof(data, "\tissuer: %s\n", issuer);
643
644   PR_Free(subject);
645   PR_Free(issuer);
646   PR_Free(common_name);
647 }
648
649 static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
650 {
651   SSLChannelInfo channel;
652   SSLCipherSuiteInfo suite;
653   CERTCertificate *cert;
654   CERTCertificate *cert2;
655   CERTCertificate *cert3;
656   PRTime now;
657   int i;
658
659   if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
660      SECSuccess && channel.length == sizeof channel &&
661      channel.cipherSuite) {
662     if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
663                               &suite, sizeof suite) == SECSuccess) {
664       infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
665     }
666   }
667
668   cert = SSL_PeerCertificate(sock);
669
670   if(cert) {
671     infof(conn->data, "Server certificate:\n");
672
673     if(!conn->data->set.ssl.certinfo) {
674       display_cert_info(conn->data, cert);
675       CERT_DestroyCertificate(cert);
676     }
677     else {
678       /* Count certificates in chain. */
679       now = PR_Now();
680       i = 1;
681       if(!cert->isRoot) {
682         cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
683         while(cert2) {
684           i++;
685           if(cert2->isRoot) {
686             CERT_DestroyCertificate(cert2);
687             break;
688           }
689           cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
690           CERT_DestroyCertificate(cert2);
691           cert2 = cert3;
692         }
693       }
694       Curl_ssl_init_certinfo(conn->data, i);
695       for(i = 0; cert; cert = cert2) {
696         Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
697                               (char *)cert->derCert.data + cert->derCert.len);
698         if(cert->isRoot) {
699           CERT_DestroyCertificate(cert);
700           break;
701         }
702         cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
703         CERT_DestroyCertificate(cert);
704       }
705     }
706   }
707
708   return;
709 }
710
711 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
712 {
713   struct connectdata *conn = (struct connectdata *)arg;
714   struct SessionHandle *data = conn->data;
715   PRErrorCode err = PR_GetError();
716   CERTCertificate *cert;
717
718   /* remember the cert verification result */
719   data->set.ssl.certverifyresult = err;
720
721   if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
722     /* we are asked not to verify the host name */
723     return SECSuccess;
724
725   /* print only info about the cert, the error is printed off the callback */
726   cert = SSL_PeerCertificate(sock);
727   if(cert) {
728     infof(data, "Server certificate:\n");
729     display_cert_info(data, cert);
730     CERT_DestroyCertificate(cert);
731   }
732
733   return SECFailure;
734 }
735
736 /**
737  *
738  * Check that the Peer certificate's issuer certificate matches the one found
739  * by issuer_nickname.  This is not exactly the way OpenSSL and GNU TLS do the
740  * issuer check, so we provide comments that mimic the OpenSSL
741  * X509_check_issued function (in x509v3/v3_purp.c)
742  */
743 static SECStatus check_issuer_cert(PRFileDesc *sock,
744                                    char *issuer_nickname)
745 {
746   CERTCertificate *cert,*cert_issuer,*issuer;
747   SECStatus res=SECSuccess;
748   void *proto_win = NULL;
749
750   /*
751     PRArenaPool   *tmpArena = NULL;
752     CERTAuthKeyID *authorityKeyID = NULL;
753     SECITEM       *caname = NULL;
754   */
755
756   cert = SSL_PeerCertificate(sock);
757   cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
758
759   proto_win = SSL_RevealPinArg(sock);
760   issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
761
762   if((!cert_issuer) || (!issuer))
763     res = SECFailure;
764   else if(SECITEM_CompareItem(&cert_issuer->derCert,
765                               &issuer->derCert)!=SECEqual)
766     res = SECFailure;
767
768   CERT_DestroyCertificate(cert);
769   CERT_DestroyCertificate(issuer);
770   CERT_DestroyCertificate(cert_issuer);
771   return res;
772 }
773
774 /**
775  *
776  * Callback to pick the SSL client certificate.
777  */
778 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
779                                   struct CERTDistNamesStr *caNames,
780                                   struct CERTCertificateStr **pRetCert,
781                                   struct SECKEYPrivateKeyStr **pRetKey)
782 {
783   struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
784   struct SessionHandle *data = connssl->data;
785   const char *nickname = connssl->client_nickname;
786
787   if(connssl->obj_clicert) {
788     /* use the cert/key provided by PEM reader */
789     static const char pem_slotname[] = "PEM Token #1";
790     SECItem cert_der = { 0, NULL, 0 };
791     void *proto_win = SSL_RevealPinArg(sock);
792     struct CERTCertificateStr *cert;
793     struct SECKEYPrivateKeyStr *key;
794
795     PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
796     if(NULL == slot) {
797       failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
798       return SECFailure;
799     }
800
801     if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
802                              &cert_der) != SECSuccess) {
803       failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
804       PK11_FreeSlot(slot);
805       return SECFailure;
806     }
807
808     cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
809     SECITEM_FreeItem(&cert_der, PR_FALSE);
810     if(NULL == cert) {
811       failf(data, "NSS: client certificate from file not found");
812       PK11_FreeSlot(slot);
813       return SECFailure;
814     }
815
816     key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
817     PK11_FreeSlot(slot);
818     if(NULL == key) {
819       failf(data, "NSS: private key from file not found");
820       CERT_DestroyCertificate(cert);
821       return SECFailure;
822     }
823
824     infof(data, "NSS: client certificate from file\n");
825     display_cert_info(data, cert);
826
827     *pRetCert = cert;
828     *pRetKey = key;
829     return SECSuccess;
830   }
831
832   /* use the default NSS hook */
833   if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
834                                           pRetCert, pRetKey)
835       || NULL == *pRetCert) {
836
837     if(NULL == nickname)
838       failf(data, "NSS: client certificate not found (nickname not "
839             "specified)");
840     else
841       failf(data, "NSS: client certificate not found: %s", nickname);
842
843     return SECFailure;
844   }
845
846   /* get certificate nickname if any */
847   nickname = (*pRetCert)->nickname;
848   if(NULL == nickname)
849     nickname = "[unknown]";
850
851   if(NULL == *pRetKey) {
852     failf(data, "NSS: private key not found for certificate: %s", nickname);
853     return SECFailure;
854   }
855
856   infof(data, "NSS: using client certificate: %s\n", nickname);
857   display_cert_info(data, *pRetCert);
858   return SECSuccess;
859 }
860
861 /* This function is supposed to decide, which error codes should be used
862  * to conclude server is TLS intolerant.
863  *
864  * taken from xulrunner - nsNSSIOLayer.cpp
865  */
866 static PRBool
867 isTLSIntoleranceError(PRInt32 err)
868 {
869   switch (err) {
870   case SSL_ERROR_BAD_MAC_ALERT:
871   case SSL_ERROR_BAD_MAC_READ:
872   case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
873   case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
874   case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE:
875   case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
876   case SSL_ERROR_NO_CYPHER_OVERLAP:
877   case SSL_ERROR_BAD_SERVER:
878   case SSL_ERROR_BAD_BLOCK_PADDING:
879   case SSL_ERROR_UNSUPPORTED_VERSION:
880   case SSL_ERROR_PROTOCOL_VERSION_ALERT:
881   case SSL_ERROR_RX_MALFORMED_FINISHED:
882   case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE:
883   case SSL_ERROR_DECODE_ERROR_ALERT:
884   case SSL_ERROR_RX_UNKNOWN_ALERT:
885     return PR_TRUE;
886   default:
887     return PR_FALSE;
888   }
889 }
890
891 static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir)
892 {
893   NSSInitParameters initparams;
894
895   if(nss_context != NULL)
896     return CURLE_OK;
897
898   memset((void *) &initparams, '\0', sizeof(initparams));
899   initparams.length = sizeof(initparams);
900
901   if(cert_dir) {
902     const bool use_sql = NSS_VersionCheck("3.12.0");
903     char *certpath = aprintf("%s%s", use_sql ? "sql:" : "", cert_dir);
904     if(!certpath)
905       return CURLE_OUT_OF_MEMORY;
906
907     infof(data, "Initializing NSS with certpath: %s\n", certpath);
908     nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
909             NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
910     free(certpath);
911
912     if(nss_context != NULL)
913       return CURLE_OK;
914
915     infof(data, "Unable to initialize NSS database\n");
916   }
917
918   infof(data, "Initializing NSS with certpath: none\n");
919   nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
920          | NSS_INIT_NOCERTDB   | NSS_INIT_NOMODDB       | NSS_INIT_FORCEOPEN
921          | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
922   if(nss_context != NULL)
923     return CURLE_OK;
924
925   infof(data, "Unable to initialize NSS\n");
926   return CURLE_SSL_CACERT_BADFILE;
927 }
928
929 static CURLcode nss_init(struct SessionHandle *data)
930 {
931   char *cert_dir;
932   struct_stat st;
933   CURLcode rv;
934
935   if(initialized)
936     return CURLE_OK;
937
938   /* First we check if $SSL_DIR points to a valid dir */
939   cert_dir = getenv("SSL_DIR");
940   if(cert_dir) {
941     if((stat(cert_dir, &st) != 0) ||
942         (!S_ISDIR(st.st_mode))) {
943       cert_dir = NULL;
944     }
945   }
946
947   /* Now we check if the default location is a valid dir */
948   if(!cert_dir) {
949     if((stat(SSL_DIR, &st) == 0) &&
950         (S_ISDIR(st.st_mode))) {
951       cert_dir = (char *)SSL_DIR;
952     }
953   }
954
955   rv = nss_init_core(data, cert_dir);
956   if(rv)
957     return rv;
958
959   if(num_enabled_ciphers() == 0)
960     NSS_SetDomesticPolicy();
961
962   initialized = 1;
963   return CURLE_OK;
964 }
965
966 /**
967  * Global SSL init
968  *
969  * @retval 0 error initializing SSL
970  * @retval 1 SSL initialized successfully
971  */
972 int Curl_nss_init(void)
973 {
974   /* curl_global_init() is not thread-safe so this test is ok */
975   if(nss_initlock == NULL) {
976     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
977     nss_initlock = PR_NewLock();
978     nss_crllock = PR_NewLock();
979   }
980
981   /* We will actually initialize NSS later */
982
983   return 1;
984 }
985
986 CURLcode Curl_nss_force_init(struct SessionHandle *data)
987 {
988   CURLcode rv;
989   if(!nss_initlock) {
990     failf(data,
991           "unable to initialize NSS, curl_global_init() should have been "
992           "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
993     return CURLE_FAILED_INIT;
994   }
995
996   PR_Lock(nss_initlock);
997   rv = nss_init(data);
998   PR_Unlock(nss_initlock);
999   return rv;
1000 }
1001
1002 /* Global cleanup */
1003 void Curl_nss_cleanup(void)
1004 {
1005   /* This function isn't required to be threadsafe and this is only done
1006    * as a safety feature.
1007    */
1008   PR_Lock(nss_initlock);
1009   if(initialized) {
1010     /* Free references to client certificates held in the SSL session cache.
1011      * Omitting this hampers destruction of the security module owning
1012      * the certificates. */
1013     SSL_ClearSessionCache();
1014
1015     if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1016       SECMOD_DestroyModule(mod);
1017       mod = NULL;
1018     }
1019     NSS_ShutdownContext(nss_context);
1020     nss_context = NULL;
1021   }
1022   PR_Unlock(nss_initlock);
1023
1024   PR_DestroyLock(nss_initlock);
1025   PR_DestroyLock(nss_crllock);
1026   nss_initlock = NULL;
1027
1028   initialized = 0;
1029 }
1030
1031 /*
1032  * This function uses SSL_peek to determine connection status.
1033  *
1034  * Return codes:
1035  *     1 means the connection is still in place
1036  *     0 means the connection has been closed
1037  *    -1 means the connection status is unknown
1038  */
1039 int
1040 Curl_nss_check_cxn(struct connectdata *conn)
1041 {
1042   int rc;
1043   char buf;
1044
1045   rc =
1046     PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1047             PR_SecondsToInterval(1));
1048   if(rc > 0)
1049     return 1; /* connection still in place */
1050
1051   if(rc == 0)
1052     return 0; /* connection has been closed */
1053
1054   return -1;  /* connection status unknown */
1055 }
1056
1057 /*
1058  * This function is called when an SSL connection is closed.
1059  */
1060 void Curl_nss_close(struct connectdata *conn, int sockindex)
1061 {
1062   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1063
1064   if(connssl->handle) {
1065     /* NSS closes the socket we previously handed to it, so we must mark it
1066        as closed to avoid double close */
1067     fake_sclose(conn->sock[sockindex]);
1068     conn->sock[sockindex] = CURL_SOCKET_BAD;
1069
1070     if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
1071       /* A server might require different authentication based on the
1072        * particular path being requested by the client.  To support this
1073        * scenario, we must ensure that a connection will never reuse the
1074        * authentication data from a previous connection. */
1075       SSL_InvalidateSession(connssl->handle);
1076
1077     if(connssl->client_nickname != NULL) {
1078       free(connssl->client_nickname);
1079       connssl->client_nickname = NULL;
1080     }
1081     /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1082     Curl_llist_destroy(connssl->obj_list, NULL);
1083     connssl->obj_list = NULL;
1084     connssl->obj_clicert = NULL;
1085
1086     PR_Close(connssl->handle);
1087     connssl->handle = NULL;
1088   }
1089 }
1090
1091 /*
1092  * This function is called when the 'data' struct is going away. Close
1093  * down everything and free all resources!
1094  */
1095 int Curl_nss_close_all(struct SessionHandle *data)
1096 {
1097   (void)data;
1098   return 0;
1099 }
1100
1101 /* return true if NSS can provide error code (and possibly msg) for the
1102    error */
1103 static bool is_nss_error(CURLcode err)
1104 {
1105   switch(err) {
1106   case CURLE_PEER_FAILED_VERIFICATION:
1107   case CURLE_SSL_CACERT:
1108   case CURLE_SSL_CERTPROBLEM:
1109   case CURLE_SSL_CONNECT_ERROR:
1110   case CURLE_SSL_ISSUER_ERROR:
1111     return true;
1112
1113   default:
1114     return false;
1115   }
1116 }
1117
1118 /* return true if the given error code is related to a client certificate */
1119 static bool is_cc_error(PRInt32 err)
1120 {
1121   switch(err) {
1122   case SSL_ERROR_BAD_CERT_ALERT:
1123   case SSL_ERROR_EXPIRED_CERT_ALERT:
1124   case SSL_ERROR_REVOKED_CERT_ALERT:
1125     return true;
1126
1127   default:
1128     return false;
1129   }
1130 }
1131
1132 static Curl_recv nss_recv;
1133 static Curl_send nss_send;
1134
1135 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1136                                          int sockindex)
1137 {
1138   struct SessionHandle *data = conn->data;
1139   const char *cafile = data->set.ssl.CAfile;
1140   const char *capath = data->set.ssl.CApath;
1141
1142   if(cafile) {
1143     CURLcode rv = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1144     if(CURLE_OK != rv)
1145       return rv;
1146   }
1147
1148   if(capath) {
1149     struct_stat st;
1150     if(stat(capath, &st) == -1)
1151       return CURLE_SSL_CACERT_BADFILE;
1152
1153     if(S_ISDIR(st.st_mode)) {
1154       PRDirEntry *entry;
1155       PRDir *dir = PR_OpenDir(capath);
1156       if(!dir)
1157         return CURLE_SSL_CACERT_BADFILE;
1158
1159       while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1160         char *fullpath = aprintf("%s/%s", capath, entry->name);
1161         if(!fullpath) {
1162           PR_CloseDir(dir);
1163           return CURLE_OUT_OF_MEMORY;
1164         }
1165
1166         if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1167           /* This is purposefully tolerant of errors so non-PEM files can
1168            * be in the same directory */
1169           infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1170
1171         free(fullpath);
1172       }
1173
1174       PR_CloseDir(dir);
1175     }
1176     else
1177       infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1178   }
1179
1180   infof(data, "  CAfile: %s\n  CApath: %s\n",
1181       cafile ? cafile : "none",
1182       capath ? capath : "none");
1183
1184   return CURLE_OK;
1185 }
1186
1187 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1188                                 struct SessionHandle *data)
1189 {
1190   switch (data->set.ssl.version) {
1191   default:
1192   case CURL_SSLVERSION_DEFAULT:
1193     if(data->state.ssl_connect_retry) {
1194       infof(data, "TLS disabled due to previous handshake failure\n");
1195       sslver->max = SSL_LIBRARY_VERSION_3_0;
1196     }
1197     return CURLE_OK;
1198
1199   case CURL_SSLVERSION_TLSv1:
1200     sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1201 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1202     sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1203 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1204     sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1205 #else
1206     sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1207 #endif
1208     return CURLE_OK;
1209
1210   case CURL_SSLVERSION_SSLv2:
1211     sslver->min = SSL_LIBRARY_VERSION_2;
1212     sslver->max = SSL_LIBRARY_VERSION_2;
1213     return CURLE_OK;
1214
1215   case CURL_SSLVERSION_SSLv3:
1216     sslver->min = SSL_LIBRARY_VERSION_3_0;
1217     sslver->max = SSL_LIBRARY_VERSION_3_0;
1218     return CURLE_OK;
1219
1220   case CURL_SSLVERSION_TLSv1_0:
1221     sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1222     sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1223     return CURLE_OK;
1224
1225   case CURL_SSLVERSION_TLSv1_1:
1226 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1227     sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1228     sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1229     return CURLE_OK;
1230 #endif
1231     break;
1232
1233   case CURL_SSLVERSION_TLSv1_2:
1234 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1235     sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1236     sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1237     return CURLE_OK;
1238 #endif
1239     break;
1240   }
1241
1242   failf(data, "TLS minor version cannot be set");
1243   return CURLE_SSL_CONNECT_ERROR;
1244 }
1245
1246 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1247 {
1248   PRErrorCode err = 0;
1249   PRFileDesc *model = NULL;
1250   PRBool ssl_no_cache;
1251   PRBool ssl_cbc_random_iv;
1252   struct SessionHandle *data = conn->data;
1253   curl_socket_t sockfd = conn->sock[sockindex];
1254   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1255   CURLcode curlerr;
1256   const int *cipher_to_enable;
1257   PRSocketOptionData sock_opt;
1258   long time_left;
1259   PRUint32 timeout;
1260
1261   SSLVersionRange sslver = {
1262     SSL_LIBRARY_VERSION_3_0,      /* min */
1263     SSL_LIBRARY_VERSION_TLS_1_0   /* max */
1264   };
1265
1266   if(connssl->state == ssl_connection_complete)
1267     return CURLE_OK;
1268
1269   connssl->data = data;
1270
1271   /* list of all NSS objects we need to destroy in Curl_nss_close() */
1272   connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1273   if(!connssl->obj_list)
1274     return CURLE_OUT_OF_MEMORY;
1275
1276   /* FIXME. NSS doesn't support multiple databases open at the same time. */
1277   PR_Lock(nss_initlock);
1278   curlerr = nss_init(conn->data);
1279   if(CURLE_OK != curlerr) {
1280     PR_Unlock(nss_initlock);
1281     goto error;
1282   }
1283
1284   curlerr = CURLE_SSL_CONNECT_ERROR;
1285
1286   if(!mod) {
1287     char *configstring = aprintf("library=%s name=PEM", pem_library);
1288     if(!configstring) {
1289       PR_Unlock(nss_initlock);
1290       goto error;
1291     }
1292     mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1293     free(configstring);
1294
1295     if(!mod || !mod->loaded) {
1296       if(mod) {
1297         SECMOD_DestroyModule(mod);
1298         mod = NULL;
1299       }
1300       infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1301             "OpenSSL PEM certificates will not work.\n", pem_library);
1302     }
1303   }
1304
1305   PK11_SetPasswordFunc(nss_get_password);
1306   PR_Unlock(nss_initlock);
1307
1308   model = PR_NewTCPSocket();
1309   if(!model)
1310     goto error;
1311   model = SSL_ImportFD(NULL, model);
1312
1313   if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1314     goto error;
1315   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1316     goto error;
1317   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1318     goto error;
1319
1320   /* do not use SSL cache if disabled or we are not going to verify peer */
1321   ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
1322     PR_FALSE : PR_TRUE;
1323   if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1324     goto error;
1325
1326   /* enable/disable the requested SSL version(s) */
1327   if(nss_init_sslver(&sslver, data) != CURLE_OK)
1328     goto error;
1329   if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1330     goto error;
1331
1332   ssl_cbc_random_iv = !data->set.ssl_enable_beast;
1333 #ifdef SSL_CBC_RANDOM_IV
1334   /* unless the user explicitly asks to allow the protocol vulnerability, we
1335      use the work-around */
1336   if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1337     infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1338           ssl_cbc_random_iv);
1339 #else
1340   if(ssl_cbc_random_iv)
1341     infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1342 #endif
1343
1344   /* reset the flag to avoid an infinite loop */
1345   data->state.ssl_connect_retry = FALSE;
1346
1347   /* enable all ciphers from enable_ciphers_by_default */
1348   cipher_to_enable = enable_ciphers_by_default;
1349   while(SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
1350     if(SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
1351       curlerr = CURLE_SSL_CIPHER;
1352       goto error;
1353     }
1354     cipher_to_enable++;
1355   }
1356
1357   if(data->set.ssl.cipher_list) {
1358     if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1359       curlerr = CURLE_SSL_CIPHER;
1360       goto error;
1361     }
1362   }
1363
1364   if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
1365     infof(data, "warning: ignoring value of ssl.verifyhost\n");
1366
1367   /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1368    * verify peer */
1369   if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1370     goto error;
1371
1372   data->set.ssl.certverifyresult=0; /* not checked yet */
1373   if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1374     goto error;
1375
1376   if(SSL_HandshakeCallback(model, HandshakeCallback, NULL) != SECSuccess)
1377     goto error;
1378
1379   if(data->set.ssl.verifypeer) {
1380     const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1381     if(CURLE_OK != rv) {
1382       curlerr = rv;
1383       goto error;
1384     }
1385   }
1386
1387   if(data->set.ssl.CRLfile) {
1388     if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) {
1389       curlerr = CURLE_SSL_CRL_BADFILE;
1390       goto error;
1391     }
1392     infof(data,
1393           "  CRLfile: %s\n",
1394           data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
1395   }
1396
1397   if(data->set.str[STRING_CERT]) {
1398     char *nickname = dup_nickname(data, STRING_CERT);
1399     if(nickname) {
1400       /* we are not going to use libnsspem.so to read the client cert */
1401       connssl->obj_clicert = NULL;
1402     }
1403     else {
1404       CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1405                                data->set.str[STRING_KEY]);
1406       if(CURLE_OK != rv) {
1407         /* failf() is already done in cert_stuff() */
1408         curlerr = rv;
1409         goto error;
1410       }
1411     }
1412
1413     /* store the nickname for SelectClientCert() called during handshake */
1414     connssl->client_nickname = nickname;
1415   }
1416   else
1417     connssl->client_nickname = NULL;
1418
1419   if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1420                                (void *)connssl) != SECSuccess) {
1421     curlerr = CURLE_SSL_CERTPROBLEM;
1422     goto error;
1423   }
1424
1425   /* Import our model socket  onto the existing file descriptor */
1426   connssl->handle = PR_ImportTCPSocket(sockfd);
1427   connssl->handle = SSL_ImportFD(model, connssl->handle);
1428   if(!connssl->handle)
1429     goto error;
1430
1431   PR_Close(model); /* We don't need this any more */
1432   model = NULL;
1433
1434   /* This is the password associated with the cert that we're using */
1435   if(data->set.str[STRING_KEY_PASSWD]) {
1436     SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1437   }
1438
1439   /* Force handshake on next I/O */
1440   SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1441
1442   SSL_SetURL(connssl->handle, conn->host.name);
1443
1444   /* check timeout situation */
1445   time_left = Curl_timeleft(data, NULL, TRUE);
1446   if(time_left < 0L) {
1447     failf(data, "timed out before SSL handshake");
1448     curlerr = CURLE_OPERATION_TIMEDOUT;
1449     goto error;
1450   }
1451   timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1452
1453   /* Force the handshake now */
1454   if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1455     if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1456       curlerr = CURLE_PEER_FAILED_VERIFICATION;
1457     else if(conn->data->set.ssl.certverifyresult!=0)
1458       curlerr = CURLE_SSL_CACERT;
1459     goto error;
1460   }
1461
1462   /* switch the SSL socket into non-blocking mode */
1463   sock_opt.option = PR_SockOpt_Nonblocking;
1464   sock_opt.value.non_blocking = PR_TRUE;
1465   if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1466     goto error;
1467
1468   connssl->state = ssl_connection_complete;
1469   conn->recv[sockindex] = nss_recv;
1470   conn->send[sockindex] = nss_send;
1471
1472   display_conn_info(conn, connssl->handle);
1473
1474   if(data->set.str[STRING_SSL_ISSUERCERT]) {
1475     SECStatus ret = SECFailure;
1476     char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
1477     if(nickname) {
1478       /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
1479       ret = check_issuer_cert(connssl->handle, nickname);
1480       free(nickname);
1481     }
1482
1483     if(SECFailure == ret) {
1484       infof(data,"SSL certificate issuer check failed\n");
1485       curlerr = CURLE_SSL_ISSUER_ERROR;
1486       goto error;
1487     }
1488     else {
1489       infof(data, "SSL certificate issuer check ok\n");
1490     }
1491   }
1492
1493   return CURLE_OK;
1494
1495   error:
1496   /* reset the flag to avoid an infinite loop */
1497   data->state.ssl_connect_retry = FALSE;
1498
1499   if(is_nss_error(curlerr)) {
1500     /* read NSPR error code */
1501     err = PR_GetError();
1502     if(is_cc_error(err))
1503       curlerr = CURLE_SSL_CERTPROBLEM;
1504
1505     /* print the error number and error string */
1506     infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1507
1508     /* print a human-readable message describing the error if available */
1509     nss_print_error_message(data, err);
1510   }
1511
1512   if(model)
1513     PR_Close(model);
1514
1515   /* cleanup on connection failure */
1516   Curl_llist_destroy(connssl->obj_list, NULL);
1517   connssl->obj_list = NULL;
1518
1519   if((sslver.min == SSL_LIBRARY_VERSION_3_0)
1520       && (sslver.max == SSL_LIBRARY_VERSION_TLS_1_0)
1521       && isTLSIntoleranceError(err)) {
1522     /* schedule reconnect through Curl_retry_request() */
1523     data->state.ssl_connect_retry = TRUE;
1524     infof(data, "Error in TLS handshake, trying SSLv3...\n");
1525     return CURLE_OK;
1526   }
1527
1528   return curlerr;
1529 }
1530
1531 static ssize_t nss_send(struct connectdata *conn,  /* connection data */
1532                         int sockindex,             /* socketindex */
1533                         const void *mem,           /* send this data */
1534                         size_t len,                /* amount to write */
1535                         CURLcode *curlcode)
1536 {
1537   ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
1538                        PR_INTERVAL_NO_WAIT);
1539   if(rc < 0) {
1540     PRInt32 err = PR_GetError();
1541     if(err == PR_WOULD_BLOCK_ERROR)
1542       *curlcode = CURLE_AGAIN;
1543     else {
1544       /* print the error number and error string */
1545       const char *err_name = nss_error_to_name(err);
1546       infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
1547
1548       /* print a human-readable message describing the error if available */
1549       nss_print_error_message(conn->data, err);
1550
1551       *curlcode = (is_cc_error(err))
1552         ? CURLE_SSL_CERTPROBLEM
1553         : CURLE_SEND_ERROR;
1554     }
1555     return -1;
1556   }
1557   return rc; /* number of bytes */
1558 }
1559
1560 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1561                         int num,                   /* socketindex */
1562                         char *buf,                 /* store read data here */
1563                         size_t buffersize,         /* max amount to read */
1564                         CURLcode *curlcode)
1565 {
1566   ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
1567                           PR_INTERVAL_NO_WAIT);
1568   if(nread < 0) {
1569     /* failed SSL read */
1570     PRInt32 err = PR_GetError();
1571
1572     if(err == PR_WOULD_BLOCK_ERROR)
1573       *curlcode = CURLE_AGAIN;
1574     else {
1575       /* print the error number and error string */
1576       const char *err_name = nss_error_to_name(err);
1577       infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
1578
1579       /* print a human-readable message describing the error if available */
1580       nss_print_error_message(conn->data, err);
1581
1582       *curlcode = (is_cc_error(err))
1583         ? CURLE_SSL_CERTPROBLEM
1584         : CURLE_RECV_ERROR;
1585     }
1586     return -1;
1587   }
1588   return nread;
1589 }
1590
1591 size_t Curl_nss_version(char *buffer, size_t size)
1592 {
1593   return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
1594 }
1595
1596 int Curl_nss_seed(struct SessionHandle *data)
1597 {
1598   /* make sure that NSS is initialized */
1599   return !!Curl_nss_force_init(data);
1600 }
1601
1602 void Curl_nss_random(struct SessionHandle *data,
1603                      unsigned char *entropy,
1604                      size_t length)
1605 {
1606   Curl_nss_seed(data);  /* Initiate the seed if not already done */
1607   if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length))) {
1608     /* no way to signal a failure from here, we have to abort */
1609     failf(data, "PK11_GenerateRandom() failed, calling abort()...");
1610     abort();
1611   }
1612 }
1613
1614 void Curl_nss_md5sum(unsigned char *tmp, /* input */
1615                      size_t tmplen,
1616                      unsigned char *md5sum, /* output */
1617                      size_t md5len)
1618 {
1619   PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
1620   unsigned int MD5out;
1621   PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
1622   PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
1623   PK11_DestroyContext(MD5pw, PR_TRUE);
1624 }
1625
1626 #endif /* USE_NSS */