1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
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.
28 #include "curl_setup.h"
34 #include "formdata.h" /* for the boundary function */
35 #include "url.h" /* for the ssl config check function */
41 #include "curl_printf.h"
59 #include <keyhi.h> /* for SECKEY_DestroyPublicKey() */
61 #define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH)
63 #if NSSVERNUM >= 0x030f00 /* 3.15.0 */
71 /* The last #include files should be: */
72 #include "curl_memory.h"
75 #define SSL_DIR "/etc/pki/nssdb"
77 /* enough to fit the string "PEM Token #[0|1]" */
80 PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
81 static PRLock *nss_initlock = NULL;
82 static PRLock *nss_crllock = NULL;
83 static PRLock *nss_findslot_lock = NULL;
84 static struct curl_llist *nss_crl_list = NULL;
85 static NSSInitContext *nss_context = NULL;
86 static volatile int initialized = 0;
93 #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
94 CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
95 ptr->type = (_type); \
96 ptr->pValue = (_val); \
97 ptr->ulValueLen = (_len); \
100 #define CERT_NewTempCertificate __CERT_NewTempCertificate
102 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
103 static const cipher_s cipherlist[] = {
104 /* SSL2 cipher suites */
105 {"rc4", SSL_EN_RC4_128_WITH_MD5},
106 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
107 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
108 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
109 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
110 {"des", SSL_EN_DES_64_CBC_WITH_MD5},
111 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
112 /* SSL3/TLS cipher suites */
113 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
114 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
115 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
116 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
117 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
118 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
119 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
120 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
121 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
122 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
123 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
124 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
125 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
126 /* TLS 1.0: Exportable 56-bit Cipher Suites. */
127 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
128 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
130 {"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
131 {"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
132 {"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
133 {"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
134 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
135 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
137 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
138 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
139 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
140 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
141 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
142 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
143 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
144 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
145 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
146 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
147 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
148 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
149 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
150 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
151 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
152 {"ecdhe_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
153 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
154 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
155 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
156 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
157 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
158 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
159 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
160 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
161 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
162 #ifdef TLS_RSA_WITH_NULL_SHA256
163 /* new HMAC-SHA256 cipher suites specified in RFC */
164 {"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
165 {"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
166 {"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
167 {"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
168 {"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
169 {"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
170 {"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
172 #ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
173 /* AES GCM cipher suites in RFC 5288 and RFC 5289 */
174 {"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
175 {"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
176 {"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
177 {"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
178 {"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
179 {"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
180 {"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
182 #ifdef TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
183 /* cipher suites using SHA384 */
184 {"rsa_aes_256_gcm_sha_384", TLS_RSA_WITH_AES_256_GCM_SHA384},
185 {"dhe_rsa_aes_256_gcm_sha_384", TLS_DHE_RSA_WITH_AES_256_GCM_SHA384},
186 {"dhe_dss_aes_256_gcm_sha_384", TLS_DHE_DSS_WITH_AES_256_GCM_SHA384},
187 {"ecdhe_ecdsa_aes_256_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384},
188 {"ecdhe_rsa_aes_256_sha_384", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384},
189 {"ecdhe_ecdsa_aes_256_gcm_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
190 {"ecdhe_rsa_aes_256_gcm_sha_384", TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
192 #ifdef TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
193 /* chacha20-poly1305 cipher suites */
194 {"ecdhe_rsa_chacha20_poly1305_sha_256",
195 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
196 {"ecdhe_ecdsa_chacha20_poly1305_sha_256",
197 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256},
198 {"dhe_rsa_chacha20_poly1305_sha_256",
199 TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
203 static const char *pem_library = "libnsspem.so";
204 static SECMODModule *mod = NULL;
206 /* NSPR I/O layer we use to detect blocking direction during SSL handshake */
207 static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
208 static PRIOMethods nspr_io_methods;
210 static const char *nss_error_to_name(PRErrorCode code)
212 const char *name = PR_ErrorToName(code);
216 return "unknown error";
219 static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
221 failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
224 static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
228 PRBool cipher_state[NUM_OF_CIPHERS];
232 /* use accessors to avoid dynamic linking issues after an update of NSS */
233 const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
234 const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
235 if(!implemented_ciphers)
238 /* First disable all ciphers. This uses a different max value in case
239 * NSS adds more ciphers later we don't want them available by
242 for(i = 0; i < num_implemented_ciphers; i++) {
243 SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
246 /* Set every entry in our list to false */
247 for(i = 0; i < NUM_OF_CIPHERS; i++) {
248 cipher_state[i] = PR_FALSE;
251 cipher = cipher_list;
253 while(cipher_list && (cipher_list[0])) {
254 while((*cipher) && (ISSPACE(*cipher)))
257 cipher_list = strchr(cipher, ',');
259 *cipher_list++ = '\0';
264 for(i=0; i<NUM_OF_CIPHERS; i++) {
265 if(strcasecompare(cipher, cipherlist[i].name)) {
266 cipher_state[i] = PR_TRUE;
272 if(found == PR_FALSE) {
273 failf(data, "Unknown cipher in list: %s", cipher);
278 cipher = cipher_list;
282 /* Finally actually enable the selected ciphers */
283 for(i=0; i<NUM_OF_CIPHERS; i++) {
287 if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
288 failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
297 * Return true if at least one cipher-suite is enabled. Used to determine
298 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
300 static bool any_cipher_enabled(void)
304 for(i=0; i<NUM_OF_CIPHERS; i++) {
306 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
315 * Determine whether the nickname passed in is a filename that needs to
316 * be loaded as a PEM or a regular NSS nickname.
318 * returns 1 for a file
319 * returns 0 for not a file (NSS nickname)
321 static int is_file(const char *filename)
328 if(stat(filename, &st) == 0)
329 if(S_ISREG(st.st_mode))
335 /* Check if the given string is filename or nickname of a certificate. If the
336 * given string is recognized as filename, return NULL. If the given string is
337 * recognized as nickname, return a duplicated string. The returned string
338 * should be later deallocated using free(). If the OOM failure occurs, we
341 static char *dup_nickname(struct Curl_easy *data, const char *str)
346 /* no such file exists, use the string as nickname */
349 /* search the first slash; we require at least one slash in a file name */
350 n = strchr(str, '/');
352 infof(data, "warning: certificate file name \"%s\" handled as nickname; "
353 "please use \"./%s\" to force file name\n", str, str);
357 /* we'll use the PEM reader to read the certificate from file */
361 /* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition
362 * in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN. For more
363 * details, go to <https://bugzilla.mozilla.org/1297397>.
365 static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name)
368 PR_Lock(nss_findslot_lock);
369 slot = PK11_FindSlotByName(slot_name);
370 PR_Unlock(nss_findslot_lock);
374 /* Call PK11_CreateGenericObject() with the given obj_class and filename. If
375 * the call succeeds, append the object handle to the list of objects so that
376 * the object can be destroyed in Curl_nss_close(). */
377 static CURLcode nss_create_object(struct ssl_connect_data *ssl,
378 CK_OBJECT_CLASS obj_class,
379 const char *filename, bool cacert)
382 PK11GenericObject *obj;
383 CK_BBOOL cktrue = CK_TRUE;
384 CK_BBOOL ckfalse = CK_FALSE;
385 CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
387 CURLcode result = (cacert)
388 ? CURLE_SSL_CACERT_BADFILE
389 : CURLE_SSL_CERTPROBLEM;
391 const int slot_id = (cacert) ? 0 : 1;
392 char *slot_name = aprintf("PEM Token #%d", slot_id);
394 return CURLE_OUT_OF_MEMORY;
396 slot = nss_find_slot_by_name(slot_name);
401 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
402 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
403 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
404 strlen(filename) + 1);
406 if(CKO_CERTIFICATE == obj_class) {
407 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
408 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
411 obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
416 if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
417 PK11_DestroyGenericObject(obj);
418 return CURLE_OUT_OF_MEMORY;
421 if(!cacert && CKO_CERTIFICATE == obj_class)
422 /* store reference to a client certificate */
423 ssl->obj_clicert = obj;
428 /* Destroy the NSS object whose handle is given by ptr. This function is
429 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
430 * NSS objects in Curl_nss_close() */
431 static void nss_destroy_object(void *user, void *ptr)
433 PK11GenericObject *obj = (PK11GenericObject *)ptr;
435 PK11_DestroyGenericObject(obj);
438 /* same as nss_destroy_object() but for CRL items */
439 static void nss_destroy_crl_item(void *user, void *ptr)
441 SECItem *crl_der = (SECItem *)ptr;
443 SECITEM_FreeItem(crl_der, PR_TRUE);
446 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
447 const char *filename, PRBool cacert)
449 CURLcode result = (cacert)
450 ? CURLE_SSL_CACERT_BADFILE
451 : CURLE_SSL_CERTPROBLEM;
453 /* libnsspem.so leaks memory if the requested file does not exist. For more
454 * details, go to <https://bugzilla.redhat.com/734760>. */
455 if(is_file(filename))
456 result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
458 if(!result && !cacert) {
459 /* we have successfully loaded a client certificate */
460 CERTCertificate *cert;
461 char *nickname = NULL;
462 char *n = strrchr(filename, '/');
466 /* The following undocumented magic helps to avoid a SIGSEGV on call
467 * of PK11_ReadRawAttribute() from SelectClientCert() when using an
468 * immature version of libnsspem.so. For more details, go to
469 * <https://bugzilla.redhat.com/733685>. */
470 nickname = aprintf("PEM Token #1:%s", n);
472 cert = PK11_FindCertFromNickname(nickname, NULL);
474 CERT_DestroyCertificate(cert);
483 /* add given CRL to cache if it is not already there */
484 static CURLcode nss_cache_crl(SECItem *crl_der)
486 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
487 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
489 /* CRL already cached */
491 SECITEM_FreeItem(crl_der, PR_TRUE);
495 /* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
496 PR_Lock(nss_crllock);
498 /* store the CRL item so that we can free it in Curl_nss_cleanup() */
499 if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
500 SECITEM_FreeItem(crl_der, PR_TRUE);
501 PR_Unlock(nss_crllock);
502 return CURLE_OUT_OF_MEMORY;
505 if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
506 /* unable to cache CRL */
507 PR_Unlock(nss_crllock);
508 return CURLE_SSL_CRL_BADFILE;
511 /* we need to clear session cache, so that the CRL could take effect */
512 SSL_ClearSessionCache();
513 PR_Unlock(nss_crllock);
517 static CURLcode nss_load_crl(const char *crlfilename)
521 SECItem filedata = { 0, NULL, 0 };
522 SECItem *crl_der = NULL;
525 infile = PR_Open(crlfilename, PR_RDONLY, 0);
527 return CURLE_SSL_CRL_BADFILE;
529 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
532 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
535 if(info.size != PR_Read(infile, filedata.data, info.size))
538 crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
542 /* place a trailing zero right after the visible data */
543 body = (char *)filedata.data;
544 body[--filedata.len] = '\0';
546 body = strstr(body, "-----BEGIN");
550 char *begin = PORT_Strchr(body, '\n');
552 begin = PORT_Strchr(body, '\r');
556 trailer = strstr(++begin, "-----END");
560 /* retrieve DER from ASCII */
562 if(ATOB_ConvertAsciiToItem(crl_der, begin))
565 SECITEM_FreeItem(&filedata, PR_FALSE);
572 return nss_cache_crl(crl_der);
576 SECITEM_FreeItem(crl_der, PR_TRUE);
577 SECITEM_FreeItem(&filedata, PR_FALSE);
578 return CURLE_SSL_CRL_BADFILE;
581 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
587 struct ssl_connect_data *ssl = conn->ssl;
588 struct Curl_easy *data = conn->data;
590 (void)sockindex; /* unused */
592 result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
594 PR_SetError(SEC_ERROR_BAD_KEY, 0);
598 slot = nss_find_slot_by_name("PEM Token #1");
600 return CURLE_SSL_CERTPROBLEM;
602 /* This will force the token to be seen as re-inserted */
603 SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
604 PK11_IsPresent(slot);
606 status = PK11_Authenticate(slot, PR_TRUE, SSL_SET_OPTION(key_passwd));
609 return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
612 static int display_error(struct connectdata *conn, PRInt32 err,
613 const char *filename)
616 case SEC_ERROR_BAD_PASSWORD:
617 failf(conn->data, "Unable to load client key: Incorrect password");
619 case SEC_ERROR_UNKNOWN_CERT:
620 failf(conn->data, "Unable to load certificate %s", filename);
625 return 0; /* The caller will print a generic error */
628 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
629 char *cert_file, char *key_file)
631 struct Curl_easy *data = conn->data;
635 result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
637 const PRErrorCode err = PR_GetError();
638 if(!display_error(conn, err, cert_file)) {
639 const char *err_name = nss_error_to_name(err);
640 failf(data, "unable to load client cert: %d (%s)", err, err_name);
647 if(key_file || (is_file(cert_file))) {
649 result = nss_load_key(conn, sockindex, key_file);
651 /* In case the cert file also has the key */
652 result = nss_load_key(conn, sockindex, cert_file);
654 const PRErrorCode err = PR_GetError();
655 if(!display_error(conn, err, key_file)) {
656 const char *err_name = nss_error_to_name(err);
657 failf(data, "unable to load client key: %d (%s)", err, err_name);
667 static char *nss_get_password(PK11SlotInfo *slot, PRBool retry, void *arg)
669 (void)slot; /* unused */
671 if(retry || NULL == arg)
674 return (char *)PORT_Strdup((char *)arg);
677 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
679 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
682 struct connectdata *conn = (struct connectdata *)arg;
684 #ifdef SSL_ENABLE_OCSP_STAPLING
685 if(SSL_CONN_CONFIG(verifystatus)) {
686 SECStatus cacheResult;
688 const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
690 failf(conn->data, "Invalid OCSP response");
695 failf(conn->data, "No OCSP response received");
699 cacheResult = CERT_CacheOCSPResponseFromSideChannel(
700 CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
701 PR_Now(), &csa->items[0], arg
704 if(cacheResult != SECSuccess) {
705 failf(conn->data, "Invalid OCSP response");
711 if(!SSL_CONN_CONFIG(verifypeer)) {
712 infof(conn->data, "skipping SSL peer certificate verification\n");
716 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
720 * Inform the application that the handshake is complete.
722 static void HandshakeCallback(PRFileDesc *sock, void *arg)
724 struct connectdata *conn = (struct connectdata*) arg;
725 unsigned int buflenmax = 50;
726 unsigned char buf[50];
728 SSLNextProtoState state;
730 if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
734 if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
737 #if NSSVERNUM >= 0x031a00 /* 3.26.0 */
738 /* used by NSS internally to implement 0-RTT */
739 case SSL_NEXT_PROTO_EARLY_VALUE:
742 case SSL_NEXT_PROTO_NO_SUPPORT:
743 case SSL_NEXT_PROTO_NO_OVERLAP:
744 infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
746 #ifdef SSL_ENABLE_ALPN
747 case SSL_NEXT_PROTO_SELECTED:
748 infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
751 case SSL_NEXT_PROTO_NEGOTIATED:
752 infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
757 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
758 !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
759 conn->negnpn = CURL_HTTP_VERSION_2;
763 if(buflen == ALPN_HTTP_1_1_LENGTH &&
764 !memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
765 conn->negnpn = CURL_HTTP_VERSION_1_1;
770 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
771 static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
772 PRBool *canFalseStart)
774 struct connectdata *conn = client_data;
775 struct Curl_easy *data = conn->data;
777 SSLChannelInfo channelInfo;
778 SSLCipherSuiteInfo cipherInfo;
781 PRBool negotiatedExtension;
783 *canFalseStart = PR_FALSE;
785 if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
788 if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
789 sizeof(cipherInfo)) != SECSuccess)
792 /* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
793 * TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
795 if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
798 /* Only allow ECDHE key exchange algorithm.
799 * See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
800 if(cipherInfo.keaType != ssl_kea_ecdh)
803 /* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
804 * mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
805 * design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
806 if(cipherInfo.symCipher != ssl_calg_aes_gcm)
809 /* Enforce ALPN or NPN to do False Start, as an indicator of server
811 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
812 &negotiatedExtension);
813 if(rv != SECSuccess || !negotiatedExtension) {
814 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
815 &negotiatedExtension);
818 if(rv != SECSuccess || !negotiatedExtension)
821 *canFalseStart = PR_TRUE;
823 infof(data, "Trying TLS False Start\n");
830 static void display_cert_info(struct Curl_easy *data,
831 CERTCertificate *cert)
833 char *subject, *issuer, *common_name;
834 PRExplodedTime printableTime;
835 char timeString[256];
836 PRTime notBefore, notAfter;
838 subject = CERT_NameToAscii(&cert->subject);
839 issuer = CERT_NameToAscii(&cert->issuer);
840 common_name = CERT_GetCommonName(&cert->subject);
841 infof(data, "\tsubject: %s\n", subject);
843 CERT_GetCertTimes(cert, ¬Before, ¬After);
844 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
845 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
846 infof(data, "\tstart date: %s\n", timeString);
847 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
848 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
849 infof(data, "\texpire date: %s\n", timeString);
850 infof(data, "\tcommon name: %s\n", common_name);
851 infof(data, "\tissuer: %s\n", issuer);
855 PR_Free(common_name);
858 static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
860 CURLcode result = CURLE_OK;
861 SSLChannelInfo channel;
862 SSLCipherSuiteInfo suite;
863 CERTCertificate *cert;
864 CERTCertificate *cert2;
865 CERTCertificate *cert3;
869 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
870 SECSuccess && channel.length == sizeof channel &&
871 channel.cipherSuite) {
872 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
873 &suite, sizeof suite) == SECSuccess) {
874 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
878 cert = SSL_PeerCertificate(sock);
880 infof(conn->data, "Server certificate:\n");
882 if(!conn->data->set.ssl.certinfo) {
883 display_cert_info(conn->data, cert);
884 CERT_DestroyCertificate(cert);
887 /* Count certificates in chain. */
891 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
895 CERT_DestroyCertificate(cert2);
898 cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
899 CERT_DestroyCertificate(cert2);
904 result = Curl_ssl_init_certinfo(conn->data, i);
906 for(i = 0; cert; cert = cert2) {
907 result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
908 (char *)cert->derCert.data +
914 CERT_DestroyCertificate(cert);
918 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
919 CERT_DestroyCertificate(cert);
928 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
930 struct connectdata *conn = (struct connectdata *)arg;
931 struct Curl_easy *data = conn->data;
932 PRErrorCode err = PR_GetError();
933 CERTCertificate *cert;
935 /* remember the cert verification result */
937 data->set.proxy_ssl.certverifyresult = err;
939 data->set.ssl.certverifyresult = err;
941 if(err == SSL_ERROR_BAD_CERT_DOMAIN && !SSL_CONN_CONFIG(verifyhost))
942 /* we are asked not to verify the host name */
945 /* print only info about the cert, the error is printed off the callback */
946 cert = SSL_PeerCertificate(sock);
948 infof(data, "Server certificate:\n");
949 display_cert_info(data, cert);
950 CERT_DestroyCertificate(cert);
958 * Check that the Peer certificate's issuer certificate matches the one found
959 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
960 * issuer check, so we provide comments that mimic the OpenSSL
961 * X509_check_issued function (in x509v3/v3_purp.c)
963 static SECStatus check_issuer_cert(PRFileDesc *sock,
964 char *issuer_nickname)
966 CERTCertificate *cert, *cert_issuer, *issuer;
967 SECStatus res=SECSuccess;
968 void *proto_win = NULL;
970 cert = SSL_PeerCertificate(sock);
971 cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
973 proto_win = SSL_RevealPinArg(sock);
974 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
976 if((!cert_issuer) || (!issuer))
978 else if(SECITEM_CompareItem(&cert_issuer->derCert,
979 &issuer->derCert)!=SECEqual)
982 CERT_DestroyCertificate(cert);
983 CERT_DestroyCertificate(issuer);
984 CERT_DestroyCertificate(cert_issuer);
988 static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
989 const char *pinnedpubkey)
991 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
992 struct Curl_easy *data = connssl->data;
993 CERTCertificate *cert;
996 /* no pinned public key specified */
999 /* get peer certificate */
1000 cert = SSL_PeerCertificate(connssl->handle);
1002 /* extract public key from peer certificate */
1003 SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
1005 /* encode the public key as DER */
1006 SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
1008 /* compare the public key with the pinned public key */
1009 result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data,
1011 SECITEM_FreeItem(cert_der, PR_TRUE);
1013 SECKEY_DestroyPublicKey(pubkey);
1015 CERT_DestroyCertificate(cert);
1018 /* report the resulting status */
1021 infof(data, "pinned public key verified successfully!\n");
1023 case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
1024 failf(data, "failed to verify pinned public key");
1036 * Callback to pick the SSL client certificate.
1038 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
1039 struct CERTDistNamesStr *caNames,
1040 struct CERTCertificateStr **pRetCert,
1041 struct SECKEYPrivateKeyStr **pRetKey)
1043 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
1044 struct Curl_easy *data = connssl->data;
1045 const char *nickname = connssl->client_nickname;
1046 static const char pem_slotname[] = "PEM Token #1";
1048 if(connssl->obj_clicert) {
1049 /* use the cert/key provided by PEM reader */
1050 SECItem cert_der = { 0, NULL, 0 };
1051 void *proto_win = SSL_RevealPinArg(sock);
1052 struct CERTCertificateStr *cert;
1053 struct SECKEYPrivateKeyStr *key;
1055 PK11SlotInfo *slot = nss_find_slot_by_name(pem_slotname);
1057 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
1061 if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
1062 &cert_der) != SECSuccess) {
1063 failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
1064 PK11_FreeSlot(slot);
1068 cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
1069 SECITEM_FreeItem(&cert_der, PR_FALSE);
1071 failf(data, "NSS: client certificate from file not found");
1072 PK11_FreeSlot(slot);
1076 key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
1077 PK11_FreeSlot(slot);
1079 failf(data, "NSS: private key from file not found");
1080 CERT_DestroyCertificate(cert);
1084 infof(data, "NSS: client certificate from file\n");
1085 display_cert_info(data, cert);
1092 /* use the default NSS hook */
1093 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
1095 || NULL == *pRetCert) {
1097 if(NULL == nickname)
1098 failf(data, "NSS: client certificate not found (nickname not "
1101 failf(data, "NSS: client certificate not found: %s", nickname);
1106 /* get certificate nickname if any */
1107 nickname = (*pRetCert)->nickname;
1108 if(NULL == nickname)
1109 nickname = "[unknown]";
1111 if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) {
1112 failf(data, "NSS: refusing previously loaded certificate from file: %s",
1117 if(NULL == *pRetKey) {
1118 failf(data, "NSS: private key not found for certificate: %s", nickname);
1122 infof(data, "NSS: using client certificate: %s\n", nickname);
1123 display_cert_info(data, *pRetCert);
1127 /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
1128 static void nss_update_connecting_state(ssl_connect_state state, void *secret)
1130 struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
1131 if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
1132 /* an unrelated error is passing by */
1135 switch(connssl->connecting_state) {
1137 case ssl_connect_2_reading:
1138 case ssl_connect_2_writing:
1141 /* we are not called from an SSL handshake */
1145 /* update the state accordingly */
1146 connssl->connecting_state = state;
1149 /* recv() wrapper we use to detect blocking direction during SSL handshake */
1150 static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
1151 PRIntn flags, PRIntervalTime timeout)
1153 const PRRecvFN recv_fn = fd->lower->methods->recv;
1154 const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
1156 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1157 nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
1161 /* send() wrapper we use to detect blocking direction during SSL handshake */
1162 static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
1163 PRIntn flags, PRIntervalTime timeout)
1165 const PRSendFN send_fn = fd->lower->methods->send;
1166 const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
1168 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1169 nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
1173 /* close() wrapper to avoid assertion failure due to fd->secret != NULL */
1174 static PRStatus nspr_io_close(PRFileDesc *fd)
1176 const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
1178 return close_fn(fd);
1181 /* data might be NULL */
1182 static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
1184 NSSInitParameters initparams;
1186 if(nss_context != NULL)
1189 memset((void *) &initparams, '\0', sizeof(initparams));
1190 initparams.length = sizeof(initparams);
1193 char *certpath = aprintf("sql:%s", cert_dir);
1195 return CURLE_OUT_OF_MEMORY;
1197 infof(data, "Initializing NSS with certpath: %s\n", certpath);
1198 nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
1199 NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
1202 if(nss_context != NULL)
1205 infof(data, "Unable to initialize NSS database\n");
1208 infof(data, "Initializing NSS with certpath: none\n");
1209 nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
1210 | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
1211 | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
1212 if(nss_context != NULL)
1215 infof(data, "Unable to initialize NSS\n");
1216 return CURLE_SSL_CACERT_BADFILE;
1219 /* data might be NULL */
1220 static CURLcode nss_init(struct Curl_easy *data)
1229 /* list of all CRL items we need to destroy in Curl_nss_cleanup() */
1230 nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
1232 return CURLE_OUT_OF_MEMORY;
1234 /* First we check if $SSL_DIR points to a valid dir */
1235 cert_dir = getenv("SSL_DIR");
1237 if((stat(cert_dir, &st) != 0) ||
1238 (!S_ISDIR(st.st_mode))) {
1243 /* Now we check if the default location is a valid dir */
1245 if((stat(SSL_DIR, &st) == 0) &&
1246 (S_ISDIR(st.st_mode))) {
1247 cert_dir = (char *)SSL_DIR;
1251 if(nspr_io_identity == PR_INVALID_IO_LAYER) {
1252 /* allocate an identity for our own NSPR I/O layer */
1253 nspr_io_identity = PR_GetUniqueIdentity("libcurl");
1254 if(nspr_io_identity == PR_INVALID_IO_LAYER)
1255 return CURLE_OUT_OF_MEMORY;
1257 /* the default methods just call down to the lower I/O layer */
1258 memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
1260 /* override certain methods in the table by our wrappers */
1261 nspr_io_methods.recv = nspr_io_recv;
1262 nspr_io_methods.send = nspr_io_send;
1263 nspr_io_methods.close = nspr_io_close;
1266 result = nss_init_core(data, cert_dir);
1270 if(!any_cipher_enabled())
1271 NSS_SetDomesticPolicy();
1281 * @retval 0 error initializing SSL
1282 * @retval 1 SSL initialized successfully
1284 int Curl_nss_init(void)
1286 /* curl_global_init() is not thread-safe so this test is ok */
1287 if(nss_initlock == NULL) {
1288 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
1289 nss_initlock = PR_NewLock();
1290 nss_crllock = PR_NewLock();
1291 nss_findslot_lock = PR_NewLock();
1294 /* We will actually initialize NSS later */
1299 /* data might be NULL */
1300 CURLcode Curl_nss_force_init(struct Curl_easy *data)
1305 failf(data, "unable to initialize NSS, curl_global_init() should have "
1306 "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1307 return CURLE_FAILED_INIT;
1310 PR_Lock(nss_initlock);
1311 result = nss_init(data);
1312 PR_Unlock(nss_initlock);
1317 /* Global cleanup */
1318 void Curl_nss_cleanup(void)
1320 /* This function isn't required to be threadsafe and this is only done
1321 * as a safety feature.
1323 PR_Lock(nss_initlock);
1325 /* Free references to client certificates held in the SSL session cache.
1326 * Omitting this hampers destruction of the security module owning
1327 * the certificates. */
1328 SSL_ClearSessionCache();
1330 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1331 SECMOD_DestroyModule(mod);
1334 NSS_ShutdownContext(nss_context);
1338 /* destroy all CRL items */
1339 Curl_llist_destroy(nss_crl_list, NULL);
1340 nss_crl_list = NULL;
1342 PR_Unlock(nss_initlock);
1344 PR_DestroyLock(nss_initlock);
1345 PR_DestroyLock(nss_crllock);
1346 PR_DestroyLock(nss_findslot_lock);
1347 nss_initlock = NULL;
1353 * This function uses SSL_peek to determine connection status.
1356 * 1 means the connection is still in place
1357 * 0 means the connection has been closed
1358 * -1 means the connection status is unknown
1361 Curl_nss_check_cxn(struct connectdata *conn)
1367 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1368 PR_SecondsToInterval(1));
1370 return 1; /* connection still in place */
1373 return 0; /* connection has been closed */
1375 return -1; /* connection status unknown */
1378 static void nss_close(struct ssl_connect_data *connssl)
1380 /* before the cleanup, check whether we are using a client certificate */
1381 const bool client_cert = (connssl->client_nickname != NULL)
1382 || (connssl->obj_clicert != NULL);
1384 free(connssl->client_nickname);
1385 connssl->client_nickname = NULL;
1387 /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1388 Curl_llist_destroy(connssl->obj_list, NULL);
1389 connssl->obj_list = NULL;
1390 connssl->obj_clicert = NULL;
1392 if(connssl->handle) {
1394 /* A server might require different authentication based on the
1395 * particular path being requested by the client. To support this
1396 * scenario, we must ensure that a connection will never reuse the
1397 * authentication data from a previous connection. */
1398 SSL_InvalidateSession(connssl->handle);
1400 PR_Close(connssl->handle);
1401 connssl->handle = NULL;
1406 * This function is called when an SSL connection is closed.
1408 void Curl_nss_close(struct connectdata *conn, int sockindex)
1410 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1411 struct ssl_connect_data *connssl_proxy = &conn->proxy_ssl[sockindex];
1413 if(connssl->handle || connssl_proxy->handle) {
1414 /* NSS closes the socket we previously handed to it, so we must mark it
1415 as closed to avoid double close */
1416 fake_sclose(conn->sock[sockindex]);
1417 conn->sock[sockindex] = CURL_SOCKET_BAD;
1421 /* nss_close(connssl) will transitively close also connssl_proxy->handle
1422 if both are used. Clear it to avoid a double close leading to crash. */
1423 connssl_proxy->handle = NULL;
1426 nss_close(connssl_proxy);
1429 /* return true if NSS can provide error code (and possibly msg) for the
1431 static bool is_nss_error(CURLcode err)
1434 case CURLE_PEER_FAILED_VERIFICATION:
1435 case CURLE_SSL_CACERT:
1436 case CURLE_SSL_CERTPROBLEM:
1437 case CURLE_SSL_CONNECT_ERROR:
1438 case CURLE_SSL_ISSUER_ERROR:
1446 /* return true if the given error code is related to a client certificate */
1447 static bool is_cc_error(PRInt32 err)
1450 case SSL_ERROR_BAD_CERT_ALERT:
1451 case SSL_ERROR_EXPIRED_CERT_ALERT:
1452 case SSL_ERROR_REVOKED_CERT_ALERT:
1460 static Curl_recv nss_recv;
1461 static Curl_send nss_send;
1463 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1466 struct Curl_easy *data = conn->data;
1467 const char *cafile = SSL_CONN_CONFIG(CAfile);
1468 const char *capath = SSL_CONN_CONFIG(CApath);
1471 CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1478 if(stat(capath, &st) == -1)
1479 return CURLE_SSL_CACERT_BADFILE;
1481 if(S_ISDIR(st.st_mode)) {
1483 PRDir *dir = PR_OpenDir(capath);
1485 return CURLE_SSL_CACERT_BADFILE;
1487 while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1488 char *fullpath = aprintf("%s/%s", capath, entry->name);
1491 return CURLE_OUT_OF_MEMORY;
1494 if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1495 /* This is purposefully tolerant of errors so non-PEM files can
1496 * be in the same directory */
1497 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1505 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1508 infof(data, " CAfile: %s\n CApath: %s\n",
1509 cafile ? cafile : "none",
1510 capath ? capath : "none");
1515 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1516 struct Curl_easy *data,
1517 struct connectdata *conn)
1519 switch(SSL_CONN_CONFIG(version)) {
1520 case CURL_SSLVERSION_DEFAULT:
1521 /* map CURL_SSLVERSION_DEFAULT to NSS default */
1522 if(SSL_VersionRangeGetDefault(ssl_variant_stream, sslver) != SECSuccess)
1523 return CURLE_SSL_CONNECT_ERROR;
1524 /* ... but make sure we use at least TLSv1.0 according to libcurl API */
1525 if(sslver->min < SSL_LIBRARY_VERSION_TLS_1_0)
1526 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1529 case CURL_SSLVERSION_TLSv1:
1530 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1531 /* TODO: set sslver->max to SSL_LIBRARY_VERSION_TLS_1_3 once stable */
1532 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1533 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1534 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1535 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1537 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1541 case CURL_SSLVERSION_SSLv2:
1542 sslver->min = SSL_LIBRARY_VERSION_2;
1543 sslver->max = SSL_LIBRARY_VERSION_2;
1546 case CURL_SSLVERSION_SSLv3:
1547 sslver->min = SSL_LIBRARY_VERSION_3_0;
1548 sslver->max = SSL_LIBRARY_VERSION_3_0;
1551 case CURL_SSLVERSION_TLSv1_0:
1552 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1553 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1556 case CURL_SSLVERSION_TLSv1_1:
1557 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1558 sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1559 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1564 case CURL_SSLVERSION_TLSv1_2:
1565 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1566 sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1567 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1572 case CURL_SSLVERSION_TLSv1_3:
1573 #ifdef SSL_LIBRARY_VERSION_TLS_1_3
1574 sslver->min = SSL_LIBRARY_VERSION_TLS_1_3;
1575 sslver->max = SSL_LIBRARY_VERSION_TLS_1_3;
1581 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
1582 return CURLE_SSL_CONNECT_ERROR;
1585 failf(data, "TLS minor version cannot be set");
1586 return CURLE_SSL_CONNECT_ERROR;
1589 static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
1590 struct Curl_easy *data,
1593 PRErrorCode err = 0;
1595 if(is_nss_error(curlerr)) {
1596 /* read NSPR error code */
1597 err = PR_GetError();
1598 if(is_cc_error(err))
1599 curlerr = CURLE_SSL_CERTPROBLEM;
1601 /* print the error number and error string */
1602 infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1604 /* print a human-readable message describing the error if available */
1605 nss_print_error_message(data, err);
1608 /* cleanup on connection failure */
1609 Curl_llist_destroy(connssl->obj_list, NULL);
1610 connssl->obj_list = NULL;
1615 /* Switch the SSL socket into blocking or non-blocking mode. */
1616 static CURLcode nss_set_blocking(struct ssl_connect_data *connssl,
1617 struct Curl_easy *data,
1620 static PRSocketOptionData sock_opt;
1621 sock_opt.option = PR_SockOpt_Nonblocking;
1622 sock_opt.value.non_blocking = !blocking;
1624 if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1625 return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
1630 static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
1632 PRFileDesc *model = NULL;
1633 PRFileDesc *nspr_io = NULL;
1634 PRFileDesc *nspr_io_stub = NULL;
1635 PRBool ssl_no_cache;
1636 PRBool ssl_cbc_random_iv;
1637 struct Curl_easy *data = conn->data;
1638 curl_socket_t sockfd = conn->sock[sockindex];
1639 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1641 bool second_layer = FALSE;
1643 SSLVersionRange sslver = {
1644 SSL_LIBRARY_VERSION_TLS_1_0, /* min */
1645 SSL_LIBRARY_VERSION_TLS_1_0 /* max */
1648 connssl->data = data;
1650 /* list of all NSS objects we need to destroy in Curl_nss_close() */
1651 connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1652 if(!connssl->obj_list)
1653 return CURLE_OUT_OF_MEMORY;
1655 /* FIXME. NSS doesn't support multiple databases open at the same time. */
1656 PR_Lock(nss_initlock);
1657 result = nss_init(conn->data);
1659 PR_Unlock(nss_initlock);
1663 result = CURLE_SSL_CONNECT_ERROR;
1666 char *configstring = aprintf("library=%s name=PEM", pem_library);
1668 PR_Unlock(nss_initlock);
1671 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1674 if(!mod || !mod->loaded) {
1676 SECMOD_DestroyModule(mod);
1679 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1680 "OpenSSL PEM certificates will not work.\n", pem_library);
1684 PK11_SetPasswordFunc(nss_get_password);
1685 PR_Unlock(nss_initlock);
1687 model = PR_NewTCPSocket();
1690 model = SSL_ImportFD(NULL, model);
1692 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1694 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1696 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1699 /* do not use SSL cache if disabled or we are not going to verify peer */
1700 ssl_no_cache = (data->set.general_ssl.sessionid
1701 && SSL_CONN_CONFIG(verifypeer)) ? PR_FALSE : PR_TRUE;
1702 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1705 /* enable/disable the requested SSL version(s) */
1706 if(nss_init_sslver(&sslver, data, conn) != CURLE_OK)
1708 if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1711 ssl_cbc_random_iv = !SSL_SET_OPTION(enable_beast);
1712 #ifdef SSL_CBC_RANDOM_IV
1713 /* unless the user explicitly asks to allow the protocol vulnerability, we
1714 use the work-around */
1715 if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1716 infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1719 if(ssl_cbc_random_iv)
1720 infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1723 if(SSL_CONN_CONFIG(cipher_list)) {
1724 if(set_ciphers(data, model, SSL_CONN_CONFIG(cipher_list)) != SECSuccess) {
1725 result = CURLE_SSL_CIPHER;
1730 if(!SSL_CONN_CONFIG(verifypeer) && SSL_CONN_CONFIG(verifyhost))
1731 infof(data, "warning: ignoring value of ssl.verifyhost\n");
1733 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1735 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1738 /* not checked yet */
1740 data->set.proxy_ssl.certverifyresult = 0;
1742 data->set.ssl.certverifyresult = 0;
1744 if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1747 if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
1750 if(SSL_CONN_CONFIG(verifypeer)) {
1751 const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1758 if(SSL_SET_OPTION(CRLfile)) {
1759 const CURLcode rv = nss_load_crl(SSL_SET_OPTION(CRLfile));
1764 infof(data, " CRLfile: %s\n", SSL_SET_OPTION(CRLfile));
1767 if(SSL_SET_OPTION(cert)) {
1768 char *nickname = dup_nickname(data, SSL_SET_OPTION(cert));
1770 /* we are not going to use libnsspem.so to read the client cert */
1771 connssl->obj_clicert = NULL;
1774 CURLcode rv = cert_stuff(conn, sockindex, SSL_SET_OPTION(cert),
1775 SSL_SET_OPTION(key));
1777 /* failf() is already done in cert_stuff() */
1783 /* store the nickname for SelectClientCert() called during handshake */
1784 connssl->client_nickname = nickname;
1787 connssl->client_nickname = NULL;
1789 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1790 (void *)connssl) != SECSuccess) {
1791 result = CURLE_SSL_CERTPROBLEM;
1795 if(conn->proxy_ssl[sockindex].use) {
1796 DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
1797 DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
1798 nspr_io = conn->proxy_ssl[sockindex].handle;
1799 second_layer = TRUE;
1802 /* wrap OS file descriptor by NSPR's file descriptor abstraction */
1803 nspr_io = PR_ImportTCPSocket(sockfd);
1808 /* create our own NSPR I/O layer */
1809 nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
1816 /* make the per-connection data accessible from NSPR I/O callbacks */
1817 nspr_io_stub->secret = (void *)connssl;
1819 /* push our new layer to the NSPR I/O stack */
1820 if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
1823 PR_Close(nspr_io_stub);
1827 /* import our model socket onto the current I/O stack */
1828 connssl->handle = SSL_ImportFD(model, nspr_io);
1829 if(!connssl->handle) {
1835 PR_Close(model); /* We don't need this any more */
1838 /* This is the password associated with the cert that we're using */
1839 if(SSL_SET_OPTION(key_passwd)) {
1840 SSL_SetPKCS11PinArg(connssl->handle, SSL_SET_OPTION(key_passwd));
1843 #ifdef SSL_ENABLE_OCSP_STAPLING
1844 if(SSL_CONN_CONFIG(verifystatus)) {
1845 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
1851 #ifdef SSL_ENABLE_NPN
1852 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
1853 ? PR_TRUE : PR_FALSE) != SECSuccess)
1857 #ifdef SSL_ENABLE_ALPN
1858 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
1859 ? PR_TRUE : PR_FALSE) != SECSuccess)
1863 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
1864 if(data->set.ssl.falsestart) {
1865 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
1869 if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
1870 conn) != SECSuccess)
1875 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
1876 if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
1878 unsigned char protocols[128];
1881 if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
1882 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
1883 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
1884 NGHTTP2_PROTO_VERSION_ID_LEN);
1885 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1888 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
1889 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1890 cur += ALPN_HTTP_1_1_LENGTH;
1892 if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
1898 /* Force handshake on next I/O */
1899 if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE)
1903 /* propagate hostname to the TLS layer */
1904 if(SSL_SetURL(connssl->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name :
1905 conn->host.name) != SECSuccess)
1908 /* prevent NSS from re-using the session for a different hostname */
1909 if(SSL_SetSockPeerID(connssl->handle, SSL_IS_PROXY() ?
1910 conn->http_proxy.host.name : conn->host.name)
1920 return nss_fail_connect(connssl, data, result);
1923 static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
1925 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1926 struct Curl_easy *data = conn->data;
1927 CURLcode result = CURLE_SSL_CONNECT_ERROR;
1929 long * const certverifyresult = SSL_IS_PROXY() ?
1930 &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
1931 const char * const pinnedpubkey = SSL_IS_PROXY() ?
1932 data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
1933 data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
1936 /* check timeout situation */
1937 const long time_left = Curl_timeleft(data, NULL, TRUE);
1938 if(time_left < 0L) {
1939 failf(data, "timed out before SSL handshake");
1940 result = CURLE_OPERATION_TIMEDOUT;
1944 /* Force the handshake now */
1945 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1946 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1947 if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
1948 /* blocking direction is updated by nss_update_connecting_state() */
1950 else if(*certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1951 result = CURLE_PEER_FAILED_VERIFICATION;
1952 else if(*certverifyresult != 0)
1953 result = CURLE_SSL_CACERT;
1957 result = display_conn_info(conn, connssl->handle);
1961 if(SSL_SET_OPTION(issuercert)) {
1962 SECStatus ret = SECFailure;
1963 char *nickname = dup_nickname(data, SSL_SET_OPTION(issuercert));
1965 /* we support only nicknames in case of issuercert for now */
1966 ret = check_issuer_cert(connssl->handle, nickname);
1970 if(SECFailure == ret) {
1971 infof(data, "SSL certificate issuer check failed\n");
1972 result = CURLE_SSL_ISSUER_ERROR;
1976 infof(data, "SSL certificate issuer check ok\n");
1980 result = cmp_peer_pubkey(connssl, pinnedpubkey);
1982 /* status already printed */
1988 return nss_fail_connect(connssl, data, result);
1991 static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
1994 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1995 struct Curl_easy *data = conn->data;
1996 const bool blocking = (done == NULL);
1999 if(connssl->state == ssl_connection_complete) {
2005 if(connssl->connecting_state == ssl_connect_1) {
2006 result = nss_setup_connect(conn, sockindex);
2008 /* we do not expect CURLE_AGAIN from nss_setup_connect() */
2011 connssl->connecting_state = ssl_connect_2;
2014 /* enable/disable blocking mode before handshake */
2015 result = nss_set_blocking(connssl, data, blocking);
2019 result = nss_do_connect(conn, sockindex);
2025 /* CURLE_AGAIN in non-blocking mode is not an error */
2033 /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
2034 result = nss_set_blocking(connssl, data, /* blocking */ FALSE);
2039 /* signal completed SSL handshake */
2042 connssl->state = ssl_connection_complete;
2043 conn->recv[sockindex] = nss_recv;
2044 conn->send[sockindex] = nss_send;
2046 /* ssl_connect_done is never used outside, go back to the initial state */
2047 connssl->connecting_state = ssl_connect_1;
2052 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
2054 return nss_connect_common(conn, sockindex, /* blocking */ NULL);
2057 CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
2058 int sockindex, bool *done)
2060 return nss_connect_common(conn, sockindex, done);
2063 static ssize_t nss_send(struct connectdata *conn, /* connection data */
2064 int sockindex, /* socketindex */
2065 const void *mem, /* send this data */
2066 size_t len, /* amount to write */
2069 ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
2070 PR_INTERVAL_NO_WAIT);
2072 PRInt32 err = PR_GetError();
2073 if(err == PR_WOULD_BLOCK_ERROR)
2074 *curlcode = CURLE_AGAIN;
2076 /* print the error number and error string */
2077 const char *err_name = nss_error_to_name(err);
2078 infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
2080 /* print a human-readable message describing the error if available */
2081 nss_print_error_message(conn->data, err);
2083 *curlcode = (is_cc_error(err))
2084 ? CURLE_SSL_CERTPROBLEM
2091 return rc; /* number of bytes */
2094 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
2095 int num, /* socketindex */
2096 char *buf, /* store read data here */
2097 size_t buffersize, /* max amount to read */
2100 ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
2101 PR_INTERVAL_NO_WAIT);
2103 /* failed SSL read */
2104 PRInt32 err = PR_GetError();
2106 if(err == PR_WOULD_BLOCK_ERROR)
2107 *curlcode = CURLE_AGAIN;
2109 /* print the error number and error string */
2110 const char *err_name = nss_error_to_name(err);
2111 infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
2113 /* print a human-readable message describing the error if available */
2114 nss_print_error_message(conn->data, err);
2116 *curlcode = (is_cc_error(err))
2117 ? CURLE_SSL_CERTPROBLEM
2127 size_t Curl_nss_version(char *buffer, size_t size)
2129 return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
2132 /* data might be NULL */
2133 int Curl_nss_seed(struct Curl_easy *data)
2135 /* make sure that NSS is initialized */
2136 return !!Curl_nss_force_init(data);
2139 /* data might be NULL */
2140 CURLcode Curl_nss_random(struct Curl_easy *data,
2141 unsigned char *entropy,
2144 Curl_nss_seed(data); /* Initiate the seed if not already done */
2146 if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
2147 /* signal a failure */
2148 return CURLE_FAILED_INIT;
2153 void Curl_nss_md5sum(unsigned char *tmp, /* input */
2155 unsigned char *md5sum, /* output */
2158 PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
2159 unsigned int MD5out;
2161 PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
2162 PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
2163 PK11_DestroyContext(MD5pw, PR_TRUE);
2166 void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
2168 unsigned char *sha256sum, /* output */
2171 PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
2172 unsigned int SHA256out;
2174 PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
2175 PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
2176 PK11_DestroyContext(SHA256pw, PR_TRUE);
2179 bool Curl_nss_cert_status_request(void)
2181 #ifdef SSL_ENABLE_OCSP_STAPLING
2188 bool Curl_nss_false_start(void)
2190 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
2197 #endif /* USE_NSS */