source: UsbWattMeter/trunk/curl-7.47.1/lib/vtls/nss.c@ 167

Last change on this file since 167 was 167, checked in by coas-nagasima, 8 years ago

MIMEにSJISを設定

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