Git init
[external/curl.git] / lib / nss.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, 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 "setup.h"
29
30 #include <string.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
35 #endif
36
37 #include "urldata.h"
38 #include "sendf.h"
39 #include "formdata.h" /* for the boundary function */
40 #include "url.h" /* for the ssl config check function */
41 #include "connect.h"
42 #include "strequal.h"
43 #include "select.h"
44 #include "sslgen.h"
45
46 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
47 #include <curl/mprintf.h>
48
49 #ifdef USE_NSS
50
51 #include "nssg.h"
52 #include <nspr.h>
53 #include <nss.h>
54 #include <ssl.h>
55 #include <sslerr.h>
56 #include <secerr.h>
57 #include <secmod.h>
58 #include <sslproto.h>
59 #include <prtypes.h>
60 #include <pk11pub.h>
61 #include <prio.h>
62 #include <secitem.h>
63 #include <secport.h>
64 #include <certdb.h>
65 #include <base64.h>
66 #include <cert.h>
67
68 #include "curl_memory.h"
69 #include "rawstr.h"
70 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
71
72 /* The last #include file should be: */
73 #include "memdebug.h"
74
75 #define SSL_DIR "/etc/pki/nssdb"
76
77 /* enough to fit the string "PEM Token #[0|1]" */
78 #define SLOTSIZE 13
79
80 PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
81
82 PRLock * nss_initlock = NULL;
83 PRLock * nss_crllock = NULL;
84
85 volatile int initialized = 0;
86
87 typedef struct {
88   const char *name;
89   int num;
90   PRInt32 version; /* protocol version valid for this cipher */
91 } cipher_s;
92
93 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id);       \
94   (x)->pValue=(v); (x)->ulValueLen = (l)
95
96 #define CERT_NewTempCertificate __CERT_NewTempCertificate
97
98 enum sslversion { SSL2 = 1, SSL3 = 2, TLS = 4 };
99
100 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
101 static const cipher_s cipherlist[] = {
102   /* SSL2 cipher suites */
103   {"rc4", SSL_EN_RC4_128_WITH_MD5, SSL2},
104   {"rc4-md5", SSL_EN_RC4_128_WITH_MD5, SSL2},
105   {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL2},
106   {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5, SSL2},
107   {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL2},
108   {"des", SSL_EN_DES_64_CBC_WITH_MD5, SSL2},
109   {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL2},
110   /* SSL3/TLS cipher suites */
111   {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5, SSL3 | TLS},
112   {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA, SSL3 | TLS},
113   {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
114   {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA, SSL3 | TLS},
115   {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL3 | TLS},
116   {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL3 | TLS},
117   {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5, SSL3 | TLS},
118   {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA, SSL3 | TLS},
119   {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
120   {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL3 | TLS},
121   {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, SSL3 | TLS},
122   {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, SSL3 | TLS},
123   {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA, SSL3 | TLS},
124   /* TLS 1.0: Exportable 56-bit Cipher Suites. */
125   {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL3 | TLS},
126   {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL3 | TLS},
127   /* AES ciphers. */
128   {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA, SSL3 | TLS},
129   {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA, SSL3 | TLS},
130 #ifdef NSS_ENABLE_ECC
131   /* ECC ciphers. */
132   {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA, TLS},
133   {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS},
134   {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
135   {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS},
136   {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS},
137   {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS},
138   {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS},
139   {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
140   {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS},
141   {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS},
142   {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA, TLS},
143   {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS},
144   {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
145   {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS},
146   {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS},
147   {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA, TLS},
148   {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS},
149   {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
150   {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS},
151   {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS},
152   {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA, TLS},
153   {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA, TLS},
154   {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, TLS},
155   {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS},
156   {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA, TLS},
157 #endif
158 };
159
160 /* following ciphers are new in NSS 3.4 and not enabled by default, therefore
161    they are enabled explicitly */
162 static const int enable_ciphers_by_default[] = {
163   TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
164   TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
165   TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
166   TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
167   TLS_RSA_WITH_AES_128_CBC_SHA,
168   TLS_RSA_WITH_AES_256_CBC_SHA,
169   SSL_NULL_WITH_NULL_NULL
170 };
171
172 #ifdef HAVE_PK11_CREATEGENERICOBJECT
173 static const char* pem_library = "libnsspem.so";
174 #endif
175 SECMODModule* mod = NULL;
176
177 static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
178                              char *cipher_list)
179 {
180   unsigned int i;
181   PRBool cipher_state[NUM_OF_CIPHERS];
182   PRBool found;
183   char *cipher;
184   SECStatus rv;
185
186   /* First disable all ciphers. This uses a different max value in case
187    * NSS adds more ciphers later we don't want them available by
188    * accident
189    */
190   for(i=0; i<SSL_NumImplementedCiphers; i++) {
191     SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
192   }
193
194   /* Set every entry in our list to false */
195   for(i=0; i<NUM_OF_CIPHERS; i++) {
196     cipher_state[i] = PR_FALSE;
197   }
198
199   cipher = cipher_list;
200
201   while(cipher_list && (cipher_list[0])) {
202     while((*cipher) && (ISSPACE(*cipher)))
203       ++cipher;
204
205     if((cipher_list = strchr(cipher, ','))) {
206       *cipher_list++ = '\0';
207     }
208
209     found = PR_FALSE;
210
211     for(i=0; i<NUM_OF_CIPHERS; i++) {
212       if(Curl_raw_equal(cipher, cipherlist[i].name)) {
213         cipher_state[i] = PR_TRUE;
214         found = PR_TRUE;
215         break;
216       }
217     }
218
219     if(found == PR_FALSE) {
220       failf(data, "Unknown cipher in list: %s", cipher);
221       return SECFailure;
222     }
223
224     if(cipher_list) {
225       cipher = cipher_list;
226     }
227   }
228
229   /* Finally actually enable the selected ciphers */
230   for(i=0; i<NUM_OF_CIPHERS; i++) {
231     rv = SSL_CipherPrefSet(model, cipherlist[i].num, cipher_state[i]);
232     if(rv != SECSuccess) {
233       failf(data, "Unknown cipher in cipher list");
234       return SECFailure;
235     }
236   }
237
238   return SECSuccess;
239 }
240
241 /*
242  * Get the number of ciphers that are enabled. We use this to determine
243  * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
244  */
245 static int num_enabled_ciphers(void)
246 {
247   PRInt32 policy = 0;
248   int count = 0;
249   unsigned int i;
250
251   for(i=0; i<NUM_OF_CIPHERS; i++) {
252     SSL_CipherPolicyGet(cipherlist[i].num, &policy);
253     if(policy)
254       count++;
255   }
256   return count;
257 }
258
259 /*
260  * Determine whether the nickname passed in is a filename that needs to
261  * be loaded as a PEM or a regular NSS nickname.
262  *
263  * returns 1 for a file
264  * returns 0 for not a file (NSS nickname)
265  */
266 static int is_file(const char *filename)
267 {
268   struct_stat st;
269
270   if(filename == NULL)
271     return 0;
272
273   if(stat(filename, &st) == 0)
274     if(S_ISREG(st.st_mode))
275       return 1;
276
277   return 0;
278 }
279
280 static char *fmt_nickname(char *str, bool *nickname_alloc)
281 {
282   char *nickname = NULL;
283   *nickname_alloc = FALSE;
284
285   if(is_file(str)) {
286     char *n = strrchr(str, '/');
287     if(n) {
288       *nickname_alloc = TRUE;
289       n++; /* skip last slash */
290       nickname = aprintf("PEM Token #%d:%s", 1, n);
291     }
292     return nickname;
293   }
294
295   return str;
296 }
297
298 static int nss_load_cert(struct ssl_connect_data *ssl,
299                          const char *filename, PRBool cacert)
300 {
301 #ifdef HAVE_PK11_CREATEGENERICOBJECT
302   CK_SLOT_ID slotID;
303   PK11SlotInfo * slot = NULL;
304   CK_ATTRIBUTE *attrs;
305   CK_ATTRIBUTE theTemplate[20];
306   CK_BBOOL cktrue = CK_TRUE;
307   CK_BBOOL ckfalse = CK_FALSE;
308   CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
309   char slotname[SLOTSIZE];
310 #endif
311   CERTCertificate *cert;
312   char *nickname = NULL;
313   char *n = NULL;
314
315   /* If there is no slash in the filename it is assumed to be a regular
316    * NSS nickname.
317    */
318   if(is_file(filename)) {
319     n = strrchr(filename, '/');
320     if(n)
321       n++;
322     if(!mod)
323       return 1;
324   }
325   else {
326     /* A nickname from the NSS internal database */
327     if(cacert)
328       return 0; /* You can't specify an NSS CA nickname this way */
329     nickname = strdup(filename);
330     if(!nickname)
331       return 0;
332     goto done;
333   }
334
335 #ifdef HAVE_PK11_CREATEGENERICOBJECT
336   attrs = theTemplate;
337
338   /* All CA and trust objects go into slot 0. Other slots are used
339    * for storing certificates. With each new user certificate we increment
340    * the slot count. We only support 1 user certificate right now.
341    */
342   if(cacert)
343     slotID = 0;
344   else
345     slotID = 1;
346
347   snprintf(slotname, SLOTSIZE, "PEM Token #%ld", slotID);
348
349   nickname = aprintf("PEM Token #%ld:%s", slotID, n);
350   if(!nickname)
351     return 0;
352
353   slot = PK11_FindSlotByName(slotname);
354
355   if(!slot) {
356     free(nickname);
357     return 0;
358   }
359
360   PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) );
361   attrs++;
362   PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) );
363   attrs++;
364   PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)filename,
365                 strlen(filename)+1);
366   attrs++;
367   if(cacert) {
368     PK11_SETATTRS(attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) );
369   }
370   else {
371     PK11_SETATTRS(attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) );
372   }
373   attrs++;
374
375   /* This load the certificate in our PEM module into the appropriate
376    * slot.
377    */
378   ssl->cacert[slotID] = PK11_CreateGenericObject(slot, theTemplate, 4,
379                                                  PR_FALSE /* isPerm */);
380
381   PK11_FreeSlot(slot);
382
383   if(ssl->cacert[slotID] == NULL) {
384     free(nickname);
385     return 0;
386   }
387 #else
388   /* We don't have PK11_CreateGenericObject but a file-based cert was passed
389    * in. We need to fail.
390    */
391   return 0;
392 #endif
393
394   done:
395   /* Double-check that the certificate or nickname requested exists in
396    * either the token or the NSS certificate database.
397    */
398   if(!cacert) {
399     cert = PK11_FindCertFromNickname((char *)nickname, NULL);
400
401     /* An invalid nickname was passed in */
402     if(cert == NULL) {
403       free(nickname);
404       PR_SetError(SEC_ERROR_UNKNOWN_CERT, 0);
405       return 0;
406     }
407
408     CERT_DestroyCertificate(cert);
409   }
410
411   free(nickname);
412
413   return 1;
414 }
415
416 /* add given CRL to cache if it is not already there */
417 static SECStatus nss_cache_crl(SECItem *crlDER)
418 {
419   CERTCertDBHandle *db = CERT_GetDefaultCertDB();
420   CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0);
421   if(crl) {
422     /* CRL already cached */
423     SEC_DestroyCrl(crl);
424     SECITEM_FreeItem(crlDER, PR_FALSE);
425     return SECSuccess;
426   }
427
428   /* acquire lock before call of CERT_CacheCRL() */
429   PR_Lock(nss_crllock);
430   if(SECSuccess != CERT_CacheCRL(db, crlDER)) {
431     /* unable to cache CRL */
432     PR_Unlock(nss_crllock);
433     SECITEM_FreeItem(crlDER, PR_FALSE);
434     return SECFailure;
435   }
436
437   /* we need to clear session cache, so that the CRL could take effect */
438   SSL_ClearSessionCache();
439   PR_Unlock(nss_crllock);
440   return SECSuccess;
441 }
442
443 static SECStatus nss_load_crl(const char* crlfilename)
444 {
445   PRFileDesc *infile;
446   PRFileInfo  info;
447   SECItem filedata = { 0, NULL, 0 };
448   SECItem crlDER = { 0, NULL, 0 };
449   char *body;
450
451   infile = PR_Open(crlfilename, PR_RDONLY, 0);
452   if(!infile)
453     return SECFailure;
454
455   if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
456     goto fail;
457
458   if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
459     goto fail;
460
461   if(info.size != PR_Read(infile, filedata.data, info.size))
462     goto fail;
463
464   /* place a trailing zero right after the visible data */
465   body = (char*)filedata.data;
466   body[--filedata.len] = '\0';
467
468   body = strstr(body, "-----BEGIN");
469   if(body) {
470     /* assume ASCII */
471     char *trailer;
472     char *begin = PORT_Strchr(body, '\n');
473     if(!begin)
474       begin = PORT_Strchr(body, '\r');
475     if(!begin)
476       goto fail;
477
478     trailer = strstr(++begin, "-----END");
479     if(!trailer)
480       goto fail;
481
482     /* retrieve DER from ASCII */
483     *trailer = '\0';
484     if(ATOB_ConvertAsciiToItem(&crlDER, begin))
485       goto fail;
486
487     SECITEM_FreeItem(&filedata, PR_FALSE);
488   }
489   else
490     /* assume DER */
491     crlDER = filedata;
492
493   PR_Close(infile);
494   return nss_cache_crl(&crlDER);
495
496 fail:
497   PR_Close(infile);
498   SECITEM_FreeItem(&filedata, PR_FALSE);
499   return SECFailure;
500 }
501
502 static int nss_load_key(struct connectdata *conn, int sockindex,
503                         char *key_file)
504 {
505 #ifdef HAVE_PK11_CREATEGENERICOBJECT
506   PK11SlotInfo * slot = NULL;
507   CK_ATTRIBUTE *attrs;
508   CK_ATTRIBUTE theTemplate[20];
509   CK_BBOOL cktrue = CK_TRUE;
510   CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
511   CK_SLOT_ID slotID;
512   char slotname[SLOTSIZE];
513   struct ssl_connect_data *sslconn = &conn->ssl[sockindex];
514
515   attrs = theTemplate;
516
517   /* FIXME: grok the various file types */
518
519   slotID = 1; /* hardcoded for now */
520
521   snprintf(slotname, sizeof(slotname), "PEM Token #%ld", slotID);
522   slot = PK11_FindSlotByName(slotname);
523
524   if(!slot)
525     return 0;
526
527   PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
528   PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
529   PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)key_file,
530                 strlen(key_file)+1); attrs++;
531
532   /* When adding an encrypted key the PKCS#11 will be set as removed */
533   sslconn->key = PK11_CreateGenericObject(slot, theTemplate, 3,
534                                           PR_FALSE /* isPerm */);
535   if(sslconn->key == NULL) {
536     PR_SetError(SEC_ERROR_BAD_KEY, 0);
537     return 0;
538   }
539
540   /* This will force the token to be seen as re-inserted */
541   SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
542   PK11_IsPresent(slot);
543
544   /* parg is initialized in nss_Init_Tokens() */
545   if(PK11_Authenticate(slot, PR_TRUE,
546                        conn->data->set.str[STRING_KEY_PASSWD]) != SECSuccess) {
547
548     PK11_FreeSlot(slot);
549     return 0;
550   }
551   PK11_FreeSlot(slot);
552
553   return 1;
554 #else
555   /* If we don't have PK11_CreateGenericObject then we can't load a file-based
556    * key.
557    */
558   (void)conn; /* unused */
559   (void)key_file; /* unused */
560   return 0;
561 #endif
562 }
563
564 static int display_error(struct connectdata *conn, PRInt32 err,
565                          const char *filename)
566 {
567   switch(err) {
568   case SEC_ERROR_BAD_PASSWORD:
569     failf(conn->data, "Unable to load client key: Incorrect password");
570     return 1;
571   case SEC_ERROR_UNKNOWN_CERT:
572     failf(conn->data, "Unable to load certificate %s", filename);
573     return 1;
574   default:
575     break;
576   }
577   return 0; /* The caller will print a generic error */
578 }
579
580 static int cert_stuff(struct connectdata *conn,
581                       int sockindex, char *cert_file, char *key_file)
582 {
583   struct SessionHandle *data = conn->data;
584   int rv = 0;
585
586   if(cert_file) {
587     rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
588     if(!rv) {
589       if(!display_error(conn, PR_GetError(), cert_file))
590         failf(data, "Unable to load client cert %d.", PR_GetError());
591       return 0;
592     }
593   }
594   if(key_file || (is_file(cert_file))) {
595     if(key_file)
596       rv = nss_load_key(conn, sockindex, key_file);
597     else
598       /* In case the cert file also has the key */
599       rv = nss_load_key(conn, sockindex, cert_file);
600     if(!rv) {
601       if(!display_error(conn, PR_GetError(), key_file))
602         failf(data, "Unable to load client key %d.", PR_GetError());
603
604       return 0;
605     }
606   }
607   return 1;
608 }
609
610 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
611 {
612   (void)slot; /* unused */
613   if(retry || NULL == arg)
614     return NULL;
615   else
616     return (char *)PORT_Strdup((char *)arg);
617 }
618
619 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
620 {
621   SECStatus success = SECSuccess;
622   struct connectdata *conn = (struct connectdata *)arg;
623   PRErrorCode err = PR_GetError();
624   CERTCertificate *cert = NULL;
625   char *subject, *subject_cn, *issuer;
626
627   if(conn->data->set.ssl.certverifyresult!=0)
628     return success;
629
630   conn->data->set.ssl.certverifyresult=err;
631   cert = SSL_PeerCertificate(sock);
632   subject = CERT_NameToAscii(&cert->subject);
633   subject_cn = CERT_GetCommonName(&cert->subject);
634   issuer = CERT_NameToAscii(&cert->issuer);
635   CERT_DestroyCertificate(cert);
636
637   switch(err) {
638   case SEC_ERROR_CA_CERT_INVALID:
639     infof(conn->data, "Issuer certificate is invalid: '%s'\n", issuer);
640     if(conn->data->set.ssl.verifypeer)
641       success = SECFailure;
642     break;
643   case SEC_ERROR_UNTRUSTED_ISSUER:
644     if(conn->data->set.ssl.verifypeer)
645       success = SECFailure;
646     infof(conn->data, "Certificate is signed by an untrusted issuer: '%s'\n",
647           issuer);
648     break;
649   case SSL_ERROR_BAD_CERT_DOMAIN:
650     if(conn->data->set.ssl.verifyhost) {
651       failf(conn->data, "SSL: certificate subject name '%s' does not match "
652             "target host name '%s'", subject_cn, conn->host.dispname);
653       success = SECFailure;
654     } else {
655       infof(conn->data, "warning: SSL: certificate subject name '%s' does not "
656             "match target host name '%s'\n", subject_cn, conn->host.dispname);
657     }
658     break;
659   case SEC_ERROR_EXPIRED_CERTIFICATE:
660     if(conn->data->set.ssl.verifypeer)
661       success = SECFailure;
662     infof(conn->data, "Remote Certificate has expired.\n");
663     break;
664   case SEC_ERROR_UNKNOWN_ISSUER:
665     if(conn->data->set.ssl.verifypeer)
666       success = SECFailure;
667     infof(conn->data, "Peer's certificate issuer is not recognized: '%s'\n",
668           issuer);
669     break;
670   default:
671     if(conn->data->set.ssl.verifypeer)
672       success = SECFailure;
673     infof(conn->data, "Bad certificate received. Subject = '%s', "
674           "Issuer = '%s'\n", subject, issuer);
675     break;
676   }
677   if(success == SECSuccess)
678     infof(conn->data, "SSL certificate verify ok.\n");
679   PR_Free(subject);
680   PR_Free(subject_cn);
681   PR_Free(issuer);
682
683   return success;
684 }
685
686 /**
687  * Inform the application that the handshake is complete.
688  */
689 static SECStatus HandshakeCallback(PRFileDesc *sock, void *arg)
690 {
691   (void)sock;
692   (void)arg;
693   return SECSuccess;
694 }
695
696 static void display_cert_info(struct SessionHandle *data,
697                               CERTCertificate *cert)
698 {
699   char *subject, *issuer, *common_name;
700   PRExplodedTime printableTime;
701   char timeString[256];
702   PRTime notBefore, notAfter;
703
704   subject = CERT_NameToAscii(&cert->subject);
705   issuer = CERT_NameToAscii(&cert->issuer);
706   common_name = CERT_GetCommonName(&cert->subject);
707   infof(data, "\tsubject: %s\n", subject);
708
709   CERT_GetCertTimes(cert, &notBefore, &notAfter);
710   PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
711   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
712   infof(data, "\tstart date: %s\n", timeString);
713   PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
714   PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
715   infof(data, "\texpire date: %s\n", timeString);
716   infof(data, "\tcommon name: %s\n", common_name);
717   infof(data, "\tissuer: %s\n", issuer);
718
719   PR_Free(subject);
720   PR_Free(issuer);
721   PR_Free(common_name);
722 }
723
724 static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
725 {
726   SSLChannelInfo channel;
727   SSLCipherSuiteInfo suite;
728   CERTCertificate *cert;
729
730   if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
731      SECSuccess && channel.length == sizeof channel &&
732      channel.cipherSuite) {
733     if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
734                               &suite, sizeof suite) == SECSuccess) {
735       infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
736     }
737   }
738
739   infof(conn->data, "Server certificate:\n");
740
741   cert = SSL_PeerCertificate(sock);
742   display_cert_info(conn->data, cert);
743   CERT_DestroyCertificate(cert);
744
745   return;
746 }
747
748 /**
749  *
750  * Check that the Peer certificate's issuer certificate matches the one found
751  * by issuer_nickname.  This is not exactly the way OpenSSL and GNU TLS do the
752  * issuer check, so we provide comments that mimic the OpenSSL
753  * X509_check_issued function (in x509v3/v3_purp.c)
754  */
755 static SECStatus check_issuer_cert(PRFileDesc *sock,
756                                    char *issuer_nickname)
757 {
758   CERTCertificate *cert,*cert_issuer,*issuer;
759   SECStatus res=SECSuccess;
760   void *proto_win = NULL;
761
762   /*
763     PRArenaPool   *tmpArena = NULL;
764     CERTAuthKeyID *authorityKeyID = NULL;
765     SECITEM       *caname = NULL;
766   */
767
768   cert = SSL_PeerCertificate(sock);
769   cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
770
771   proto_win = SSL_RevealPinArg(sock);
772   issuer = NULL;
773   issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
774
775   if ((!cert_issuer) || (!issuer))
776     res = SECFailure;
777   else if (SECITEM_CompareItem(&cert_issuer->derCert,
778                                &issuer->derCert)!=SECEqual)
779     res = SECFailure;
780
781   CERT_DestroyCertificate(cert);
782   CERT_DestroyCertificate(issuer);
783   CERT_DestroyCertificate(cert_issuer);
784   return res;
785 }
786
787 /**
788  *
789  * Callback to pick the SSL client certificate.
790  */
791 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
792                                   struct CERTDistNamesStr *caNames,
793                                   struct CERTCertificateStr **pRetCert,
794                                   struct SECKEYPrivateKeyStr **pRetKey)
795 {
796   static const char pem_nickname[] = "PEM Token #1";
797   const char *pem_slotname = pem_nickname;
798
799   struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
800   struct SessionHandle *data = connssl->data;
801   const char *nickname = connssl->client_nickname;
802
803   if (mod && nickname &&
804       0 == strncmp(nickname, pem_nickname, /* length of "PEM Token" */ 9)) {
805
806     /* use the cert/key provided by PEM reader */
807     PK11SlotInfo *slot;
808     void *proto_win = SSL_RevealPinArg(sock);
809     *pRetKey = NULL;
810
811     *pRetCert = PK11_FindCertFromNickname(nickname, proto_win);
812     if (NULL == *pRetCert) {
813       failf(data, "NSS: client certificate not found: %s", nickname);
814       return SECFailure;
815     }
816
817     slot = PK11_FindSlotByName(pem_slotname);
818     if (NULL == slot) {
819       failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
820       return SECFailure;
821     }
822
823     *pRetKey = PK11_FindPrivateKeyFromCert(slot, *pRetCert, NULL);
824     PK11_FreeSlot(slot);
825     if (NULL == *pRetKey) {
826       failf(data, "NSS: private key not found for certificate: %s", nickname);
827       return SECFailure;
828     }
829
830     infof(data, "NSS: client certificate: %s\n", nickname);
831     display_cert_info(data, *pRetCert);
832     return SECSuccess;
833   }
834
835   /* use the default NSS hook */
836   if (SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
837                                           pRetCert, pRetKey)
838       || NULL == *pRetCert) {
839
840     if (NULL == nickname)
841       failf(data, "NSS: client certificate not found (nickname not "
842             "specified)");
843     else
844       failf(data, "NSS: client certificate not found: %s", nickname);
845
846     return SECFailure;
847   }
848
849   /* get certificate nickname if any */
850   nickname = (*pRetCert)->nickname;
851   if (NULL == nickname)
852     nickname = "[unknown]";
853
854   if (NULL == *pRetKey) {
855     failf(data, "NSS: private key not found for certificate: %s", nickname);
856     return SECFailure;
857   }
858
859   infof(data, "NSS: using client certificate: %s\n", nickname);
860   display_cert_info(data, *pRetCert);
861   return SECSuccess;
862 }
863
864 /* This function is supposed to decide, which error codes should be used
865  * to conclude server is TLS intolerant.
866  *
867  * taken from xulrunner - nsNSSIOLayer.cpp
868  */
869 static PRBool
870 isTLSIntoleranceError(PRInt32 err)
871 {
872   switch (err) {
873   case SSL_ERROR_BAD_MAC_ALERT:
874   case SSL_ERROR_BAD_MAC_READ:
875   case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
876   case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
877   case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE:
878   case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
879   case SSL_ERROR_NO_CYPHER_OVERLAP:
880   case SSL_ERROR_BAD_SERVER:
881   case SSL_ERROR_BAD_BLOCK_PADDING:
882   case SSL_ERROR_UNSUPPORTED_VERSION:
883   case SSL_ERROR_PROTOCOL_VERSION_ALERT:
884   case SSL_ERROR_RX_MALFORMED_FINISHED:
885   case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE:
886   case SSL_ERROR_DECODE_ERROR_ALERT:
887   case SSL_ERROR_RX_UNKNOWN_ALERT:
888     return PR_TRUE;
889   default:
890     return PR_FALSE;
891   }
892 }
893
894 static CURLcode init_nss(struct SessionHandle *data)
895 {
896   char *cert_dir;
897   struct_stat st;
898   if(initialized)
899     return CURLE_OK;
900
901   /* First we check if $SSL_DIR points to a valid dir */
902   cert_dir = getenv("SSL_DIR");
903   if(cert_dir) {
904     if((stat(cert_dir, &st) != 0) ||
905         (!S_ISDIR(st.st_mode))) {
906       cert_dir = NULL;
907     }
908   }
909
910   /* Now we check if the default location is a valid dir */
911   if(!cert_dir) {
912     if((stat(SSL_DIR, &st) == 0) &&
913         (S_ISDIR(st.st_mode))) {
914       cert_dir = (char *)SSL_DIR;
915     }
916   }
917
918   if(!NSS_IsInitialized()) {
919     SECStatus rv;
920     initialized = 1;
921     infof(data, "Initializing NSS with certpath: %s\n",
922           cert_dir ? cert_dir : "none");
923     if(!cert_dir) {
924       rv = NSS_NoDB_Init(NULL);
925     }
926     else {
927       char *certpath =
928         PR_smprintf("%s%s", NSS_VersionCheck("3.12.0") ? "sql:" : "", cert_dir);
929       rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY);
930       PR_smprintf_free(certpath);
931     }
932     if(rv != SECSuccess) {
933       infof(data, "Unable to initialize NSS database\n");
934       initialized = 0;
935       return CURLE_SSL_CACERT_BADFILE;
936     }
937   }
938
939   if(num_enabled_ciphers() == 0)
940     NSS_SetDomesticPolicy();
941
942   return CURLE_OK;
943 }
944
945 /**
946  * Global SSL init
947  *
948  * @retval 0 error initializing SSL
949  * @retval 1 SSL initialized successfully
950  */
951 int Curl_nss_init(void)
952 {
953   /* curl_global_init() is not thread-safe so this test is ok */
954   if (nss_initlock == NULL) {
955     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
956     nss_initlock = PR_NewLock();
957     nss_crllock = PR_NewLock();
958   }
959
960   /* We will actually initialize NSS later */
961
962   return 1;
963 }
964
965 CURLcode Curl_nss_force_init(struct SessionHandle *data)
966 {
967   CURLcode rv;
968   if(!nss_initlock) {
969     failf(data, "unable to initialize NSS, curl_global_init() should have been "
970                 "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
971     return CURLE_OUT_OF_MEMORY;
972   }
973
974   PR_Lock(nss_initlock);
975   rv = init_nss(data);
976   PR_Unlock(nss_initlock);
977   return rv;
978 }
979
980 /* Global cleanup */
981 void Curl_nss_cleanup(void)
982 {
983   /* This function isn't required to be threadsafe and this is only done
984    * as a safety feature.
985    */
986   PR_Lock(nss_initlock);
987   if (initialized) {
988     /* Free references to client certificates held in the SSL session cache.
989      * Omitting this hampers destruction of the security module owning
990      * the certificates. */
991     SSL_ClearSessionCache();
992
993     if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
994       SECMOD_DestroyModule(mod);
995       mod = NULL;
996     }
997     NSS_Shutdown();
998   }
999   PR_Unlock(nss_initlock);
1000
1001   PR_DestroyLock(nss_initlock);
1002   PR_DestroyLock(nss_crllock);
1003   nss_initlock = NULL;
1004
1005   initialized = 0;
1006 }
1007
1008 /*
1009  * This function uses SSL_peek to determine connection status.
1010  *
1011  * Return codes:
1012  *     1 means the connection is still in place
1013  *     0 means the connection has been closed
1014  *    -1 means the connection status is unknown
1015  */
1016 int
1017 Curl_nss_check_cxn(struct connectdata *conn)
1018 {
1019   int rc;
1020   char buf;
1021
1022   rc =
1023     PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1024             PR_SecondsToInterval(1));
1025   if(rc > 0)
1026     return 1; /* connection still in place */
1027
1028   if(rc == 0)
1029     return 0; /* connection has been closed */
1030
1031   return -1;  /* connection status unknown */
1032 }
1033
1034 /*
1035  * This function is called when an SSL connection is closed.
1036  */
1037 void Curl_nss_close(struct connectdata *conn, int sockindex)
1038 {
1039   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1040
1041   if(connssl->handle) {
1042     PR_Close(connssl->handle);
1043
1044     /* NSS closes the socket we previously handed to it, so we must mark it
1045        as closed to avoid double close */
1046     fake_sclose(conn->sock[sockindex]);
1047     conn->sock[sockindex] = CURL_SOCKET_BAD;
1048     if(connssl->client_nickname != NULL) {
1049       free(connssl->client_nickname);
1050       connssl->client_nickname = NULL;
1051     }
1052 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1053     if(connssl->key)
1054       (void)PK11_DestroyGenericObject(connssl->key);
1055     if(connssl->cacert[1])
1056       (void)PK11_DestroyGenericObject(connssl->cacert[1]);
1057     if(connssl->cacert[0])
1058       (void)PK11_DestroyGenericObject(connssl->cacert[0]);
1059 #endif
1060     connssl->handle = NULL;
1061   }
1062 }
1063
1064 /*
1065  * This function is called when the 'data' struct is going away. Close
1066  * down everything and free all resources!
1067  */
1068 int Curl_nss_close_all(struct SessionHandle *data)
1069 {
1070   (void)data;
1071   return 0;
1072 }
1073
1074 /* handle client certificate related errors if any; return false otherwise */
1075 static bool handle_cc_error(PRInt32 err, struct SessionHandle *data)
1076 {
1077   switch(err) {
1078   case SSL_ERROR_BAD_CERT_ALERT:
1079     failf(data, "SSL error: SSL_ERROR_BAD_CERT_ALERT");
1080     return true;
1081
1082   case SSL_ERROR_REVOKED_CERT_ALERT:
1083     failf(data, "SSL error: SSL_ERROR_REVOKED_CERT_ALERT");
1084     return true;
1085
1086   case SSL_ERROR_EXPIRED_CERT_ALERT:
1087     failf(data, "SSL error: SSL_ERROR_EXPIRED_CERT_ALERT");
1088     return true;
1089
1090   default:
1091     return false;
1092   }
1093 }
1094
1095 static Curl_recv nss_recv;
1096 static Curl_send nss_send;
1097
1098 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1099 {
1100   PRInt32 err;
1101   PRFileDesc *model = NULL;
1102   PRBool ssl2 = PR_FALSE;
1103   PRBool ssl3 = PR_FALSE;
1104   PRBool tlsv1 = PR_FALSE;
1105   struct SessionHandle *data = conn->data;
1106   curl_socket_t sockfd = conn->sock[sockindex];
1107   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1108   int curlerr;
1109   const int *cipher_to_enable;
1110   PRSocketOptionData sock_opt;
1111   long time_left;
1112   PRUint32 timeout;
1113
1114   if (connssl->state == ssl_connection_complete)
1115     return CURLE_OK;
1116
1117   connssl->data = data;
1118
1119 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1120   connssl->cacert[0] = NULL;
1121   connssl->cacert[1] = NULL;
1122   connssl->key = NULL;
1123 #endif
1124
1125   /* FIXME. NSS doesn't support multiple databases open at the same time. */
1126   PR_Lock(nss_initlock);
1127   curlerr = init_nss(conn->data);
1128   if(CURLE_OK != curlerr) {
1129     PR_Unlock(nss_initlock);
1130     goto error;
1131   }
1132
1133   curlerr = CURLE_SSL_CONNECT_ERROR;
1134
1135 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1136   if(!mod) {
1137     char *configstring = aprintf("library=%s name=PEM", pem_library);
1138     if(!configstring) {
1139       PR_Unlock(nss_initlock);
1140       goto error;
1141     }
1142     mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1143     free(configstring);
1144
1145     if(!mod || !mod->loaded) {
1146       if(mod) {
1147         SECMOD_DestroyModule(mod);
1148         mod = NULL;
1149       }
1150       infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1151             "OpenSSL PEM certificates will not work.\n", pem_library);
1152     }
1153   }
1154 #endif
1155
1156   PK11_SetPasswordFunc(nss_get_password);
1157   PR_Unlock(nss_initlock);
1158
1159   model = PR_NewTCPSocket();
1160   if(!model)
1161     goto error;
1162   model = SSL_ImportFD(NULL, model);
1163
1164   /* make the socket nonblocking */
1165   sock_opt.option = PR_SockOpt_Nonblocking;
1166   sock_opt.value.non_blocking = PR_TRUE;
1167   if(PR_SetSocketOption(model, &sock_opt) != SECSuccess)
1168     goto error;
1169
1170   if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1171     goto error;
1172   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1173     goto error;
1174   if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1175     goto error;
1176
1177   switch (data->set.ssl.version) {
1178   default:
1179   case CURL_SSLVERSION_DEFAULT:
1180     ssl3 = PR_TRUE;
1181     if (data->state.ssl_connect_retry)
1182       infof(data, "TLS disabled due to previous handshake failure\n");
1183     else
1184       tlsv1 = PR_TRUE;
1185     break;
1186   case CURL_SSLVERSION_TLSv1:
1187     tlsv1 = PR_TRUE;
1188     break;
1189   case CURL_SSLVERSION_SSLv2:
1190     ssl2 = PR_TRUE;
1191     break;
1192   case CURL_SSLVERSION_SSLv3:
1193     ssl3 = PR_TRUE;
1194     break;
1195   }
1196
1197   if(SSL_OptionSet(model, SSL_ENABLE_SSL2, ssl2) != SECSuccess)
1198     goto error;
1199   if(SSL_OptionSet(model, SSL_ENABLE_SSL3, ssl3) != SECSuccess)
1200     goto error;
1201   if(SSL_OptionSet(model, SSL_ENABLE_TLS, tlsv1) != SECSuccess)
1202     goto error;
1203
1204   if(SSL_OptionSet(model, SSL_V2_COMPATIBLE_HELLO, ssl2) != SECSuccess)
1205     goto error;
1206
1207   /* reset the flag to avoid an infinite loop */
1208   data->state.ssl_connect_retry = FALSE;
1209
1210   /* enable all ciphers from enable_ciphers_by_default */
1211   cipher_to_enable = enable_ciphers_by_default;
1212   while (SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
1213     if (SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
1214       curlerr = CURLE_SSL_CIPHER;
1215       goto error;
1216     }
1217     cipher_to_enable++;
1218   }
1219
1220   if(data->set.ssl.cipher_list) {
1221     if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1222       curlerr = CURLE_SSL_CIPHER;
1223       goto error;
1224     }
1225   }
1226
1227   if(data->set.ssl.verifyhost == 1)
1228     infof(data, "warning: ignoring unsupported value (1) of ssl.verifyhost\n");
1229
1230   data->set.ssl.certverifyresult=0; /* not checked yet */
1231   if(SSL_BadCertHook(model, (SSLBadCertHandler) BadCertHandler, conn)
1232      != SECSuccess) {
1233     goto error;
1234   }
1235   if(SSL_HandshakeCallback(model, (SSLHandshakeCallback) HandshakeCallback,
1236                            NULL) != SECSuccess)
1237     goto error;
1238
1239   if(!data->set.ssl.verifypeer)
1240     /* skip the verifying of the peer */
1241     ;
1242   else if(data->set.ssl.CAfile) {
1243     int rc = nss_load_cert(&conn->ssl[sockindex], data->set.ssl.CAfile,
1244                            PR_TRUE);
1245     if(!rc) {
1246       curlerr = CURLE_SSL_CACERT_BADFILE;
1247       goto error;
1248     }
1249   }
1250   else if(data->set.ssl.CApath) {
1251     struct_stat st;
1252     PRDir      *dir;
1253     PRDirEntry *entry;
1254
1255     if(stat(data->set.ssl.CApath, &st) == -1) {
1256       curlerr = CURLE_SSL_CACERT_BADFILE;
1257       goto error;
1258     }
1259
1260     if(S_ISDIR(st.st_mode)) {
1261       int rc;
1262
1263       dir = PR_OpenDir(data->set.ssl.CApath);
1264       do {
1265         entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN);
1266
1267         if(entry) {
1268           char fullpath[PATH_MAX];
1269
1270           snprintf(fullpath, sizeof(fullpath), "%s/%s", data->set.ssl.CApath,
1271                    entry->name);
1272           rc = nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE);
1273           /* FIXME: check this return value! */
1274         }
1275         /* This is purposefully tolerant of errors so non-PEM files
1276          * can be in the same directory */
1277       } while(entry != NULL);
1278       PR_CloseDir(dir);
1279     }
1280   }
1281   infof(data,
1282         "  CAfile: %s\n"
1283         "  CApath: %s\n",
1284         data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
1285         data->set.ssl.CApath ? data->set.ssl.CApath : "none");
1286
1287   if (data->set.ssl.CRLfile) {
1288     if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) {
1289       curlerr = CURLE_SSL_CRL_BADFILE;
1290       goto error;
1291     }
1292     infof(data,
1293           "  CRLfile: %s\n",
1294           data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
1295   }
1296
1297   if(data->set.str[STRING_CERT]) {
1298     bool nickname_alloc = FALSE;
1299     char *nickname = fmt_nickname(data->set.str[STRING_CERT], &nickname_alloc);
1300     if(!nickname)
1301       return CURLE_OUT_OF_MEMORY;
1302
1303     if(!cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1304                    data->set.str[STRING_KEY])) {
1305       /* failf() is already done in cert_stuff() */
1306       if(nickname_alloc)
1307         free(nickname);
1308       return CURLE_SSL_CERTPROBLEM;
1309     }
1310
1311     /* this "takes over" the pointer to the allocated name or makes a
1312        dup of it */
1313     connssl->client_nickname = nickname_alloc?nickname:strdup(nickname);
1314     if(!connssl->client_nickname)
1315       return CURLE_OUT_OF_MEMORY;
1316
1317   }
1318   else
1319     connssl->client_nickname = NULL;
1320
1321   if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1322                                (void *)connssl) != SECSuccess) {
1323     curlerr = CURLE_SSL_CERTPROBLEM;
1324     goto error;
1325   }
1326
1327   /* Import our model socket  onto the existing file descriptor */
1328   connssl->handle = PR_ImportTCPSocket(sockfd);
1329   connssl->handle = SSL_ImportFD(model, connssl->handle);
1330   if(!connssl->handle)
1331     goto error;
1332
1333   PR_Close(model); /* We don't need this any more */
1334   model = NULL;
1335
1336   /* This is the password associated with the cert that we're using */
1337   if (data->set.str[STRING_KEY_PASSWD]) {
1338     SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1339   }
1340
1341   /* Force handshake on next I/O */
1342   SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1343
1344   SSL_SetURL(connssl->handle, conn->host.name);
1345
1346   /* check timeout situation */
1347   time_left = Curl_timeleft(conn, NULL, TRUE);
1348   if(time_left < 0L) {
1349     failf(data, "timed out before SSL handshake");
1350     goto error;
1351   }
1352   timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1353
1354   /* Force the handshake now */
1355   if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1356     if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1357       curlerr = CURLE_PEER_FAILED_VERIFICATION;
1358     else if(conn->data->set.ssl.certverifyresult!=0)
1359       curlerr = CURLE_SSL_CACERT;
1360     goto error;
1361   }
1362
1363   connssl->state = ssl_connection_complete;
1364   conn->recv[sockindex] = nss_recv;
1365   conn->send[sockindex] = nss_send;
1366
1367   display_conn_info(conn, connssl->handle);
1368
1369   if (data->set.str[STRING_SSL_ISSUERCERT]) {
1370     SECStatus ret;
1371     bool nickname_alloc = FALSE;
1372     char *nickname = fmt_nickname(data->set.str[STRING_SSL_ISSUERCERT],
1373                                   &nickname_alloc);
1374
1375     if(!nickname)
1376       return CURLE_OUT_OF_MEMORY;
1377
1378     ret = check_issuer_cert(connssl->handle, nickname);
1379
1380     if(nickname_alloc)
1381       free(nickname);
1382
1383     if(SECFailure == ret) {
1384       infof(data,"SSL certificate issuer check failed\n");
1385       curlerr = CURLE_SSL_ISSUER_ERROR;
1386       goto error;
1387     }
1388     else {
1389       infof(data, "SSL certificate issuer check ok\n");
1390     }
1391   }
1392
1393   return CURLE_OK;
1394
1395   error:
1396   /* reset the flag to avoid an infinite loop */
1397   data->state.ssl_connect_retry = FALSE;
1398
1399   err = PR_GetError();
1400   if(handle_cc_error(err, data))
1401     curlerr = CURLE_SSL_CERTPROBLEM;
1402   else
1403     infof(data, "NSS error %d\n", err);
1404
1405   if(model)
1406     PR_Close(model);
1407
1408   if (ssl3 && tlsv1 && isTLSIntoleranceError(err)) {
1409     /* schedule reconnect through Curl_retry_request() */
1410     data->state.ssl_connect_retry = TRUE;
1411     infof(data, "Error in TLS handshake, trying SSLv3...\n");
1412     return CURLE_OK;
1413   }
1414
1415   return curlerr;
1416 }
1417
1418 static ssize_t nss_send(struct connectdata *conn,  /* connection data */
1419                         int sockindex,             /* socketindex */
1420                         const void *mem,           /* send this data */
1421                         size_t len,                /* amount to write */
1422                         CURLcode *curlcode)
1423 {
1424   int rc;
1425
1426   rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0, -1);
1427
1428   if(rc < 0) {
1429     PRInt32 err = PR_GetError();
1430     if(err == PR_WOULD_BLOCK_ERROR)
1431       *curlcode = CURLE_AGAIN;
1432     else if(handle_cc_error(err, conn->data))
1433       *curlcode = CURLE_SSL_CERTPROBLEM;
1434     else {
1435       failf(conn->data, "SSL write: error %d", err);
1436       *curlcode = CURLE_SEND_ERROR;
1437     }
1438     return -1;
1439   }
1440   return rc; /* number of bytes */
1441 }
1442
1443 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1444                         int num,                   /* socketindex */
1445                         char *buf,                 /* store read data here */
1446                         size_t buffersize,         /* max amount to read */
1447                         CURLcode *curlcode)
1448 {
1449   ssize_t nread;
1450
1451   nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0, -1);
1452   if(nread < 0) {
1453     /* failed SSL read */
1454     PRInt32 err = PR_GetError();
1455
1456     if(err == PR_WOULD_BLOCK_ERROR)
1457       *curlcode = CURLE_AGAIN;
1458     else if(handle_cc_error(err, conn->data))
1459       *curlcode = CURLE_SSL_CERTPROBLEM;
1460     else {
1461       failf(conn->data, "SSL read: errno %d", err);
1462       *curlcode = CURLE_RECV_ERROR;
1463     }
1464     return -1;
1465   }
1466   return nread;
1467 }
1468
1469 size_t Curl_nss_version(char *buffer, size_t size)
1470 {
1471   return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
1472 }
1473
1474 int Curl_nss_seed(struct SessionHandle *data)
1475 {
1476   /* TODO: implement? */
1477   (void) data;
1478   return 0;
1479 }
1480
1481 #endif /* USE_NSS */