Commit 7a36f7f3c4 for openssl.org

commit 7a36f7f3c46548ce74ef3d96eb93fc1049aff573
Author: kinchpik <kinchpik@kuicksilver.io>
Date:   Wed Oct 28 17:23:16 2026 +0500

    SSL_send_fatal_alert: address review comments

    Use ssl_reset_error_state() at the start of SSL_send_fatal_alert(), so
    that a connection that has already failed is rejected in the same way
    as by the other I/O functions. The only exception is a retry of an
    alert that an earlier call to SSL_send_fatal_alert() queued and could
    not write because the write BIO blocked.

    To tell that alert apart from one queued internally by SSLfatal(),
    record in the new s3.app_fatal_alert flag that the queued alert came
    from SSL_send_fatal_alert(), and clear it once the alert has been
    written. Before this change, an internal alert whose write had
    blocked could be completed by SSL_send_fatal_alert() if the
    application passed the same alert description, which contradicted
    the documentation. Such a call now fails with
    SSL_R_PROTOCOL_IS_SHUTDOWN and writes nothing.

    Document that calling SSL_send_fatal_alert() from any libssl callback
    is not supported. Only calls from within the handshake state machine
    are detected; callbacks invoked from the record layer, such as the
    record padding callback, are not.

    Describe the behaviour as compatible with BoringSSL in CHANGES.md
    rather than identical.

    Add DTLSv1.3 cases to test_send_fatal_alert, and a test for a
    connection that failed internally while its alert write blocked.

    Reviewed-by: Matt Caswell <matt@openssl.foundation>
    Reviewed-by: Dmitry Belyavskiy <beldmit@gmail.com>
    Merge-date: Mon Nov 23 17:07:48 2026
    Merged-from: https://github.com/openssl/openssl/pull/33421

diff --git a/CHANGES.md b/CHANGES.md
index 8fe0c55c0a..c88a9b0760 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -72,8 +72,8 @@ OpenSSL 4.2
    until now there was no public API to do so. After the call the connection
    is in the same failed state as after an internally detected fatal error,
    and `SSL_shutdown()` does not send a close_notify. The function has the
-   same signature and semantics as in BoringSSL. It is not supported on QUIC
-   objects.
+   same signature as in BoringSSL and compatible behaviour. It is not
+   supported on QUIC objects.

    *kinchpik*

diff --git a/doc/man3/SSL_send_fatal_alert.pod b/doc/man3/SSL_send_fatal_alert.pod
index af461e4ccb..6982d78c04 100644
--- a/doc/man3/SSL_send_fatal_alert.pod
+++ b/doc/man3/SSL_send_fatal_alert.pod
@@ -35,9 +35,17 @@ The application should then close the underlying transport.
 The function may be called after the handshake has completed, or during the
 handshake between calls to L<SSL_do_handshake(3)>, L<SSL_connect(3)> or
 L<SSL_accept(3)>, for example when using nonblocking I/O.
-It must not be called from within a callback invoked by libssl while it is
-processing the handshake; such callbacks have their own means of aborting the
-handshake with an alert.
+It must not be called from within any callback invoked by libssl, for example
+a certificate verification callback, an info callback set with
+L<SSL_CTX_set_info_callback(3)>, a message callback set with
+L<SSL_CTX_set_msg_callback(3)> or a record padding callback set with
+L<SSL_CTX_set_record_padding_callback(3)>.
+Such calls are not supported.
+A call made while the handshake state machine is running is detected and
+fails, but calls from other callbacks, such as those invoked by the record
+layer, are not detected and lead to undefined behaviour.
+Callbacks that run during the handshake have their own means of aborting it
+with an alert.
 During the handshake the alert is protected with the keys that are current
 for the sender, so a peer that has moved to different keys, or that expects a
 different record version, may report a record layer error rather than the
@@ -52,7 +60,8 @@ B<SSL_ERROR_WANT_WRITE>.
 The connection is nevertheless already in the failed state.
 The application should call SSL_send_fatal_alert() again, with the same
 I<alert>, once the write BIO is writable, to finish sending the alert.
-Calling it with a different I<alert> at that point fails.
+Such a retry is the only call that succeeds on a connection that has already
+failed; calling it with a different I<alert> at that point fails.

 The alert description must be valid for the protocol version in use.
 The closure alerts B<SSL_AD_CLOSE_NOTIFY> and B<SSL_AD_USER_CANCELLED> are not
@@ -61,6 +70,9 @@ cleanly.
 The function fails if a fatal alert has already been sent, if the connection
 has already failed, or if a close_notify alert has already been sent, and the
 state of the connection is then left unchanged.
+This includes a connection on which libssl itself detected a fatal error but
+could not yet write its own alert because the write BIO blocked: that alert is
+not sent by SSL_send_fatal_alert(), and no other alert is sent in its place.

 SSL_send_fatal_alert() is not supported for QUIC connection or stream objects,
 which signal errors with a CONNECTION_CLOSE frame instead; see
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index 3ab85fef27..1d8c444aff 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -3243,7 +3243,19 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
         return -1;
     }

-    sc->statem.error_state = ERROR_STATE_NOERROR;
+    if (ssl_reset_error_state(sc) == 0) {
+        /*
+         * The connection has already failed. Only a retry of a blocked
+         * alert queued by an earlier call to this function may continue,
+         * not one queued internally by SSLfatal().
+         */
+        if (!sc->s3.app_fatal_alert
+            || sc->s3.alert_dispatch == SSL_ALERT_DISPATCH_NONE) {
+            ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
+            return -1;
+        }
+        sc->statem.error_state = ERROR_STATE_NOERROR;
+    }
     sc->rwstate = SSL_NOTHING;

     if (sc->handshake_func == NULL) {
@@ -3255,6 +3267,9 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
     /*
      * Calling this from a callback invoked by the handshake state machine
      * would leave the state machine running after the alert has been sent.
+     * Callbacks invoked outside the state machine, for example from the
+     * record layer, are not detected here; calling this function from any
+     * libssl callback is documented as unsupported.
      */
     if (ossl_statem_get_in_handshake(sc)) {
         ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
@@ -3278,20 +3293,19 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
     }

     if (sc->s3.alert_dispatch != SSL_ALERT_DISPATCH_NONE) {
-        /* Only a retry of the same fatal alert can continue */
-        if (sc->s3.send_alert[0] != SSL3_AL_FATAL
-            || sc->s3.send_alert[1] != desc) {
+        /*
+         * Only a retry of our own fatal alert, with the same description,
+         * can continue. Any other queued alert, such as a close_notify from
+         * SSL_shutdown(), is left alone.
+         */
+        if (!sc->s3.app_fatal_alert || sc->s3.send_alert[1] != desc) {
             ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
             sc->statem.error_state = ERROR_STATE_SSL;
             return -1;
         }
     } else {
-        /*
-         * A connection that has already failed, or that has sent a
-         * close_notify, cannot send a fatal alert.
-         */
-        if (ossl_statem_in_error(sc)
-            || (sc->shutdown & SSL_SENT_SHUTDOWN) != 0) {
+        /* A connection that has sent a close_notify cannot send an alert */
+        if ((sc->shutdown & SSL_SENT_SHUTDOWN) != 0) {
             ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
             sc->statem.error_state = ERROR_STATE_SSL;
             return -1;
@@ -3302,10 +3316,13 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
          * detected fatal error and queue the alert. This also removes the
          * session from the cache.
          */
+        sc->s3.app_fatal_alert = 1;
         ossl_statem_send_fatal(sc, alert);
     }

     ret = ssl_dispatch_fatal_alert(s, sc);
+    if (sc->s3.alert_dispatch == SSL_ALERT_DISPATCH_NONE)
+        sc->s3.app_fatal_alert = 0;
     if (ret <= 0 && !SSL_want_write(s))
         ssl_update_error_state(sc);
     return ret;
diff --git a/ssl/ssl_local.h b/ssl/ssl_local.h
index 4ccc6c3382..8ca187cfe0 100644
--- a/ssl/ssl_local.h
+++ b/ssl/ssl_local.h
@@ -1431,6 +1431,11 @@ struct ssl_connection_st {
          */
         int alert_dispatch;
         unsigned char send_alert[2];
+        /*
+         * Set while the alert in send_alert was queued by
+         * SSL_send_fatal_alert() and has not been written out yet
+         */
+        int app_fatal_alert;
         /*
          * This flag is set when we should renegotiate ASAP, basically when there
          * is no more data in the read or write buffers
diff --git a/test/sslapitest.c b/test/sslapitest.c
index 80b76cb29a..2f582363eb 100644
--- a/test/sslapitest.c
+++ b/test/sslapitest.c
@@ -13171,7 +13171,7 @@ end:

 /*
  * Set up a connection for the SSL_send_fatal_alert() tests.
- * prot 0: TLSv1.3, prot 1: TLSv1.2, prot 2: DTLSv1.2
+ * prot 0: TLSv1.3, prot 1: TLSv1.2, prot 2: DTLSv1.2, prot 3: DTLSv1.3
  */
 static int fatal_alert_setup(int prot, SSL_CTX **sctx, SSL_CTX **cctx,
     SSL **serverssl, SSL **clientssl)
@@ -13187,11 +13187,16 @@ static int fatal_alert_setup(int prot, SSL_CTX **sctx, SSL_CTX **cctx,
     case 1:
         version = TLS1_2_VERSION;
         break;
-    default:
+    case 2:
         smeth = DTLS_server_method();
         cmeth = DTLS_client_method();
         version = DTLS1_2_VERSION;
         break;
+    default:
+        smeth = DTLS_server_method();
+        cmeth = DTLS_client_method();
+        version = DTLS1_3_VERSION;
+        break;
     }

     return TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, version,
@@ -13217,11 +13222,17 @@ static int fatal_alert_prot_skip(int prot)
 #else
         return 0;
 #endif
-    default:
+    case 2:
 #if defined(OPENSSL_NO_DTLS) || defined(OPENSSL_NO_DTLS1_2)
         return 1;
 #else
         return 0;
+#endif
+    default:
+#if defined(OPENSSL_NO_DTLS) || defined(OSSL_NO_USABLE_DTLS1_3)
+        return 1;
+#else
+        return 0;
 #endif
     }
 }
@@ -13234,6 +13245,8 @@ static int fatal_alert_prot_skip(int prot)
  * Test 3: TLSv1.2, server sends the alert
  * Test 4: DTLSv1.2, client sends the alert
  * Test 5: DTLSv1.2, server sends the alert
+ * Test 6: DTLSv1.3, client sends the alert
+ * Test 7: DTLSv1.3, server sends the alert
  */
 static int test_send_fatal_alert(int idx)
 {
@@ -13382,6 +13395,100 @@ end:
     return testresult;
 }

+/*
+ * Test SSL_send_fatal_alert() on a connection that has failed internally
+ * while the write BIO was blocked, so that libssl's own alert is still queued.
+ * The call must fail and must not write that alert or its own alert.
+ * Test 0: TLSv1.3
+ * Test 1: TLSv1.2
+ */
+static int test_send_fatal_alert_internal_blocked(int idx)
+{
+    SSL_CTX *cctx = NULL, *sctx = NULL;
+    SSL *clientssl = NULL, *serverssl = NULL;
+    int testresult = 0;
+    char buf[80];
+    /* An application data record that cannot be decrypted */
+    static const unsigned char badrec[] = {
+        0x17, 0x03, 0x03, 0x00, 0x20,
+        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
+    };
+    BIO *bretry = NULL, *tmp = NULL;
+    uint64_t written;
+
+    if (fatal_alert_prot_skip(idx))
+        return TEST_skip("Protocol version not usable");
+
+    if (!TEST_ptr(bretry = BIO_new(bio_s_always_retry()))
+        || !fatal_alert_setup(idx, &sctx, &cctx, &serverssl, &clientssl))
+        goto end;
+
+    /* Swap the client's write BIO so that its alert write blocks */
+    tmp = SSL_get_wbio(clientssl);
+    if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
+        tmp = NULL;
+        goto end;
+    }
+    SSL_set0_wbio(clientssl, bretry);
+    bretry = NULL;
+
+    /* The client fails internally with SSLfatal() and queues an alert */
+    if (!TEST_int_eq(BIO_write(SSL_get_rbio(clientssl), badrec,
+                         sizeof(badrec)),
+            (int)sizeof(badrec))
+        || !TEST_int_le(SSL_read(clientssl, buf, sizeof(buf)), 0)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL))
+        goto end;
+    ERR_clear_error();
+
+    /* Reinstate the original write BIO: the queued alert could now be sent */
+    SSL_set0_wbio(clientssl, tmp);
+    tmp = NULL;
+    written = BIO_number_written(SSL_get_wbio(clientssl));
+
+    /*
+     * Neither our alert nor the internally queued one, even with the same
+     * description, may be sent.
+     */
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, SSL_AD_ACCESS_DENIED),
+            -1)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_PROTOCOL_IS_SHUTDOWN))
+        goto end;
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, SSL_AD_BAD_RECORD_MAC),
+            -1)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_PROTOCOL_IS_SHUTDOWN)
+        || !TEST_uint64_t_eq(BIO_number_written(SSL_get_wbio(clientssl)),
+            written))
+        goto end;
+    ERR_clear_error();
+
+    /* The server has received nothing from the client */
+    if (!TEST_int_le(SSL_read(serverssl, buf, sizeof(buf)), 0)
+        || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_READ))
+        goto end;
+
+    testresult = 1;
+
+end:
+    ERR_clear_error();
+    BIO_free(bretry);
+    BIO_free(tmp);
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+
+    return testresult;
+}
+
 /*
  * Test SSL_send_fatal_alert() failure cases that leave the connection usable.
  * Test 0: close_notify is not a fatal alert
@@ -20409,8 +20516,9 @@ int setup_tests(void)
     ADD_TEST(test_ticket_abort_session_leak);
     ADD_ALL_TESTS(test_shutdown, 7);
     ADD_TEST(test_async_shutdown);
-    ADD_ALL_TESTS(test_send_fatal_alert, 6);
+    ADD_ALL_TESTS(test_send_fatal_alert, 8);
     ADD_ALL_TESTS(test_send_fatal_alert_pending_write, 2);
+    ADD_ALL_TESTS(test_send_fatal_alert_internal_blocked, 2);
     ADD_ALL_TESTS(test_send_fatal_alert_errors, 3);
     ADD_ALL_TESTS(test_send_fatal_alert_in_handshake, 2);
     ADD_ALL_TESTS(test_ssl_bio_eof, 2);