1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, 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 sslgen.c should ever call or use these functions.
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
39 #include "formdata.h" /* for the boundary function */
40 #include "url.h" /* for the ssl config check function */
46 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
47 #include <curl/mprintf.h>
68 #include "curl_memory.h"
70 #include "easyif.h" /* for Curl_convert_from_utf8 prototype */
72 /* The last #include file should be: */
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;
85 volatile int initialized = 0;
90 PRInt32 version; /* protocol version valid for this cipher */
93 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
94 (x)->pValue=(v); (x)->ulValueLen = (l)
96 #define CERT_NewTempCertificate __CERT_NewTempCertificate
98 enum sslversion { SSL2 = 1, SSL3 = 2, TLS = 4 };
100 #define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
101 static const cipher_s cipherlist[] = {
102 /* SSL2 cipher suites */
103 {"rc4", SSL_EN_RC4_128_WITH_MD5, SSL2},
104 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5, SSL2},
105 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL2},
106 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5, SSL2},
107 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL2},
108 {"des", SSL_EN_DES_64_CBC_WITH_MD5, SSL2},
109 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL2},
110 /* SSL3/TLS cipher suites */
111 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5, SSL3 | TLS},
112 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA, SSL3 | TLS},
113 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
114 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA, SSL3 | TLS},
115 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL3 | TLS},
116 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL3 | TLS},
117 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5, SSL3 | TLS},
118 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA, SSL3 | TLS},
119 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL3 | TLS},
120 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL3 | TLS},
121 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, SSL3 | TLS},
122 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, SSL3 | TLS},
123 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA, SSL3 | TLS},
124 /* TLS 1.0: Exportable 56-bit Cipher Suites. */
125 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL3 | TLS},
126 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL3 | TLS},
128 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA, SSL3 | TLS},
129 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA, SSL3 | TLS},
130 #ifdef NSS_ENABLE_ECC
132 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA, TLS},
133 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS},
134 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
135 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS},
136 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS},
137 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS},
138 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS},
139 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS},
140 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS},
141 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS},
142 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA, TLS},
143 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS},
144 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
145 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS},
146 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS},
147 {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA, TLS},
148 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS},
149 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, TLS},
150 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS},
151 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS},
152 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA, TLS},
153 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA, TLS},
154 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, TLS},
155 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS},
156 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA, TLS},
160 /* following ciphers are new in NSS 3.4 and not enabled by default, therefore
161 they are enabled explicitly */
162 static const int enable_ciphers_by_default[] = {
163 TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
164 TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
165 TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
166 TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
167 TLS_RSA_WITH_AES_128_CBC_SHA,
168 TLS_RSA_WITH_AES_256_CBC_SHA,
169 SSL_NULL_WITH_NULL_NULL
172 #ifdef HAVE_PK11_CREATEGENERICOBJECT
173 static const char* pem_library = "libnsspem.so";
175 SECMODModule* mod = NULL;
177 static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
181 PRBool cipher_state[NUM_OF_CIPHERS];
186 /* First disable all ciphers. This uses a different max value in case
187 * NSS adds more ciphers later we don't want them available by
190 for(i=0; i<SSL_NumImplementedCiphers; i++) {
191 SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
194 /* Set every entry in our list to false */
195 for(i=0; i<NUM_OF_CIPHERS; i++) {
196 cipher_state[i] = PR_FALSE;
199 cipher = cipher_list;
201 while(cipher_list && (cipher_list[0])) {
202 while((*cipher) && (ISSPACE(*cipher)))
205 if((cipher_list = strchr(cipher, ','))) {
206 *cipher_list++ = '\0';
211 for(i=0; i<NUM_OF_CIPHERS; i++) {
212 if(Curl_raw_equal(cipher, cipherlist[i].name)) {
213 cipher_state[i] = PR_TRUE;
219 if(found == PR_FALSE) {
220 failf(data, "Unknown cipher in list: %s", cipher);
225 cipher = cipher_list;
229 /* Finally actually enable the selected ciphers */
230 for(i=0; i<NUM_OF_CIPHERS; i++) {
231 rv = SSL_CipherPrefSet(model, cipherlist[i].num, cipher_state[i]);
232 if(rv != SECSuccess) {
233 failf(data, "Unknown cipher in cipher list");
242 * Get the number of ciphers that are enabled. We use this to determine
243 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
245 static int num_enabled_ciphers(void)
251 for(i=0; i<NUM_OF_CIPHERS; i++) {
252 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
260 * Determine whether the nickname passed in is a filename that needs to
261 * be loaded as a PEM or a regular NSS nickname.
263 * returns 1 for a file
264 * returns 0 for not a file (NSS nickname)
266 static int is_file(const char *filename)
273 if(stat(filename, &st) == 0)
274 if(S_ISREG(st.st_mode))
280 static char *fmt_nickname(char *str, bool *nickname_alloc)
282 char *nickname = NULL;
283 *nickname_alloc = FALSE;
286 char *n = strrchr(str, '/');
288 *nickname_alloc = TRUE;
289 n++; /* skip last slash */
290 nickname = aprintf("PEM Token #%d:%s", 1, n);
298 static int nss_load_cert(struct ssl_connect_data *ssl,
299 const char *filename, PRBool cacert)
301 #ifdef HAVE_PK11_CREATEGENERICOBJECT
303 PK11SlotInfo * slot = NULL;
305 CK_ATTRIBUTE theTemplate[20];
306 CK_BBOOL cktrue = CK_TRUE;
307 CK_BBOOL ckfalse = CK_FALSE;
308 CK_OBJECT_CLASS objClass = CKO_CERTIFICATE;
309 char slotname[SLOTSIZE];
311 CERTCertificate *cert;
312 char *nickname = NULL;
315 /* If there is no slash in the filename it is assumed to be a regular
318 if(is_file(filename)) {
319 n = strrchr(filename, '/');
326 /* A nickname from the NSS internal database */
328 return 0; /* You can't specify an NSS CA nickname this way */
329 nickname = strdup(filename);
335 #ifdef HAVE_PK11_CREATEGENERICOBJECT
338 /* All CA and trust objects go into slot 0. Other slots are used
339 * for storing certificates. With each new user certificate we increment
340 * the slot count. We only support 1 user certificate right now.
347 snprintf(slotname, SLOTSIZE, "PEM Token #%ld", slotID);
349 nickname = aprintf("PEM Token #%ld:%s", slotID, n);
353 slot = PK11_FindSlotByName(slotname);
360 PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) );
362 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) );
364 PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)filename,
368 PK11_SETATTRS(attrs, CKA_TRUST, &cktrue, sizeof(CK_BBOOL) );
371 PK11_SETATTRS(attrs, CKA_TRUST, &ckfalse, sizeof(CK_BBOOL) );
375 /* This load the certificate in our PEM module into the appropriate
378 ssl->cacert[slotID] = PK11_CreateGenericObject(slot, theTemplate, 4,
379 PR_FALSE /* isPerm */);
383 if(ssl->cacert[slotID] == NULL) {
388 /* We don't have PK11_CreateGenericObject but a file-based cert was passed
389 * in. We need to fail.
395 /* Double-check that the certificate or nickname requested exists in
396 * either the token or the NSS certificate database.
399 cert = PK11_FindCertFromNickname((char *)nickname, NULL);
401 /* An invalid nickname was passed in */
404 PR_SetError(SEC_ERROR_UNKNOWN_CERT, 0);
408 CERT_DestroyCertificate(cert);
416 /* add given CRL to cache if it is not already there */
417 static SECStatus nss_cache_crl(SECItem *crlDER)
419 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
420 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0);
422 /* CRL already cached */
424 SECITEM_FreeItem(crlDER, PR_FALSE);
428 /* acquire lock before call of CERT_CacheCRL() */
429 PR_Lock(nss_crllock);
430 if(SECSuccess != CERT_CacheCRL(db, crlDER)) {
431 /* unable to cache CRL */
432 PR_Unlock(nss_crllock);
433 SECITEM_FreeItem(crlDER, PR_FALSE);
437 /* we need to clear session cache, so that the CRL could take effect */
438 SSL_ClearSessionCache();
439 PR_Unlock(nss_crllock);
443 static SECStatus nss_load_crl(const char* crlfilename)
447 SECItem filedata = { 0, NULL, 0 };
448 SECItem crlDER = { 0, NULL, 0 };
451 infile = PR_Open(crlfilename, PR_RDONLY, 0);
455 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
458 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
461 if(info.size != PR_Read(infile, filedata.data, info.size))
464 /* place a trailing zero right after the visible data */
465 body = (char*)filedata.data;
466 body[--filedata.len] = '\0';
468 body = strstr(body, "-----BEGIN");
472 char *begin = PORT_Strchr(body, '\n');
474 begin = PORT_Strchr(body, '\r');
478 trailer = strstr(++begin, "-----END");
482 /* retrieve DER from ASCII */
484 if(ATOB_ConvertAsciiToItem(&crlDER, begin))
487 SECITEM_FreeItem(&filedata, PR_FALSE);
494 return nss_cache_crl(&crlDER);
498 SECITEM_FreeItem(&filedata, PR_FALSE);
502 static int nss_load_key(struct connectdata *conn, int sockindex,
505 #ifdef HAVE_PK11_CREATEGENERICOBJECT
506 PK11SlotInfo * slot = NULL;
508 CK_ATTRIBUTE theTemplate[20];
509 CK_BBOOL cktrue = CK_TRUE;
510 CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY;
512 char slotname[SLOTSIZE];
513 struct ssl_connect_data *sslconn = &conn->ssl[sockindex];
517 /* FIXME: grok the various file types */
519 slotID = 1; /* hardcoded for now */
521 snprintf(slotname, sizeof(slotname), "PEM Token #%ld", slotID);
522 slot = PK11_FindSlotByName(slotname);
527 PK11_SETATTRS(attrs, CKA_CLASS, &objClass, sizeof(objClass) ); attrs++;
528 PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL) ); attrs++;
529 PK11_SETATTRS(attrs, CKA_LABEL, (unsigned char *)key_file,
530 strlen(key_file)+1); attrs++;
532 /* When adding an encrypted key the PKCS#11 will be set as removed */
533 sslconn->key = PK11_CreateGenericObject(slot, theTemplate, 3,
534 PR_FALSE /* isPerm */);
535 if(sslconn->key == NULL) {
536 PR_SetError(SEC_ERROR_BAD_KEY, 0);
540 /* This will force the token to be seen as re-inserted */
541 SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
542 PK11_IsPresent(slot);
544 /* parg is initialized in nss_Init_Tokens() */
545 if(PK11_Authenticate(slot, PR_TRUE,
546 conn->data->set.str[STRING_KEY_PASSWD]) != SECSuccess) {
555 /* If we don't have PK11_CreateGenericObject then we can't load a file-based
558 (void)conn; /* unused */
559 (void)key_file; /* unused */
564 static int display_error(struct connectdata *conn, PRInt32 err,
565 const char *filename)
568 case SEC_ERROR_BAD_PASSWORD:
569 failf(conn->data, "Unable to load client key: Incorrect password");
571 case SEC_ERROR_UNKNOWN_CERT:
572 failf(conn->data, "Unable to load certificate %s", filename);
577 return 0; /* The caller will print a generic error */
580 static int cert_stuff(struct connectdata *conn,
581 int sockindex, char *cert_file, char *key_file)
583 struct SessionHandle *data = conn->data;
587 rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
589 if(!display_error(conn, PR_GetError(), cert_file))
590 failf(data, "Unable to load client cert %d.", PR_GetError());
594 if(key_file || (is_file(cert_file))) {
596 rv = nss_load_key(conn, sockindex, key_file);
598 /* In case the cert file also has the key */
599 rv = nss_load_key(conn, sockindex, cert_file);
601 if(!display_error(conn, PR_GetError(), key_file))
602 failf(data, "Unable to load client key %d.", PR_GetError());
610 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
612 (void)slot; /* unused */
613 if(retry || NULL == arg)
616 return (char *)PORT_Strdup((char *)arg);
619 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
621 SECStatus success = SECSuccess;
622 struct connectdata *conn = (struct connectdata *)arg;
623 PRErrorCode err = PR_GetError();
624 CERTCertificate *cert = NULL;
625 char *subject, *subject_cn, *issuer;
627 if(conn->data->set.ssl.certverifyresult!=0)
630 conn->data->set.ssl.certverifyresult=err;
631 cert = SSL_PeerCertificate(sock);
632 subject = CERT_NameToAscii(&cert->subject);
633 subject_cn = CERT_GetCommonName(&cert->subject);
634 issuer = CERT_NameToAscii(&cert->issuer);
635 CERT_DestroyCertificate(cert);
638 case SEC_ERROR_CA_CERT_INVALID:
639 infof(conn->data, "Issuer certificate is invalid: '%s'\n", issuer);
640 if(conn->data->set.ssl.verifypeer)
641 success = SECFailure;
643 case SEC_ERROR_UNTRUSTED_ISSUER:
644 if(conn->data->set.ssl.verifypeer)
645 success = SECFailure;
646 infof(conn->data, "Certificate is signed by an untrusted issuer: '%s'\n",
649 case SSL_ERROR_BAD_CERT_DOMAIN:
650 if(conn->data->set.ssl.verifyhost) {
651 failf(conn->data, "SSL: certificate subject name '%s' does not match "
652 "target host name '%s'", subject_cn, conn->host.dispname);
653 success = SECFailure;
655 infof(conn->data, "warning: SSL: certificate subject name '%s' does not "
656 "match target host name '%s'\n", subject_cn, conn->host.dispname);
659 case SEC_ERROR_EXPIRED_CERTIFICATE:
660 if(conn->data->set.ssl.verifypeer)
661 success = SECFailure;
662 infof(conn->data, "Remote Certificate has expired.\n");
664 case SEC_ERROR_UNKNOWN_ISSUER:
665 if(conn->data->set.ssl.verifypeer)
666 success = SECFailure;
667 infof(conn->data, "Peer's certificate issuer is not recognized: '%s'\n",
671 if(conn->data->set.ssl.verifypeer)
672 success = SECFailure;
673 infof(conn->data, "Bad certificate received. Subject = '%s', "
674 "Issuer = '%s'\n", subject, issuer);
677 if(success == SECSuccess)
678 infof(conn->data, "SSL certificate verify ok.\n");
687 * Inform the application that the handshake is complete.
689 static SECStatus HandshakeCallback(PRFileDesc *sock, void *arg)
696 static void display_cert_info(struct SessionHandle *data,
697 CERTCertificate *cert)
699 char *subject, *issuer, *common_name;
700 PRExplodedTime printableTime;
701 char timeString[256];
702 PRTime notBefore, notAfter;
704 subject = CERT_NameToAscii(&cert->subject);
705 issuer = CERT_NameToAscii(&cert->issuer);
706 common_name = CERT_GetCommonName(&cert->subject);
707 infof(data, "\tsubject: %s\n", subject);
709 CERT_GetCertTimes(cert, ¬Before, ¬After);
710 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
711 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
712 infof(data, "\tstart date: %s\n", timeString);
713 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
714 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
715 infof(data, "\texpire date: %s\n", timeString);
716 infof(data, "\tcommon name: %s\n", common_name);
717 infof(data, "\tissuer: %s\n", issuer);
721 PR_Free(common_name);
724 static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
726 SSLChannelInfo channel;
727 SSLCipherSuiteInfo suite;
728 CERTCertificate *cert;
730 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
731 SECSuccess && channel.length == sizeof channel &&
732 channel.cipherSuite) {
733 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
734 &suite, sizeof suite) == SECSuccess) {
735 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
739 infof(conn->data, "Server certificate:\n");
741 cert = SSL_PeerCertificate(sock);
742 display_cert_info(conn->data, cert);
743 CERT_DestroyCertificate(cert);
750 * Check that the Peer certificate's issuer certificate matches the one found
751 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
752 * issuer check, so we provide comments that mimic the OpenSSL
753 * X509_check_issued function (in x509v3/v3_purp.c)
755 static SECStatus check_issuer_cert(PRFileDesc *sock,
756 char *issuer_nickname)
758 CERTCertificate *cert,*cert_issuer,*issuer;
759 SECStatus res=SECSuccess;
760 void *proto_win = NULL;
763 PRArenaPool *tmpArena = NULL;
764 CERTAuthKeyID *authorityKeyID = NULL;
765 SECITEM *caname = NULL;
768 cert = SSL_PeerCertificate(sock);
769 cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
771 proto_win = SSL_RevealPinArg(sock);
773 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
775 if ((!cert_issuer) || (!issuer))
777 else if (SECITEM_CompareItem(&cert_issuer->derCert,
778 &issuer->derCert)!=SECEqual)
781 CERT_DestroyCertificate(cert);
782 CERT_DestroyCertificate(issuer);
783 CERT_DestroyCertificate(cert_issuer);
789 * Callback to pick the SSL client certificate.
791 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
792 struct CERTDistNamesStr *caNames,
793 struct CERTCertificateStr **pRetCert,
794 struct SECKEYPrivateKeyStr **pRetKey)
796 static const char pem_nickname[] = "PEM Token #1";
797 const char *pem_slotname = pem_nickname;
799 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
800 struct SessionHandle *data = connssl->data;
801 const char *nickname = connssl->client_nickname;
803 if (mod && nickname &&
804 0 == strncmp(nickname, pem_nickname, /* length of "PEM Token" */ 9)) {
806 /* use the cert/key provided by PEM reader */
808 void *proto_win = SSL_RevealPinArg(sock);
811 *pRetCert = PK11_FindCertFromNickname(nickname, proto_win);
812 if (NULL == *pRetCert) {
813 failf(data, "NSS: client certificate not found: %s", nickname);
817 slot = PK11_FindSlotByName(pem_slotname);
819 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
823 *pRetKey = PK11_FindPrivateKeyFromCert(slot, *pRetCert, NULL);
825 if (NULL == *pRetKey) {
826 failf(data, "NSS: private key not found for certificate: %s", nickname);
830 infof(data, "NSS: client certificate: %s\n", nickname);
831 display_cert_info(data, *pRetCert);
835 /* use the default NSS hook */
836 if (SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
838 || NULL == *pRetCert) {
840 if (NULL == nickname)
841 failf(data, "NSS: client certificate not found (nickname not "
844 failf(data, "NSS: client certificate not found: %s", nickname);
849 /* get certificate nickname if any */
850 nickname = (*pRetCert)->nickname;
851 if (NULL == nickname)
852 nickname = "[unknown]";
854 if (NULL == *pRetKey) {
855 failf(data, "NSS: private key not found for certificate: %s", nickname);
859 infof(data, "NSS: using client certificate: %s\n", nickname);
860 display_cert_info(data, *pRetCert);
864 /* This function is supposed to decide, which error codes should be used
865 * to conclude server is TLS intolerant.
867 * taken from xulrunner - nsNSSIOLayer.cpp
870 isTLSIntoleranceError(PRInt32 err)
873 case SSL_ERROR_BAD_MAC_ALERT:
874 case SSL_ERROR_BAD_MAC_READ:
875 case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
876 case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
877 case SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE:
878 case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
879 case SSL_ERROR_NO_CYPHER_OVERLAP:
880 case SSL_ERROR_BAD_SERVER:
881 case SSL_ERROR_BAD_BLOCK_PADDING:
882 case SSL_ERROR_UNSUPPORTED_VERSION:
883 case SSL_ERROR_PROTOCOL_VERSION_ALERT:
884 case SSL_ERROR_RX_MALFORMED_FINISHED:
885 case SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE:
886 case SSL_ERROR_DECODE_ERROR_ALERT:
887 case SSL_ERROR_RX_UNKNOWN_ALERT:
894 static CURLcode init_nss(struct SessionHandle *data)
901 /* First we check if $SSL_DIR points to a valid dir */
902 cert_dir = getenv("SSL_DIR");
904 if((stat(cert_dir, &st) != 0) ||
905 (!S_ISDIR(st.st_mode))) {
910 /* Now we check if the default location is a valid dir */
912 if((stat(SSL_DIR, &st) == 0) &&
913 (S_ISDIR(st.st_mode))) {
914 cert_dir = (char *)SSL_DIR;
918 if(!NSS_IsInitialized()) {
921 infof(data, "Initializing NSS with certpath: %s\n",
922 cert_dir ? cert_dir : "none");
924 rv = NSS_NoDB_Init(NULL);
928 PR_smprintf("%s%s", NSS_VersionCheck("3.12.0") ? "sql:" : "", cert_dir);
929 rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY);
930 PR_smprintf_free(certpath);
932 if(rv != SECSuccess) {
933 infof(data, "Unable to initialize NSS database\n");
935 return CURLE_SSL_CACERT_BADFILE;
939 if(num_enabled_ciphers() == 0)
940 NSS_SetDomesticPolicy();
948 * @retval 0 error initializing SSL
949 * @retval 1 SSL initialized successfully
951 int Curl_nss_init(void)
953 /* curl_global_init() is not thread-safe so this test is ok */
954 if (nss_initlock == NULL) {
955 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
956 nss_initlock = PR_NewLock();
957 nss_crllock = PR_NewLock();
960 /* We will actually initialize NSS later */
965 CURLcode Curl_nss_force_init(struct SessionHandle *data)
969 failf(data, "unable to initialize NSS, curl_global_init() should have been "
970 "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
971 return CURLE_OUT_OF_MEMORY;
974 PR_Lock(nss_initlock);
976 PR_Unlock(nss_initlock);
981 void Curl_nss_cleanup(void)
983 /* This function isn't required to be threadsafe and this is only done
984 * as a safety feature.
986 PR_Lock(nss_initlock);
988 /* Free references to client certificates held in the SSL session cache.
989 * Omitting this hampers destruction of the security module owning
990 * the certificates. */
991 SSL_ClearSessionCache();
993 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
994 SECMOD_DestroyModule(mod);
999 PR_Unlock(nss_initlock);
1001 PR_DestroyLock(nss_initlock);
1002 PR_DestroyLock(nss_crllock);
1003 nss_initlock = NULL;
1009 * This function uses SSL_peek to determine connection status.
1012 * 1 means the connection is still in place
1013 * 0 means the connection has been closed
1014 * -1 means the connection status is unknown
1017 Curl_nss_check_cxn(struct connectdata *conn)
1023 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1024 PR_SecondsToInterval(1));
1026 return 1; /* connection still in place */
1029 return 0; /* connection has been closed */
1031 return -1; /* connection status unknown */
1035 * This function is called when an SSL connection is closed.
1037 void Curl_nss_close(struct connectdata *conn, int sockindex)
1039 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1041 if(connssl->handle) {
1042 PR_Close(connssl->handle);
1044 /* NSS closes the socket we previously handed to it, so we must mark it
1045 as closed to avoid double close */
1046 fake_sclose(conn->sock[sockindex]);
1047 conn->sock[sockindex] = CURL_SOCKET_BAD;
1048 if(connssl->client_nickname != NULL) {
1049 free(connssl->client_nickname);
1050 connssl->client_nickname = NULL;
1052 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1054 (void)PK11_DestroyGenericObject(connssl->key);
1055 if(connssl->cacert[1])
1056 (void)PK11_DestroyGenericObject(connssl->cacert[1]);
1057 if(connssl->cacert[0])
1058 (void)PK11_DestroyGenericObject(connssl->cacert[0]);
1060 connssl->handle = NULL;
1065 * This function is called when the 'data' struct is going away. Close
1066 * down everything and free all resources!
1068 int Curl_nss_close_all(struct SessionHandle *data)
1074 /* handle client certificate related errors if any; return false otherwise */
1075 static bool handle_cc_error(PRInt32 err, struct SessionHandle *data)
1078 case SSL_ERROR_BAD_CERT_ALERT:
1079 failf(data, "SSL error: SSL_ERROR_BAD_CERT_ALERT");
1082 case SSL_ERROR_REVOKED_CERT_ALERT:
1083 failf(data, "SSL error: SSL_ERROR_REVOKED_CERT_ALERT");
1086 case SSL_ERROR_EXPIRED_CERT_ALERT:
1087 failf(data, "SSL error: SSL_ERROR_EXPIRED_CERT_ALERT");
1095 static Curl_recv nss_recv;
1096 static Curl_send nss_send;
1098 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1101 PRFileDesc *model = NULL;
1102 PRBool ssl2 = PR_FALSE;
1103 PRBool ssl3 = PR_FALSE;
1104 PRBool tlsv1 = PR_FALSE;
1105 struct SessionHandle *data = conn->data;
1106 curl_socket_t sockfd = conn->sock[sockindex];
1107 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1109 const int *cipher_to_enable;
1110 PRSocketOptionData sock_opt;
1114 if (connssl->state == ssl_connection_complete)
1117 connssl->data = data;
1119 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1120 connssl->cacert[0] = NULL;
1121 connssl->cacert[1] = NULL;
1122 connssl->key = NULL;
1125 /* FIXME. NSS doesn't support multiple databases open at the same time. */
1126 PR_Lock(nss_initlock);
1127 curlerr = init_nss(conn->data);
1128 if(CURLE_OK != curlerr) {
1129 PR_Unlock(nss_initlock);
1133 curlerr = CURLE_SSL_CONNECT_ERROR;
1135 #ifdef HAVE_PK11_CREATEGENERICOBJECT
1137 char *configstring = aprintf("library=%s name=PEM", pem_library);
1139 PR_Unlock(nss_initlock);
1142 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1145 if(!mod || !mod->loaded) {
1147 SECMOD_DestroyModule(mod);
1150 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1151 "OpenSSL PEM certificates will not work.\n", pem_library);
1156 PK11_SetPasswordFunc(nss_get_password);
1157 PR_Unlock(nss_initlock);
1159 model = PR_NewTCPSocket();
1162 model = SSL_ImportFD(NULL, model);
1164 /* make the socket nonblocking */
1165 sock_opt.option = PR_SockOpt_Nonblocking;
1166 sock_opt.value.non_blocking = PR_TRUE;
1167 if(PR_SetSocketOption(model, &sock_opt) != SECSuccess)
1170 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1172 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1174 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1177 switch (data->set.ssl.version) {
1179 case CURL_SSLVERSION_DEFAULT:
1181 if (data->state.ssl_connect_retry)
1182 infof(data, "TLS disabled due to previous handshake failure\n");
1186 case CURL_SSLVERSION_TLSv1:
1189 case CURL_SSLVERSION_SSLv2:
1192 case CURL_SSLVERSION_SSLv3:
1197 if(SSL_OptionSet(model, SSL_ENABLE_SSL2, ssl2) != SECSuccess)
1199 if(SSL_OptionSet(model, SSL_ENABLE_SSL3, ssl3) != SECSuccess)
1201 if(SSL_OptionSet(model, SSL_ENABLE_TLS, tlsv1) != SECSuccess)
1204 if(SSL_OptionSet(model, SSL_V2_COMPATIBLE_HELLO, ssl2) != SECSuccess)
1207 /* reset the flag to avoid an infinite loop */
1208 data->state.ssl_connect_retry = FALSE;
1210 /* enable all ciphers from enable_ciphers_by_default */
1211 cipher_to_enable = enable_ciphers_by_default;
1212 while (SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
1213 if (SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
1214 curlerr = CURLE_SSL_CIPHER;
1220 if(data->set.ssl.cipher_list) {
1221 if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1222 curlerr = CURLE_SSL_CIPHER;
1227 if(data->set.ssl.verifyhost == 1)
1228 infof(data, "warning: ignoring unsupported value (1) of ssl.verifyhost\n");
1230 data->set.ssl.certverifyresult=0; /* not checked yet */
1231 if(SSL_BadCertHook(model, (SSLBadCertHandler) BadCertHandler, conn)
1235 if(SSL_HandshakeCallback(model, (SSLHandshakeCallback) HandshakeCallback,
1236 NULL) != SECSuccess)
1239 if(!data->set.ssl.verifypeer)
1240 /* skip the verifying of the peer */
1242 else if(data->set.ssl.CAfile) {
1243 int rc = nss_load_cert(&conn->ssl[sockindex], data->set.ssl.CAfile,
1246 curlerr = CURLE_SSL_CACERT_BADFILE;
1250 else if(data->set.ssl.CApath) {
1255 if(stat(data->set.ssl.CApath, &st) == -1) {
1256 curlerr = CURLE_SSL_CACERT_BADFILE;
1260 if(S_ISDIR(st.st_mode)) {
1263 dir = PR_OpenDir(data->set.ssl.CApath);
1265 entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN);
1268 char fullpath[PATH_MAX];
1270 snprintf(fullpath, sizeof(fullpath), "%s/%s", data->set.ssl.CApath,
1272 rc = nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE);
1273 /* FIXME: check this return value! */
1275 /* This is purposefully tolerant of errors so non-PEM files
1276 * can be in the same directory */
1277 } while(entry != NULL);
1284 data->set.ssl.CAfile ? data->set.ssl.CAfile : "none",
1285 data->set.ssl.CApath ? data->set.ssl.CApath : "none");
1287 if (data->set.ssl.CRLfile) {
1288 if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) {
1289 curlerr = CURLE_SSL_CRL_BADFILE;
1294 data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
1297 if(data->set.str[STRING_CERT]) {
1298 bool nickname_alloc = FALSE;
1299 char *nickname = fmt_nickname(data->set.str[STRING_CERT], &nickname_alloc);
1301 return CURLE_OUT_OF_MEMORY;
1303 if(!cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1304 data->set.str[STRING_KEY])) {
1305 /* failf() is already done in cert_stuff() */
1308 return CURLE_SSL_CERTPROBLEM;
1311 /* this "takes over" the pointer to the allocated name or makes a
1313 connssl->client_nickname = nickname_alloc?nickname:strdup(nickname);
1314 if(!connssl->client_nickname)
1315 return CURLE_OUT_OF_MEMORY;
1319 connssl->client_nickname = NULL;
1321 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1322 (void *)connssl) != SECSuccess) {
1323 curlerr = CURLE_SSL_CERTPROBLEM;
1327 /* Import our model socket onto the existing file descriptor */
1328 connssl->handle = PR_ImportTCPSocket(sockfd);
1329 connssl->handle = SSL_ImportFD(model, connssl->handle);
1330 if(!connssl->handle)
1333 PR_Close(model); /* We don't need this any more */
1336 /* This is the password associated with the cert that we're using */
1337 if (data->set.str[STRING_KEY_PASSWD]) {
1338 SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1341 /* Force handshake on next I/O */
1342 SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1344 SSL_SetURL(connssl->handle, conn->host.name);
1346 /* check timeout situation */
1347 time_left = Curl_timeleft(conn, NULL, TRUE);
1348 if(time_left < 0L) {
1349 failf(data, "timed out before SSL handshake");
1352 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1354 /* Force the handshake now */
1355 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1356 if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1357 curlerr = CURLE_PEER_FAILED_VERIFICATION;
1358 else if(conn->data->set.ssl.certverifyresult!=0)
1359 curlerr = CURLE_SSL_CACERT;
1363 connssl->state = ssl_connection_complete;
1364 conn->recv[sockindex] = nss_recv;
1365 conn->send[sockindex] = nss_send;
1367 display_conn_info(conn, connssl->handle);
1369 if (data->set.str[STRING_SSL_ISSUERCERT]) {
1371 bool nickname_alloc = FALSE;
1372 char *nickname = fmt_nickname(data->set.str[STRING_SSL_ISSUERCERT],
1376 return CURLE_OUT_OF_MEMORY;
1378 ret = check_issuer_cert(connssl->handle, nickname);
1383 if(SECFailure == ret) {
1384 infof(data,"SSL certificate issuer check failed\n");
1385 curlerr = CURLE_SSL_ISSUER_ERROR;
1389 infof(data, "SSL certificate issuer check ok\n");
1396 /* reset the flag to avoid an infinite loop */
1397 data->state.ssl_connect_retry = FALSE;
1399 err = PR_GetError();
1400 if(handle_cc_error(err, data))
1401 curlerr = CURLE_SSL_CERTPROBLEM;
1403 infof(data, "NSS error %d\n", err);
1408 if (ssl3 && tlsv1 && isTLSIntoleranceError(err)) {
1409 /* schedule reconnect through Curl_retry_request() */
1410 data->state.ssl_connect_retry = TRUE;
1411 infof(data, "Error in TLS handshake, trying SSLv3...\n");
1418 static ssize_t nss_send(struct connectdata *conn, /* connection data */
1419 int sockindex, /* socketindex */
1420 const void *mem, /* send this data */
1421 size_t len, /* amount to write */
1426 rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0, -1);
1429 PRInt32 err = PR_GetError();
1430 if(err == PR_WOULD_BLOCK_ERROR)
1431 *curlcode = CURLE_AGAIN;
1432 else if(handle_cc_error(err, conn->data))
1433 *curlcode = CURLE_SSL_CERTPROBLEM;
1435 failf(conn->data, "SSL write: error %d", err);
1436 *curlcode = CURLE_SEND_ERROR;
1440 return rc; /* number of bytes */
1443 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1444 int num, /* socketindex */
1445 char *buf, /* store read data here */
1446 size_t buffersize, /* max amount to read */
1451 nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0, -1);
1453 /* failed SSL read */
1454 PRInt32 err = PR_GetError();
1456 if(err == PR_WOULD_BLOCK_ERROR)
1457 *curlcode = CURLE_AGAIN;
1458 else if(handle_cc_error(err, conn->data))
1459 *curlcode = CURLE_SSL_CERTPROBLEM;
1461 failf(conn->data, "SSL read: errno %d", err);
1462 *curlcode = CURLE_RECV_ERROR;
1469 size_t Curl_nss_version(char *buffer, size_t size)
1471 return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
1474 int Curl_nss_seed(struct SessionHandle *data)
1476 /* TODO: implement? */
1481 #endif /* USE_NSS */