Skip to content
Open
127 changes: 87 additions & 40 deletions src/internal.c
Original file line number Diff line number Diff line change
Expand Up @@ -8202,10 +8202,9 @@ int InitSSL_Suites(WOLFSSL* ssl)
writeDup flag indicating this is a write dup only

WOLFSSL_SUCCESS return value on success */
#ifdef OPENSSL_EXTRA
/* Apply the protocol version mask and downgrade rules. Returns VERSION_ERROR
* when the requested options are inconsistent, 0 otherwise. */
static int SetSSL_CTX_CheckVersion(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
int SetSSL_CTX_CheckVersion(WOLFSSL* ssl, WOLFSSL_CTX* ctx)
{
#ifdef WOLFSSL_TLS13
if (ssl->version.minor == TLSv1_3_MINOR &&
Expand Down Expand Up @@ -8271,7 +8270,6 @@ static int SetSSL_CTX_CheckVersion(WOLFSSL* ssl, WOLFSSL_CTX* ctx)

return 0;
}
#endif /* OPENSSL_EXTRA */

#ifndef NO_CERTS
/* Give the SSL object the certificate, certificate chain and private key of
Expand Down Expand Up @@ -9024,6 +9022,13 @@ int ReinitSSL(WOLFSSL* ssl, WOLFSSL_CTX* ctx, int writeDup)
}
(void)ctx;

/* Called on every connect/accept, so only when a connection starts. */
if (!ssl->options.handShakeDone &&
(((ssl->options.side == WOLFSSL_CLIENT_END) ?
ssl->options.connectState : ssl->options.acceptState) == 0)) {
ResetPeerResults(ssl);
}
Comment on lines +9025 to +9030

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Resumed client connections now report X509_V_OK from wolfSSL_get_verify_result(), even when the cached session recorded a verify error. The new ResetPeerResults() call in ReinitSSL runs at the first wolfSSL_connect(). That is after wolfSSL_set_session() has copied session->peerVerifyRet into ssl->peerVerifyRet (ssl_sess.c:1750). A resumption verifies no certificate, so the value stays 0. Fix: keep a value restored from the session (and one set with wolfSSL_set_verify_result()) when the connection starts. For example, skip the peerVerifyRet reset when options.resuming is set, or re-apply ssl->session->peerVerifyRet after the reset.

Why this was flagged

An OPENSSL_EXTRA client using WOLFSSL_VERIFY_NONE completes a first handshake with a bad certificate, so peerVerifyRet is nonzero. For the next connection the app calls wolfSSL_set_session(). SetSession sets options.resuming and copies session->peerVerifyRet into ssl->peerVerifyRet (ssl_sess.c:1750). wolfSSL_connect() then calls ReinitSSL (ssl_api_hs.c:413, tls13.c:16992). At that point handShakeDone == 0 and connectState == CONNECT_BEGIN (0), so the new block at internal.c:9025-9030 calls ResetPeerResults(), which sets peerVerifyRet = 0 (internal.c:10968). The resumed handshake processes no Certificate, so wolfSSL_get_verify_result() returns 0 (X509_V_OK). An app that checks the verify result by hand then accepts an unverified peer. When the session is saved again, ssl_sess.c:4076 writes the 0 back, so the error is gone for every later resumption too. On the base branch, ReinitSSL never touched peerVerifyRet, so the restored error was still reported.

Verification: SetSession restores the result before connect (ssl_sess.c:1750). In wolfSSL_connect (ssl_api_hs.c:413), ReinitSSL runs while handShakeDone==0 and connectState==CONNECT_BEGIN, so the new block at internal.c:9025-9030 calls ResetPeerResults(), which sets ssl->peerVerifyRet = 0; (internal.c:10968). On the base branch this reset did not exist. The new tests check only full handshakes and never resumption.


ssl->options.shutdownDone = 0;
if (ssl->session != NULL)
ssl->session->side = (byte)ssl->options.side;
Expand Down Expand Up @@ -10951,7 +10956,47 @@ void wolfSSL_ResourceFree(WOLFSSL* ssl)
#endif /* WOLFSSL_STATIC_MEMORY */
}

/* Drop what the application could query about the previous connection. */
void ResetPeerResults(WOLFSSL* ssl)
{
ssl->alert_history.last_rx.code = -1;
ssl->alert_history.last_rx.level = -1;
ssl->alert_history.last_tx.code = -1;
ssl->alert_history.last_tx.level = -1;
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
defined(OPENSSL_ALL)
ssl->peerVerifyRet = 0;
#endif
}

/* Free any handshake resources no longer needed */
/* Free the ephemeral key exchange material. Each handshake, a renegotiation
* included, makes its own. */
void FreeEphemeralKeys(WOLFSSL* ssl)
{
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
/* Present holds the type; only an ECC key is left allocated without it. */
FreeKey(ssl, (ssl->eccTempKeyPresent != 0) ? ssl->eccTempKeyPresent :
DYNAMIC_TYPE_ECC, (void**)&ssl->eccTempKey);
ssl->eccTempKeyPresent = 0;
#endif
#ifndef NO_DH
if (ssl->buffers.serverDH_Priv.buffer != NULL) {
ForceZero(ssl->buffers.serverDH_Priv.buffer,
ssl->buffers.serverDH_Priv.length);
}
XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap,
DYNAMIC_TYPE_PRIVATE_KEY);
ssl->buffers.serverDH_Priv.buffer = NULL;
ssl->buffers.serverDH_Priv.length = 0;
XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
ssl->buffers.serverDH_Pub.buffer = NULL;
ssl->buffers.serverDH_Pub.length = 0;
FreeKey(ssl, DYNAMIC_TYPE_DH, (void**)&ssl->buffers.serverDH_Key);
#endif
(void)ssl;
}

void FreeHandshakeResources(WOLFSSL* ssl)
{
WOLFSSL_ENTER("FreeHandshakeResources");
Expand All @@ -10975,6 +11020,8 @@ void FreeHandshakeResources(WOLFSSL* ssl)
}
#endif

FreeEphemeralKeys(ssl);
Comment thread
kareem-wolfssl marked this conversation as resolved.
Resolved
Comment thread
kareem-wolfssl marked this conversation as resolved.
Resolved

#ifdef HAVE_SECURE_RENEGOTIATION
/* advertiseOnly clients never renegotiate, so do not retain (and leave
* unzeroed) the master secret and other handshake resources for them. */
Expand Down Expand Up @@ -11048,35 +11095,6 @@ void FreeHandshakeResources(WOLFSSL* ssl)
FreeKey(ssl, DYNAMIC_TYPE_ECC, (void**)&ssl->peerEccKey);
ssl->peerEccKeyPresent = 0;
#endif
#if defined(HAVE_ECC) || defined(HAVE_CURVE25519) || defined(HAVE_CURVE448)
{
int dtype;
#ifdef HAVE_ECC
dtype = DYNAMIC_TYPE_ECC;
#elif defined(HAVE_CURVE25519)
dtype = DYNAMIC_TYPE_CURVE25519;
#else
dtype = DYNAMIC_TYPE_CURVE448;
#endif
#if defined(HAVE_ECC) && defined(HAVE_CURVE25519)
if (ssl->peerX25519KeyPresent ||
ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE25519)
{
dtype = DYNAMIC_TYPE_CURVE25519;
}
#endif
#if (defined(HAVE_ECC) || defined(HAVE_CURVE25519)) && \
defined(HAVE_CURVE448)
if (ssl->peerX448KeyPresent ||
ssl->eccTempKeyPresent == DYNAMIC_TYPE_CURVE448)
{
dtype = DYNAMIC_TYPE_CURVE448;
}
#endif
FreeKey(ssl, dtype, (void**)&ssl->eccTempKey);
ssl->eccTempKeyPresent = 0;
}
#endif /* HAVE_ECC || HAVE_CURVE25519 || HAVE_CURVE448 */
#ifdef HAVE_CURVE25519
FreeKey(ssl, DYNAMIC_TYPE_CURVE25519, (void**)&ssl->peerX25519Key);
ssl->peerX25519KeyPresent = 0;
Expand All @@ -11087,14 +11105,6 @@ void FreeHandshakeResources(WOLFSSL* ssl)
#endif

#ifndef NO_DH
if (ssl->buffers.serverDH_Priv.buffer) {
ForceZero(ssl->buffers.serverDH_Priv.buffer,
ssl->buffers.serverDH_Priv.length);
}
XFREE(ssl->buffers.serverDH_Priv.buffer, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
ssl->buffers.serverDH_Priv.buffer = NULL;
XFREE(ssl->buffers.serverDH_Pub.buffer, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
ssl->buffers.serverDH_Pub.buffer = NULL;
/* Release the parameters (p,g) back here rather than hold them for
* the life of the connection. */
if (ssl->buffers.weOwnDH) {
Expand Down Expand Up @@ -22732,6 +22742,7 @@ static int ResetHandshakeStateForReneg(WOLFSSL* ssl)
ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
ssl->options.handShakeState = NULL_STATE;
ssl->secure_renegotiation->cache_status = SCR_CACHE_NEEDED;
FreeEphemeralKeys(ssl);
/* Reset for the renegotiation_info presence check below. */
ssl->secure_renegotiation->renegInfoSeen = 0;

Expand Down Expand Up @@ -37359,6 +37370,34 @@ static int IsTls13CipherSuite(byte first, byte second)
return 1;
}

/* A full handshake makes a new session. Drop what would resume the
* previous one, so it is not kept beside this handshake's secret. */
int ResetSessionForFullHandshake(WOLFSSL* ssl)
{
WOLFSSL_SESSION* session = ssl->session;

if ((session->sessionIDSz == 0) && !session->haveAltSessionID
#ifdef HAVE_SESSION_TICKET
&& (session->ticketLen == 0)
#endif
) {
return 0;
}
if (!HaveUniqueSessionObj(ssl))
return MEMORY_ERROR;
session = ssl->session;

ForceZero(session->sessionID, ID_LEN);
session->sessionIDSz = 0;
ForceZero(session->altSessionID, ID_LEN);
session->haveAltSessionID = 0;
#ifdef HAVE_SESSION_TICKET
return SetSessionTicket(session, NULL, 0);
#else
return 0;
#endif
}

#ifndef WOLFSSL_NO_TLS12

/* handle generation of client_hello (1) */
Expand Down Expand Up @@ -38334,6 +38373,9 @@ static int IsTls13CipherSuite(byte first, byte second)
ssl->options.resuming = 0; /* server denied resumption try */
}
}
ret = ResetSessionForFullHandshake(ssl);
if (ret != 0)
return ret;
Comment on lines +38408 to +38410

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing: TLS 1.2 clients whose session ticket the server declines still keep the old ticket and session ID beside the new handshake's secret. The new ResetSessionForFullHandshake() runs only in the non-resuming branch of CompleteServerHello. With a ticket, DSH_CheckSessionId() returns true (internal.c:37815), so the full handshake is only detected later at internal.c:22964, and that path never calls the reset. Fix: reset the session wherever a client drops resumption, including the Not resuming as thought path at internal.c:22964, and not only in CompleteServerHello.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

Trigger: a TLS 1.2 client calls wolfSSL_set_session() with a ticket session. The server cannot decrypt the ticket (for example a new ticket key, as in test_tls12_resume_ticket_decline_fallback) and does a full handshake with an empty session ID. In CompleteServerHello, ssl->options.resuming is set and DSH_CheckSessionId() returns 1 because ssl->session->ticketLen > 0 (internal.c:37815). It takes the resumption branch and returns before the new ResetSessionForFullHandshake() call at internal.c:38376. When the server's Certificate arrives, internal.c:22960-22966 only sets resuming = 0 and peerAuthGood = 0. ssl->session->ticket still holds the old ticket next to the new master secret. If the server sends no NewSessionTicket, the client caches that pair. A later connection to a server that can decrypt the old ticket then resumes with the old secret while the client uses the new one, so the handshake fails. The base branch behaves the same, but this PR's stated goal of clearing the ticket on every full handshake misses this path, which is the usual one for a TLS 1.2 ticket decline.

Verification: Pre-existing. Trigger: a TLS 1.2 client resumes with a ticket, and the server declines the ticket, replies with an empty session ID and does a full handshake. The base has the same behavior; this PR's new reset just does not reach this path. The full handshake is detected later, in DoHandShakeMsgType (src/internal.c:22926-22966). It never calls ResetSessionForFullHandshake.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known issue already fixed by #12064. Not duplicating that work here.

return SetCipherSpecs(ssl);
}

Expand Down Expand Up @@ -45034,6 +45076,11 @@ static int AddPSKtoPreMasterSecret(WOLFSSL* ssl)
}

XMEMCPY(ssl->clSuites->suites, input + i, ssl->clSuites->suiteSz);
#ifdef OPENSSL_EXTRA
/* Built from the previous hello's list. */
wolfSSL_sk_SSL_CIPHER_free(ssl->clSuitesStack);
ssl->clSuitesStack = NULL;
#endif

#ifdef HAVE_SERVER_RENEGOTIATION_INFO
/* check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV suite */
Expand Down
125 changes: 101 additions & 24 deletions src/ssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -5777,7 +5777,9 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
defined(HAVE_CURL)
#endif

int wolfSSL_clear(WOLFSSL* ssl)
/* keepResults: wolfSSL_shutdown() leaves what the application can still
* query about the ended connection. */
int ClearSSL(WOLFSSL* ssl, byte keepResults)
{
WOLFSSL_ENTER("wolfSSL_clear");

Expand Down Expand Up @@ -5815,6 +5817,32 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
SslWaivedCAsFree(ssl);
#endif

if (!keepResults) {
/* The peer's version is not the limit for the next connection. */
if (ssl->options.downgrade) {
ssl->version.minor = ssl->options.versionSet ?
ssl->options.maxVersionMinor :
ssl->ctx->method->version.minor;
/* The version mask only covers TLS. */
if (!ssl->options.dtls &&
(SetSSL_CTX_CheckVersion(ssl, ssl->ctx) != 0)) {
return WOLFSSL_FAILURE;
}
}

ResetPeerResults(ssl);
#if !defined(WOLFSSL_NO_CA_NAMES) && defined(OPENSSL_EXTRA)
wolfSSL_sk_X509_NAME_pop_free(ssl->peer_ca_names, NULL);
ssl->peer_ca_names = NULL;
#endif
#ifdef OPENSSL_EXTRA
wolfSSL_sk_X509_pop_free(ssl->peerCertChain, NULL);
ssl->peerCertChain = NULL;
wolfSSL_sk_X509_pop_free(ssl->verifiedChain, NULL);
ssl->verifiedChain = NULL;
#endif
}

/* reset error */
ssl->error = 0;

Expand All @@ -5834,13 +5862,6 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
ssl->options.acceptState = ACCEPT_BEGIN;
ssl->options.handShakeState = NULL_STATE;
ssl->options.handShakeDone = 0;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WOLFSSL_ASYNC_CERT_YIELD)
/* A per-certificate yield (WOLFSSL_ASYNC_CERT_YIELD) sets this and it is
* normally cleared on the next ProcessPeerCerts re-entry. Clear it here
* so reusing this object after abandoning a yielded handshake cannot
* skip the ProcessPeerCerts state reset on the next fresh entry. */
ssl->options.certYieldPending = 0;
#endif
ssl->recordSzOverhead = 0;
#ifdef WOLFSSL_TLS13_STREAM_CERT_VERIFY
/* Drop any half-sent streamed CertificateVerify. Left in place, the
Expand Down Expand Up @@ -5921,11 +5942,65 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
#ifdef HAVE_CURVE448
ssl->peerX448KeyPresent = 0;
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
/* An abandoned handshake can leave a queued event, whose key is freed
* below, and a handler's resume state. */
if (ssl->asyncDev != NULL) {
if (ssl->asyncDev->event.state == WOLF_EVENT_STATE_PENDING &&
ssl->ctx != NULL) {
(void)wolfEventQueue_Remove(&ssl->ctx->event_queue,
&ssl->asyncDev->event);
}
XMEMSET(&ssl->asyncDev->event, 0, sizeof(WOLF_EVENT));
Comment thread
kareem-wolfssl marked this conversation as resolved.
Resolved
ssl->asyncDev = NULL;
}
#ifdef WOLFSSL_TLS13
ssl->options.buildArgs13Set = 0;
ssl->options.chHashInput = 0;
ssl->options.asyncReplayMsg = 0;
#endif
#ifdef WOLFSSL_ASYNC_CERT_YIELD
ssl->options.certYieldPending = 0;
#endif
#endif
#ifdef WOLFSSL_ASYNC_IO
FreeAsyncCtx(ssl, 1);
#endif
ssl->options.asyncState = TLS_ASYNC_BEGIN;
/* Drop the peer certificate public key left by an abandoned handshake. */
FreePeerCertKeys(ssl);
#ifdef HAVE_PK_CALLBACKS
#ifdef HAVE_ECC
XFREE(ssl->buffers.peerEccDsaKey.buffer, ssl->heap, DYNAMIC_TYPE_ECC);
ssl->buffers.peerEccDsaKey.buffer = NULL;
ssl->buffers.peerEccDsaKey.length = 0;
#endif
#ifndef NO_RSA
XFREE(ssl->buffers.peerRsaKey.buffer, ssl->heap, DYNAMIC_TYPE_RSA);
ssl->buffers.peerRsaKey.buffer = NULL;
ssl->buffers.peerRsaKey.length = 0;
#endif
#ifdef HAVE_ED25519
XFREE(ssl->buffers.peerEd25519Key.buffer, ssl->heap,
DYNAMIC_TYPE_ED25519);
ssl->buffers.peerEd25519Key.buffer = NULL;
ssl->buffers.peerEd25519Key.length = 0;
#endif
#ifdef HAVE_ED448
XFREE(ssl->buffers.peerEd448Key.buffer, ssl->heap, DYNAMIC_TYPE_ED448);
ssl->buffers.peerEd448Key.buffer = NULL;
ssl->buffers.peerEd448Key.length = 0;
#endif
#endif /* HAVE_PK_CALLBACKS */
FreeEphemeralKeys(ssl);
Comment thread
kareem-wolfssl marked this conversation as resolved.
Resolved
Comment thread
kareem-wolfssl marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlinking can’t cancel a hardware request, the async layer has no cancel API, and wolfSSL_free() already frees the same keys the same way. Applications have to let a pending operation finish before clearing or freeing.


ssl->pssAlgo = 0;
#ifdef WOLFSSL_DTLS
ssl->options.dtlsStateful = 0;
#endif
#if defined(WOLFSSL_DTLS_CID) && defined(WOLFSSL_DTLS13)
ssl->options.haveSupportedVersions = 0;
#endif
#ifdef WOLFSSL_TLS13
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK)
ssl->options.pskNegotiated = 0;
Expand All @@ -5944,22 +6019,6 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
#if defined(WOLFSSL_ASYNC_REINVOKE) && !defined(NO_HMAC)
Tls13FreeHsHmac(ssl);
#endif
#ifdef WOLFSSL_ASYNC_CRYPT
ssl->options.buildArgs13Set = 0;
/* An abandoned handshake can leave a mid-flight handler resume
* state and a queued key-schedule event behind; a reused object
* must start fresh. */
ssl->options.asyncState = TLS_ASYNC_BEGIN;
if (ssl->asyncDev == &ssl->kdfAsyncDev) {
if (ssl->kdfAsyncDev.event.state == WOLF_EVENT_STATE_PENDING &&
ssl->ctx != NULL) {
(void)wolfEventQueue_Remove(&ssl->ctx->event_queue,
&ssl->kdfAsyncDev.event);
}
XMEMSET(&ssl->kdfAsyncDev.event, 0, sizeof(WOLF_EVENT));
ssl->asyncDev = NULL;
}
#endif
#endif
#ifdef HAVE_SESSION_TICKET
#ifdef WOLFSSL_TLS13
Expand Down Expand Up @@ -6001,6 +6060,11 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
TLSX_CertificateAuthorities_FreeAll(ssl->ws_peer_ca_names, ssl->heap);
ssl->ws_peer_ca_names = NULL;
#endif
#if defined(HAVE_TLS_EXTENSIONS) && defined(HAVE_ALPN)
XFREE(ssl->alpn_peer_requested, ssl->heap, DYNAMIC_TYPE_ALPN);
ssl->alpn_peer_requested = NULL;
ssl->alpn_peer_requested_length = 0;
#endif

#if defined(HAVE_TLS_EXTENSIONS) && !defined(NO_TLS)
TLSX_FreeAll(ssl->extensions, ssl->heap);
Expand Down Expand Up @@ -6028,6 +6092,12 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
ssl->buffers.clearOutputBuffer.length = 0;
ssl->buffers.inputBuffer.idx = 0;
ssl->buffers.inputBuffer.length = 0;
/* Output the last connection could not send is not the next peer's. */
ShrinkOutputBuffer(ssl);
ssl->buffers.prevSent = 0;
ssl->buffers.plainSz = 0;
ssl->pendingAlert.code = 0;
ssl->pendingAlert.level = alert_none;
/* Recycling the object for a new connection must not carry the
* previous connection's key material along with it. A freshly
* created object has all of this zeroed. */
Expand Down Expand Up @@ -6124,6 +6194,8 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,

FreeCiphers(ssl);
InitCiphers(ssl);
ssl->encrypt.state = CIPHER_STATE_BEGIN;
ssl->decrypt.state = CIPHER_STATE_BEGIN;
InitCipherSpecs(&ssl->specs);

if (InitSSL_Suites(ssl) != WOLFSSL_SUCCESS)
Expand All @@ -6147,6 +6219,11 @@ size_t wolfSSL_get_client_random(const WOLFSSL* ssl, unsigned char* out,
return WOLFSSL_SUCCESS;
}

int wolfSSL_clear(WOLFSSL* ssl)
{
return ClearSSL(ssl, 0);
}

#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER) || defined(HAVE_MEMCACHED)
long wolfSSL_CTX_set_mode(WOLFSSL_CTX* ctx, long mode)
{
Expand Down
Loading
Loading