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