Commit 8748d990b3 for openssl.org

commit 8748d990b3150e9c3beaa97119fb936525157afd
Author: kinchpik <kinchpik@kuicksilver.io>
Date:   Wed Oct 28 17:47:24 2026 +0500

    SSL_send_fatal_alert: flush the alert and stop the DTLS timer

    During the handshake libssl writes through a buffering BIO, so the
    alert record only reaches the transport when that BIO is flushed. The
    result of the flush in the alert dispatch functions is ignored, so if
    the write BIO blocked, SSL_send_fatal_alert() returned 1 although the
    alert had not been sent, and a retry then failed because the call was
    considered complete. Flush the write BIO after dispatching the alert
    and report SSL_ERROR_WANT_WRITE if the flush needs to be retried.
    s3.app_fatal_alert now stays set until the flush has succeeded, and a
    retry is accepted while the alert is queued or still being flushed.

    On DTLS, the retransmission timer stayed armed after the alert, so
    DTLSv1_handle_timeout() retransmitted the current handshake flight
    after it. Stop the timer before queueing the alert.

    Replace SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE in sslapitest.c with
    SSL_R_TLS_ALERT_HANDSHAKE_FAILURE. The former is a legacy alias that
    is not available in no-deprecated builds.

    Run test_send_fatal_alert_in_handshake for DTLSv1.2 and DTLSv1.3 as
    well, and add cases in which the alert write blocks and is retried.
    Add test_send_fatal_alert_dtls_timer to check that nothing is
    retransmitted after the alert. Tighten the wording of the man page.

    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/doc/man3/SSL_send_fatal_alert.pod b/doc/man3/SSL_send_fatal_alert.pod
index 6982d78c04..ced73163ef 100644
--- a/doc/man3/SSL_send_fatal_alert.pod
+++ b/doc/man3/SSL_send_fatal_alert.pod
@@ -30,20 +30,21 @@ more: subsequent calls to L<SSL_read_ex(3)>, L<SSL_write_ex(3)>,
 L<SSL_do_handshake(3)> and related functions fail, and L<SSL_shutdown(3)> fails
 without sending a close_notify alert.
 The session is removed from the session cache and cannot be resumed.
+For DTLS the retransmission timer is stopped, so L<DTLSv1_handle_timeout(3)>
+does not retransmit any handshake messages after the alert.
 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 any callback invoked by libssl, for example
-a certificate verification callback, an info callback set with
+Calls 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.
+L<SSL_CTX_set_record_padding_callback(3)>, must not be made.
 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.
+layer, are not detected.
 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
@@ -54,13 +55,13 @@ alert itself.
 If an earlier call to L<SSL_write_ex(3)> left a record only partially written
 because of a nonblocking write BIO, that record is written out first, followed
 by the alert.
-If the alert cannot be written immediately, SSL_send_fatal_alert() returns a
-value less than or equal to 0 and L<SSL_get_error(3)> returns
+If the alert cannot be written and flushed immediately, SSL_send_fatal_alert()
+returns a value less than or equal to 0 and L<SSL_get_error(3)> returns
 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.
-Such a retry is the only call that succeeds on a connection that has already
+Such a retry is the only call that is accepted 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.
@@ -81,7 +82,7 @@ L<SSL_shutdown_ex(3)>.
 =head1 RETURN VALUES

 SSL_send_fatal_alert() returns 1 if the alert has been written to the write
-BIO.
+BIO and the write BIO has been flushed.
 It returns a value less than or equal to 0 if the alert could not be sent yet
 or if an error occurred.
 In that case L<SSL_get_error(3)> should be called to find out whether the
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index 1d8c444aff..27e8b46aea 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -3203,15 +3203,13 @@ int SSL_shutdown(SSL *s)
 /*
  * Write out a fatal alert queued by SSL_send_fatal_alert(). A record left
  * partially written by an earlier SSL_write() is completed first, since the
- * alert cannot be written until it has been.
+ * alert cannot be written until it has been. During the handshake the alert
+ * goes into the buffering BIO, so it is only sent once that has been flushed.
  */
 static int ssl_dispatch_fatal_alert(SSL *s, SSL_CONNECTION *sc)
 {
     int ret;

-    if (sc->s3.alert_dispatch == SSL_ALERT_DISPATCH_NONE)
-        return 1;
-
     if (sc->s3.alert_dispatch == SSL_ALERT_DISPATCH_PENDING
         && RECORD_LAYER_write_pending(&sc->rlayer)) {
         ret = HANDLE_RLAYER_WRITE_RETURN(sc,
@@ -3221,7 +3219,20 @@ static int ssl_dispatch_fatal_alert(SSL *s, SSL_CONNECTION *sc)
         sc->rlayer.wpend_tot = 0;
     }

-    return s->method->ssl_dispatch_alert(s);
+    if (sc->s3.alert_dispatch != SSL_ALERT_DISPATCH_NONE) {
+        ret = s->method->ssl_dispatch_alert(s);
+        if (ret <= 0)
+            return ret;
+    }
+
+    if (sc->wbio != NULL) {
+        sc->rwstate = SSL_WRITING;
+        if (BIO_flush(sc->wbio) <= 0)
+            return -1;
+        sc->rwstate = SSL_NOTHING;
+    }
+
+    return 1;
 }

 int SSL_send_fatal_alert(SSL *s, uint8_t alert)
@@ -3245,12 +3256,11 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)

     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().
+         * The connection has already failed. Only a retry of an alert that
+         * an earlier call to this function could not finish writing may
+         * continue, not an alert queued internally by SSLfatal().
          */
-        if (!sc->s3.app_fatal_alert
-            || sc->s3.alert_dispatch == SSL_ALERT_DISPATCH_NONE) {
+        if (!sc->s3.app_fatal_alert) {
             ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
             return -1;
         }
@@ -3292,17 +3302,26 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
         return -1;
     }

-    if (sc->s3.alert_dispatch != SSL_ALERT_DISPATCH_NONE) {
+    if (sc->s3.app_fatal_alert) {
         /*
-         * 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.
+         * A retry: our alert is still queued, or it has been written but
+         * the write BIO has not been flushed yet. Only the same alert can
+         * be retried.
          */
-        if (!sc->s3.app_fatal_alert || sc->s3.send_alert[1] != desc) {
+        if (sc->s3.send_alert[0] != SSL3_AL_FATAL
+            || 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 if (sc->s3.alert_dispatch != SSL_ALERT_DISPATCH_NONE) {
+        /*
+         * Any other queued alert, such as a close_notify from SSL_shutdown(),
+         * is left alone.
+         */
+        ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
+        sc->statem.error_state = ERROR_STATE_SSL;
+        return -1;
     } else {
         /* A connection that has sent a close_notify cannot send an alert */
         if ((sc->shutdown & SSL_SENT_SHUTDOWN) != 0) {
@@ -3314,14 +3333,22 @@ int SSL_send_fatal_alert(SSL *s, uint8_t alert)
         /*
          * Put the connection into the same error state as an internally
          * detected fatal error and queue the alert. This also removes the
-         * session from the cache.
+         * session from the cache. In DTLS, stop the retransmission timer
+         * first, so that DTLSv1_handle_timeout() does not retransmit the
+         * current flight after the alert.
          */
+        if (SSL_CONNECTION_IS_DTLS(sc))
+            dtls1_stop_timer(sc);
         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)
+    /*
+     * Keep the flag while the alert is still queued or not yet flushed, so
+     * that the call can be retried.
+     */
+    if (ret > 0 || !SSL_want_write(s))
         sc->s3.app_fatal_alert = 0;
     if (ret <= 0 && !SSL_want_write(s))
         ssl_update_error_state(sc);
diff --git a/ssl/ssl_local.h b/ssl/ssl_local.h
index 8ca187cfe0..53f884a6d7 100644
--- a/ssl/ssl_local.h
+++ b/ssl/ssl_local.h
@@ -1433,7 +1433,8 @@ struct ssl_connection_st {
         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
+         * SSL_send_fatal_alert() and has not been written out and flushed
+         * yet
          */
         int app_fatal_alert;
         /*
diff --git a/test/sslapitest.c b/test/sslapitest.c
index 2f582363eb..0edcb8e9e8 100644
--- a/test/sslapitest.c
+++ b/test/sslapitest.c
@@ -13170,11 +13170,12 @@ end:
 }

 /*
- * Set up a connection for the SSL_send_fatal_alert() tests.
+ * Set up the objects for the SSL_send_fatal_alert() tests, and complete the
+ * handshake if |connect| is set.
  * 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)
+static int fatal_alert_setup(int prot, int connect, SSL_CTX **sctx,
+    SSL_CTX **cctx, SSL **serverssl, SSL **clientssl)
 {
     const SSL_METHOD *smeth = TLS_server_method();
     const SSL_METHOD *cmeth = TLS_client_method();
@@ -13203,8 +13204,9 @@ static int fatal_alert_setup(int prot, SSL_CTX **sctx, SSL_CTX **cctx,
                version, sctx, cctx, cert, privkey))
         && TEST_true(create_ssl_objects(*sctx, *cctx, serverssl, clientssl,
             NULL, NULL))
-        && TEST_true(create_ssl_connection(*serverssl, *clientssl,
-            SSL_ERROR_NONE));
+        && (!connect
+            || TEST_true(create_ssl_connection(*serverssl, *clientssl,
+                SSL_ERROR_NONE)));
 }

 static int fatal_alert_prot_skip(int prot)
@@ -13261,7 +13263,7 @@ static int test_send_fatal_alert(int idx)
     if (fatal_alert_prot_skip(prot))
         return TEST_skip("Protocol version not usable");

-    if (!fatal_alert_setup(prot, &sctx, &cctx, &serverssl, &clientssl))
+    if (!fatal_alert_setup(prot, 1, &sctx, &cctx, &serverssl, &clientssl))
         goto end;

     sender = (idx % 2 == 0) ? clientssl : serverssl;
@@ -13334,7 +13336,7 @@ static int test_send_fatal_alert_pending_write(int 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))
+        || !fatal_alert_setup(idx, 1, &sctx, &cctx, &serverssl, &clientssl))
         goto end;

     /* Swap the client's write BIO to force a retry */
@@ -13423,7 +13425,7 @@ static int test_send_fatal_alert_internal_blocked(int 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))
+        || !fatal_alert_setup(idx, 1, &sctx, &cctx, &serverssl, &clientssl))
         goto end;

     /* Swap the client's write BIO so that its alert write blocks */
@@ -13567,25 +13569,26 @@ end:
 /*
  * Test SSL_send_fatal_alert() by a server during the handshake, between calls
  * to SSL_accept(), after it has sent its first flight.
- * Test 0: TLSv1.2
- * Test 1: TLSv1.3
+ * Test 0: TLSv1.3
+ * Test 1: TLSv1.2
+ * Test 2: DTLSv1.2
+ * Test 3: DTLSv1.3
+ * Test 4-7: As 0-3, but the alert write blocks first and is retried
  */
 static int test_send_fatal_alert_in_handshake(int idx)
 {
     SSL_CTX *cctx = NULL, *sctx = NULL;
     SSL *clientssl = NULL, *serverssl = NULL;
     int testresult = 0, ret;
-    int version = (idx == 0) ? TLS1_2_VERSION : TLS1_3_VERSION;
+    int prot = idx % 4, blocked = idx >= 4;
     char buf[80];
+    BIO *bretry = NULL, *tmp = NULL;

-    if (fatal_alert_prot_skip(idx == 0 ? 1 : 0))
+    if (fatal_alert_prot_skip(prot))
         return TEST_skip("Protocol version not usable");

-    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
-            TLS_client_method(), version, version, &sctx,
-            &cctx, cert, privkey))
-        || !TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
-            NULL, NULL)))
+    if (!TEST_ptr(bretry = BIO_new(bio_s_always_retry()))
+        || !fatal_alert_setup(prot, 0, &sctx, &cctx, &serverssl, &clientssl))
         goto end;

     /* Send the ClientHello and the server's first flight */
@@ -13596,6 +13599,27 @@ static int test_send_fatal_alert_in_handshake(int idx)
         goto end;

     ERR_clear_error();
+    if (blocked) {
+        /* Swap the server's write BIO so that the alert cannot be sent */
+        tmp = SSL_get_wbio(serverssl);
+        if (!TEST_ptr(tmp) || !TEST_true(BIO_up_ref(tmp))) {
+            tmp = NULL;
+            goto end;
+        }
+        SSL_set0_wbio(serverssl, bretry);
+        bretry = NULL;
+
+        if (!TEST_int_eq(SSL_send_fatal_alert(serverssl,
+                             SSL_AD_HANDSHAKE_FAILURE),
+                -1)
+            || !TEST_int_eq(SSL_get_error(serverssl, -1),
+                SSL_ERROR_WANT_WRITE))
+            goto end;
+
+        /* Reinstate the original write BIO and retry */
+        SSL_set0_wbio(serverssl, tmp);
+        tmp = NULL;
+    }
     if (!TEST_int_eq(SSL_send_fatal_alert(serverssl, SSL_AD_HANDSHAKE_FAILURE),
             1))
         goto end;
@@ -13607,7 +13631,7 @@ static int test_send_fatal_alert_in_handshake(int idx)
     ERR_clear_error();

     /*
-     * The client fails once it reads the alert. In TLSv1.3 the client
+     * The client fails once it reads the alert. In (D)TLSv1.3 the client
      * completes its side of the handshake before it reads the alert.
      */
     ret = SSL_connect(clientssl);
@@ -13616,13 +13640,15 @@ static int test_send_fatal_alert_in_handshake(int idx)
     if (!TEST_int_le(ret, 0)
         || !TEST_int_eq(SSL_get_error(clientssl, ret), SSL_ERROR_SSL)
         || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
-            SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE))
+            SSL_R_TLS_ALERT_HANDSHAKE_FAILURE))
         goto end;

     testresult = 1;

 end:
     ERR_clear_error();
+    BIO_free(bretry);
+    BIO_free(tmp);
     SSL_free(serverssl);
     SSL_free(clientssl);
     SSL_CTX_free(sctx);
@@ -13631,6 +13657,58 @@ end:
     return testresult;
 }

+#ifndef OPENSSL_NO_DTLS
+/*
+ * Test that DTLSv1_handle_timeout() does not retransmit the handshake flight
+ * after SSL_send_fatal_alert().
+ * Test 0: DTLSv1.2
+ * Test 1: DTLSv1.3
+ */
+static int test_send_fatal_alert_dtls_timer(int idx)
+{
+    SSL_CTX *cctx = NULL, *sctx = NULL;
+    SSL *clientssl = NULL, *serverssl = NULL;
+    int testresult = 0;
+    int prot = idx + 2;
+    struct timeval timeout;
+    uint64_t written;
+
+    if (fatal_alert_prot_skip(prot))
+        return TEST_skip("Protocol version not usable");
+
+    if (!fatal_alert_setup(prot, 0, &sctx, &cctx, &serverssl, &clientssl))
+        goto end;
+
+    /* Send the ClientHello, which starts the retransmission timer */
+    if (!TEST_int_le(SSL_connect(clientssl), 0)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_WANT_READ))
+        goto end;
+
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, SSL_AD_ACCESS_DENIED), 1))
+        goto end;
+
+    /* The timer is stopped, so nothing is retransmitted */
+    written = BIO_number_written(SSL_get_wbio(clientssl));
+    if (!TEST_false(DTLSv1_get_timeout(clientssl, &timeout))
+        || !TEST_int_le(DTLSv1_handle_timeout(clientssl), 0)
+        || !TEST_uint64_t_eq(BIO_number_written(SSL_get_wbio(clientssl)),
+            written))
+        goto end;
+
+    testresult = 1;
+
+end:
+    ERR_clear_error();
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+
+    return testresult;
+}
+#endif
+
 /*
  * Test bi-directional shutdown.
  * Test 0: TLSv1.2
@@ -20520,7 +20598,10 @@ int setup_tests(void)
     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_send_fatal_alert_in_handshake, 8);
+#ifndef OPENSSL_NO_DTLS
+    ADD_ALL_TESTS(test_send_fatal_alert_dtls_timer, 2);
+#endif
     ADD_ALL_TESTS(test_ssl_bio_eof, 2);
     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
     ADD_ALL_TESTS(test_cert_cb, 6);