1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2015, 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 http://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);
82 PRLock * nss_initlock = NULL;
83 PRLock * nss_crllock = NULL;
84 struct curl_llist *nss_crl_list = NULL;
85 NSSInitContext * nss_context = NULL;
87 volatile int initialized = 0;
94 #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
95 CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
96 ptr->type = (_type); \
97 ptr->pValue = (_val); \
98 ptr->ulValueLen = (_len); \
101 #define CERT_NewTempCertificate __CERT_NewTempCertificate
103 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
104 static const cipher_s cipherlist[] = {
105 /* SSL2 cipher suites */
106 {"rc4", SSL_EN_RC4_128_WITH_MD5},
107 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
108 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
109 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
110 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
111 {"des", SSL_EN_DES_64_CBC_WITH_MD5},
112 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
113 /* SSL3/TLS cipher suites */
114 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
115 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
116 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
117 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
118 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
119 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
120 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
121 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
122 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
123 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
124 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
125 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
126 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
127 /* TLS 1.0: Exportable 56-bit Cipher Suites. */
128 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
129 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
131 {"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
132 {"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
133 {"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
134 {"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
135 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
136 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
138 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
139 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
140 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
141 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
142 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
143 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
144 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
145 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
146 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
147 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
148 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
149 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
150 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
151 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
152 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
153 {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
154 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
155 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
156 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
157 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
158 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
159 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
160 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
161 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
162 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
163 #ifdef TLS_RSA_WITH_NULL_SHA256
164 /* new HMAC-SHA256 cipher suites specified in RFC */
165 {"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
166 {"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
167 {"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
168 {"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
169 {"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
170 {"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
171 {"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
173 #ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
174 /* AES GCM cipher suites in RFC 5288 and RFC 5289 */
175 {"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
176 {"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
177 {"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
178 {"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
179 {"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
180 {"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
181 {"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
185 static const char* pem_library = "libnsspem.so";
186 SECMODModule* mod = NULL;
188 /* NSPR I/O layer we use to detect blocking direction during SSL handshake */
189 static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
190 static PRIOMethods nspr_io_methods;
192 static const char* nss_error_to_name(PRErrorCode code)
194 const char *name = PR_ErrorToName(code);
198 return "unknown error";
201 static void nss_print_error_message(struct SessionHandle *data, PRUint32 err)
203 failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
206 static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
210 PRBool cipher_state[NUM_OF_CIPHERS];
214 /* First disable all ciphers. This uses a different max value in case
215 * NSS adds more ciphers later we don't want them available by
218 for(i=0; i<SSL_NumImplementedCiphers; i++) {
219 SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], PR_FALSE);
222 /* Set every entry in our list to false */
223 for(i=0; i<NUM_OF_CIPHERS; i++) {
224 cipher_state[i] = PR_FALSE;
227 cipher = cipher_list;
229 while(cipher_list && (cipher_list[0])) {
230 while((*cipher) && (ISSPACE(*cipher)))
233 if((cipher_list = strchr(cipher, ','))) {
234 *cipher_list++ = '\0';
239 for(i=0; i<NUM_OF_CIPHERS; i++) {
240 if(Curl_raw_equal(cipher, cipherlist[i].name)) {
241 cipher_state[i] = PR_TRUE;
247 if(found == PR_FALSE) {
248 failf(data, "Unknown cipher in list: %s", cipher);
253 cipher = cipher_list;
257 /* Finally actually enable the selected ciphers */
258 for(i=0; i<NUM_OF_CIPHERS; i++) {
262 if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
263 failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
272 * Get the number of ciphers that are enabled. We use this to determine
273 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
275 static int num_enabled_ciphers(void)
281 for(i=0; i<NUM_OF_CIPHERS; i++) {
282 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
290 * Determine whether the nickname passed in is a filename that needs to
291 * be loaded as a PEM or a regular NSS nickname.
293 * returns 1 for a file
294 * returns 0 for not a file (NSS nickname)
296 static int is_file(const char *filename)
303 if(stat(filename, &st) == 0)
304 if(S_ISREG(st.st_mode))
310 /* Check if the given string is filename or nickname of a certificate. If the
311 * given string is recognized as filename, return NULL. If the given string is
312 * recognized as nickname, return a duplicated string. The returned string
313 * should be later deallocated using free(). If the OOM failure occurs, we
316 static char* dup_nickname(struct SessionHandle *data, enum dupstring cert_kind)
318 const char *str = data->set.str[cert_kind];
322 /* no such file exists, use the string as nickname */
325 /* search the last slash; we require at least one slash in a file name */
326 n = strrchr(str, '/');
328 infof(data, "warning: certificate file name \"%s\" handled as nickname; "
329 "please use \"./%s\" to force file name\n", str, str);
333 /* we'll use the PEM reader to read the certificate from file */
337 /* Call PK11_CreateGenericObject() with the given obj_class and filename. If
338 * the call succeeds, append the object handle to the list of objects so that
339 * the object can be destroyed in Curl_nss_close(). */
340 static CURLcode nss_create_object(struct ssl_connect_data *ssl,
341 CK_OBJECT_CLASS obj_class,
342 const char *filename, bool cacert)
345 PK11GenericObject *obj;
346 CK_BBOOL cktrue = CK_TRUE;
347 CK_BBOOL ckfalse = CK_FALSE;
348 CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
350 CURLcode result = (cacert)
351 ? CURLE_SSL_CACERT_BADFILE
352 : CURLE_SSL_CERTPROBLEM;
354 const int slot_id = (cacert) ? 0 : 1;
355 char *slot_name = aprintf("PEM Token #%d", slot_id);
357 return CURLE_OUT_OF_MEMORY;
359 slot = PK11_FindSlotByName(slot_name);
364 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
365 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
366 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
367 strlen(filename) + 1);
369 if(CKO_CERTIFICATE == obj_class) {
370 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
371 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
374 obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
379 if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
380 PK11_DestroyGenericObject(obj);
381 return CURLE_OUT_OF_MEMORY;
384 if(!cacert && CKO_CERTIFICATE == obj_class)
385 /* store reference to a client certificate */
386 ssl->obj_clicert = obj;
391 /* Destroy the NSS object whose handle is given by ptr. This function is
392 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
393 * NSS objects in Curl_nss_close() */
394 static void nss_destroy_object(void *user, void *ptr)
396 PK11GenericObject *obj = (PK11GenericObject *)ptr;
398 PK11_DestroyGenericObject(obj);
401 /* same as nss_destroy_object() but for CRL items */
402 static void nss_destroy_crl_item(void *user, void *ptr)
404 SECItem *crl_der = (SECItem *)ptr;
406 SECITEM_FreeItem(crl_der, PR_TRUE);
409 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
410 const char *filename, PRBool cacert)
412 CURLcode result = (cacert)
413 ? CURLE_SSL_CACERT_BADFILE
414 : CURLE_SSL_CERTPROBLEM;
416 /* libnsspem.so leaks memory if the requested file does not exist. For more
417 * details, go to <https://bugzilla.redhat.com/734760>. */
418 if(is_file(filename))
419 result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
421 if(!result && !cacert) {
422 /* we have successfully loaded a client certificate */
423 CERTCertificate *cert;
424 char *nickname = NULL;
425 char *n = strrchr(filename, '/');
429 /* The following undocumented magic helps to avoid a SIGSEGV on call
430 * of PK11_ReadRawAttribute() from SelectClientCert() when using an
431 * immature version of libnsspem.so. For more details, go to
432 * <https://bugzilla.redhat.com/733685>. */
433 nickname = aprintf("PEM Token #1:%s", n);
435 cert = PK11_FindCertFromNickname(nickname, NULL);
437 CERT_DestroyCertificate(cert);
446 /* add given CRL to cache if it is not already there */
447 static CURLcode nss_cache_crl(SECItem *crl_der)
449 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
450 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
452 /* CRL already cached */
454 SECITEM_FreeItem(crl_der, PR_TRUE);
458 /* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
459 PR_Lock(nss_crllock);
461 /* store the CRL item so that we can free it in Curl_nss_cleanup() */
462 if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
463 SECITEM_FreeItem(crl_der, PR_TRUE);
464 PR_Unlock(nss_crllock);
465 return CURLE_OUT_OF_MEMORY;
468 if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
469 /* unable to cache CRL */
470 PR_Unlock(nss_crllock);
471 return CURLE_SSL_CRL_BADFILE;
474 /* we need to clear session cache, so that the CRL could take effect */
475 SSL_ClearSessionCache();
476 PR_Unlock(nss_crllock);
480 static CURLcode nss_load_crl(const char* crlfilename)
484 SECItem filedata = { 0, NULL, 0 };
485 SECItem *crl_der = NULL;
488 infile = PR_Open(crlfilename, PR_RDONLY, 0);
490 return CURLE_SSL_CRL_BADFILE;
492 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
495 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
498 if(info.size != PR_Read(infile, filedata.data, info.size))
501 crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
505 /* place a trailing zero right after the visible data */
506 body = (char*)filedata.data;
507 body[--filedata.len] = '\0';
509 body = strstr(body, "-----BEGIN");
513 char *begin = PORT_Strchr(body, '\n');
515 begin = PORT_Strchr(body, '\r');
519 trailer = strstr(++begin, "-----END");
523 /* retrieve DER from ASCII */
525 if(ATOB_ConvertAsciiToItem(crl_der, begin))
528 SECITEM_FreeItem(&filedata, PR_FALSE);
535 return nss_cache_crl(crl_der);
539 SECITEM_FreeItem(crl_der, PR_TRUE);
540 SECITEM_FreeItem(&filedata, PR_FALSE);
541 return CURLE_SSL_CRL_BADFILE;
544 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
550 struct ssl_connect_data *ssl = conn->ssl;
552 (void)sockindex; /* unused */
554 result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
556 PR_SetError(SEC_ERROR_BAD_KEY, 0);
560 slot = PK11_FindSlotByName("PEM Token #1");
562 return CURLE_SSL_CERTPROBLEM;
564 /* This will force the token to be seen as re-inserted */
565 SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
566 PK11_IsPresent(slot);
568 status = PK11_Authenticate(slot, PR_TRUE,
569 conn->data->set.str[STRING_KEY_PASSWD]);
572 return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
575 static int display_error(struct connectdata *conn, PRInt32 err,
576 const char *filename)
579 case SEC_ERROR_BAD_PASSWORD:
580 failf(conn->data, "Unable to load client key: Incorrect password");
582 case SEC_ERROR_UNKNOWN_CERT:
583 failf(conn->data, "Unable to load certificate %s", filename);
588 return 0; /* The caller will print a generic error */
591 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
592 char *cert_file, char *key_file)
594 struct SessionHandle *data = conn->data;
598 result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
600 const PRErrorCode err = PR_GetError();
601 if(!display_error(conn, err, cert_file)) {
602 const char *err_name = nss_error_to_name(err);
603 failf(data, "unable to load client cert: %d (%s)", err, err_name);
610 if(key_file || (is_file(cert_file))) {
612 result = nss_load_key(conn, sockindex, key_file);
614 /* In case the cert file also has the key */
615 result = nss_load_key(conn, sockindex, cert_file);
617 const PRErrorCode err = PR_GetError();
618 if(!display_error(conn, err, key_file)) {
619 const char *err_name = nss_error_to_name(err);
620 failf(data, "unable to load client key: %d (%s)", err, err_name);
630 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
632 (void)slot; /* unused */
634 if(retry || NULL == arg)
637 return (char *)PORT_Strdup((char *)arg);
640 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
642 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
645 struct connectdata *conn = (struct connectdata *)arg;
647 #ifdef SSL_ENABLE_OCSP_STAPLING
648 if(conn->data->set.ssl.verifystatus) {
649 SECStatus cacheResult;
651 const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
653 failf(conn->data, "Invalid OCSP response");
658 failf(conn->data, "No OCSP response received");
662 cacheResult = CERT_CacheOCSPResponseFromSideChannel(
663 CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
664 PR_Now(), &csa->items[0], arg
667 if(cacheResult != SECSuccess) {
668 failf(conn->data, "Invalid OCSP response");
674 if(!conn->data->set.ssl.verifypeer) {
675 infof(conn->data, "skipping SSL peer certificate verification\n");
679 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
683 * Inform the application that the handshake is complete.
685 static void HandshakeCallback(PRFileDesc *sock, void *arg)
687 struct connectdata *conn = (struct connectdata*) arg;
688 unsigned int buflenmax = 50;
689 unsigned char buf[50];
691 SSLNextProtoState state;
693 if(!conn->data->set.ssl_enable_npn && !conn->data->set.ssl_enable_alpn) {
697 if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
700 case SSL_NEXT_PROTO_NO_SUPPORT:
701 case SSL_NEXT_PROTO_NO_OVERLAP:
702 infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
704 #ifdef SSL_ENABLE_ALPN
705 case SSL_NEXT_PROTO_SELECTED:
706 infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
709 case SSL_NEXT_PROTO_NEGOTIATED:
710 infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
715 if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
716 !memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
717 conn->negnpn = CURL_HTTP_VERSION_2_0;
721 if(buflen == ALPN_HTTP_1_1_LENGTH &&
722 !memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
723 conn->negnpn = CURL_HTTP_VERSION_1_1;
728 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
729 static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
730 PRBool *canFalseStart)
732 struct connectdata *conn = client_data;
733 struct SessionHandle *data = conn->data;
735 SSLChannelInfo channelInfo;
736 SSLCipherSuiteInfo cipherInfo;
739 PRBool negotiatedExtension;
741 *canFalseStart = PR_FALSE;
743 if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
746 if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
747 sizeof(cipherInfo)) != SECSuccess)
750 /* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
751 * TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
753 if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
756 /* Only allow ECDHE key exchange algorithm.
757 * See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
758 if(cipherInfo.keaType != ssl_kea_ecdh)
761 /* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
762 * mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
763 * design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
764 if(cipherInfo.symCipher != ssl_calg_aes_gcm)
767 /* Enforce ALPN or NPN to do False Start, as an indicator of server
769 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
770 &negotiatedExtension);
771 if(rv != SECSuccess || !negotiatedExtension) {
772 rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
773 &negotiatedExtension);
776 if(rv != SECSuccess || !negotiatedExtension)
779 *canFalseStart = PR_TRUE;
781 infof(data, "Trying TLS False Start\n");
788 static void display_cert_info(struct SessionHandle *data,
789 CERTCertificate *cert)
791 char *subject, *issuer, *common_name;
792 PRExplodedTime printableTime;
793 char timeString[256];
794 PRTime notBefore, notAfter;
796 subject = CERT_NameToAscii(&cert->subject);
797 issuer = CERT_NameToAscii(&cert->issuer);
798 common_name = CERT_GetCommonName(&cert->subject);
799 infof(data, "\tsubject: %s\n", subject);
801 CERT_GetCertTimes(cert, ¬Before, ¬After);
802 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
803 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
804 infof(data, "\tstart date: %s\n", timeString);
805 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
806 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
807 infof(data, "\texpire date: %s\n", timeString);
808 infof(data, "\tcommon name: %s\n", common_name);
809 infof(data, "\tissuer: %s\n", issuer);
813 PR_Free(common_name);
816 static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
818 CURLcode result = CURLE_OK;
819 SSLChannelInfo channel;
820 SSLCipherSuiteInfo suite;
821 CERTCertificate *cert;
822 CERTCertificate *cert2;
823 CERTCertificate *cert3;
827 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
828 SECSuccess && channel.length == sizeof channel &&
829 channel.cipherSuite) {
830 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
831 &suite, sizeof suite) == SECSuccess) {
832 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
836 cert = SSL_PeerCertificate(sock);
838 infof(conn->data, "Server certificate:\n");
840 if(!conn->data->set.ssl.certinfo) {
841 display_cert_info(conn->data, cert);
842 CERT_DestroyCertificate(cert);
845 /* Count certificates in chain. */
849 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
853 CERT_DestroyCertificate(cert2);
856 cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
857 CERT_DestroyCertificate(cert2);
862 result = Curl_ssl_init_certinfo(conn->data, i);
864 for(i = 0; cert; cert = cert2) {
865 result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
866 (char *)cert->derCert.data +
872 CERT_DestroyCertificate(cert);
876 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
877 CERT_DestroyCertificate(cert);
886 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
888 struct connectdata *conn = (struct connectdata *)arg;
889 struct SessionHandle *data = conn->data;
890 PRErrorCode err = PR_GetError();
891 CERTCertificate *cert;
893 /* remember the cert verification result */
894 data->set.ssl.certverifyresult = err;
896 if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
897 /* we are asked not to verify the host name */
900 /* print only info about the cert, the error is printed off the callback */
901 cert = SSL_PeerCertificate(sock);
903 infof(data, "Server certificate:\n");
904 display_cert_info(data, cert);
905 CERT_DestroyCertificate(cert);
913 * Check that the Peer certificate's issuer certificate matches the one found
914 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
915 * issuer check, so we provide comments that mimic the OpenSSL
916 * X509_check_issued function (in x509v3/v3_purp.c)
918 static SECStatus check_issuer_cert(PRFileDesc *sock,
919 char *issuer_nickname)
921 CERTCertificate *cert, *cert_issuer, *issuer;
922 SECStatus res=SECSuccess;
923 void *proto_win = NULL;
926 PRArenaPool *tmpArena = NULL;
927 CERTAuthKeyID *authorityKeyID = NULL;
928 SECITEM *caname = NULL;
931 cert = SSL_PeerCertificate(sock);
932 cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
934 proto_win = SSL_RevealPinArg(sock);
935 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
937 if((!cert_issuer) || (!issuer))
939 else if(SECITEM_CompareItem(&cert_issuer->derCert,
940 &issuer->derCert)!=SECEqual)
943 CERT_DestroyCertificate(cert);
944 CERT_DestroyCertificate(issuer);
945 CERT_DestroyCertificate(cert_issuer);
949 static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
950 const char *pinnedpubkey)
952 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
953 struct SessionHandle *data = connssl->data;
954 CERTCertificate *cert;
957 /* no pinned public key specified */
960 /* get peer certificate */
961 cert = SSL_PeerCertificate(connssl->handle);
963 /* extract public key from peer certificate */
964 SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
966 /* encode the public key as DER */
967 SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
969 /* compare the public key with the pinned public key */
970 result = Curl_pin_peer_pubkey(pinnedpubkey,
973 SECITEM_FreeItem(cert_der, PR_TRUE);
975 SECKEY_DestroyPublicKey(pubkey);
977 CERT_DestroyCertificate(cert);
980 /* report the resulting status */
983 infof(data, "pinned public key verified successfully!\n");
985 case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
986 failf(data, "failed to verify pinned public key");
998 * Callback to pick the SSL client certificate.
1000 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
1001 struct CERTDistNamesStr *caNames,
1002 struct CERTCertificateStr **pRetCert,
1003 struct SECKEYPrivateKeyStr **pRetKey)
1005 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
1006 struct SessionHandle *data = connssl->data;
1007 const char *nickname = connssl->client_nickname;
1009 if(connssl->obj_clicert) {
1010 /* use the cert/key provided by PEM reader */
1011 static const char pem_slotname[] = "PEM Token #1";
1012 SECItem cert_der = { 0, NULL, 0 };
1013 void *proto_win = SSL_RevealPinArg(sock);
1014 struct CERTCertificateStr *cert;
1015 struct SECKEYPrivateKeyStr *key;
1017 PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
1019 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
1023 if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
1024 &cert_der) != SECSuccess) {
1025 failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
1026 PK11_FreeSlot(slot);
1030 cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
1031 SECITEM_FreeItem(&cert_der, PR_FALSE);
1033 failf(data, "NSS: client certificate from file not found");
1034 PK11_FreeSlot(slot);
1038 key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
1039 PK11_FreeSlot(slot);
1041 failf(data, "NSS: private key from file not found");
1042 CERT_DestroyCertificate(cert);
1046 infof(data, "NSS: client certificate from file\n");
1047 display_cert_info(data, cert);
1054 /* use the default NSS hook */
1055 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
1057 || NULL == *pRetCert) {
1059 if(NULL == nickname)
1060 failf(data, "NSS: client certificate not found (nickname not "
1063 failf(data, "NSS: client certificate not found: %s", nickname);
1068 /* get certificate nickname if any */
1069 nickname = (*pRetCert)->nickname;
1070 if(NULL == nickname)
1071 nickname = "[unknown]";
1073 if(NULL == *pRetKey) {
1074 failf(data, "NSS: private key not found for certificate: %s", nickname);
1078 infof(data, "NSS: using client certificate: %s\n", nickname);
1079 display_cert_info(data, *pRetCert);
1083 /* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
1084 static void nss_update_connecting_state(ssl_connect_state state, void *secret)
1086 struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
1087 if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
1088 /* an unrelated error is passing by */
1091 switch(connssl->connecting_state) {
1093 case ssl_connect_2_reading:
1094 case ssl_connect_2_writing:
1097 /* we are not called from an SSL handshake */
1101 /* update the state accordingly */
1102 connssl->connecting_state = state;
1105 /* recv() wrapper we use to detect blocking direction during SSL handshake */
1106 static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
1107 PRIntn flags, PRIntervalTime timeout)
1109 const PRRecvFN recv_fn = fd->lower->methods->recv;
1110 const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
1112 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1113 nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
1117 /* send() wrapper we use to detect blocking direction during SSL handshake */
1118 static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
1119 PRIntn flags, PRIntervalTime timeout)
1121 const PRSendFN send_fn = fd->lower->methods->send;
1122 const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
1124 /* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
1125 nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
1129 /* close() wrapper to avoid assertion failure due to fd->secret != NULL */
1130 static PRStatus nspr_io_close(PRFileDesc *fd)
1132 const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
1134 return close_fn(fd);
1137 /* data might be NULL */
1138 static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir)
1140 NSSInitParameters initparams;
1142 if(nss_context != NULL)
1145 memset((void *) &initparams, '\0', sizeof(initparams));
1146 initparams.length = sizeof(initparams);
1149 char *certpath = aprintf("sql:%s", cert_dir);
1151 return CURLE_OUT_OF_MEMORY;
1153 infof(data, "Initializing NSS with certpath: %s\n", certpath);
1154 nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
1155 NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
1158 if(nss_context != NULL)
1161 infof(data, "Unable to initialize NSS database\n");
1164 infof(data, "Initializing NSS with certpath: none\n");
1165 nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
1166 | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
1167 | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
1168 if(nss_context != NULL)
1171 infof(data, "Unable to initialize NSS\n");
1172 return CURLE_SSL_CACERT_BADFILE;
1175 /* data might be NULL */
1176 static CURLcode nss_init(struct SessionHandle *data)
1185 /* list of all CRL items we need to destroy in Curl_nss_cleanup() */
1186 nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
1188 return CURLE_OUT_OF_MEMORY;
1190 /* First we check if $SSL_DIR points to a valid dir */
1191 cert_dir = getenv("SSL_DIR");
1193 if((stat(cert_dir, &st) != 0) ||
1194 (!S_ISDIR(st.st_mode))) {
1199 /* Now we check if the default location is a valid dir */
1201 if((stat(SSL_DIR, &st) == 0) &&
1202 (S_ISDIR(st.st_mode))) {
1203 cert_dir = (char *)SSL_DIR;
1207 if(nspr_io_identity == PR_INVALID_IO_LAYER) {
1208 /* allocate an identity for our own NSPR I/O layer */
1209 nspr_io_identity = PR_GetUniqueIdentity("libcurl");
1210 if(nspr_io_identity == PR_INVALID_IO_LAYER)
1211 return CURLE_OUT_OF_MEMORY;
1213 /* the default methods just call down to the lower I/O layer */
1214 memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
1216 /* override certain methods in the table by our wrappers */
1217 nspr_io_methods.recv = nspr_io_recv;
1218 nspr_io_methods.send = nspr_io_send;
1219 nspr_io_methods.close = nspr_io_close;
1222 result = nss_init_core(data, cert_dir);
1226 if(num_enabled_ciphers() == 0)
1227 NSS_SetDomesticPolicy();
1237 * @retval 0 error initializing SSL
1238 * @retval 1 SSL initialized successfully
1240 int Curl_nss_init(void)
1242 /* curl_global_init() is not thread-safe so this test is ok */
1243 if(nss_initlock == NULL) {
1244 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
1245 nss_initlock = PR_NewLock();
1246 nss_crllock = PR_NewLock();
1249 /* We will actually initialize NSS later */
1254 /* data might be NULL */
1255 CURLcode Curl_nss_force_init(struct SessionHandle *data)
1260 failf(data, "unable to initialize NSS, curl_global_init() should have "
1261 "been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1262 return CURLE_FAILED_INIT;
1265 PR_Lock(nss_initlock);
1266 result = nss_init(data);
1267 PR_Unlock(nss_initlock);
1272 /* Global cleanup */
1273 void Curl_nss_cleanup(void)
1275 /* This function isn't required to be threadsafe and this is only done
1276 * as a safety feature.
1278 PR_Lock(nss_initlock);
1280 /* Free references to client certificates held in the SSL session cache.
1281 * Omitting this hampers destruction of the security module owning
1282 * the certificates. */
1283 SSL_ClearSessionCache();
1285 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1286 SECMOD_DestroyModule(mod);
1289 NSS_ShutdownContext(nss_context);
1293 /* destroy all CRL items */
1294 Curl_llist_destroy(nss_crl_list, NULL);
1295 nss_crl_list = NULL;
1297 PR_Unlock(nss_initlock);
1299 PR_DestroyLock(nss_initlock);
1300 PR_DestroyLock(nss_crllock);
1301 nss_initlock = NULL;
1307 * This function uses SSL_peek to determine connection status.
1310 * 1 means the connection is still in place
1311 * 0 means the connection has been closed
1312 * -1 means the connection status is unknown
1315 Curl_nss_check_cxn(struct connectdata *conn)
1321 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1322 PR_SecondsToInterval(1));
1324 return 1; /* connection still in place */
1327 return 0; /* connection has been closed */
1329 return -1; /* connection status unknown */
1333 * This function is called when an SSL connection is closed.
1335 void Curl_nss_close(struct connectdata *conn, int sockindex)
1337 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1339 if(connssl->handle) {
1340 /* NSS closes the socket we previously handed to it, so we must mark it
1341 as closed to avoid double close */
1342 fake_sclose(conn->sock[sockindex]);
1343 conn->sock[sockindex] = CURL_SOCKET_BAD;
1345 if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
1346 /* A server might require different authentication based on the
1347 * particular path being requested by the client. To support this
1348 * scenario, we must ensure that a connection will never reuse the
1349 * authentication data from a previous connection. */
1350 SSL_InvalidateSession(connssl->handle);
1352 free(connssl->client_nickname);
1353 connssl->client_nickname = NULL;
1354 /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1355 Curl_llist_destroy(connssl->obj_list, NULL);
1356 connssl->obj_list = NULL;
1357 connssl->obj_clicert = NULL;
1359 PR_Close(connssl->handle);
1360 connssl->handle = NULL;
1364 /* return true if NSS can provide error code (and possibly msg) for the
1366 static bool is_nss_error(CURLcode err)
1369 case CURLE_PEER_FAILED_VERIFICATION:
1370 case CURLE_SSL_CACERT:
1371 case CURLE_SSL_CERTPROBLEM:
1372 case CURLE_SSL_CONNECT_ERROR:
1373 case CURLE_SSL_ISSUER_ERROR:
1381 /* return true if the given error code is related to a client certificate */
1382 static bool is_cc_error(PRInt32 err)
1385 case SSL_ERROR_BAD_CERT_ALERT:
1386 case SSL_ERROR_EXPIRED_CERT_ALERT:
1387 case SSL_ERROR_REVOKED_CERT_ALERT:
1395 static Curl_recv nss_recv;
1396 static Curl_send nss_send;
1398 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1401 struct SessionHandle *data = conn->data;
1402 const char *cafile = data->set.ssl.CAfile;
1403 const char *capath = data->set.ssl.CApath;
1406 CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1413 if(stat(capath, &st) == -1)
1414 return CURLE_SSL_CACERT_BADFILE;
1416 if(S_ISDIR(st.st_mode)) {
1418 PRDir *dir = PR_OpenDir(capath);
1420 return CURLE_SSL_CACERT_BADFILE;
1422 while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1423 char *fullpath = aprintf("%s/%s", capath, entry->name);
1426 return CURLE_OUT_OF_MEMORY;
1429 if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1430 /* This is purposefully tolerant of errors so non-PEM files can
1431 * be in the same directory */
1432 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1440 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1443 infof(data, " CAfile: %s\n CApath: %s\n",
1444 cafile ? cafile : "none",
1445 capath ? capath : "none");
1450 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1451 struct SessionHandle *data)
1453 switch(data->set.ssl.version) {
1455 case CURL_SSLVERSION_DEFAULT:
1456 case CURL_SSLVERSION_TLSv1:
1457 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1458 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1459 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1460 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1461 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1463 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1467 case CURL_SSLVERSION_SSLv2:
1468 sslver->min = SSL_LIBRARY_VERSION_2;
1469 sslver->max = SSL_LIBRARY_VERSION_2;
1472 case CURL_SSLVERSION_SSLv3:
1473 sslver->min = SSL_LIBRARY_VERSION_3_0;
1474 sslver->max = SSL_LIBRARY_VERSION_3_0;
1477 case CURL_SSLVERSION_TLSv1_0:
1478 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1479 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1482 case CURL_SSLVERSION_TLSv1_1:
1483 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1484 sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1485 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1490 case CURL_SSLVERSION_TLSv1_2:
1491 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1492 sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1493 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1499 failf(data, "TLS minor version cannot be set");
1500 return CURLE_SSL_CONNECT_ERROR;
1503 static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
1504 struct SessionHandle *data,
1507 PRErrorCode err = 0;
1509 if(is_nss_error(curlerr)) {
1510 /* read NSPR error code */
1511 err = PR_GetError();
1512 if(is_cc_error(err))
1513 curlerr = CURLE_SSL_CERTPROBLEM;
1515 /* print the error number and error string */
1516 infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1518 /* print a human-readable message describing the error if available */
1519 nss_print_error_message(data, err);
1522 /* cleanup on connection failure */
1523 Curl_llist_destroy(connssl->obj_list, NULL);
1524 connssl->obj_list = NULL;
1529 /* Switch the SSL socket into non-blocking mode. */
1530 static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
1531 struct SessionHandle *data)
1533 static PRSocketOptionData sock_opt;
1534 sock_opt.option = PR_SockOpt_Nonblocking;
1535 sock_opt.value.non_blocking = PR_TRUE;
1537 if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1538 return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
1543 static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
1545 PRFileDesc *model = NULL;
1546 PRFileDesc *nspr_io = NULL;
1547 PRFileDesc *nspr_io_stub = NULL;
1548 PRBool ssl_no_cache;
1549 PRBool ssl_cbc_random_iv;
1550 struct SessionHandle *data = conn->data;
1551 curl_socket_t sockfd = conn->sock[sockindex];
1552 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1555 SSLVersionRange sslver = {
1556 SSL_LIBRARY_VERSION_TLS_1_0, /* min */
1557 SSL_LIBRARY_VERSION_TLS_1_0 /* max */
1560 connssl->data = data;
1562 /* list of all NSS objects we need to destroy in Curl_nss_close() */
1563 connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1564 if(!connssl->obj_list)
1565 return CURLE_OUT_OF_MEMORY;
1567 /* FIXME. NSS doesn't support multiple databases open at the same time. */
1568 PR_Lock(nss_initlock);
1569 result = nss_init(conn->data);
1571 PR_Unlock(nss_initlock);
1575 result = CURLE_SSL_CONNECT_ERROR;
1578 char *configstring = aprintf("library=%s name=PEM", pem_library);
1580 PR_Unlock(nss_initlock);
1583 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1586 if(!mod || !mod->loaded) {
1588 SECMOD_DestroyModule(mod);
1591 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1592 "OpenSSL PEM certificates will not work.\n", pem_library);
1596 PK11_SetPasswordFunc(nss_get_password);
1597 PR_Unlock(nss_initlock);
1599 model = PR_NewTCPSocket();
1602 model = SSL_ImportFD(NULL, model);
1604 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1606 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1608 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1611 /* do not use SSL cache if disabled or we are not going to verify peer */
1612 ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
1614 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1617 /* enable/disable the requested SSL version(s) */
1618 if(nss_init_sslver(&sslver, data) != CURLE_OK)
1620 if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1623 ssl_cbc_random_iv = !data->set.ssl_enable_beast;
1624 #ifdef SSL_CBC_RANDOM_IV
1625 /* unless the user explicitly asks to allow the protocol vulnerability, we
1626 use the work-around */
1627 if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1628 infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1631 if(ssl_cbc_random_iv)
1632 infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1635 if(data->set.ssl.cipher_list) {
1636 if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1637 result = CURLE_SSL_CIPHER;
1642 if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
1643 infof(data, "warning: ignoring value of ssl.verifyhost\n");
1645 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1647 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1650 data->set.ssl.certverifyresult=0; /* not checked yet */
1651 if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1654 if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
1657 if(data->set.ssl.verifypeer) {
1658 const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1665 if(data->set.ssl.CRLfile) {
1666 const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
1671 infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
1674 if(data->set.str[STRING_CERT]) {
1675 char *nickname = dup_nickname(data, STRING_CERT);
1677 /* we are not going to use libnsspem.so to read the client cert */
1678 connssl->obj_clicert = NULL;
1681 CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1682 data->set.str[STRING_KEY]);
1684 /* failf() is already done in cert_stuff() */
1690 /* store the nickname for SelectClientCert() called during handshake */
1691 connssl->client_nickname = nickname;
1694 connssl->client_nickname = NULL;
1696 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1697 (void *)connssl) != SECSuccess) {
1698 result = CURLE_SSL_CERTPROBLEM;
1702 /* wrap OS file descriptor by NSPR's file descriptor abstraction */
1703 nspr_io = PR_ImportTCPSocket(sockfd);
1707 /* create our own NSPR I/O layer */
1708 nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
1714 /* make the per-connection data accessible from NSPR I/O callbacks */
1715 nspr_io_stub->secret = (void *)connssl;
1717 /* push our new layer to the NSPR I/O stack */
1718 if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
1720 PR_Close(nspr_io_stub);
1724 /* import our model socket onto the current I/O stack */
1725 connssl->handle = SSL_ImportFD(model, nspr_io);
1726 if(!connssl->handle) {
1731 PR_Close(model); /* We don't need this any more */
1734 /* This is the password associated with the cert that we're using */
1735 if(data->set.str[STRING_KEY_PASSWD]) {
1736 SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1739 #ifdef SSL_ENABLE_OCSP_STAPLING
1740 if(data->set.ssl.verifystatus) {
1741 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
1747 #ifdef SSL_ENABLE_NPN
1748 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, data->set.ssl_enable_npn
1749 ? PR_TRUE : PR_FALSE) != SECSuccess)
1753 #ifdef SSL_ENABLE_ALPN
1754 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, data->set.ssl_enable_alpn
1755 ? PR_TRUE : PR_FALSE) != SECSuccess)
1759 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
1760 if(data->set.ssl.falsestart) {
1761 if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
1765 if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
1766 conn) != SECSuccess)
1771 #if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
1772 if(data->set.ssl_enable_npn || data->set.ssl_enable_alpn) {
1774 unsigned char protocols[128];
1777 if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
1778 protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
1779 memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
1780 NGHTTP2_PROTO_VERSION_ID_LEN);
1781 cur += NGHTTP2_PROTO_VERSION_ID_LEN;
1784 protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
1785 memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
1786 cur += ALPN_HTTP_1_1_LENGTH;
1788 if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
1794 /* Force handshake on next I/O */
1795 SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1797 SSL_SetURL(connssl->handle, conn->host.name);
1805 return nss_fail_connect(connssl, data, result);
1808 static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
1810 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1811 struct SessionHandle *data = conn->data;
1812 CURLcode result = CURLE_SSL_CONNECT_ERROR;
1815 /* check timeout situation */
1816 const long time_left = Curl_timeleft(data, NULL, TRUE);
1817 if(time_left < 0L) {
1818 failf(data, "timed out before SSL handshake");
1819 result = CURLE_OPERATION_TIMEDOUT;
1823 /* Force the handshake now */
1824 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1825 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1826 if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
1827 /* blocking direction is updated by nss_update_connecting_state() */
1829 else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1830 result = CURLE_PEER_FAILED_VERIFICATION;
1831 else if(conn->data->set.ssl.certverifyresult!=0)
1832 result = CURLE_SSL_CACERT;
1836 result = display_conn_info(conn, connssl->handle);
1840 if(data->set.str[STRING_SSL_ISSUERCERT]) {
1841 SECStatus ret = SECFailure;
1842 char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
1844 /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
1845 ret = check_issuer_cert(connssl->handle, nickname);
1849 if(SECFailure == ret) {
1850 infof(data, "SSL certificate issuer check failed\n");
1851 result = CURLE_SSL_ISSUER_ERROR;
1855 infof(data, "SSL certificate issuer check ok\n");
1859 result = cmp_peer_pubkey(connssl, data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
1861 /* status already printed */
1867 return nss_fail_connect(connssl, data, result);
1870 static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
1873 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1874 struct SessionHandle *data = conn->data;
1875 const bool blocking = (done == NULL);
1878 if(connssl->state == ssl_connection_complete)
1881 if(connssl->connecting_state == ssl_connect_1) {
1882 result = nss_setup_connect(conn, sockindex);
1884 /* we do not expect CURLE_AGAIN from nss_setup_connect() */
1888 /* in non-blocking mode, set NSS non-blocking mode before handshake */
1889 result = nss_set_nonblock(connssl, data);
1894 connssl->connecting_state = ssl_connect_2;
1897 result = nss_do_connect(conn, sockindex);
1903 /* CURLE_AGAIN in non-blocking mode is not an error */
1911 /* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
1912 result = nss_set_nonblock(connssl, data);
1917 /* signal completed SSL handshake */
1920 connssl->state = ssl_connection_complete;
1921 conn->recv[sockindex] = nss_recv;
1922 conn->send[sockindex] = nss_send;
1924 /* ssl_connect_done is never used outside, go back to the initial state */
1925 connssl->connecting_state = ssl_connect_1;
1930 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1932 return nss_connect_common(conn, sockindex, /* blocking */ NULL);
1935 CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
1936 int sockindex, bool *done)
1938 return nss_connect_common(conn, sockindex, done);
1941 static ssize_t nss_send(struct connectdata *conn, /* connection data */
1942 int sockindex, /* socketindex */
1943 const void *mem, /* send this data */
1944 size_t len, /* amount to write */
1947 ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
1948 PR_INTERVAL_NO_WAIT);
1950 PRInt32 err = PR_GetError();
1951 if(err == PR_WOULD_BLOCK_ERROR)
1952 *curlcode = CURLE_AGAIN;
1954 /* print the error number and error string */
1955 const char *err_name = nss_error_to_name(err);
1956 infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
1958 /* print a human-readable message describing the error if available */
1959 nss_print_error_message(conn->data, err);
1961 *curlcode = (is_cc_error(err))
1962 ? CURLE_SSL_CERTPROBLEM
1969 return rc; /* number of bytes */
1972 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1973 int num, /* socketindex */
1974 char *buf, /* store read data here */
1975 size_t buffersize, /* max amount to read */
1978 ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
1979 PR_INTERVAL_NO_WAIT);
1981 /* failed SSL read */
1982 PRInt32 err = PR_GetError();
1984 if(err == PR_WOULD_BLOCK_ERROR)
1985 *curlcode = CURLE_AGAIN;
1987 /* print the error number and error string */
1988 const char *err_name = nss_error_to_name(err);
1989 infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
1991 /* print a human-readable message describing the error if available */
1992 nss_print_error_message(conn->data, err);
1994 *curlcode = (is_cc_error(err))
1995 ? CURLE_SSL_CERTPROBLEM
2005 size_t Curl_nss_version(char *buffer, size_t size)
2007 return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
2010 /* data might be NULL */
2011 int Curl_nss_seed(struct SessionHandle *data)
2013 /* make sure that NSS is initialized */
2014 return !!Curl_nss_force_init(data);
2017 /* data might be NULL */
2018 int Curl_nss_random(struct SessionHandle *data,
2019 unsigned char *entropy,
2022 Curl_nss_seed(data); /* Initiate the seed if not already done */
2024 if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
2025 /* signal a failure */
2031 void Curl_nss_md5sum(unsigned char *tmp, /* input */
2033 unsigned char *md5sum, /* output */
2036 PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
2037 unsigned int MD5out;
2039 PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
2040 PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
2041 PK11_DestroyContext(MD5pw, PR_TRUE);
2044 void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
2046 unsigned char *sha256sum, /* output */
2049 PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
2050 unsigned int SHA256out;
2052 PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
2053 PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
2054 PK11_DestroyContext(SHA256pw, PR_TRUE);
2057 bool Curl_nss_cert_status_request(void)
2059 #ifdef SSL_ENABLE_OCSP_STAPLING
2066 bool Curl_nss_false_start(void) {
2067 #if NSSVERNUM >= 0x030f04 /* 3.15.4 */
2074 #endif /* USE_NSS */