Commit 8e317e44e1 for openssl.org

commit 8e317e44e103e2d3e2e0bf6e594199189fe0b26b
Author: Mounir IDRASSI <mounir.idrassi@idrix.fr>
Date:   Thu Nov 12 21:26:11 2026 +0900

    ssl: fix use after free of cached SSL_CTX after callbacks

    Fetch the current SSL_CTX after callbacks in SNI and session processing.
    A callback can replace it with SSL_set_SSL_CTX, leaving the saved
    pointer stale or referring to freed memory.

    Restrict the sess_accept transfer to servers and use the context
    selected by the servername callback. Add regression tests for context
    switches and context destruction with TLS 1.2 and TLS 1.3.

    Fix tls_early_post_process_client_hello() as well. It kept using the
    SSL_CTX saved on entry after callbacks that can replace and free it.

    Hold a reference to that context while the ClientHello is processed. The
    DTLS cookie is still checked with its verifier: after DTLSv1_listen()
    the replacement context may have none, and SSL_accept() would then fail.
    Look up compression methods in the current context after
    ssl_allow_compression().

    Test the cookie verifier when the connection holds the last reference to
    the old context, and test the listen-to-accept handoff without a
    verifier on the replacement context.

    Assisted-by: pi:claude-opus-5.5
    Assisted-by: pi:gpt-6.2-astra
    Reviewed-by: Viktor Dukhovni <viktor@openssl.org>
    Reviewed-by: Nikola Pajkovsky <nikolap@openssl.org>
    Merge-date: Wed Dec  2 08:58:11 2026
    Merged-from: https://github.com/openssl/openssl/pull/33716

diff --git a/ssl/statem/extensions.c b/ssl/statem/extensions.c
index 4d74815538..a9de7c9878 100644
--- a/ssl/statem/extensions.c
+++ b/ssl/statem/extensions.c
@@ -1389,6 +1389,12 @@ static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
         ret = s->session_ctx->ext.servername_cb(ussl, &altmp,
             s->session_ctx->ext.servername_arg);

+    /*
+     * The callback may have called SSL_set_SSL_CTX(), which can free the
+     * context we started with. Use the current one from here on.
+     */
+    sctx = SSL_CONNECTION_GET_CTX(s);
+
     /*
      * For servers, propagate the SNI hostname from the temporary
      * storage in the SSL to the persistent SSL_SESSION, now that we
@@ -1414,7 +1420,7 @@ static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
      * context, to avoid the confusing situation of having sess_accept_good
      * exceed sess_accept (zero) for the new context.
      */
-    if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
+    if (s->server && SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
         && s->hello_retry_request == SSL_HRR_NONE) {
         ssl_tsan_counter(sctx, &sctx->stats.sess_accept);
         ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
diff --git a/ssl/statem/extensions_srvr.c b/ssl/statem/extensions_srvr.c
index 8bd856af3f..42b7c1d432 100644
--- a/ssl/statem/extensions_srvr.c
+++ b/ssl/statem/extensions_srvr.c
@@ -1361,7 +1361,6 @@ int tls_parse_ctos_psk(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
     SSL_SESSION *sess = NULL;
     unsigned int id, i, ext = 0;
     const EVP_MD *md = NULL;
-    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);

     /*
@@ -1578,13 +1577,18 @@ int tls_parse_ctos_psk(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
             continue;
         }

-        md = ssl_md(sctx, sess->cipher->algorithm2);
+        /*
+         * The callbacks above may have called SSL_set_SSL_CTX(), which can
+         * free the context this function started with, so always look up
+         * the digests in the current one.
+         */
+        md = ssl_md(SSL_CONNECTION_GET_CTX(s), sess->cipher->algorithm2);
         if (md == NULL) {
             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
             goto err;
         }
         if (!EVP_MD_is_a(md,
-                EVP_MD_get0_name(ssl_md(sctx,
+                EVP_MD_get0_name(ssl_md(SSL_CONNECTION_GET_CTX(s),
                     s->s3.tmp.new_cipher->algorithm2)))) {
             /* The ciphersuite is not compatible with this session. */
             SSL_SESSION_free(sess);
diff --git a/ssl/statem/statem_srvr.c b/ssl/statem/statem_srvr.c
index 6d4fb93c1f..ff2efa6f58 100644
--- a/ssl/statem/statem_srvr.c
+++ b/ssl/statem/statem_srvr.c
@@ -2291,7 +2291,7 @@ err:
     return MSG_PROCESS_ERROR;
 }

-static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
+static int early_post_process_client_hello(SSL_CONNECTION *s)
 {
     unsigned int j;
     int i, al = SSL_AD_INTERNAL_ERROR;
@@ -2299,12 +2299,18 @@ static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
     unsigned long id;
 #ifndef OPENSSL_NO_COMP
     SSL_COMP *comp = NULL;
+    const STACK_OF(SSL_COMP) *comp_methods;
 #endif
     const SSL_CIPHER *c;
     STACK_OF(SSL_CIPHER) *ciphers = NULL;
     STACK_OF(SSL_CIPHER) *scsvs = NULL;
     CLIENTHELLO_MSG *clienthello = s->clienthello;
     DOWNGRADE dgrd = DOWNGRADE_NONE;
+    /*
+     * After the ClientHello callback, sctx is used only to choose the DTLS
+     * cookie verifier, even if the callback has replaced the SSL_CTX. See
+     * tls_early_post_process_client_hello().
+     */
     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
@@ -2692,8 +2698,8 @@ static int tls_early_post_process_client_hello(SSL_CONNECTION *s)

     /*
      * Worst case, we will use the NULL compression, but if we have other
-     * options, we will now look for them.  We have complen-1 compression
-     * algorithms from the client, starting at q.
+     * options, we will now look for them. Fetch the current context's methods
+     * after ssl_allow_compression(), which can invoke the security callback.
      */
     s->s3.tmp.new_compression = NULL;
     if (SSL_CONNECTION_IS_VERSION13(s)) {
@@ -2720,9 +2726,10 @@ static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
                 SSL_R_INCONSISTENT_COMPRESSION);
             goto err;
         }
-        /* Look for resumed compression method */
-        for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {
-            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
+        /* Look for the resumed compression method in the current SSL_CTX. */
+        comp_methods = SSL_CONNECTION_GET_CTX(s)->comp_methods;
+        for (m = 0; m < sk_SSL_COMP_num(comp_methods); m++) {
+            comp = sk_SSL_COMP_value(comp_methods, m);
             if (comp_id == comp->id) {
                 s->s3.tmp.new_compression = comp;
                 break;
@@ -2745,14 +2752,15 @@ static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
         }
     } else if (s->hit) {
         comp = NULL;
-    } else if (ssl_allow_compression(s) && sctx->comp_methods) {
+    } else if (ssl_allow_compression(s)
+        && (comp_methods = SSL_CONNECTION_GET_CTX(s)->comp_methods) != NULL) {
         /* See if we have a match */
         int m, nn, v, done = 0;
         unsigned int o;

-        nn = sk_SSL_COMP_num(sctx->comp_methods);
+        nn = sk_SSL_COMP_num(comp_methods);
         for (m = 0; m < nn; m++) {
-            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
+            comp = sk_SSL_COMP_value(comp_methods, m);
             v = comp->id;
             for (o = 0; o < clienthello->compressions_len; o++) {
                 if (v == clienthello->compressions[o]) {
@@ -2818,6 +2826,30 @@ err:
     return 0;
 }

+/*
+ * The callbacks run while the ClientHello is processed can replace the
+ * SSL_CTX with SSL_set_SSL_CTX() and free the one in use on entry. The
+ * reference taken here keeps that SSL_CTX alive until this call returns.
+ *
+ * Its verify callback checks the DTLS cookie: DTLSv1_listen() keeps no
+ * copy of the cookie in the connection, and the replacement SSL_CTX may
+ * have no verify callback. After SSL_CLIENT_HELLO_RETRY, the next call
+ * enters with the replacement SSL_CTX and uses its verify callback.
+ */
+static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
+{
+    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
+    int ret;
+
+    if (!SSL_CTX_up_ref(sctx)) {
+        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
+        return 0;
+    }
+    ret = early_post_process_client_hello(s);
+    SSL_CTX_free(sctx);
+    return ret;
+}
+
 /*
  * Call the status request callback if needed. Upon success, returns 1.
  * Upon failure, returns 0.
diff --git a/ssl/t1_lib.c b/ssl/t1_lib.c
index 3490f584a1..0a634fe52b 100644
--- a/ssl/t1_lib.c
+++ b/ssl/t1_lib.c
@@ -3364,6 +3364,11 @@ SSL_TICKET_STATUS tls_decrypt_ticket(SSL_CONNECTION *s,
     slen += declen;
     p = sdec;

+    /*
+     * The ticket key callback may have called SSL_set_SSL_CTX(), which can
+     * free the context we started with, so fetch the current one here.
+     */
+    sctx = SSL_CONNECTION_GET_CTX(s);
     sess = d2i_SSL_SESSION_ex(NULL, &p, slen, sctx->libctx, sctx->propq);
     slen -= (int)(p - sdec);
     OPENSSL_free(sdec);
diff --git a/test/dtlstest.c b/test/dtlstest.c
index d853d5ee2c..1ee7ccf9d5 100644
--- a/test/dtlstest.c
+++ b/test/dtlstest.c
@@ -654,6 +654,121 @@ end:
     return testresult;
 }

+#ifndef OPENSSL_NO_DTLS1_2
+static int old_cookie_verify_count, new_cookie_verify_count;
+static int old_cookie_ctx_freed;
+static int cookie_ctx_ex_index = -1;
+
+static void cookie_ctx_free_cb(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+    int idx, long argl, void *argp)
+{
+    if (ptr != NULL)
+        (*(int *)ptr)++;
+}
+
+static int verify_old_ctx_cookie_cb(SSL *ssl, const unsigned char *cookie,
+    unsigned int cookie_len)
+{
+    old_cookie_verify_count++;
+    /* The SSL_CTX this callback was set on must still be alive */
+    if (!TEST_int_eq(old_cookie_ctx_freed, 0))
+        return 0;
+    return verify_cookie_cb(ssl, cookie, cookie_len);
+}
+
+static int verify_new_ctx_cookie_cb(SSL *ssl, const unsigned char *cookie,
+    unsigned int cookie_len)
+{
+    new_cookie_verify_count++;
+    return verify_cookie_cb(ssl, cookie, cookie_len);
+}
+
+static int switch_cookie_ctx_cb(SSL *ssl, int *al, void *arg)
+{
+    if (SSL_set_SSL_CTX(ssl, arg) == NULL) {
+        *al = SSL_AD_INTERNAL_ERROR;
+        return SSL_CLIENT_HELLO_ERROR;
+    }
+    return SSL_CLIENT_HELLO_SUCCESS;
+}
+
+/*
+ * With the server restricted to DTLS 1.2, the ClientHello callback runs on
+ * the ClientHello carrying the cookie. A context switch must not change
+ * which callback verifies it during the handshake.
+ * Test 0: Switch away from the session context before SSL_accept(), then
+ * switch back in the callback. Both contexts have verifiers. The switch drops
+ * the last reference to the old context, whose verifier fails if it runs
+ * after that context is freed.
+ * Test 1: DTLSv1_listen() then SSL_accept() with no verifier on the replacement.
+ */
+static int test_cookie_ctx_switch(int listen)
+{
+    SSL_CTX *sctx = NULL, *cctx = NULL, *newsctx = NULL;
+    SSL *serverssl = NULL, *clientssl = NULL;
+    int testresult = 0;
+
+#ifdef OPENSSL_NO_SOCK
+    if (listen)
+        return TEST_skip("DTLSv1_listen() requires socket support");
+#endif
+
+    if (cookie_ctx_ex_index == -1
+        && !TEST_int_ge(cookie_ctx_ex_index = SSL_CTX_get_ex_new_index(0, NULL,
+                            NULL, NULL, cookie_ctx_free_cb),
+            0))
+        goto end;
+
+    if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
+            DTLS_client_method(), DTLS1_2_VERSION, DTLS1_2_VERSION,
+            &sctx, &cctx, cert, privkey))
+        || !TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(), NULL,
+            DTLS1_2_VERSION, DTLS1_2_VERSION, &newsctx, NULL, cert, privkey))
+        || !TEST_true(SSL_CTX_set_ex_data(sctx, cookie_ctx_ex_index,
+            &old_cookie_ctx_freed)))
+        goto end;
+
+    if (!listen)
+        SSL_CTX_set_cookie_verify_cb(newsctx, verify_new_ctx_cookie_cb);
+    SSL_CTX_set_cookie_generate_cb(sctx, generate_cookie_cb);
+    SSL_CTX_set_cookie_verify_cb(sctx, verify_old_ctx_cookie_cb);
+    SSL_CTX_set_client_hello_cb(sctx, switch_cookie_ctx_cb, newsctx);
+
+    old_cookie_verify_count = new_cookie_verify_count = 0;
+    old_cookie_ctx_freed = 0;
+    if (!TEST_true(create_ssl_objects(listen ? sctx : newsctx, cctx,
+            &serverssl, &clientssl, NULL, NULL)))
+        goto end;
+    if (!listen) {
+        if (!TEST_ptr_eq(SSL_set_SSL_CTX(serverssl, sctx), sctx))
+            goto end;
+        SSL_set_options(serverssl, SSL_OP_COOKIE_EXCHANGE);
+        /* Leave the connection holding the only reference to sctx */
+        SSL_CTX_free(sctx);
+        sctx = NULL;
+        if (!TEST_int_eq(old_cookie_ctx_freed, 0))
+            goto end;
+    }
+    if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
+            SSL_ERROR_NONE, 1, listen))
+        || !TEST_ptr_eq(SSL_get_SSL_CTX(serverssl), newsctx)
+        /* DTLSv1_listen() verifies the cookie before SSL_accept() checks it. */
+        || !TEST_int_eq(old_cookie_verify_count, listen ? 2 : 1)
+        || !TEST_int_eq(new_cookie_verify_count, 0)
+        || !TEST_int_eq(old_cookie_ctx_freed, listen ? 0 : 1))
+        goto end;
+
+    testresult = 1;
+end:
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+    SSL_CTX_free(newsctx);
+    return testresult;
+}
+#endif
+
 /*
  * Test just sending a Finished message as the first message. Should fail due
  * to an unexpected message.
@@ -3100,6 +3215,9 @@ int setup_tests(void)
     ADD_ALL_TESTS(test_cookie_exchange, 5);
 #endif
     ADD_TEST(test_dtls_duplicate_records);
+#ifndef OPENSSL_NO_DTLS1_2
+    ADD_ALL_TESTS(test_cookie_ctx_switch, 2);
+#endif
     ADD_TEST(test_just_finished);
 #ifndef OPENSSL_NO_DTLS1_2
     ADD_ALL_TESTS(test_swap_records_dtls1, 4);
diff --git a/test/sslapitest.c b/test/sslapitest.c
index b8be9bfa6d..1d908155b7 100644
--- a/test/sslapitest.c
+++ b/test/sslapitest.c
@@ -16303,6 +16303,287 @@ end:
     SSL_CTX_free(cctx);
     return testresult;
 }
+
+/*
+ * A callback run during the handshake may switch the connection to another
+ * SSL_CTX with SSL_set_SSL_CTX(). Subsequent accesses to the current context
+ * must use the replacement: the switch drops the connection's reference to
+ * the old context, and frees it when that was the last one. These tests cover
+ * the current-context lookups in SNI, PSK and ticket processing.
+ */
+static SSL_CTX *ctx_switch_target;
+static int ctx_switch_count;
+static int ctx_switch_ex_index = -1;
+
+static void ctx_switch_free_cb(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+    int idx, long argl, void *argp)
+{
+    if (ptr != NULL)
+        (*(int *)ptr)++;
+}
+
+static int ctx_switch_to_target(SSL *s)
+{
+    if (ctx_switch_target == NULL || SSL_get_SSL_CTX(s) == ctx_switch_target)
+        return 1;
+    if (SSL_set_SSL_CTX(s, ctx_switch_target) == NULL)
+        return 0;
+    ctx_switch_count++;
+    return 1;
+}
+
+static int ctx_switch_sni_cb(SSL *s, int *al, void *arg)
+{
+    if (!ctx_switch_to_target(s)) {
+        *al = SSL_AD_INTERNAL_ERROR;
+        return SSL_TLSEXT_ERR_ALERT_FATAL;
+    }
+    return SSL_TLSEXT_ERR_OK;
+}
+
+static int ctx_switch_tick_key_evp_cb(SSL *s, unsigned char key_name[16],
+    unsigned char iv[EVP_MAX_IV_LENGTH], EVP_CIPHER_CTX *ctx,
+    EVP_MAC_CTX *hctx, int enc)
+{
+    /* Switch while decrypting a ticket */
+    if (!enc && !ctx_switch_to_target(s))
+        return -1;
+    return tick_key_evp_cb(s, key_name, iv, ctx, hctx, enc);
+}
+
+#ifndef OSSL_NO_USABLE_TLS1_3
+static const unsigned char ctx_switch_psk_key[] = {
+    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
+};
+
+static int ctx_switch_find_session_cb(SSL *ssl, const unsigned char *identity,
+    size_t identity_len, SSL_SESSION **sess)
+{
+    if (!ctx_switch_to_target(ssl))
+        return 0;
+    return find_session_cb(ssl, identity, identity_len, sess);
+}
+#endif
+
+/*
+ * After a servername callback switches context, the handshake counts as
+ * accepted by the new server context rather than by the session context.
+ * A client context switch must leave the accept counts at zero and keep
+ * the connect counts on the session context.
+ * Test 0: TLSv1.2, server switches in the servername callback
+ * Test 1: TLSv1.3, server switches in the servername callback
+ * Test 2: TLSv1.2, client switches in the servername callback
+ * Test 3: TLSv1.3, client switches in the servername callback
+ * Test 4: TLSv1.2, client switches before the handshake
+ * Test 5: TLSv1.3, client switches before the handshake
+ */
+static int test_ctx_switch_accept_stats(int idx)
+{
+    SSL_CTX *sctx = NULL, *newctx = NULL, *cctx = NULL;
+    SSL *serverssl = NULL, *clientssl = NULL;
+    int prot = idx % 2 == 0 ? TLS1_2_VERSION : TLS1_3_VERSION;
+    int server = idx < 2;
+    int before_handshake = idx >= 4;
+    int testresult = 0;
+
+#ifdef OPENSSL_NO_TLS1_2
+    if (prot == TLS1_2_VERSION)
+        return TEST_skip("TLSv1.2 is disabled");
+#endif
+#ifdef OSSL_NO_USABLE_TLS1_3
+    if (prot == TLS1_3_VERSION)
+        return TEST_skip("No usable TLSv1.3");
+#endif
+
+    ctx_switch_count = 0;
+
+    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+            TLS_client_method(), prot, prot, &sctx, &cctx, cert, privkey))
+        || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+            TLS_client_method(), prot, prot,
+            server ? &newctx : NULL, server ? NULL : &newctx, cert, privkey))
+        || (!before_handshake
+            && !TEST_true(SSL_CTX_set_tlsext_servername_callback(server ? sctx : cctx,
+                ctx_switch_sni_cb))))
+        goto end;
+
+    ctx_switch_target = newctx;
+    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
+            NULL, NULL))
+        || !TEST_true(SSL_set_tlsext_host_name(clientssl, "localhost"))
+        || (before_handshake && !TEST_true(ctx_switch_to_target(clientssl)))
+        || !TEST_true(create_ssl_connection(serverssl, clientssl,
+            SSL_ERROR_NONE))
+        || !TEST_int_eq(ctx_switch_count, 1)
+        || !TEST_ptr_eq(SSL_get_SSL_CTX(server ? serverssl : clientssl), newctx)
+        || !TEST_long_eq(SSL_CTX_sess_accept(sctx), server ? 0 : 1)
+        || !TEST_long_eq(SSL_CTX_sess_accept_good(sctx), server ? 0 : 1)
+        || !TEST_long_eq(SSL_CTX_sess_accept(newctx), server ? 1 : 0)
+        || !TEST_long_eq(SSL_CTX_sess_accept_good(newctx), server ? 1 : 0)
+        || !TEST_long_eq(SSL_CTX_sess_accept(cctx), 0)
+        || !TEST_long_eq(SSL_CTX_sess_accept_good(cctx), 0)
+        || !TEST_long_eq(SSL_CTX_sess_connect(cctx), 1)
+        || !TEST_long_eq(SSL_CTX_sess_connect_good(cctx), 1)
+        || !TEST_long_eq(SSL_CTX_sess_connect(newctx), 0)
+        || !TEST_long_eq(SSL_CTX_sess_connect_good(newctx), 0))
+        goto end;
+
+    testresult = 1;
+end:
+    ctx_switch_target = NULL;
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(newctx);
+    SSL_CTX_free(cctx);
+    return testresult;
+}
+
+/*
+ * The connection holds the only reference to its current SSL_CTX when a
+ * callback switches it to another one, so the switch frees the old context
+ * while the handshake is still running.
+ * Test 0: TLSv1.3, the servername callback switches
+ * Test 1: TLSv1.3, the PSK find session callback switches
+ * Test 2: TLSv1.3, the ticket key callback switches while decrypting
+ * Test 3: TLSv1.2, the ticket key callback switches while decrypting
+ * Test 4: TLSv1.2, the servername callback switches
+ */
+static int test_ctx_switch_frees_old_ctx(int idx)
+{
+    SSL_CTX *sctx = NULL, *oldsctx = NULL, *newsctx = NULL, *cctx = NULL;
+    SSL *serverssl = NULL, *clientssl = NULL;
+    SSL_SESSION *sess = NULL;
+    int prot = idx >= 3 ? TLS1_2_VERSION : TLS1_3_VERSION;
+    int sni = idx == 0 || idx == 4;
+    int oldctx_freed = 0;
+    int testresult = 0;
+
+#ifdef OSSL_NO_USABLE_TLS1_3
+    if (prot == TLS1_3_VERSION)
+        return TEST_skip("No usable TLSv1.3");
+#endif
+#ifdef OPENSSL_NO_TLS1_2
+    if (prot == TLS1_2_VERSION)
+        return TEST_skip("TLSv1.2 is disabled");
+#endif
+
+    ctx_switch_target = NULL;
+    ctx_switch_count = 0;
+
+    if (ctx_switch_ex_index == -1
+        && !TEST_int_ge(ctx_switch_ex_index = SSL_CTX_get_ex_new_index(0, NULL,
+                            NULL, NULL, ctx_switch_free_cb),
+            0))
+        goto end;
+
+    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+            TLS_client_method(), prot, prot, &sctx, &cctx, cert, privkey))
+        || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
+            prot, prot, &oldsctx, NULL, cert, privkey))
+        || !TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(), NULL,
+            prot, prot, &newsctx, NULL, cert, privkey))
+        || !TEST_true(SSL_CTX_set_ex_data(oldsctx, ctx_switch_ex_index,
+            &oldctx_freed)))
+        goto end;
+
+    if (sni) {
+        /* The callback of the current context runs, and that is oldsctx */
+        if (!TEST_true(SSL_CTX_set_tlsext_servername_callback(oldsctx,
+                ctx_switch_sni_cb)))
+            goto end;
+    } else if (idx == 1) {
+#ifndef OSSL_NO_USABLE_TLS1_3
+        /* The PSK uses a SHA256 ciphersuite, so make sure we negotiate one */
+        if (!TEST_true(SSL_CTX_set_ciphersuites(cctx,
+                "TLS_AES_128_GCM_SHA256")))
+            goto end;
+        SSL_CTX_set_psk_use_session_callback(cctx, use_session_cb);
+        SSL_CTX_set_psk_find_session_callback(sctx,
+            ctx_switch_find_session_cb);
+        srvid = pskid;
+        use_session_cb_cnt = 0;
+        find_session_cb_cnt = 0;
+#endif
+    } else {
+        /* Tickets use the keys of the session context, so set them there */
+        tick_key_renew = 0;
+        if (!TEST_true(SSL_CTX_set_tlsext_ticket_key_evp_cb(sctx,
+                ctx_switch_tick_key_evp_cb))
+            || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl,
+                &clientssl, NULL, NULL))
+            || !TEST_true(create_ssl_connection(serverssl, clientssl,
+                SSL_ERROR_NONE))
+            || !TEST_ptr(sess = SSL_get1_session(clientssl)))
+            goto end;
+        shutdown_ssl_connection(serverssl, clientssl);
+        serverssl = clientssl = NULL;
+    }
+
+    if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
+            NULL, NULL))
+        || (sni && !TEST_true(SSL_set_tlsext_host_name(clientssl, "localhost")))
+        || (sess != NULL && !TEST_true(SSL_set_session(clientssl, sess)))
+        || !TEST_ptr(SSL_set_SSL_CTX(serverssl, oldsctx)))
+        goto end;
+
+#ifndef OSSL_NO_USABLE_TLS1_3
+    if (idx == 1) {
+        const SSL_CIPHER *cipher;
+
+        cipher = SSL_CIPHER_find(clientssl, TLS13_AES_128_GCM_SHA256_BYTES);
+        clientpsk = SSL_SESSION_new();
+        if (!TEST_ptr(clientpsk)
+            || !TEST_ptr(cipher)
+            || !TEST_true(SSL_SESSION_set1_master_key(clientpsk,
+                ctx_switch_psk_key, sizeof(ctx_switch_psk_key)))
+            || !TEST_true(SSL_SESSION_set_cipher(clientpsk, cipher))
+            || !TEST_true(SSL_SESSION_set_protocol_version(clientpsk,
+                TLS1_3_VERSION))
+            || !TEST_true(SSL_SESSION_up_ref(clientpsk)))
+            goto end;
+        serverpsk = clientpsk;
+    }
+#endif
+
+    /* Leave the connection holding the only reference to oldsctx */
+    SSL_CTX_free(oldsctx);
+    oldsctx = NULL;
+    if (!TEST_int_eq(oldctx_freed, 0))
+        goto end;
+
+    ctx_switch_target = newsctx;
+    if (!TEST_true(create_ssl_connection(serverssl, clientssl,
+            SSL_ERROR_NONE))
+        || !TEST_int_eq(ctx_switch_count, 1)
+        || !TEST_int_eq(oldctx_freed, 1)
+        || !TEST_ptr_eq(SSL_get_SSL_CTX(serverssl), newsctx)
+        || (sni && !TEST_str_eq(SSL_get_servername(serverssl, TLSEXT_NAMETYPE_host_name), "localhost"))
+        || (!sni && !TEST_true(SSL_session_reused(clientssl))))
+        goto end;
+
+    testresult = 1;
+end:
+    ctx_switch_target = NULL;
+    SSL_SESSION_free(sess);
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(oldsctx);
+    SSL_CTX_free(newsctx);
+    SSL_CTX_free(cctx);
+#ifndef OSSL_NO_USABLE_TLS1_3
+    if (idx == 1) {
+        SSL_SESSION_free(clientpsk);
+        SSL_SESSION_free(serverpsk);
+        clientpsk = serverpsk = NULL;
+    }
+#endif
+    return testresult;
+}
 #endif

 #ifndef OPENSSL_NO_TLS1_2
@@ -20638,6 +20919,8 @@ int setup_tests(void)
 #if !defined(OPENSSL_NO_TLS1_2) || !defined(OSSL_NO_USABLE_TLS1_3)
     ADD_ALL_TESTS(test_sigalg_ctx_switch, 4);
     ADD_ALL_TESTS(test_ctx_switch_more_custom_exts, 2);
+    ADD_ALL_TESTS(test_ctx_switch_accept_stats, 6);
+    ADD_ALL_TESTS(test_ctx_switch_frees_old_ctx, 5);
     ADD_ALL_TESTS(test_sigalg_ctx_switch_cert_cb, 2);
 #ifndef OPENSSL_NO_DEPRECATED_4_2
     ADD_TEST(test_copy_session_id_ctx_mismatch);