Newer
Older
/**
*
* Callback to pick the SSL client certificate.
*/
static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct SessionHandle *data = connssl->data;
const char *nickname = connssl->client_nickname;
/* use the cert/key provided by PEM reader */
static const char pem_slotname[] = "PEM Token #1";
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
/* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
static void nss_update_connecting_state(ssl_connect_state state, void *secret)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
/* an unrelated error is passing by */
return;
switch(connssl->connecting_state) {
case ssl_connect_2:
case ssl_connect_2_reading:
case ssl_connect_2_writing:
break;
default:
/* we are not called from an SSL handshake */
return;
}
/* update the state accordingly */
connssl->connecting_state = state;
}
/* recv() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRRecvFN recv_fn = fd->lower->methods->recv;
const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
return rv;
}
/* send() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRSendFN send_fn = fd->lower->methods->send;
const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
return rv;
}
/* close() wrapper to avoid assertion failure due to fd->secret != NULL */
static PRStatus nspr_io_close(PRFileDesc *fd)
{
const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
fd->secret = NULL;
return close_fn(fd);
}
/* data might be NULL */
static CURLcode nss_init_core(struct SessionHandle *data, const char *cert_dir)
{
if(nss_context != NULL)
return CURLE_OK;
memset((void *) &initparams, '\0', sizeof(initparams));
initparams.length = sizeof(initparams);
if(cert_dir) {
char *certpath = aprintf("sql:%s", cert_dir);
if(!certpath)
return CURLE_OUT_OF_MEMORY;
infof(data, "Initializing NSS with certpath: %s\n", certpath);
nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
free(certpath);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS database\n");
}
infof(data, "Initializing NSS with certpath: none\n");
nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
| NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
| NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS\n");
return CURLE_SSL_CACERT_BADFILE;
}
/* data might be NULL */
static CURLcode nss_init(struct SessionHandle *data)
{
char *cert_dir;
struct_stat st;
if(initialized)
return CURLE_OK;
/* list of all CRL items we need to destroy in Curl_nss_cleanup() */
nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
if(!nss_crl_list)
return CURLE_OUT_OF_MEMORY;
/* First we check if $SSL_DIR points to a valid dir */
cert_dir = getenv("SSL_DIR");
if(cert_dir) {
if((stat(cert_dir, &st) != 0) ||
(!S_ISDIR(st.st_mode))) {
cert_dir = NULL;
}
}
/* Now we check if the default location is a valid dir */
if(!cert_dir) {
if((stat(SSL_DIR, &st) == 0) &&
(S_ISDIR(st.st_mode))) {
cert_dir = (char *)SSL_DIR;
}
}
if(nspr_io_identity == PR_INVALID_IO_LAYER) {
/* allocate an identity for our own NSPR I/O layer */
nspr_io_identity = PR_GetUniqueIdentity("libcurl");
if(nspr_io_identity == PR_INVALID_IO_LAYER)
return CURLE_OUT_OF_MEMORY;
/* the default methods just call down to the lower I/O layer */
memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
/* override certain methods in the table by our wrappers */
nspr_io_methods.recv = nspr_io_recv;
nspr_io_methods.send = nspr_io_send;
nspr_io_methods.close = nspr_io_close;
}
result = nss_init_core(data, cert_dir);
if(result)
return result;
if(num_enabled_ciphers() == 0)
NSS_SetDomesticPolicy();
initialized = 1;
/**
* Global SSL init
*
* @retval 0 error initializing SSL
* @retval 1 SSL initialized successfully
*/
int Curl_nss_init(void)
{
Daniel Stenberg
committed
/* curl_global_init() is not thread-safe so this test is ok */
if(nss_initlock == NULL) {
PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
Daniel Stenberg
committed
nss_initlock = PR_NewLock();
nss_crllock = PR_NewLock();
Daniel Stenberg
committed
}
/* We will actually initialize NSS later */
return 1;
}
/* data might be NULL */
CURLcode Curl_nss_force_init(struct SessionHandle *data)
{
if(data)
failf(data, "unable to initialize NSS, curl_global_init() should have "
"been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
return CURLE_FAILED_INIT;
result = nss_init(data);
/* Global cleanup */
void Curl_nss_cleanup(void)
{
Daniel Stenberg
committed
/* This function isn't required to be threadsafe and this is only done
* as a safety feature.
*/
PR_Lock(nss_initlock);
if(initialized) {
/* Free references to client certificates held in the SSL session cache.
* Omitting this hampers destruction of the security module owning
* the certificates. */
SSL_ClearSessionCache();
if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
NSS_ShutdownContext(nss_context);
nss_context = NULL;
}
/* destroy all CRL items */
Curl_llist_destroy(nss_crl_list, NULL);
nss_crl_list = NULL;
Daniel Stenberg
committed
PR_Unlock(nss_initlock);
PR_DestroyLock(nss_initlock);
PR_DestroyLock(nss_crllock);
Daniel Stenberg
committed
nss_initlock = NULL;
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
initialized = 0;
}
/*
* This function uses SSL_peek to determine connection status.
*
* Return codes:
* 1 means the connection is still in place
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
int
Curl_nss_check_cxn(struct connectdata *conn)
{
int rc;
char buf;
rc =
PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
PR_SecondsToInterval(1));
if(rc > 0)
return 1; /* connection still in place */
if(rc == 0)
return 0; /* connection has been closed */
return -1; /* connection status unknown */
}
/*
* This function is called when an SSL connection is closed.
*/
Daniel Stenberg
committed
void Curl_nss_close(struct connectdata *conn, int sockindex)
{
Daniel Stenberg
committed
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
Daniel Stenberg
committed
if(connssl->handle) {
/* NSS closes the socket we previously handed to it, so we must mark it
as closed to avoid double close */
Daniel Stenberg
committed
fake_sclose(conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
/* A server might require different authentication based on the
* particular path being requested by the client. To support this
* scenario, we must ensure that a connection will never reuse the
* authentication data from a previous connection. */
SSL_InvalidateSession(connssl->handle);
Markus Elfring
committed
free(connssl->client_nickname);
connssl->client_nickname = NULL;
/* destroy all NSS objects in order to avoid failure of NSS shutdown */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
PR_Close(connssl->handle);
Daniel Stenberg
committed
connssl->handle = NULL;
}
}
/* return true if NSS can provide error code (and possibly msg) for the
error */
static bool is_nss_error(CURLcode err)
case CURLE_PEER_FAILED_VERIFICATION:
case CURLE_SSL_CACERT:
case CURLE_SSL_CERTPROBLEM:
case CURLE_SSL_CONNECT_ERROR:
case CURLE_SSL_ISSUER_ERROR:
default:
return false;
}
}
/* return true if the given error code is related to a client certificate */
static bool is_cc_error(PRInt32 err)
{
switch(err) {
case SSL_ERROR_BAD_CERT_ALERT:
case SSL_ERROR_EXPIRED_CERT_ALERT:
case SSL_ERROR_REVOKED_CERT_ALERT:
return true;
default:
return false;
}
}
static Curl_recv nss_recv;
static Curl_send nss_send;
static CURLcode nss_load_ca_certificates(struct connectdata *conn,
int sockindex)
{
struct SessionHandle *data = conn->data;
const char *cafile = data->set.ssl.CAfile;
const char *capath = data->set.ssl.CApath;
CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
if(result)
return result;
if(capath) {
struct_stat st;
if(stat(capath, &st) == -1)
return CURLE_SSL_CACERT_BADFILE;
if(S_ISDIR(st.st_mode)) {
PRDirEntry *entry;
PRDir *dir = PR_OpenDir(capath);
if(!dir)
return CURLE_SSL_CACERT_BADFILE;
while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
char *fullpath = aprintf("%s/%s", capath, entry->name);
if(!fullpath) {
PR_CloseDir(dir);
return CURLE_OUT_OF_MEMORY;
}
if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
/* This is purposefully tolerant of errors so non-PEM files can
* be in the same directory */
infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
free(fullpath);
}
PR_CloseDir(dir);
}
else
infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
}
infof(data, " CAfile: %s\n CApath: %s\n",
cafile ? cafile : "none",
capath ? capath : "none");
return CURLE_OK;
}
static CURLcode nss_init_sslver(SSLVersionRange *sslver,
struct SessionHandle *data)
{
switch(data->set.ssl.version) {
default:
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
#elif defined SSL_LIBRARY_VERSION_TLS_1_1
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
#else
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
return CURLE_OK;
case CURL_SSLVERSION_SSLv2:
sslver->min = SSL_LIBRARY_VERSION_2;
sslver->max = SSL_LIBRARY_VERSION_2;
return CURLE_OK;
case CURL_SSLVERSION_SSLv3:
sslver->min = SSL_LIBRARY_VERSION_3_0;
sslver->max = SSL_LIBRARY_VERSION_3_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_0:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_1:
#ifdef SSL_LIBRARY_VERSION_TLS_1_1
sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
return CURLE_OK;
#endif
break;
case CURL_SSLVERSION_TLSv1_2:
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
return CURLE_OK;
#endif
break;
}
failf(data, "TLS minor version cannot be set");
return CURLE_SSL_CONNECT_ERROR;
}
static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
struct SessionHandle *data,
CURLcode curlerr)
{
PRErrorCode err = 0;
if(is_nss_error(curlerr)) {
/* read NSPR error code */
err = PR_GetError();
if(is_cc_error(err))
curlerr = CURLE_SSL_CERTPROBLEM;
/* print the error number and error string */
infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
/* print a human-readable message describing the error if available */
nss_print_error_message(data, err);
}
/* cleanup on connection failure */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
return curlerr;
}
/* Switch the SSL socket into non-blocking mode. */
static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
struct SessionHandle *data)
{
static PRSocketOptionData sock_opt;
sock_opt.option = PR_SockOpt_Nonblocking;
sock_opt.value.non_blocking = PR_TRUE;
if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
return CURLE_OK;
}
static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
{
PRFileDesc *model = NULL;
PRFileDesc *nspr_io = NULL;
PRFileDesc *nspr_io_stub = NULL;
PRBool ssl_cbc_random_iv;
struct SessionHandle *data = conn->data;
curl_socket_t sockfd = conn->sock[sockindex];
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
SSLVersionRange sslver = {
SSL_LIBRARY_VERSION_TLS_1_0, /* min */
SSL_LIBRARY_VERSION_TLS_1_0 /* max */
};
connssl->data = data;
/* list of all NSS objects we need to destroy in Curl_nss_close() */
connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
if(!connssl->obj_list)
return CURLE_OUT_OF_MEMORY;
Daniel Stenberg
committed
/* FIXME. NSS doesn't support multiple databases open at the same time. */
Daniel Stenberg
committed
PR_Lock(nss_initlock);
result = nss_init(conn->data);
if(result) {
PR_Unlock(nss_initlock);
goto error;
}
result = CURLE_SSL_CONNECT_ERROR;
if(!mod) {
char *configstring = aprintf("library=%s name=PEM", pem_library);
if(!configstring) {
PR_Unlock(nss_initlock);
goto error;
}
mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
free(configstring);
Daniel Stenberg
committed
if(!mod || !mod->loaded) {
if(mod) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
infof(data, "WARNING: failed to load NSS PEM library %s. Using "
"OpenSSL PEM certificates will not work.\n", pem_library);
}
Daniel Stenberg
committed
PR_Unlock(nss_initlock);
model = PR_NewTCPSocket();
if(!model)
goto error;
model = SSL_ImportFD(NULL, model);
if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
goto error;
/* do not use SSL cache if disabled or we are not going to verify peer */
ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
PR_FALSE : PR_TRUE;
if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
goto error;
/* enable/disable the requested SSL version(s) */
if(nss_init_sslver(&sslver, data) != CURLE_OK)
if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
goto error;
ssl_cbc_random_iv = !data->set.ssl_enable_beast;
#ifdef SSL_CBC_RANDOM_IV
/* unless the user explicitly asks to allow the protocol vulnerability, we
use the work-around */
if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
ssl_cbc_random_iv);
#else
if(ssl_cbc_random_iv)
infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
#endif
if(data->set.ssl.cipher_list) {
if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
result = CURLE_SSL_CIPHER;
goto error;
}
}
if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
infof(data, "warning: ignoring value of ssl.verifyhost\n");
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
goto error;
data->set.ssl.certverifyresult=0; /* not checked yet */
if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
goto error;
if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
goto error;
if(data->set.ssl.verifypeer) {
const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
if(rv) {
result = rv;
if(data->set.ssl.CRLfile) {
const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
if(rv) {
result = rv;
Daniel Stenberg
committed
goto error;
}
infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
Daniel Stenberg
committed
}
Daniel Stenberg
committed
if(data->set.str[STRING_CERT]) {
char *nickname = dup_nickname(data, STRING_CERT);
if(nickname) {
/* we are not going to use libnsspem.so to read the client cert */
connssl->obj_clicert = NULL;
}
else {
CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
data->set.str[STRING_KEY]);
/* failf() is already done in cert_stuff() */
goto error;
}
}
/* store the nickname for SelectClientCert() called during handshake */
connssl->client_nickname = nickname;
}
else
connssl->client_nickname = NULL;
if(SSL_GetClientAuthDataHook(model, SelectClientCert,
(void *)connssl) != SECSuccess) {
result = CURLE_SSL_CERTPROBLEM;
goto error;
}
Daniel Stenberg
committed
/* wrap OS file descriptor by NSPR's file descriptor abstraction */
nspr_io = PR_ImportTCPSocket(sockfd);
if(!nspr_io)
goto error;
/* create our own NSPR I/O layer */
nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
if(!nspr_io_stub) {
PR_Close(nspr_io);
goto error;
}
/* make the per-connection data accessible from NSPR I/O callbacks */
nspr_io_stub->secret = (void *)connssl;
/* push our new layer to the NSPR I/O stack */
if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
PR_Close(nspr_io);
PR_Close(nspr_io_stub);
goto error;
}
/* import our model socket onto the current I/O stack */
connssl->handle = SSL_ImportFD(model, nspr_io);
if(!connssl->handle) {
PR_Close(nspr_io);
goto error;
}
PR_Close(model); /* We don't need this any more */
model = NULL;
/* This is the password associated with the cert that we're using */
if(data->set.str[STRING_KEY_PASSWD]) {
SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
}
#ifdef SSL_ENABLE_OCSP_STAPLING
if(data->set.ssl.verifystatus) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
!= SECSuccess)
goto error;
}
#endif
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, data->set.ssl_enable_npn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, data->set.ssl_enable_alpn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
if(data->set.ssl.falsestart) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
!= SECSuccess)
goto error;
if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
conn) != SECSuccess)
goto error;
}
#endif
#if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
if(data->set.ssl_enable_npn || data->set.ssl_enable_alpn) {
int cur = 0;
unsigned char protocols[128];
#ifdef USE_NGHTTP2
if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
NGHTTP2_PROTO_VERSION_ID_LEN);
cur += NGHTTP2_PROTO_VERSION_ID_LEN;
}
protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
cur += ALPN_HTTP_1_1_LENGTH;
if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
goto error;
/* Force handshake on next I/O */
SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE);
SSL_SetURL(connssl->handle, conn->host.name);
return CURLE_OK;
error:
if(model)
PR_Close(model);
return nss_fail_connect(connssl, data, result);
}
static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct SessionHandle *data = conn->data;
CURLcode result = CURLE_SSL_CONNECT_ERROR;
const long time_left = Curl_timeleft(data, NULL, TRUE);
if(time_left < 0L) {
failf(data, "timed out before SSL handshake");
result = CURLE_OPERATION_TIMEDOUT;
timeout = PR_MillisecondsToInterval((PRUint32) time_left);
Kamil Dudka
committed
if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
/* blocking direction is updated by nss_update_connecting_state() */
return CURLE_AGAIN;
else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
result = CURLE_PEER_FAILED_VERIFICATION;
else if(conn->data->set.ssl.certverifyresult!=0)
result = CURLE_SSL_CACERT;
}
result = display_conn_info(conn, connssl->handle);
if(result)
goto error;
if(data->set.str[STRING_SSL_ISSUERCERT]) {
SECStatus ret = SECFailure;
char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
if(nickname) {
/* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
ret = check_issuer_cert(connssl->handle, nickname);
Daniel Stenberg
committed
if(SECFailure == ret) {
infof(data, "SSL certificate issuer check failed\n");
result = CURLE_SSL_ISSUER_ERROR;
Daniel Stenberg
committed
goto error;
}
else {
infof(data, "SSL certificate issuer check ok\n");
Daniel Stenberg
committed
}
}
result = cmp_peer_pubkey(connssl, data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
if(result)
/* status already printed */
goto error;
return CURLE_OK;
return nss_fail_connect(connssl, data, result);
static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
bool *done)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct SessionHandle *data = conn->data;
const bool blocking = (done == NULL);
if(connssl->state == ssl_connection_complete)
return CURLE_OK;
if(connssl->connecting_state == ssl_connect_1) {
result = nss_setup_connect(conn, sockindex);
if(result)
/* we do not expect CURLE_AGAIN from nss_setup_connect() */
if(!blocking) {
/* in non-blocking mode, set NSS non-blocking mode before handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
connssl->connecting_state = ssl_connect_2;
}
result = nss_do_connect(conn, sockindex);
switch(result) {
case CURLE_OK:
break;
case CURLE_AGAIN:
if(!blocking)
/* CURLE_AGAIN in non-blocking mode is not an error */
return CURLE_OK;
/* fall through */
if(blocking) {
/* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
else
/* signal completed SSL handshake */
*done = TRUE;
connssl->state = ssl_connection_complete;
conn->recv[sockindex] = nss_recv;
conn->send[sockindex] = nss_send;
/* ssl_connect_done is never used outside, go back to the initial state */
connssl->connecting_state = ssl_connect_1;
}
CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
{
return nss_connect_common(conn, sockindex, /* blocking */ NULL);
}
CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
int sockindex, bool *done)
{
return nss_connect_common(conn, sockindex, done);
}
static ssize_t nss_send(struct connectdata *conn, /* connection data */
int sockindex, /* socketindex */
const void *mem, /* send this data */
size_t len, /* amount to write */
CURLcode *curlcode)
{
ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
PR_INTERVAL_NO_WAIT);
if(rc < 0) {
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))
? CURLE_SSL_CERTPROBLEM
: CURLE_SEND_ERROR;
return -1;
}
return rc; /* number of bytes */
}
static ssize_t nss_recv(struct connectdata * conn, /* connection data */
int num, /* socketindex */
char *buf, /* store read data here */
size_t buffersize, /* max amount to read */
CURLcode *curlcode)
{
ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
PR_INTERVAL_NO_WAIT);
if(nread < 0) {
/* failed SSL read */
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))