1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, 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.
28 #include "curl_setup.h"
34 #include "formdata.h" /* for the boundary function */
35 #include "url.h" /* for the ssl config check function */
42 #define _MPRINTF_REPLACE /* use the internal *printf() functions */
43 #include <curl/mprintf.h>
63 #include "curl_memory.h"
68 /* The last #include file should be: */
71 #define SSL_DIR "/etc/pki/nssdb"
73 /* enough to fit the string "PEM Token #[0|1]" */
76 PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
78 PRLock * nss_initlock = NULL;
79 PRLock * nss_crllock = NULL;
80 #ifdef HAVE_NSS_INITCONTEXT
81 NSSInitContext * nss_context = NULL;
84 volatile int initialized = 0;
91 #define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
92 CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
93 ptr->type = (_type); \
94 ptr->pValue = (_val); \
95 ptr->ulValueLen = (_len); \
98 #define CERT_NewTempCertificate __CERT_NewTempCertificate
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},
104 {"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
105 {"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
106 {"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
107 {"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
108 {"des", SSL_EN_DES_64_CBC_WITH_MD5},
109 {"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
110 /* SSL3/TLS cipher suites */
111 {"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
112 {"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
113 {"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
114 {"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
115 {"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
116 {"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
117 {"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
118 {"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
119 {"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
120 {"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
121 {"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
122 {"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
123 {"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
124 /* TLS 1.0: Exportable 56-bit Cipher Suites. */
125 {"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
126 {"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
128 {"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
129 {"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
130 #ifdef NSS_ENABLE_ECC
132 {"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
133 {"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
134 {"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
135 {"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
136 {"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
137 {"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
138 {"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
139 {"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
140 {"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
141 {"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
142 {"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
143 {"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
144 {"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
145 {"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
146 {"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
147 {"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
148 {"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
149 {"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
150 {"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
151 {"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
152 {"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
153 {"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
154 {"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
155 {"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
156 {"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
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 static const char* pem_library = "libnsspem.so";
173 SECMODModule* mod = NULL;
175 static const char* nss_error_to_name(PRErrorCode code)
177 const char *name = PR_ErrorToName(code);
181 return "unknown error";
184 static void nss_print_error_message(struct SessionHandle *data, PRUint32 err)
186 failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
189 static SECStatus set_ciphers(struct SessionHandle *data, PRFileDesc * model,
193 PRBool cipher_state[NUM_OF_CIPHERS];
198 /* First disable all ciphers. This uses a different max value in case
199 * NSS adds more ciphers later we don't want them available by
202 for(i=0; i<SSL_NumImplementedCiphers; i++) {
203 SSL_CipherPrefSet(model, SSL_ImplementedCiphers[i], SSL_NOT_ALLOWED);
206 /* Set every entry in our list to false */
207 for(i=0; i<NUM_OF_CIPHERS; i++) {
208 cipher_state[i] = PR_FALSE;
211 cipher = cipher_list;
213 while(cipher_list && (cipher_list[0])) {
214 while((*cipher) && (ISSPACE(*cipher)))
217 if((cipher_list = strchr(cipher, ','))) {
218 *cipher_list++ = '\0';
223 for(i=0; i<NUM_OF_CIPHERS; i++) {
224 if(Curl_raw_equal(cipher, cipherlist[i].name)) {
225 cipher_state[i] = PR_TRUE;
231 if(found == PR_FALSE) {
232 failf(data, "Unknown cipher in list: %s", cipher);
237 cipher = cipher_list;
241 /* Finally actually enable the selected ciphers */
242 for(i=0; i<NUM_OF_CIPHERS; i++) {
243 rv = SSL_CipherPrefSet(model, cipherlist[i].num, cipher_state[i]);
244 if(rv != SECSuccess) {
245 failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
254 * Get the number of ciphers that are enabled. We use this to determine
255 * if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
257 static int num_enabled_ciphers(void)
263 for(i=0; i<NUM_OF_CIPHERS; i++) {
264 SSL_CipherPolicyGet(cipherlist[i].num, &policy);
272 * Determine whether the nickname passed in is a filename that needs to
273 * be loaded as a PEM or a regular NSS nickname.
275 * returns 1 for a file
276 * returns 0 for not a file (NSS nickname)
278 static int is_file(const char *filename)
285 if(stat(filename, &st) == 0)
286 if(S_ISREG(st.st_mode))
292 /* Check if the given string is filename or nickname of a certificate. If the
293 * given string is recognized as filename, return NULL. If the given string is
294 * recognized as nickname, return a duplicated string. The returned string
295 * should be later deallocated using free(). If the OOM failure occurs, we
298 static char* dup_nickname(struct SessionHandle *data, enum dupstring cert_kind)
300 const char *str = data->set.str[cert_kind];
304 /* no such file exists, use the string as nickname */
307 /* search the last slash; we require at least one slash in a file name */
308 n = strrchr(str, '/');
310 infof(data, "warning: certificate file name \"%s\" handled as nickname; "
311 "please use \"./%s\" to force file name\n", str, str);
315 /* we'll use the PEM reader to read the certificate from file */
319 /* Call PK11_CreateGenericObject() with the given obj_class and filename. If
320 * the call succeeds, append the object handle to the list of objects so that
321 * the object can be destroyed in Curl_nss_close(). */
322 static CURLcode nss_create_object(struct ssl_connect_data *ssl,
323 CK_OBJECT_CLASS obj_class,
324 const char *filename, bool cacert)
327 PK11GenericObject *obj;
328 CK_BBOOL cktrue = CK_TRUE;
329 CK_BBOOL ckfalse = CK_FALSE;
330 CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
332 CURLcode err = (cacert)
333 ? CURLE_SSL_CACERT_BADFILE
334 : CURLE_SSL_CERTPROBLEM;
336 const int slot_id = (cacert) ? 0 : 1;
337 char *slot_name = aprintf("PEM Token #%d", slot_id);
339 return CURLE_OUT_OF_MEMORY;
341 slot = PK11_FindSlotByName(slot_name);
346 PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
347 PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
348 PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
349 strlen(filename) + 1);
351 if(CKO_CERTIFICATE == obj_class) {
352 CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
353 PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
356 obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
361 if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
362 PK11_DestroyGenericObject(obj);
363 return CURLE_OUT_OF_MEMORY;
366 if(!cacert && CKO_CERTIFICATE == obj_class)
367 /* store reference to a client certificate */
368 ssl->obj_clicert = obj;
373 /* Destroy the NSS object whose handle is given by ptr. This function is
374 * a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
375 * NSS objects in Curl_nss_close() */
376 static void nss_destroy_object(void *user, void *ptr)
378 PK11GenericObject *obj = (PK11GenericObject *)ptr;
380 PK11_DestroyGenericObject(obj);
383 static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
384 const char *filename, PRBool cacert)
386 CURLcode err = (cacert)
387 ? CURLE_SSL_CACERT_BADFILE
388 : CURLE_SSL_CERTPROBLEM;
390 /* libnsspem.so leaks memory if the requested file does not exist. For more
391 * details, go to <https://bugzilla.redhat.com/734760>. */
392 if(is_file(filename))
393 err = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
395 if(CURLE_OK == err && !cacert) {
396 /* we have successfully loaded a client certificate */
397 CERTCertificate *cert;
398 char *nickname = NULL;
399 char *n = strrchr(filename, '/');
403 /* The following undocumented magic helps to avoid a SIGSEGV on call
404 * of PK11_ReadRawAttribute() from SelectClientCert() when using an
405 * immature version of libnsspem.so. For more details, go to
406 * <https://bugzilla.redhat.com/733685>. */
407 nickname = aprintf("PEM Token #1:%s", n);
409 cert = PK11_FindCertFromNickname(nickname, NULL);
411 CERT_DestroyCertificate(cert);
420 /* add given CRL to cache if it is not already there */
421 static SECStatus nss_cache_crl(SECItem *crlDER)
423 CERTCertDBHandle *db = CERT_GetDefaultCertDB();
424 CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crlDER, 0);
426 /* CRL already cached */
428 SECITEM_FreeItem(crlDER, PR_FALSE);
432 /* acquire lock before call of CERT_CacheCRL() */
433 PR_Lock(nss_crllock);
434 if(SECSuccess != CERT_CacheCRL(db, crlDER)) {
435 /* unable to cache CRL */
436 PR_Unlock(nss_crllock);
437 SECITEM_FreeItem(crlDER, PR_FALSE);
441 /* we need to clear session cache, so that the CRL could take effect */
442 SSL_ClearSessionCache();
443 PR_Unlock(nss_crllock);
447 static SECStatus nss_load_crl(const char* crlfilename)
451 SECItem filedata = { 0, NULL, 0 };
452 SECItem crlDER = { 0, NULL, 0 };
455 infile = PR_Open(crlfilename, PR_RDONLY, 0);
459 if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
462 if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
465 if(info.size != PR_Read(infile, filedata.data, info.size))
468 /* place a trailing zero right after the visible data */
469 body = (char*)filedata.data;
470 body[--filedata.len] = '\0';
472 body = strstr(body, "-----BEGIN");
476 char *begin = PORT_Strchr(body, '\n');
478 begin = PORT_Strchr(body, '\r');
482 trailer = strstr(++begin, "-----END");
486 /* retrieve DER from ASCII */
488 if(ATOB_ConvertAsciiToItem(&crlDER, begin))
491 SECITEM_FreeItem(&filedata, PR_FALSE);
498 return nss_cache_crl(&crlDER);
502 SECITEM_FreeItem(&filedata, PR_FALSE);
506 static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
512 struct ssl_connect_data *ssl = conn->ssl;
513 (void)sockindex; /* unused */
515 rv = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
517 PR_SetError(SEC_ERROR_BAD_KEY, 0);
521 slot = PK11_FindSlotByName("PEM Token #1");
523 return CURLE_SSL_CERTPROBLEM;
525 /* This will force the token to be seen as re-inserted */
526 SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
527 PK11_IsPresent(slot);
529 status = PK11_Authenticate(slot, PR_TRUE,
530 conn->data->set.str[STRING_KEY_PASSWD]);
532 return (SECSuccess == status)
534 : CURLE_SSL_CERTPROBLEM;
537 static int display_error(struct connectdata *conn, PRInt32 err,
538 const char *filename)
541 case SEC_ERROR_BAD_PASSWORD:
542 failf(conn->data, "Unable to load client key: Incorrect password");
544 case SEC_ERROR_UNKNOWN_CERT:
545 failf(conn->data, "Unable to load certificate %s", filename);
550 return 0; /* The caller will print a generic error */
553 static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
554 char *cert_file, char *key_file)
556 struct SessionHandle *data = conn->data;
560 rv = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
562 const PRErrorCode err = PR_GetError();
563 if(!display_error(conn, err, cert_file)) {
564 const char *err_name = nss_error_to_name(err);
565 failf(data, "unable to load client cert: %d (%s)", err, err_name);
572 if(key_file || (is_file(cert_file))) {
574 rv = nss_load_key(conn, sockindex, key_file);
576 /* In case the cert file also has the key */
577 rv = nss_load_key(conn, sockindex, cert_file);
579 const PRErrorCode err = PR_GetError();
580 if(!display_error(conn, err, key_file)) {
581 const char *err_name = nss_error_to_name(err);
582 failf(data, "unable to load client key: %d (%s)", err, err_name);
592 static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
594 (void)slot; /* unused */
595 if(retry || NULL == arg)
598 return (char *)PORT_Strdup((char *)arg);
601 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
603 static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
606 struct connectdata *conn = (struct connectdata *)arg;
607 if(!conn->data->set.ssl.verifypeer) {
608 infof(conn->data, "skipping SSL peer certificate verification\n");
612 return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
616 * Inform the application that the handshake is complete.
618 static void HandshakeCallback(PRFileDesc *sock, void *arg)
624 static void display_cert_info(struct SessionHandle *data,
625 CERTCertificate *cert)
627 char *subject, *issuer, *common_name;
628 PRExplodedTime printableTime;
629 char timeString[256];
630 PRTime notBefore, notAfter;
632 subject = CERT_NameToAscii(&cert->subject);
633 issuer = CERT_NameToAscii(&cert->issuer);
634 common_name = CERT_GetCommonName(&cert->subject);
635 infof(data, "\tsubject: %s\n", subject);
637 CERT_GetCertTimes(cert, ¬Before, ¬After);
638 PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
639 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
640 infof(data, "\tstart date: %s\n", timeString);
641 PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
642 PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
643 infof(data, "\texpire date: %s\n", timeString);
644 infof(data, "\tcommon name: %s\n", common_name);
645 infof(data, "\tissuer: %s\n", issuer);
649 PR_Free(common_name);
652 static void display_conn_info(struct connectdata *conn, PRFileDesc *sock)
654 SSLChannelInfo channel;
655 SSLCipherSuiteInfo suite;
656 CERTCertificate *cert;
657 CERTCertificate *cert2;
658 CERTCertificate *cert3;
662 if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
663 SECSuccess && channel.length == sizeof channel &&
664 channel.cipherSuite) {
665 if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
666 &suite, sizeof suite) == SECSuccess) {
667 infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
671 cert = SSL_PeerCertificate(sock);
674 infof(conn->data, "Server certificate:\n");
676 if(!conn->data->set.ssl.certinfo) {
677 display_cert_info(conn->data, cert);
678 CERT_DestroyCertificate(cert);
681 /* Count certificates in chain. */
685 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
689 CERT_DestroyCertificate(cert2);
692 cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
693 CERT_DestroyCertificate(cert2);
697 Curl_ssl_init_certinfo(conn->data, i);
698 for(i = 0; cert; cert = cert2) {
699 Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
700 (char *)cert->derCert.data + cert->derCert.len);
702 CERT_DestroyCertificate(cert);
705 cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
706 CERT_DestroyCertificate(cert);
714 static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
716 struct connectdata *conn = (struct connectdata *)arg;
717 struct SessionHandle *data = conn->data;
718 PRErrorCode err = PR_GetError();
719 CERTCertificate *cert;
721 /* remember the cert verification result */
722 data->set.ssl.certverifyresult = err;
724 if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
725 /* we are asked not to verify the host name */
728 /* print only info about the cert, the error is printed off the callback */
729 cert = SSL_PeerCertificate(sock);
731 infof(data, "Server certificate:\n");
732 display_cert_info(data, cert);
733 CERT_DestroyCertificate(cert);
741 * Check that the Peer certificate's issuer certificate matches the one found
742 * by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
743 * issuer check, so we provide comments that mimic the OpenSSL
744 * X509_check_issued function (in x509v3/v3_purp.c)
746 static SECStatus check_issuer_cert(PRFileDesc *sock,
747 char *issuer_nickname)
749 CERTCertificate *cert,*cert_issuer,*issuer;
750 SECStatus res=SECSuccess;
751 void *proto_win = NULL;
754 PRArenaPool *tmpArena = NULL;
755 CERTAuthKeyID *authorityKeyID = NULL;
756 SECITEM *caname = NULL;
759 cert = SSL_PeerCertificate(sock);
760 cert_issuer = CERT_FindCertIssuer(cert,PR_Now(),certUsageObjectSigner);
762 proto_win = SSL_RevealPinArg(sock);
763 issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
765 if((!cert_issuer) || (!issuer))
767 else if(SECITEM_CompareItem(&cert_issuer->derCert,
768 &issuer->derCert)!=SECEqual)
771 CERT_DestroyCertificate(cert);
772 CERT_DestroyCertificate(issuer);
773 CERT_DestroyCertificate(cert_issuer);
779 * Callback to pick the SSL client certificate.
781 static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
782 struct CERTDistNamesStr *caNames,
783 struct CERTCertificateStr **pRetCert,
784 struct SECKEYPrivateKeyStr **pRetKey)
786 struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
787 struct SessionHandle *data = connssl->data;
788 const char *nickname = connssl->client_nickname;
790 if(connssl->obj_clicert) {
791 /* use the cert/key provided by PEM reader */
792 static const char pem_slotname[] = "PEM Token #1";
793 SECItem cert_der = { 0, NULL, 0 };
794 void *proto_win = SSL_RevealPinArg(sock);
795 struct CERTCertificateStr *cert;
796 struct SECKEYPrivateKeyStr *key;
798 PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
800 failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
804 if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
805 &cert_der) != SECSuccess) {
806 failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
811 cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
812 SECITEM_FreeItem(&cert_der, PR_FALSE);
814 failf(data, "NSS: client certificate from file not found");
819 key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
822 failf(data, "NSS: private key from file not found");
823 CERT_DestroyCertificate(cert);
827 infof(data, "NSS: client certificate from file\n");
828 display_cert_info(data, cert);
835 /* use the default NSS hook */
836 if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
838 || NULL == *pRetCert) {
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;
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 nss_init_core(struct SessionHandle *data, const char *cert_dir)
896 #ifdef HAVE_NSS_INITCONTEXT
897 NSSInitParameters initparams;
899 if(nss_context != NULL)
902 memset((void *) &initparams, '\0', sizeof(initparams));
903 initparams.length = sizeof(initparams);
904 #else /* HAVE_NSS_INITCONTEXT */
907 if(NSS_IsInitialized())
912 const bool use_sql = NSS_VersionCheck("3.12.0");
913 char *certpath = aprintf("%s%s", use_sql ? "sql:" : "", cert_dir);
915 return CURLE_OUT_OF_MEMORY;
917 infof(data, "Initializing NSS with certpath: %s\n", certpath);
918 #ifdef HAVE_NSS_INITCONTEXT
919 nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
920 NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
923 if(nss_context != NULL)
925 #else /* HAVE_NSS_INITCONTEXT */
926 rv = NSS_Initialize(certpath, "", "", "", NSS_INIT_READONLY);
933 infof(data, "Unable to initialize NSS database\n");
936 infof(data, "Initializing NSS with certpath: none\n");
937 #ifdef HAVE_NSS_INITCONTEXT
938 nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
939 | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
940 | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
941 if(nss_context != NULL)
943 #else /* HAVE_NSS_INITCONTEXT */
944 if(NSS_NoDB_Init(NULL) == SECSuccess)
948 infof(data, "Unable to initialize NSS\n");
949 return CURLE_SSL_CACERT_BADFILE;
952 static CURLcode nss_init(struct SessionHandle *data)
961 /* First we check if $SSL_DIR points to a valid dir */
962 cert_dir = getenv("SSL_DIR");
964 if((stat(cert_dir, &st) != 0) ||
965 (!S_ISDIR(st.st_mode))) {
970 /* Now we check if the default location is a valid dir */
972 if((stat(SSL_DIR, &st) == 0) &&
973 (S_ISDIR(st.st_mode))) {
974 cert_dir = (char *)SSL_DIR;
978 rv = nss_init_core(data, cert_dir);
982 if(num_enabled_ciphers() == 0)
983 NSS_SetDomesticPolicy();
992 * @retval 0 error initializing SSL
993 * @retval 1 SSL initialized successfully
995 int Curl_nss_init(void)
997 /* curl_global_init() is not thread-safe so this test is ok */
998 if(nss_initlock == NULL) {
999 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
1000 nss_initlock = PR_NewLock();
1001 nss_crllock = PR_NewLock();
1004 /* We will actually initialize NSS later */
1009 CURLcode Curl_nss_force_init(struct SessionHandle *data)
1014 "unable to initialize NSS, curl_global_init() should have been "
1015 "called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
1016 return CURLE_FAILED_INIT;
1019 PR_Lock(nss_initlock);
1020 rv = nss_init(data);
1021 PR_Unlock(nss_initlock);
1025 /* Global cleanup */
1026 void Curl_nss_cleanup(void)
1028 /* This function isn't required to be threadsafe and this is only done
1029 * as a safety feature.
1031 PR_Lock(nss_initlock);
1033 /* Free references to client certificates held in the SSL session cache.
1034 * Omitting this hampers destruction of the security module owning
1035 * the certificates. */
1036 SSL_ClearSessionCache();
1038 if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
1039 SECMOD_DestroyModule(mod);
1042 #ifdef HAVE_NSS_INITCONTEXT
1043 NSS_ShutdownContext(nss_context);
1045 #else /* HAVE_NSS_INITCONTEXT */
1049 PR_Unlock(nss_initlock);
1051 PR_DestroyLock(nss_initlock);
1052 PR_DestroyLock(nss_crllock);
1053 nss_initlock = NULL;
1059 * This function uses SSL_peek to determine connection status.
1062 * 1 means the connection is still in place
1063 * 0 means the connection has been closed
1064 * -1 means the connection status is unknown
1067 Curl_nss_check_cxn(struct connectdata *conn)
1073 PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
1074 PR_SecondsToInterval(1));
1076 return 1; /* connection still in place */
1079 return 0; /* connection has been closed */
1081 return -1; /* connection status unknown */
1085 * This function is called when an SSL connection is closed.
1087 void Curl_nss_close(struct connectdata *conn, int sockindex)
1089 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1091 if(connssl->handle) {
1092 /* NSS closes the socket we previously handed to it, so we must mark it
1093 as closed to avoid double close */
1094 fake_sclose(conn->sock[sockindex]);
1095 conn->sock[sockindex] = CURL_SOCKET_BAD;
1097 if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
1098 /* A server might require different authentication based on the
1099 * particular path being requested by the client. To support this
1100 * scenario, we must ensure that a connection will never reuse the
1101 * authentication data from a previous connection. */
1102 SSL_InvalidateSession(connssl->handle);
1104 if(connssl->client_nickname != NULL) {
1105 free(connssl->client_nickname);
1106 connssl->client_nickname = NULL;
1108 /* destroy all NSS objects in order to avoid failure of NSS shutdown */
1109 Curl_llist_destroy(connssl->obj_list, NULL);
1110 connssl->obj_list = NULL;
1111 connssl->obj_clicert = NULL;
1113 PR_Close(connssl->handle);
1114 connssl->handle = NULL;
1119 * This function is called when the 'data' struct is going away. Close
1120 * down everything and free all resources!
1122 int Curl_nss_close_all(struct SessionHandle *data)
1128 /* return true if NSS can provide error code (and possibly msg) for the
1130 static bool is_nss_error(CURLcode err)
1133 case CURLE_PEER_FAILED_VERIFICATION:
1134 case CURLE_SSL_CACERT:
1135 case CURLE_SSL_CERTPROBLEM:
1136 case CURLE_SSL_CONNECT_ERROR:
1137 case CURLE_SSL_ISSUER_ERROR:
1145 /* return true if the given error code is related to a client certificate */
1146 static bool is_cc_error(PRInt32 err)
1149 case SSL_ERROR_BAD_CERT_ALERT:
1150 case SSL_ERROR_EXPIRED_CERT_ALERT:
1151 case SSL_ERROR_REVOKED_CERT_ALERT:
1159 static Curl_recv nss_recv;
1160 static Curl_send nss_send;
1162 static CURLcode nss_load_ca_certificates(struct connectdata *conn,
1165 struct SessionHandle *data = conn->data;
1166 const char *cafile = data->set.ssl.CAfile;
1167 const char *capath = data->set.ssl.CApath;
1170 CURLcode rv = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
1177 if(stat(capath, &st) == -1)
1178 return CURLE_SSL_CACERT_BADFILE;
1180 if(S_ISDIR(st.st_mode)) {
1182 PRDir *dir = PR_OpenDir(capath);
1184 return CURLE_SSL_CACERT_BADFILE;
1186 while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
1187 char *fullpath = aprintf("%s/%s", capath, entry->name);
1190 return CURLE_OUT_OF_MEMORY;
1193 if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
1194 /* This is purposefully tolerant of errors so non-PEM files can
1195 * be in the same directory */
1196 infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
1204 infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
1207 infof(data, " CAfile: %s\n CApath: %s\n",
1208 cafile ? cafile : "none",
1209 capath ? capath : "none");
1214 static CURLcode nss_init_sslver(SSLVersionRange *sslver,
1215 struct SessionHandle *data)
1217 switch (data->set.ssl.version) {
1219 case CURL_SSLVERSION_DEFAULT:
1220 sslver->min = SSL_LIBRARY_VERSION_3_0;
1221 if(data->state.ssl_connect_retry) {
1222 infof(data, "TLS disabled due to previous handshake failure\n");
1223 sslver->max = SSL_LIBRARY_VERSION_3_0;
1226 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1229 case CURL_SSLVERSION_TLSv1:
1230 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1231 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1232 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1233 #elif defined SSL_LIBRARY_VERSION_TLS_1_1
1234 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1236 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1240 case CURL_SSLVERSION_SSLv2:
1241 sslver->min = SSL_LIBRARY_VERSION_2;
1242 sslver->max = SSL_LIBRARY_VERSION_2;
1245 case CURL_SSLVERSION_SSLv3:
1246 sslver->min = SSL_LIBRARY_VERSION_3_0;
1247 sslver->max = SSL_LIBRARY_VERSION_3_0;
1250 case CURL_SSLVERSION_TLSv1_0:
1251 sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
1252 sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
1255 case CURL_SSLVERSION_TLSv1_1:
1256 #ifdef SSL_LIBRARY_VERSION_TLS_1_1
1257 sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
1258 sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
1263 case CURL_SSLVERSION_TLSv1_2:
1264 #ifdef SSL_LIBRARY_VERSION_TLS_1_2
1265 sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
1266 sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
1272 failf(data, "TLS minor version cannot be set");
1273 return CURLE_SSL_CONNECT_ERROR;
1276 CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
1278 PRErrorCode err = 0;
1279 PRFileDesc *model = NULL;
1280 SSLVersionRange sslver;
1281 PRBool ssl_no_cache;
1282 PRBool ssl_cbc_random_iv;
1283 struct SessionHandle *data = conn->data;
1284 curl_socket_t sockfd = conn->sock[sockindex];
1285 struct ssl_connect_data *connssl = &conn->ssl[sockindex];
1287 const int *cipher_to_enable;
1288 PRSocketOptionData sock_opt;
1292 if(connssl->state == ssl_connection_complete)
1295 connssl->data = data;
1297 /* list of all NSS objects we need to destroy in Curl_nss_close() */
1298 connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
1299 if(!connssl->obj_list)
1300 return CURLE_OUT_OF_MEMORY;
1302 /* FIXME. NSS doesn't support multiple databases open at the same time. */
1303 PR_Lock(nss_initlock);
1304 curlerr = nss_init(conn->data);
1305 if(CURLE_OK != curlerr) {
1306 PR_Unlock(nss_initlock);
1310 curlerr = CURLE_SSL_CONNECT_ERROR;
1313 char *configstring = aprintf("library=%s name=PEM", pem_library);
1315 PR_Unlock(nss_initlock);
1318 mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
1321 if(!mod || !mod->loaded) {
1323 SECMOD_DestroyModule(mod);
1326 infof(data, "WARNING: failed to load NSS PEM library %s. Using "
1327 "OpenSSL PEM certificates will not work.\n", pem_library);
1331 PK11_SetPasswordFunc(nss_get_password);
1332 PR_Unlock(nss_initlock);
1334 model = PR_NewTCPSocket();
1337 model = SSL_ImportFD(NULL, model);
1339 if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
1341 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
1343 if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
1346 /* do not use SSL cache if disabled or we are not going to verify peer */
1347 ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
1349 if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
1352 /* enable/disable the requested SSL version(s) */
1353 if(nss_init_sslver(&sslver, data) != CURLE_OK)
1355 if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
1358 ssl_cbc_random_iv = !data->set.ssl_enable_beast;
1359 #ifdef SSL_CBC_RANDOM_IV
1360 /* unless the user explicitly asks to allow the protocol vulnerability, we
1361 use the work-around */
1362 if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
1363 infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
1366 if(ssl_cbc_random_iv)
1367 infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
1370 /* reset the flag to avoid an infinite loop */
1371 data->state.ssl_connect_retry = FALSE;
1373 /* enable all ciphers from enable_ciphers_by_default */
1374 cipher_to_enable = enable_ciphers_by_default;
1375 while(SSL_NULL_WITH_NULL_NULL != *cipher_to_enable) {
1376 if(SSL_CipherPrefSet(model, *cipher_to_enable, PR_TRUE) != SECSuccess) {
1377 curlerr = CURLE_SSL_CIPHER;
1383 if(data->set.ssl.cipher_list) {
1384 if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
1385 curlerr = CURLE_SSL_CIPHER;
1390 if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
1391 infof(data, "warning: ignoring value of ssl.verifyhost\n");
1393 /* bypass the default SSL_AuthCertificate() hook in case we do not want to
1395 if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
1398 data->set.ssl.certverifyresult=0; /* not checked yet */
1399 if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
1402 if(SSL_HandshakeCallback(model, HandshakeCallback, NULL) != SECSuccess)
1405 if(data->set.ssl.verifypeer) {
1406 const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
1407 if(CURLE_OK != rv) {
1413 if(data->set.ssl.CRLfile) {
1414 if(SECSuccess != nss_load_crl(data->set.ssl.CRLfile)) {
1415 curlerr = CURLE_SSL_CRL_BADFILE;
1420 data->set.ssl.CRLfile ? data->set.ssl.CRLfile : "none");
1423 if(data->set.str[STRING_CERT]) {
1424 char *nickname = dup_nickname(data, STRING_CERT);
1426 /* we are not going to use libnsspem.so to read the client cert */
1427 connssl->obj_clicert = NULL;
1430 CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
1431 data->set.str[STRING_KEY]);
1432 if(CURLE_OK != rv) {
1433 /* failf() is already done in cert_stuff() */
1439 /* store the nickname for SelectClientCert() called during handshake */
1440 connssl->client_nickname = nickname;
1443 connssl->client_nickname = NULL;
1445 if(SSL_GetClientAuthDataHook(model, SelectClientCert,
1446 (void *)connssl) != SECSuccess) {
1447 curlerr = CURLE_SSL_CERTPROBLEM;
1451 /* Import our model socket onto the existing file descriptor */
1452 connssl->handle = PR_ImportTCPSocket(sockfd);
1453 connssl->handle = SSL_ImportFD(model, connssl->handle);
1454 if(!connssl->handle)
1457 PR_Close(model); /* We don't need this any more */
1460 /* This is the password associated with the cert that we're using */
1461 if(data->set.str[STRING_KEY_PASSWD]) {
1462 SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
1465 /* Force handshake on next I/O */
1466 SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
1468 SSL_SetURL(connssl->handle, conn->host.name);
1470 /* check timeout situation */
1471 time_left = Curl_timeleft(data, NULL, TRUE);
1472 if(time_left < 0L) {
1473 failf(data, "timed out before SSL handshake");
1474 curlerr = CURLE_OPERATION_TIMEDOUT;
1477 timeout = PR_MillisecondsToInterval((PRUint32) time_left);
1479 /* Force the handshake now */
1480 if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
1481 if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
1482 curlerr = CURLE_PEER_FAILED_VERIFICATION;
1483 else if(conn->data->set.ssl.certverifyresult!=0)
1484 curlerr = CURLE_SSL_CACERT;
1488 /* switch the SSL socket into non-blocking mode */
1489 sock_opt.option = PR_SockOpt_Nonblocking;
1490 sock_opt.value.non_blocking = PR_TRUE;
1491 if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
1494 connssl->state = ssl_connection_complete;
1495 conn->recv[sockindex] = nss_recv;
1496 conn->send[sockindex] = nss_send;
1498 display_conn_info(conn, connssl->handle);
1500 if(data->set.str[STRING_SSL_ISSUERCERT]) {
1501 SECStatus ret = SECFailure;
1502 char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
1504 /* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
1505 ret = check_issuer_cert(connssl->handle, nickname);
1509 if(SECFailure == ret) {
1510 infof(data,"SSL certificate issuer check failed\n");
1511 curlerr = CURLE_SSL_ISSUER_ERROR;
1515 infof(data, "SSL certificate issuer check ok\n");
1522 /* reset the flag to avoid an infinite loop */
1523 data->state.ssl_connect_retry = FALSE;
1525 if(is_nss_error(curlerr)) {
1526 /* read NSPR error code */
1527 err = PR_GetError();
1528 if(is_cc_error(err))
1529 curlerr = CURLE_SSL_CERTPROBLEM;
1531 /* print the error number and error string */
1532 infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
1534 /* print a human-readable message describing the error if available */
1535 nss_print_error_message(data, err);
1541 /* cleanup on connection failure */
1542 Curl_llist_destroy(connssl->obj_list, NULL);
1543 connssl->obj_list = NULL;
1545 if((sslver.min == SSL_LIBRARY_VERSION_3_0)
1546 && (sslver.max == SSL_LIBRARY_VERSION_TLS_1_0)
1547 && isTLSIntoleranceError(err)) {
1548 /* schedule reconnect through Curl_retry_request() */
1549 data->state.ssl_connect_retry = TRUE;
1550 infof(data, "Error in TLS handshake, trying SSLv3...\n");
1557 static ssize_t nss_send(struct connectdata *conn, /* connection data */
1558 int sockindex, /* socketindex */
1559 const void *mem, /* send this data */
1560 size_t len, /* amount to write */
1563 ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
1564 PR_INTERVAL_NO_WAIT);
1566 PRInt32 err = PR_GetError();
1567 if(err == PR_WOULD_BLOCK_ERROR)
1568 *curlcode = CURLE_AGAIN;
1570 /* print the error number and error string */
1571 const char *err_name = nss_error_to_name(err);
1572 infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
1574 /* print a human-readable message describing the error if available */
1575 nss_print_error_message(conn->data, err);
1577 *curlcode = (is_cc_error(err))
1578 ? CURLE_SSL_CERTPROBLEM
1583 return rc; /* number of bytes */
1586 static ssize_t nss_recv(struct connectdata * conn, /* connection data */
1587 int num, /* socketindex */
1588 char *buf, /* store read data here */
1589 size_t buffersize, /* max amount to read */
1592 ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
1593 PR_INTERVAL_NO_WAIT);
1595 /* failed SSL read */
1596 PRInt32 err = PR_GetError();
1598 if(err == PR_WOULD_BLOCK_ERROR)
1599 *curlcode = CURLE_AGAIN;
1601 /* print the error number and error string */
1602 const char *err_name = nss_error_to_name(err);
1603 infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
1605 /* print a human-readable message describing the error if available */
1606 nss_print_error_message(conn->data, err);
1608 *curlcode = (is_cc_error(err))
1609 ? CURLE_SSL_CERTPROBLEM
1617 size_t Curl_nss_version(char *buffer, size_t size)
1619 return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
1622 int Curl_nss_seed(struct SessionHandle *data)
1624 /* make sure that NSS is initialized */
1625 return !!Curl_nss_force_init(data);
1628 void Curl_nss_random(struct SessionHandle *data,
1629 unsigned char *entropy,
1632 Curl_nss_seed(data); /* Initiate the seed if not already done */
1633 if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length))) {
1634 /* no way to signal a failure from here, we have to abort */
1635 failf(data, "PK11_GenerateRandom() failed, calling abort()...");
1640 void Curl_nss_md5sum(unsigned char *tmp, /* input */
1642 unsigned char *md5sum, /* output */
1645 PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
1646 unsigned int MD5out;
1647 PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
1648 PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
1649 PK11_DestroyContext(MD5pw, PR_TRUE);
1652 #endif /* USE_NSS */