1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, 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 {"echde_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},
184 static const char* pem_library = "libnsspem.so";
185 static SECMODModule* mod = NULL;
187 /* NSPR I/O layer we use to detect blocking direction during SSL handshake */
188 static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
189 static PRIOMethods nspr_io_methods;
191 static const char* nss_error_to_name(PRErrorCode code)
193 const char *name = PR_ErrorToName(code);
197 return "unknown error";
200 static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
202 failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
205 static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
209 PRBool cipher_state[NUM_OF_CIPHERS];
213 /* use accessors to avoid dynamic linking issues after an update of NSS */
214 const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
215 const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
216 if(!implemented_ciphers)
219 /* First disable all ciphers. This uses a different max value in case
220 * NSS adds more ciphers later we don't want them available by
223 for(i = 0; i < num_implemented_ciphers; i++) {
224 SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
227 /* Set every entry in our list to false */
228 for(i = 0; i < NUM_OF_CIPHERS; i++) {
229 cipher_state[i] = PR_FALSE;
232 cipher = cipher_list;
234 while(cipher_list && (cipher_list[0])) {
235 while((*cipher) && (ISSPACE(*cipher)))
238 if((cipher_list = strchr(cipher, ','))) {
239 *cipher_list++ = '\0';
244 for(i=0; i<NUM_OF_CIPHERS; i++) {
245 if(Curl_raw_equal(cipher, cipherlist[i].name)) {
246 cipher_state[i] = PR_TRUE;
252 if(found == PR_FALSE) {
253 failf(data, "Unknown cipher in list: %s", cipher);
258 cipher = cipher_list;
262 /* Finally actually enable the selected ciphers */
263 for(i=0; i<NUM_OF_CIPHERS; i++) {
267 if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
268 failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
277 * Return true if at least one cipher-suite is enabled. Used to determine
278 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
280 static bool any_cipher_enabled(void)
284 for(i=0; i<NUM_OF_CIPHERS; i++) {
286 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
295 * Determine whether the nickname passed in is a filename that needs to
296 * be loaded as a PEM or a regular NSS nickname.
298 * returns 1 for a file
299 * returns 0 for not a file (NSS nickname)
301 static int is_file(const char *filename)
308 if(stat(filename, &st) == 0)
309 if(S_ISREG(st.st_mode))
315 /* Check if the given string is filename or nickname of a certificate. If the
316 * given string is recognized as filename, return NULL. If the given string is
317 * recognized as nickname, return a duplicated string. The returned string
318 * should be later deallocated using free(). If the OOM failure occurs, we
321 static char* dup_nickname(struct Curl_easy *data, enum dupstring cert_kind)
323 const char *str = data->set.str[cert_kind];
327 /* no such file exists, use the string as nickname */
330 /* search the first slash; we require at least one slash in a file name */
331 n = strchr(str, '/');
333 infof(data, "warning: certificate file name \"%s\" handled as nickname; "
334 "please use \"./%s\" to force file name\n", str, str);
338 /* we'll use the PEM reader to read the certificate from file */
342 /* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition
343 * in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN. For more
344 * details, go to <https://bugzilla.mozilla.org/1297397>.
346 static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name)
349 PR_Lock(nss_initlock);
350 slot = PK11_FindSlotByName(slot_name);
351 PR_Unlock(nss_initlock);
355 /* Call PK11_CreateGenericObject() with the given obj_class and filename. If
356 * the call succeeds, append the object handle to the list of objects so that
357 * the object can be destroyed in Curl_nss_close(). */
358 static CURLcode nss_create_object(struct ssl_connect_data *ssl,
359 CK_OBJECT_CLASS obj_class,
360 const char *filename, bool cacert)
363 PK11GenericObject *obj;
364 CK_BBOOL cktrue = CK_TRUE;
365 CK_BBOOL ckfalse = CK_FALSE;
366 CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
368 CURLcode result = (cacert)
369 ? CURLE_SSL_CACERT_BADFILE
370 : CURLE_SSL_CERTPROBLEM;
372 const int slot_id = (cacert) ? 0 : 1;
373 char *slot_name = aprintf("PEM Token #%d", slot_id);
375 return CURLE_OUT_OF_MEMORY;
377 slot = nss_find_slot_by_name(slot_name);
382 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
383 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
384 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
385 strlen(filename) + 1);
387 if(CKO_CERTIFICATE == obj_class) {
388 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
389 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
392 obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
397 if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
398 PK11_DestroyGenericObject(obj);
399 return CURLE_OUT_OF_MEMORY;
402 if(!cacert && CKO_CERTIFICATE == obj_class)
403 /* store reference to a client certificate */
404 ssl->obj_clicert = obj;
409 /* Destroy the NSS object whose handle is given by ptr. This function is
410 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
411 * NSS objects in Curl_nss_close() */
412 static void nss_destroy_object(void *user, void *ptr)
414 PK11GenericObject *obj = (PK11GenericObject *)ptr;
416 PK11_DestroyGenericObject(obj);
419 /* same as nss_destroy_object() but for CRL items */
420 static void nss_destroy_crl_item(void *user, void *ptr)
422 SECItem *crl_der = (SECItem *)ptr;
424 SECITEM_FreeItem(crl_der, PR_TRUE);
427 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
428 const char *filename, PRBool cacert)
430 CURLcode result = (cacert)
431 ? CURLE_SSL_CACERT_BADFILE
432 : CURLE_SSL_CERTPROBLEM;
434 /* libnsspem.so leaks memory if the requested file does not exist. For more
435 * details, go to <https://bugzilla.redhat.com/734760>. */
436 if(is_file(filename))
437 result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
439 if(!result && !cacert) {
440 /* we have successfully loaded a client certificate */
441 CERTCertificate *cert;
442 char *nickname = NULL;
443 char *n = strrchr(filename, '/');
447 /* The following undocumented magic helps to avoid a SIGSEGV on call
448 * of PK11_ReadRawAttribute() from SelectClientCert() when using an
449 * immature version of libnsspem.so. For more details, go to
450 * <https://bugzilla.redhat.com/733685>. */
451 nickname = aprintf("PEM Token #1:%s", n);
453 cert = PK11_FindCertFromNickname(nickname, NULL);
455 CERT_DestroyCertificate(cert);
464 /* add given CRL to cache if it is not already there */
465 static CURLcode nss_cache_crl(SECItem *crl_der)
467 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
468 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
470 /* CRL already cached */
472 SECITEM_FreeItem(crl_der, PR_TRUE);
476 /* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
477 PR_Lock(nss_crllock);
479 /* store the CRL item so that we can free it in Curl_nss_cleanup() */
480 if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
481 SECITEM_FreeItem(crl_der, PR_TRUE);
482 PR_Unlock(nss_crllock);
483 return CURLE_OUT_OF_MEMORY;
486 if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
487 /* unable to cache CRL */
488 PR_Unlock(nss_crllock);
489 return CURLE_SSL_CRL_BADFILE;
492 /* we need to clear session cache, so that the CRL could take effect */
493 SSL_ClearSessionCache();
494 PR_Unlock(nss_crllock);
498 static CURLcode nss_load_crl(const char* crlfilename)
502 SECItem filedata = { 0, NULL, 0 };
503 SECItem *crl_der = NULL;
506 infile = PR_Open(crlfilename, PR_RDONLY, 0);
508 return CURLE_SSL_CRL_BADFILE;
510 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
513 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
516 if(info.size != PR_Read(infile, filedata.data, info.size))
519 crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
523 /* place a trailing zero right after the visible data */
524 body = (char*)filedata.data;
525 body[--filedata.len] = '\0';
527 body = strstr(body, "-----BEGIN");
531 char *begin = PORT_Strchr(body, '\n');
533 begin = PORT_Strchr(body, '\r');
537 trailer = strstr(++begin, "-----END");
541 /* retrieve DER from ASCII */
543 if(ATOB_ConvertAsciiToItem(crl_der, begin))
546 SECITEM_FreeItem(&filedata, PR_FALSE);
553 return nss_cache_crl(crl_der);
557 SECITEM_FreeItem(crl_der, PR_TRUE);
558 SECITEM_FreeItem(&filedata, PR_FALSE);
559 return CURLE_SSL_CRL_BADFILE;
562 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
568 struct ssl_connect_data *ssl = conn->ssl;
570 (void)sockindex; /* unused */
572 result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
574 PR_SetError(SEC_ERROR_BAD_KEY, 0);
578 slot = nss_find_slot_by_name("PEM Token #1");
580 return CURLE_SSL_CERTPROBLEM;
582 /* This will force the token to be seen as re-inserted */
583 SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
584 PK11_IsPresent(slot);
586 status = PK11_Authenticate(slot, PR_TRUE,
587 conn->data->set.str[STRING_KEY_PASSWD]);
590 return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
593 static int display_error(struct connectdata *conn, PRInt32 err,
594 const char *filename)
597 case SEC_ERROR_BAD_PASSWORD:
598 failf(conn->data, "Unable to load client key: Incorrect password");
600 case SEC_ERROR_UNKNOWN_CERT:
601 failf(conn->data, "Unable to load certificate %s", filename);
606 return 0; /* The caller will print a generic error */
609 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
610 char *cert_file, char *key_file)
612 struct Curl_easy *data = conn->data;
616 result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
618 const PRErrorCode err = PR_GetError();
619 if(!display_error(conn, err, cert_file)) {
620 const char *err_name = nss_error_to_name(err);
621 failf(data, "unable to load client cert: %d (%s)", err, err_name);
628 if(key_file || (is_file(cert_file))) {
630 result = nss_load_key(conn, sockindex, key_file);
632 /* In case the cert file also has the key */
633 result = nss_load_key(conn, sockindex, cert_file);
635 const PRErrorCode err = PR_GetError();
636 if(!display_error(conn, err, key_file)) {
637 const char *err_name = nss_error_to_name(err);
638 failf(data, "unable to load client key: %d (%s)", err, err_name);
648 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
650 (void)slot; /* unused */
652 if(retry || NULL == arg)
655 return (char *)PORT_Strdup((char *)arg);
658 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
660 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
663 struct connectdata *conn = (struct connectdata *)arg;
665 #ifdef SSL_ENABLE_OCSP_STAPLING
666 if(conn->data->set.ssl.verifystatus) {
667 SECStatus cacheResult;
669 const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
671 failf(conn->data, "Invalid OCSP response");
676 failf(conn->data, "No OCSP response received");
680 cacheResult = CERT_CacheOCSPResponseFromSideChannel(
681 CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
682 PR_Now(), &csa->items[0], arg
685 if(cacheResult != SECSuccess) {
686 failf(conn->data, "Invalid OCSP response");
692 if(!conn->data->set.ssl.verifypeer) {
693 infof(conn->data, "skipping SSL peer certificate verification\n");
697 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
701 * Inform the application that the handshake is complete.
703 static void HandshakeCallback(PRFileDesc *sock, void *arg)
705 struct connectdata *conn = (struct connectdata*) arg;
706 unsigned int buflenmax = 50;
707 unsigned char buf[50];
709 SSLNextProtoState state;
711 if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
715 if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
718 case SSL_NEXT_PROTO_NO_SUPPORT:
719 case SSL_NEXT_PROTO_NO_OVERLAP:
720 infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
722 #ifdef SSL_ENABLE_ALPN
723 case SSL_NEXT_PROTO_SELECTED:
724 infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
727 case SSL_NEXT_PROTO_NEGOTIATED:
728 infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
733 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
734 !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
735 conn->negnpn = CURL_HTTP_VERSION_2;
739 if(buflen == ALPN_HTTP_1_1_LENGTH &&
740 !memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
741 conn->negnpn = CURL_HTTP_VERSION_1_1;
746 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
747 static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
748 PRBool *canFalseStart)
750 struct connectdata *conn = client_data;
751 struct Curl_easy *data = conn->data;
753 SSLChannelInfo channelInfo;
754 SSLCipherSuiteInfo cipherInfo;
757 PRBool negotiatedExtension;
759 *canFalseStart = PR_FALSE;
761 if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
764 if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
765 sizeof(cipherInfo)) != SECSuccess)
768 /* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
769 * TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
771 if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
774 /* Only allow ECDHE key exchange algorithm.
775 * See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
776 if(cipherInfo.keaType != ssl_kea_ecdh)
779 /* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
780 * mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
781 * design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
782 if(cipherInfo.symCipher != ssl_calg_aes_gcm)
785 /* Enforce ALPN or NPN to do False Start, as an indicator of server
787 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
788 &negotiatedExtension);
789 if(rv != SECSuccess || !negotiatedExtension) {
790 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
791 &negotiatedExtension);
794 if(rv != SECSuccess || !negotiatedExtension)
797 *canFalseStart = PR_TRUE;
799 infof(data, "Trying TLS False Start\n");
806 static void display_cert_info(struct Curl_easy *data,
807 CERTCertificate *cert)
809 char *subject, *issuer, *common_name;
810 PRExplodedTime printableTime;
811 char timeString[256];
812 PRTime notBefore, notAfter;
814 subject = CERT_NameToAscii(&cert->subject);
815 issuer = CERT_NameToAscii(&cert->issuer);
816 common_name = CERT_GetCommonName(&cert->subject);
817 infof(data, "\tsubject: %s\n", subject);
819 CERT_GetCertTimes(cert, ¬Before, ¬After);
820 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
821 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
822 infof(data, "\tstart date: %s\n", timeString);
823 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
824 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
825 infof(data, "\texpire date: %s\n", timeString);
826 infof(data, "\tcommon name: %s\n", common_name);
827 infof(data, "\tissuer: %s\n", issuer);
831 PR_Free(common_name);
834 static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
836 CURLcode result = CURLE_OK;
837 SSLChannelInfo channel;
838 SSLCipherSuiteInfo suite;
839 CERTCertificate *cert;
840 CERTCertificate *cert2;
841 CERTCertificate *cert3;
845 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
846 SECSuccess && channel.length == sizeof channel &&
847 channel.cipherSuite) {
848 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
849 &suite, sizeof suite) == SECSuccess) {
850 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
854 cert = SSL_PeerCertificate(sock);
856 infof(conn->data, "Server certificate:\n");
858 if(!conn->data->set.ssl.certinfo) {
859 display_cert_info(conn->data, cert);
860 CERT_DestroyCertificate(cert);
863 /* Count certificates in chain. */
867 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
871 CERT_DestroyCertificate(cert2);
874 cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
875 CERT_DestroyCertificate(cert2);
880 result = Curl_ssl_init_certinfo(conn->data, i);
882 for(i = 0; cert; cert = cert2) {
883 result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
884 (char *)cert->derCert.data +
890 CERT_DestroyCertificate(cert);
894 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
895 CERT_DestroyCertificate(cert);
904 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
906 struct connectdata *conn = (struct connectdata *)arg;
907 struct Curl_easy *data = conn->data;
908 PRErrorCode err = PR_GetError();
909 CERTCertificate *cert;
911 /* remember the cert verification result */
912 data->set.ssl.certverifyresult = err;
914 if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
915 /* we are asked not to verify the host name */
918 /* print only info about the cert, the error is printed off the callback */
919 cert = SSL_PeerCertificate(sock);
921 infof(data, "Server certificate:\n");
922 display_cert_info(data, cert);
923 CERT_DestroyCertificate(cert);
931 * Check that the Peer certificate's issuer certificate matches the one found
932 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
933 * issuer check, so we provide comments that mimic the OpenSSL
934 * X509_check_issued function (in x509v3/v3_purp.c)
936 static SECStatus check_issuer_cert(PRFileDesc *sock,
937 char *issuer_nickname)
939 CERTCertificate *cert, *cert_issuer, *issuer;
940 SECStatus res=SECSuccess;
941 void *proto_win = NULL;
943 cert = SSL_PeerCertificate(sock);
944 cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
946 proto_win = SSL_RevealPinArg(sock);
947 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
949 if((!cert_issuer) || (!issuer))
951 else if(SECITEM_CompareItem(&cert_issuer->derCert,
952 &issuer->derCert)!=SECEqual)
955 CERT_DestroyCertificate(cert);
956 CERT_DestroyCertificate(issuer);
957 CERT_DestroyCertificate(cert_issuer);
961 static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
962 const char *pinnedpubkey)
964 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
965 struct Curl_easy *data = connssl->data;
966 CERTCertificate *cert;
969 /* no pinned public key specified */
972 /* get peer certificate */
973 cert = SSL_PeerCertificate(connssl->handle);
975 /* extract public key from peer certificate */
976 SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
978 /* encode the public key as DER */
979 SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
981 /* compare the public key with the pinned public key */
982 result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data,
984 SECITEM_FreeItem(cert_der, PR_TRUE);
986 SECKEY_DestroyPublicKey(pubkey);
988 CERT_DestroyCertificate(cert);
991 /* report the resulting status */
994 infof(data, "pinned public key verified successfully!\n");
996 case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
997 failf(data, "failed to verify pinned public key");
1009 * Callback to pick the SSL client certificate.
1011 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
1012 struct CERTDistNamesStr *caNames,
1013 struct CERTCertificateStr **pRetCert,
1014 struct SECKEYPrivateKeyStr **pRetKey)
1016 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
1017 struct Curl_easy *data = connssl->data;
1018 const char *nickname = connssl->client_nickname;
1019 static const char pem_slotname[] = "PEM Token #1";
1021 if(connssl->obj_clicert) {
1022 /* use the cert/key provided by PEM reader */
1023 SECItem cert_der = { 0, NULL, 0 };
1024 void *proto_win = SSL_RevealPinArg(sock);
1025 struct CERTCertificateStr *cert;
1026 struct SECKEYPrivateKeyStr *key;
1028 PK11SlotInfo *slot = nss_find_slot_by_name(pem_slotname);
1030 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
1034 if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
1035 &cert_der) != SECSuccess) {
1036 failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
1037 PK11_FreeSlot(slot);
1041 cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
1042 SECITEM_FreeItem(&cert_der, PR_FALSE);
1044 failf(data, "NSS: client certificate from file not found");
1045 PK11_FreeSlot(slot);
1049 key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
1050 PK11_FreeSlot(slot);
1052 failf(data, "NSS: private key from file not found");
1053 CERT_DestroyCertificate(cert);
1057 infof(data, "NSS: client certificate from file\n");
1058 display_cert_info(data, cert);
1065 /* use the default NSS hook */
1066 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
1068 || NULL == *pRetCert) {
1070 if(NULL == nickname)
1071 failf(data, "NSS: client certificate not found (nickname not "
1074 failf(data, "NSS: client certificate not found: %s", nickname);
1079 /* get certificate nickname if any */
1080 nickname = (*pRetCert)->nickname;
1081 if(NULL == nickname)
1082 nickname = "[unknown]";
1084 if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) {
1085 failf(data, "NSS: refusing previously loaded certificate from file: %s",
1090 if(NULL == *pRetKey) {
1091 failf(data, "NSS: private key not found for certificate: %s", nickname);
1095 infof(data, "NSS: using client certificate: %s\n", nickname);
1096 display_cert_info(data, *pRetCert);
1100 /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
1101 static void nss_update_connecting_state(ssl_connect_state state, void *secret)
1103 struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
1104 if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
1105 /* an unrelated error is passing by */
1108 switch(connssl->connecting_state) {
1110 case ssl_connect_2_reading:
1111 case ssl_connect_2_writing:
1114 /* we are not called from an SSL handshake */
1118 /* update the state accordingly */
1119 connssl->connecting_state = state;
1122 /* recv() wrapper we use to detect blocking direction during SSL handshake */
1123 static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
1124 PRIntn flags, PRIntervalTime timeout)
1126 const PRRecvFN recv_fn = fd->lower->methods->recv;
1127 const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
1129 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1130 nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
1134 /* send() wrapper we use to detect blocking direction during SSL handshake */
1135 static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
1136 PRIntn flags, PRIntervalTime timeout)
1138 const PRSendFN send_fn = fd->lower->methods->send;
1139 const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
1141 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1142 nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
1146 /* close() wrapper to avoid assertion failure due to fd->secret != NULL */
1147 static PRStatus nspr_io_close(PRFileDesc *fd)
1149 const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
1151 return close_fn(fd);
1154 /* data might be NULL */
1155 static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
1157 NSSInitParameters initparams;
1159 if(nss_context != NULL)
1162 memset((void *) &initparams, '\0', sizeof(initparams));
1163 initparams.length = sizeof(initparams);
1166 char *certpath = aprintf("sql:%s", cert_dir);
1168 return CURLE_OUT_OF_MEMORY;
1170 infof(data, "Initializing NSS with certpath: %s\n", certpath);
1171 nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
1172 NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
1175 if(nss_context != NULL)
1178 infof(data, "Unable to initialize NSS database\n");
1181 infof(data, "Initializing NSS with certpath: none\n");
1182 nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
1183 | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
1184 | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
1185 if(nss_context != NULL)
1188 infof(data, "Unable to initialize NSS\n");
1189 return CURLE_SSL_CACERT_BADFILE;
1192 /* data might be NULL */
1193 static CURLcode nss_init(struct Curl_easy *data)
1202 /* list of all CRL items we need to destroy in Curl_nss_cleanup() */
1203 nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
1205 return CURLE_OUT_OF_MEMORY;
1207 /* First we check if $SSL_DIR points to a valid dir */
1208 cert_dir = getenv("SSL_DIR");
1210 if((stat(cert_dir, &st) != 0) ||
1211 (!S_ISDIR(st.st_mode))) {
1216 /* Now we check if the default location is a valid dir */
1218 if((stat(SSL_DIR, &st) == 0) &&
1219 (S_ISDIR(st.st_mode))) {
1220 cert_dir = (char *)SSL_DIR;
1224 if(nspr_io_identity == PR_INVALID_IO_LAYER) {
1225 /* allocate an identity for our own NSPR I/O layer */
1226 nspr_io_identity = PR_GetUniqueIdentity("libcurl");
1227 if(nspr_io_identity == PR_INVALID_IO_LAYER)
1228 return CURLE_OUT_OF_MEMORY;
1230 /* the default methods just call down to the lower I/O layer */
1231 memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
1233 /* override certain methods in the table by our wrappers */
1234 nspr_io_methods.recv = nspr_io_recv;
1235 nspr_io_methods.send = nspr_io_send;
1236 nspr_io_methods.close = nspr_io_close;
1239 result = nss_init_core(data, cert_dir);
1243 if(!any_cipher_enabled())
1244 NSS_SetDomesticPolicy();
1254 * @retval 0 error initializing SSL
1255 * @retval 1 SSL initialized successfully
1257 int Curl_nss_init(void)
1259 /* curl_global_init() is not thread-safe so this test is ok */
1260 if(nss_initlock == NULL) {
1261 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
1262 nss_initlock = PR_NewLock();
1263 nss_crllock = PR_NewLock();
1264 nss_findslot_lock = PR_NewLock();
1267 /* We will actually initialize NSS later */
1272 /* data might be NULL */
1273 CURLcode Curl_nss_force_init(struct Curl_easy *data)
1278 failf(data, "unable to initialize NSS, curl_global_init() should have "
1279 "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1280 return CURLE_FAILED_INIT;
1283 PR_Lock(nss_initlock);
1284 result = nss_init(data);
1285 PR_Unlock(nss_initlock);
1290 /* Global cleanup */
1291 void Curl_nss_cleanup(void)
1293 /* This function isn't required to be threadsafe and this is only done
1294 * as a safety feature.
1296 PR_Lock(nss_initlock);
1298 /* Free references to client certificates held in the SSL session cache.
1299 * Omitting this hampers destruction of the security module owning
1300 * the certificates. */
1301 SSL_ClearSessionCache();
1303 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1304 SECMOD_DestroyModule(mod);
1307 NSS_ShutdownContext(nss_context);
1311 /* destroy all CRL items */
1312 Curl_llist_destroy(nss_crl_list, NULL);
1313 nss_crl_list = NULL;
1315 PR_Unlock(nss_initlock);
1317 PR_DestroyLock(nss_initlock);
1318 PR_DestroyLock(nss_crllock);
1319 PR_DestroyLock(nss_findslot_lock);
1320 nss_initlock = NULL;
1326 * This function uses SSL_peek to determine connection status.
1329 * 1 means the connection is still in place
1330 * 0 means the connection has been closed
1331 * -1 means the connection status is unknown
1334 Curl_nss_check_cxn(struct connectdata *conn)
1340 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1341 PR_SecondsToInterval(1));
1343 return 1; /* connection still in place */
1346 return 0; /* connection has been closed */
1348 return -1; /* connection status unknown */
1352 * This function is called when an SSL connection is closed.
1354 void Curl_nss_close(struct connectdata *conn, int sockindex)
1356 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1358 if(connssl->handle) {
1359 /* NSS closes the socket we previously handed to it, so we must mark it
1360 as closed to avoid double close */
1361 fake_sclose(conn->sock[sockindex]);
1362 conn->sock[sockindex] = CURL_SOCKET_BAD;
1364 if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
1365 /* A server might require different authentication based on the
1366 * particular path being requested by the client. To support this
1367 * scenario, we must ensure that a connection will never reuse the
1368 * authentication data from a previous connection. */
1369 SSL_InvalidateSession(connssl->handle);
1371 free(connssl->client_nickname);
1372 connssl->client_nickname = NULL;
1373 /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1374 Curl_llist_destroy(connssl->obj_list, NULL);
1375 connssl->obj_list = NULL;
1376 connssl->obj_clicert = NULL;
1378 PR_Close(connssl->handle);
1379 connssl->handle = NULL;
1383 /* return true if NSS can provide error code (and possibly msg) for the
1385 static bool is_nss_error(CURLcode err)
1388 case CURLE_PEER_FAILED_VERIFICATION:
1389 case CURLE_SSL_CACERT:
1390 case CURLE_SSL_CERTPROBLEM:
1391 case CURLE_SSL_CONNECT_ERROR:
1392 case CURLE_SSL_ISSUER_ERROR:
1400 /* return true if the given error code is related to a client certificate */
1401 static bool is_cc_error(PRInt32 err)
1404 case SSL_ERROR_BAD_CERT_ALERT:
1405 case SSL_ERROR_EXPIRED_CERT_ALERT:
1406 case SSL_ERROR_REVOKED_CERT_ALERT:
1414 static Curl_recv nss_recv;
1415 static Curl_send nss_send;
1417 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1420 struct Curl_easy *data = conn->data;
1421 const char *cafile = data->set.ssl.CAfile;
1422 const char *capath = data->set.ssl.CApath;
1425 CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1432 if(stat(capath, &st) == -1)
1433 return CURLE_SSL_CACERT_BADFILE;
1435 if(S_ISDIR(st.st_mode)) {
1437 PRDir *dir = PR_OpenDir(capath);
1439 return CURLE_SSL_CACERT_BADFILE;
1441 while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1442 char *fullpath = aprintf("%s/%s", capath, entry->name);
1445 return CURLE_OUT_OF_MEMORY;
1448 if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1449 /* This is purposefully tolerant of errors so non-PEM files can
1450 * be in the same directory */
1451 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1459 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1462 infof(data, " CAfile: %s\n CApath: %s\n",
1463 cafile ? cafile : "none",
1464 capath ? capath : "none");
1469 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1470 struct Curl_easy *data)
1472 switch(data->set.ssl.version) {
1474 case CURL_SSLVERSION_DEFAULT:
1475 case CURL_SSLVERSION_TLSv1:
1476 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1477 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1478 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1479 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1480 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1482 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1486 case CURL_SSLVERSION_SSLv2:
1487 sslver->min = SSL_LIBRARY_VERSION_2;
1488 sslver->max = SSL_LIBRARY_VERSION_2;
1491 case CURL_SSLVERSION_SSLv3:
1492 sslver->min = SSL_LIBRARY_VERSION_3_0;
1493 sslver->max = SSL_LIBRARY_VERSION_3_0;
1496 case CURL_SSLVERSION_TLSv1_0:
1497 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1498 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1501 case CURL_SSLVERSION_TLSv1_1:
1502 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1503 sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1504 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1509 case CURL_SSLVERSION_TLSv1_2:
1510 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1511 sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1512 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1518 failf(data, "TLS minor version cannot be set");
1519 return CURLE_SSL_CONNECT_ERROR;
1522 static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
1523 struct Curl_easy *data,
1526 PRErrorCode err = 0;
1528 if(is_nss_error(curlerr)) {
1529 /* read NSPR error code */
1530 err = PR_GetError();
1531 if(is_cc_error(err))
1532 curlerr = CURLE_SSL_CERTPROBLEM;
1534 /* print the error number and error string */
1535 infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1537 /* print a human-readable message describing the error if available */
1538 nss_print_error_message(data, err);
1541 /* cleanup on connection failure */
1542 Curl_llist_destroy(connssl->obj_list, NULL);
1543 connssl->obj_list = NULL;
1548 /* Switch the SSL socket into non-blocking mode. */
1549 static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
1550 struct Curl_easy *data)
1552 static PRSocketOptionData sock_opt;
1553 sock_opt.option = PR_SockOpt_Nonblocking;
1554 sock_opt.value.non_blocking = PR_TRUE;
1556 if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1557 return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
1562 static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
1564 PRFileDesc *model = NULL;
1565 PRFileDesc *nspr_io = NULL;
1566 PRFileDesc *nspr_io_stub = NULL;
1567 PRBool ssl_no_cache;
1568 PRBool ssl_cbc_random_iv;
1569 struct Curl_easy *data = conn->data;
1570 curl_socket_t sockfd = conn->sock[sockindex];
1571 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1574 SSLVersionRange sslver = {
1575 SSL_LIBRARY_VERSION_TLS_1_0, /* min */
1576 SSL_LIBRARY_VERSION_TLS_1_0 /* max */
1579 connssl->data = data;
1581 /* list of all NSS objects we need to destroy in Curl_nss_close() */
1582 connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1583 if(!connssl->obj_list)
1584 return CURLE_OUT_OF_MEMORY;
1586 /* FIXME. NSS doesn't support multiple databases open at the same time. */
1587 PR_Lock(nss_initlock);
1588 result = nss_init(conn->data);
1590 PR_Unlock(nss_initlock);
1594 result = CURLE_SSL_CONNECT_ERROR;
1597 char *configstring = aprintf("library=%s name=PEM", pem_library);
1599 PR_Unlock(nss_initlock);
1602 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1605 if(!mod || !mod->loaded) {
1607 SECMOD_DestroyModule(mod);
1610 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1611 "OpenSSL PEM certificates will not work.\n", pem_library);
1615 PK11_SetPasswordFunc(nss_get_password);
1616 PR_Unlock(nss_initlock);
1618 model = PR_NewTCPSocket();
1621 model = SSL_ImportFD(NULL, model);
1623 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1625 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1627 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1630 /* do not use SSL cache if disabled or we are not going to verify peer */
1631 ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
1633 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1636 /* enable/disable the requested SSL version(s) */
1637 if(nss_init_sslver(&sslver, data) != CURLE_OK)
1639 if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1642 ssl_cbc_random_iv = !data->set.ssl_enable_beast;
1643 #ifdef SSL_CBC_RANDOM_IV
1644 /* unless the user explicitly asks to allow the protocol vulnerability, we
1645 use the work-around */
1646 if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1647 infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1650 if(ssl_cbc_random_iv)
1651 infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1654 if(data->set.ssl.cipher_list) {
1655 if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1656 result = CURLE_SSL_CIPHER;
1661 if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
1662 infof(data, "warning: ignoring value of ssl.verifyhost\n");
1664 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1666 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1669 data->set.ssl.certverifyresult=0; /* not checked yet */
1670 if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1673 if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
1676 if(data->set.ssl.verifypeer) {
1677 const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1684 if(data->set.ssl.CRLfile) {
1685 const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
1690 infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
1693 if(data->set.str[STRING_CERT]) {
1694 char *nickname = dup_nickname(data, STRING_CERT);
1696 /* we are not going to use libnsspem.so to read the client cert */
1697 connssl->obj_clicert = NULL;
1700 CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1701 data->set.str[STRING_KEY]);
1703 /* failf() is already done in cert_stuff() */
1709 /* store the nickname for SelectClientCert() called during handshake */
1710 connssl->client_nickname = nickname;
1713 connssl->client_nickname = NULL;
1715 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1716 (void *)connssl) != SECSuccess) {
1717 result = CURLE_SSL_CERTPROBLEM;
1721 /* wrap OS file descriptor by NSPR's file descriptor abstraction */
1722 nspr_io = PR_ImportTCPSocket(sockfd);
1726 /* create our own NSPR I/O layer */
1727 nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
1733 /* make the per-connection data accessible from NSPR I/O callbacks */
1734 nspr_io_stub->secret = (void *)connssl;
1736 /* push our new layer to the NSPR I/O stack */
1737 if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
1739 PR_Close(nspr_io_stub);
1743 /* import our model socket onto the current I/O stack */
1744 connssl->handle = SSL_ImportFD(model, nspr_io);
1745 if(!connssl->handle) {
1750 PR_Close(model); /* We don't need this any more */
1753 /* This is the password associated with the cert that we're using */
1754 if(data->set.str[STRING_KEY_PASSWD]) {
1755 SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1758 #ifdef SSL_ENABLE_OCSP_STAPLING
1759 if(data->set.ssl.verifystatus) {
1760 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
1766 #ifdef SSL_ENABLE_NPN
1767 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
1768 ? PR_TRUE : PR_FALSE) != SECSuccess)
1772 #ifdef SSL_ENABLE_ALPN
1773 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
1774 ? PR_TRUE : PR_FALSE) != SECSuccess)
1778 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
1779 if(data->set.ssl.falsestart) {
1780 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
1784 if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
1785 conn) != SECSuccess)
1790 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
1791 if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
1793 unsigned char protocols[128];
1796 if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
1797 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
1798 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
1799 NGHTTP2_PROTO_VERSION_ID_LEN);
1800 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1803 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
1804 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1805 cur += ALPN_HTTP_1_1_LENGTH;
1807 if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
1813 /* Force handshake on next I/O */
1814 if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE)
1818 /* propagate hostname to the TLS layer */
1819 if(SSL_SetURL(connssl->handle, conn->host.name) != SECSuccess)
1822 /* prevent NSS from re-using the session for a different hostname */
1823 if(SSL_SetSockPeerID(connssl->handle, conn->host.name) != SECSuccess)
1832 return nss_fail_connect(connssl, data, result);
1835 static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
1837 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1838 struct Curl_easy *data = conn->data;
1839 CURLcode result = CURLE_SSL_CONNECT_ERROR;
1842 /* check timeout situation */
1843 const long time_left = Curl_timeleft(data, NULL, TRUE);
1844 if(time_left < 0L) {
1845 failf(data, "timed out before SSL handshake");
1846 result = CURLE_OPERATION_TIMEDOUT;
1850 /* Force the handshake now */
1851 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1852 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1853 if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
1854 /* blocking direction is updated by nss_update_connecting_state() */
1856 else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1857 result = CURLE_PEER_FAILED_VERIFICATION;
1858 else if(conn->data->set.ssl.certverifyresult!=0)
1859 result = CURLE_SSL_CACERT;
1863 result = display_conn_info(conn, connssl->handle);
1867 if(data->set.str[STRING_SSL_ISSUERCERT]) {
1868 SECStatus ret = SECFailure;
1869 char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
1871 /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
1872 ret = check_issuer_cert(connssl->handle, nickname);
1876 if(SECFailure == ret) {
1877 infof(data, "SSL certificate issuer check failed\n");
1878 result = CURLE_SSL_ISSUER_ERROR;
1882 infof(data, "SSL certificate issuer check ok\n");
1886 result = cmp_peer_pubkey(connssl, data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
1888 /* status already printed */
1894 return nss_fail_connect(connssl, data, result);
1897 static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
1900 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1901 struct Curl_easy *data = conn->data;
1902 const bool blocking = (done == NULL);
1905 if(connssl->state == ssl_connection_complete)
1908 if(connssl->connecting_state == ssl_connect_1) {
1909 result = nss_setup_connect(conn, sockindex);
1911 /* we do not expect CURLE_AGAIN from nss_setup_connect() */
1915 /* in non-blocking mode, set NSS non-blocking mode before handshake */
1916 result = nss_set_nonblock(connssl, data);
1921 connssl->connecting_state = ssl_connect_2;
1924 result = nss_do_connect(conn, sockindex);
1930 /* CURLE_AGAIN in non-blocking mode is not an error */
1938 /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
1939 result = nss_set_nonblock(connssl, data);
1944 /* signal completed SSL handshake */
1947 connssl->state = ssl_connection_complete;
1948 conn->recv[sockindex] = nss_recv;
1949 conn->send[sockindex] = nss_send;
1951 /* ssl_connect_done is never used outside, go back to the initial state */
1952 connssl->connecting_state = ssl_connect_1;
1957 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1959 return nss_connect_common(conn, sockindex, /* blocking */ NULL);
1962 CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
1963 int sockindex, bool *done)
1965 return nss_connect_common(conn, sockindex, done);
1968 static ssize_t nss_send(struct connectdata *conn, /* connection data */
1969 int sockindex, /* socketindex */
1970 const void *mem, /* send this data */
1971 size_t len, /* amount to write */
1974 ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
1975 PR_INTERVAL_NO_WAIT);
1977 PRInt32 err = PR_GetError();
1978 if(err == PR_WOULD_BLOCK_ERROR)
1979 *curlcode = CURLE_AGAIN;
1981 /* print the error number and error string */
1982 const char *err_name = nss_error_to_name(err);
1983 infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
1985 /* print a human-readable message describing the error if available */
1986 nss_print_error_message(conn->data, err);
1988 *curlcode = (is_cc_error(err))
1989 ? CURLE_SSL_CERTPROBLEM
1996 return rc; /* number of bytes */
1999 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
2000 int num, /* socketindex */
2001 char *buf, /* store read data here */
2002 size_t buffersize, /* max amount to read */
2005 ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
2006 PR_INTERVAL_NO_WAIT);
2008 /* failed SSL read */
2009 PRInt32 err = PR_GetError();
2011 if(err == PR_WOULD_BLOCK_ERROR)
2012 *curlcode = CURLE_AGAIN;
2014 /* print the error number and error string */
2015 const char *err_name = nss_error_to_name(err);
2016 infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
2018 /* print a human-readable message describing the error if available */
2019 nss_print_error_message(conn->data, err);
2021 *curlcode = (is_cc_error(err))
2022 ? CURLE_SSL_CERTPROBLEM
2032 size_t Curl_nss_version(char *buffer, size_t size)
2034 return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
2037 /* data might be NULL */
2038 int Curl_nss_seed(struct Curl_easy *data)
2040 /* make sure that NSS is initialized */
2041 return !!Curl_nss_force_init(data);
2044 /* data might be NULL */
2045 int Curl_nss_random(struct Curl_easy *data,
2046 unsigned char *entropy,
2049 Curl_nss_seed(data); /* Initiate the seed if not already done */
2051 if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
2052 /* signal a failure */
2058 void Curl_nss_md5sum(unsigned char *tmp, /* input */
2060 unsigned char *md5sum, /* output */
2063 PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
2064 unsigned int MD5out;
2066 PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
2067 PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
2068 PK11_DestroyContext(MD5pw, PR_TRUE);
2071 void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
2073 unsigned char *sha256sum, /* output */
2076 PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
2077 unsigned int SHA256out;
2079 PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
2080 PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
2081 PK11_DestroyContext(SHA256pw, PR_TRUE);
2084 bool Curl_nss_cert_status_request(void)
2086 #ifdef SSL_ENABLE_OCSP_STAPLING
2093 bool Curl_nss_false_start(void) {
2094 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
2101 #endif /* USE_NSS */