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