Commit a7a6ef8260 for openssl.org

commit a7a6ef826081635b978c1e06b96ebadb6e87c536
Author: kinchpik <kinchpik@kuicksilver.io>
Date:   Tue Oct 27 23:44:38 2026 +0500

    Add SSL_send_fatal_alert() to abort a connection with an alert

    RFC 9846 (TLS 1.3) section 6.2 says that on a fatal error an
    implementation SHOULD send an appropriate fatal alert and MUST close
    the connection. Some fatal errors can only be detected by the
    application, for example a failed application-level integrity check
    or a post-handshake certificate pinning check. Until now there was no
    public way to send an alert in those cases: SSL_shutdown() sends a
    close_notify, which reports a clean close, and the internal
    ssl3_send_alert() is not exported.

    SSL_send_fatal_alert() sends the given fatal alert. It then leaves the
    connection in the same failed state as an internally detected fatal
    error, so later SSL_read(), SSL_write() and SSL_do_handshake() calls
    fail, and SSL_shutdown() fails without sending a close_notify. A
    record that an earlier SSL_write() left partially written is flushed
    before the alert. If the write BIO blocks, the function returns <= 0
    with SSL_ERROR_WANT_WRITE and must be retried with the same alert. It
    fails with SSL_R_PROTOCOL_IS_SHUTDOWN if an alert or a close_notify
    has already been sent. The closure alerts close_notify and
    user_canceled are rejected. QUIC objects are not supported, because
    QUIC reports errors with CONNECTION_CLOSE.

    The signature and semantics match BoringSSL's SSL_send_fatal_alert(),
    so applications can use the same code with both libraries.

    Assisted-by: Claude Code:claude-opus-5-5
    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 1846a1c72e..8fe0c55c0a 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -65,6 +65,18 @@ OpenSSL 4.2

    *Alexandr Nedvedicky*

+ * Added `SSL_send_fatal_alert()`, which lets an application send a fatal
+   alert on a TLS or DTLS connection and abort it, for example when it detects
+   an error after the handshake that libssl cannot see. RFC 9846 recommends
+   sending an appropriate fatal alert before closing on a fatal error, but
+   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.
+
+   *kinchpik*
+
  * s390x: Disable mod-expo offloading to a crypto card for small exponents.
    Add a new keyword `cex_min_bits:<bits>` for the `OPENSSL_s390xcap`
    environment variable to specify the minimum number of bits that the
diff --git a/doc/build.info b/doc/build.info
index c7c400df15..516cb17a2d 100644
--- a/doc/build.info
+++ b/doc/build.info
@@ -2799,6 +2799,10 @@ DEPEND[html/man3/SSL_rstate_string.html]=man3/SSL_rstate_string.pod
 GENERATE[html/man3/SSL_rstate_string.html]=man3/SSL_rstate_string.pod
 DEPEND[man/man3/SSL_rstate_string.3]=man3/SSL_rstate_string.pod
 GENERATE[man/man3/SSL_rstate_string.3]=man3/SSL_rstate_string.pod
+DEPEND[html/man3/SSL_send_fatal_alert.html]=man3/SSL_send_fatal_alert.pod
+GENERATE[html/man3/SSL_send_fatal_alert.html]=man3/SSL_send_fatal_alert.pod
+DEPEND[man/man3/SSL_send_fatal_alert.3]=man3/SSL_send_fatal_alert.pod
+GENERATE[man/man3/SSL_send_fatal_alert.3]=man3/SSL_send_fatal_alert.pod
 DEPEND[html/man3/SSL_session_reused.html]=man3/SSL_session_reused.pod
 GENERATE[html/man3/SSL_session_reused.html]=man3/SSL_session_reused.pod
 DEPEND[man/man3/SSL_session_reused.3]=man3/SSL_session_reused.pod
@@ -3795,6 +3799,7 @@ html/man3/SSL_poll.html \
 html/man3/SSL_read.html \
 html/man3/SSL_read_early_data.html \
 html/man3/SSL_rstate_string.html \
+html/man3/SSL_send_fatal_alert.html \
 html/man3/SSL_session_reused.html \
 html/man3/SSL_set1_echstore.html \
 html/man3/SSL_set1_host.html \
@@ -4481,6 +4486,7 @@ man/man3/SSL_poll.3 \
 man/man3/SSL_read.3 \
 man/man3/SSL_read_early_data.3 \
 man/man3/SSL_rstate_string.3 \
+man/man3/SSL_send_fatal_alert.3 \
 man/man3/SSL_session_reused.3 \
 man/man3/SSL_set1_echstore.3 \
 man/man3/SSL_set1_host.3 \
diff --git a/doc/man3/SSL_send_fatal_alert.pod b/doc/man3/SSL_send_fatal_alert.pod
new file mode 100644
index 0000000000..af461e4ccb
--- /dev/null
+++ b/doc/man3/SSL_send_fatal_alert.pod
@@ -0,0 +1,97 @@
+=pod
+
+=head1 NAME
+
+SSL_send_fatal_alert - send a fatal alert and abort a TLS or DTLS connection
+
+=head1 SYNOPSIS
+
+ #include <openssl/ssl.h>
+
+ int SSL_send_fatal_alert(SSL *s, uint8_t alert);
+
+=head1 DESCRIPTION
+
+SSL_send_fatal_alert() sends a fatal alert with the description I<alert> to the
+peer of the TLS or DTLS connection I<s> and puts the connection into the same
+failed state as when libssl itself detects a fatal error.
+I<alert> should be one of the B<SSL_AD_*> alert descriptions, for example
+B<SSL_AD_ACCESS_DENIED> or B<SSL_AD_INTERNAL_ERROR>.
+
+This function is intended for applications that detect a fatal error that the
+TLS implementation cannot see, such as an application level integrity check
+failing or a certificate pinning check failing after the handshake.
+L<RFC 9846|https://www.rfc-editor.org/rfc/rfc9846> recommends that an
+implementation that encounters a fatal error sends an appropriate fatal alert
+and requires that it closes the connection.
+
+Once SSL_send_fatal_alert() has been called, the connection cannot be used any
+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.
+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.
+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
+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
+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.
+
+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
+error alerts and are rejected; use L<SSL_shutdown(3)> to close a connection
+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.
+
+SSL_send_fatal_alert() is not supported for QUIC connection or stream objects,
+which signal errors with a CONNECTION_CLOSE frame instead; see
+L<SSL_shutdown_ex(3)>.
+
+=head1 RETURN VALUES
+
+SSL_send_fatal_alert() returns 1 if the alert has been written to the write
+BIO.
+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
+operation should be retried (B<SSL_ERROR_WANT_WRITE>) or failed
+(B<SSL_ERROR_SSL> or B<SSL_ERROR_SYSCALL>).
+
+=head1 SEE ALSO
+
+L<ssl(7)>, L<SSL_shutdown(3)>, L<SSL_shutdown_ex(3)>, L<SSL_get_error(3)>,
+L<SSL_alert_type_string(3)>, L<SSL_CTX_set_info_callback(3)>
+
+=head1 HISTORY
+
+The SSL_send_fatal_alert() function was added in OpenSSL 4.2.
+
+=head1 COPYRIGHT
+
+Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+
+Licensed under the Apache License 2.0 (the "License").  You may not use
+this file except in compliance with the License.  You can obtain a copy
+in the file LICENSE in the source distribution or at
+L<https://www.openssl.org/source/license.html>.
+
+=cut
diff --git a/include/openssl/ssl.h.in b/include/openssl/ssl.h.in
index 9eb71eaa92..bcf8235297 100644
--- a/include/openssl/ssl.h.in
+++ b/include/openssl/ssl.h.in
@@ -2087,6 +2087,7 @@ int SSL_renegotiate_abbreviated(SSL *s);
 __owur int SSL_renegotiate_pending(const SSL *s);
 int SSL_new_session_ticket(SSL *s);
 int SSL_shutdown(SSL *s);
+int SSL_send_fatal_alert(SSL *s, uint8_t alert);
 __owur int SSL_verify_client_post_handshake(SSL *s);
 void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val);
 void SSL_set_post_handshake_auth(SSL *s, int val);
diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c
index c73eb0a87a..3ab85fef27 100644
--- a/ssl/ssl_lib.c
+++ b/ssl/ssl_lib.c
@@ -3200,6 +3200,117 @@ int SSL_shutdown(SSL *s)
     return ret;
 }

+/*
+ * 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.
+ */
+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,
+            sc->rlayer.wrlmethod->retry_write_records(sc->rlayer.wrl));
+        if (ret <= 0)
+            return ret;
+        sc->rlayer.wpend_tot = 0;
+    }
+
+    return s->method->ssl_dispatch_alert(s);
+}
+
+int SSL_send_fatal_alert(SSL *s, uint8_t alert)
+{
+    SSL_CONNECTION *sc;
+    int desc, ret;
+
+#ifndef OPENSSL_NO_QUIC
+    if (IS_QUIC(s)) {
+        /* QUIC reports fatal errors with CONNECTION_CLOSE, not alerts */
+        ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION);
+        return -1;
+    }
+#endif
+
+    sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
+    if (sc == NULL) {
+        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
+        return -1;
+    }
+
+    sc->statem.error_state = ERROR_STATE_NOERROR;
+    sc->rwstate = SSL_NOTHING;
+
+    if (sc->handshake_func == NULL) {
+        ERR_raise(ERR_LIB_SSL, SSL_R_UNINITIALIZED);
+        sc->statem.error_state = ERROR_STATE_SSL;
+        return -1;
+    }
+
+    /*
+     * Calling this from a callback invoked by the handshake state machine
+     * would leave the state machine running after the alert has been sent.
+     */
+    if (ossl_statem_get_in_handshake(sc)) {
+        ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
+        sc->statem.error_state = ERROR_STATE_SSL;
+        return -1;
+    }
+
+    /*
+     * Map the alert to the wire value in the same way as ssl3_send_alert().
+     * The closure alerts close_notify and user_canceled are not error alerts.
+     */
+    if (SSL_CONNECTION_TREAT_AS_TLS13(sc))
+        desc = tls13_alert_code(alert);
+    else
+        desc = s->method->ssl3_enc->alert_value(alert);
+    if (desc < 0 || desc == SSL3_AD_CLOSE_NOTIFY
+        || desc == TLS1_AD_USER_CANCELLED) {
+        ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_ALERT);
+        sc->statem.error_state = ERROR_STATE_SSL;
+        return -1;
+    }
+
+    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) {
+            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) {
+            ERR_raise(ERR_LIB_SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
+            sc->statem.error_state = ERROR_STATE_SSL;
+            return -1;
+        }
+
+        /*
+         * 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.
+         */
+        ossl_statem_send_fatal(sc, alert);
+    }
+
+    ret = ssl_dispatch_fatal_alert(s, sc);
+    if (ret <= 0 && !SSL_want_write(s))
+        ssl_update_error_state(sc);
+    return ret;
+}
+
 int SSL_key_update(SSL *s, int updatetype)
 {
     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
diff --git a/test/quicapitest.c b/test/quicapitest.c
index 0009d5182f..a2a211ddfb 100644
--- a/test/quicapitest.c
+++ b/test/quicapitest.c
@@ -454,6 +454,32 @@ err:
     return testresult;
 }

+/* SSL_send_fatal_alert() is not supported on QUIC objects */
+static int test_send_fatal_alert(void)
+{
+    SSL_CTX *ctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
+    SSL *ssl = NULL;
+    int testresult = 0;
+
+    if (!TEST_ptr(ctx)
+        || !TEST_ptr(ssl = SSL_new(ctx)))
+        goto err;
+
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(ssl, SSL_AD_INTERNAL_ERROR), -1)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_WRONG_SSL_VERSION))
+        goto err;
+
+    testresult = 1;
+err:
+    ERR_clear_error();
+    SSL_free(ssl);
+    SSL_CTX_free(ctx);
+
+    return testresult;
+}
+
 static int test_cipher_find(void)
 {
     SSL_CTX *cctx = SSL_CTX_new_ex(libctx, NULL, OSSL_QUIC_client_method());
@@ -5946,6 +5972,7 @@ int setup_tests(void)
     ADD_TEST(test_fin_only_blocking);
     ADD_TEST(test_ciphersuites);
     ADD_TEST(test_cipher_find);
+    ADD_TEST(test_send_fatal_alert);
     ADD_TEST(test_version);
 #if defined(DO_SSL_TRACE_TEST)
     ADD_TEST(test_ssl_trace);
diff --git a/test/sslapitest.c b/test/sslapitest.c
index 40fd1123ae..80b76cb29a 100644
--- a/test/sslapitest.c
+++ b/test/sslapitest.c
@@ -13169,6 +13169,361 @@ end:
     return testresult;
 }

+/*
+ * Set up a connection for the SSL_send_fatal_alert() tests.
+ * prot 0: TLSv1.3, prot 1: TLSv1.2, prot 2: DTLSv1.2
+ */
+static int fatal_alert_setup(int prot, SSL_CTX **sctx, SSL_CTX **cctx,
+    SSL **serverssl, SSL **clientssl)
+{
+    const SSL_METHOD *smeth = TLS_server_method();
+    const SSL_METHOD *cmeth = TLS_client_method();
+    int version;
+
+    switch (prot) {
+    case 0:
+        version = TLS1_3_VERSION;
+        break;
+    case 1:
+        version = TLS1_2_VERSION;
+        break;
+    default:
+        smeth = DTLS_server_method();
+        cmeth = DTLS_client_method();
+        version = DTLS1_2_VERSION;
+        break;
+    }
+
+    return TEST_true(create_ssl_ctx_pair(libctx, smeth, cmeth, version,
+               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));
+}
+
+static int fatal_alert_prot_skip(int prot)
+{
+    switch (prot) {
+    case 0:
+#ifdef OSSL_NO_USABLE_TLS1_3
+        return 1;
+#else
+        return 0;
+#endif
+    case 1:
+#ifdef OPENSSL_NO_TLS1_2
+        return 1;
+#else
+        return 0;
+#endif
+    default:
+#if defined(OPENSSL_NO_DTLS) || defined(OPENSSL_NO_DTLS1_2)
+        return 1;
+#else
+        return 0;
+#endif
+    }
+}
+
+/*
+ * Test SSL_send_fatal_alert() after the handshake.
+ * Test 0: TLSv1.3, client sends the alert
+ * Test 1: TLSv1.3, server sends the alert
+ * Test 2: TLSv1.2, client sends the alert
+ * Test 3: TLSv1.2, server sends the alert
+ * Test 4: DTLSv1.2, client sends the alert
+ * Test 5: DTLSv1.2, server sends the alert
+ */
+static int test_send_fatal_alert(int idx)
+{
+    SSL_CTX *cctx = NULL, *sctx = NULL;
+    SSL *clientssl = NULL, *serverssl = NULL, *sender, *peer;
+    int testresult = 0;
+    int prot = idx / 2;
+    char buf[80];
+    static const char *mess = "A test message";
+    uint64_t written;
+
+    if (fatal_alert_prot_skip(prot))
+        return TEST_skip("Protocol version not usable");
+
+    if (!fatal_alert_setup(prot, &sctx, &cctx, &serverssl, &clientssl))
+        goto end;
+
+    sender = (idx % 2 == 0) ? clientssl : serverssl;
+    peer = (idx % 2 == 0) ? serverssl : clientssl;
+
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(sender, SSL_AD_ACCESS_DENIED), 1))
+        goto end;
+
+    /* No further alert can be sent */
+    if (!TEST_int_le(SSL_send_fatal_alert(sender, SSL_AD_ACCESS_DENIED), 0)
+        || !TEST_int_eq(SSL_get_error(sender, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_PROTOCOL_IS_SHUTDOWN))
+        goto end;
+    ERR_clear_error();
+
+    /* The connection can no longer be used to send or receive data */
+    if (!TEST_int_le(SSL_write(sender, mess, (int)strlen(mess)), 0)
+        || !TEST_int_eq(SSL_get_error(sender, -1), SSL_ERROR_SSL)
+        || !TEST_int_le(SSL_read(sender, buf, sizeof(buf)), 0)
+        || !TEST_int_eq(SSL_get_error(sender, -1), SSL_ERROR_SSL))
+        goto end;
+    ERR_clear_error();
+
+    /* SSL_shutdown() must not send a close_notify after a fatal alert */
+    written = BIO_number_written(SSL_get_wbio(sender));
+    if (!TEST_int_lt(SSL_shutdown(sender), 0)
+        || !TEST_uint64_t_eq(BIO_number_written(SSL_get_wbio(sender)),
+            written)
+        || !TEST_false(SSL_get_shutdown(sender) & SSL_SENT_SHUTDOWN))
+        goto end;
+    ERR_clear_error();
+
+    /* The peer receives the alert as a fatal error */
+    if (!TEST_int_le(SSL_read(peer, buf, sizeof(buf)), 0)
+        || !TEST_int_eq(SSL_get_error(peer, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_TLSV1_ALERT_ACCESS_DENIED))
+        goto end;
+
+    testresult = 1;
+
+end:
+    ERR_clear_error();
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+
+    return testresult;
+}
+
+/*
+ * Test SSL_send_fatal_alert() while a record from an earlier SSL_write() is
+ * still pending. The pending record must be written before the alert.
+ * Test 0: TLSv1.3
+ * Test 1: TLSv1.2
+ */
+static int test_send_fatal_alert_pending_write(int idx)
+{
+    SSL_CTX *cctx = NULL, *sctx = NULL;
+    SSL *clientssl = NULL, *serverssl = NULL;
+    int testresult = 0;
+    char buf[80];
+    static const char *mess = "A test message";
+    BIO *bretry = NULL, *tmp = NULL;
+
+    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 to force a retry */
+    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;
+
+    if (!TEST_int_eq(SSL_write(clientssl, mess, (int)strlen(mess)), -1)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_WANT_WRITE))
+        goto end;
+
+    /* The alert cannot be sent yet either */
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, SSL_AD_INTERNAL_ERROR),
+            -1)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_WANT_WRITE))
+        goto end;
+
+    /* A different alert cannot be substituted while retrying */
+    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();
+
+    /* Reinstate the original write BIO and retry */
+    SSL_set0_wbio(clientssl, tmp);
+    tmp = NULL;
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, SSL_AD_INTERNAL_ERROR),
+            1))
+        goto end;
+
+    /* The server reads the pending data, then the alert */
+    if (!TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)), (int)strlen(mess))
+        || !TEST_mem_eq(buf, strlen(mess), mess, strlen(mess))
+        || !TEST_int_le(SSL_read(serverssl, buf, sizeof(buf)), 0)
+        || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()),
+            SSL_R_TLSV1_ALERT_INTERNAL_ERROR))
+        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
+ * Test 1: a close_notify has already been sent
+ * Test 2: user_canceled is not a fatal alert
+ */
+static int test_send_fatal_alert_errors(int idx)
+{
+    SSL_CTX *cctx = NULL, *sctx = NULL;
+    SSL *clientssl = NULL, *serverssl = NULL;
+    int testresult = 0;
+    char buf[80];
+    static const char *mess = "A test message";
+    int expected = SSL_R_INVALID_ALERT;
+    uint8_t alert;
+
+    switch (idx) {
+    case 0:
+        alert = SSL_AD_CLOSE_NOTIFY;
+        break;
+    case 1:
+        alert = SSL_AD_INTERNAL_ERROR;
+        expected = SSL_R_PROTOCOL_IS_SHUTDOWN;
+        break;
+    default:
+        alert = SSL_AD_USER_CANCELLED;
+        break;
+    }
+
+    if (!TEST_true(create_ssl_ctx_pair(libctx, TLS_server_method(),
+            TLS_client_method(), 0, 0, &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)))
+        goto end;
+
+    if (idx == 1 && !TEST_int_eq(SSL_shutdown(clientssl), 0))
+        goto end;
+
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(clientssl, alert), -1)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_SSL)
+        || !TEST_int_eq(ERR_GET_REASON(ERR_peek_last_error()), expected))
+        goto end;
+    ERR_clear_error();
+
+    if (idx != 1) {
+        /* Nothing was sent: the connection still works */
+        if (!TEST_int_eq(SSL_write(clientssl, mess, (int)strlen(mess)),
+                (int)strlen(mess))
+            || !TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)),
+                (int)strlen(mess)))
+            goto end;
+    } else {
+        /* The server sees a normal close_notify, not an alert */
+        if (!TEST_int_eq(SSL_read(serverssl, buf, sizeof(buf)), 0)
+            || !TEST_int_eq(SSL_get_error(serverssl, 0),
+                SSL_ERROR_ZERO_RETURN))
+            goto end;
+    }
+
+    testresult = 1;
+
+end:
+    ERR_clear_error();
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+
+    return testresult;
+}
+
+/*
+ * 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
+ */
+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;
+    char buf[80];
+
+    if (fatal_alert_prot_skip(idx == 0 ? 1 : 0))
+        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)))
+        goto end;
+
+    /* Send the ClientHello and the server's first flight */
+    if (!TEST_int_le(SSL_connect(clientssl), 0)
+        || !TEST_int_eq(SSL_get_error(clientssl, -1), SSL_ERROR_WANT_READ)
+        || !TEST_int_le(SSL_accept(serverssl), 0)
+        || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_WANT_READ))
+        goto end;
+
+    ERR_clear_error();
+    if (!TEST_int_eq(SSL_send_fatal_alert(serverssl, SSL_AD_HANDSHAKE_FAILURE),
+            1))
+        goto end;
+
+    /* The server cannot continue the handshake */
+    if (!TEST_int_le(SSL_accept(serverssl), 0)
+        || !TEST_int_eq(SSL_get_error(serverssl, -1), SSL_ERROR_SSL))
+        goto end;
+    ERR_clear_error();
+
+    /*
+     * The client fails once it reads the alert. In TLSv1.3 the client
+     * completes its side of the handshake before it reads the alert.
+     */
+    ret = SSL_connect(clientssl);
+    if (ret == 1)
+        ret = SSL_read(clientssl, buf, sizeof(buf));
+    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))
+        goto end;
+
+    testresult = 1;
+
+end:
+    ERR_clear_error();
+    SSL_free(serverssl);
+    SSL_free(clientssl);
+    SSL_CTX_free(sctx);
+    SSL_CTX_free(cctx);
+
+    return testresult;
+}
+
 /*
  * Test bi-directional shutdown.
  * Test 0: TLSv1.2
@@ -20054,6 +20409,10 @@ 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_pending_write, 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);
     ADD_ALL_TESTS(test_incorrect_shutdown, 2);
     ADD_ALL_TESTS(test_cert_cb, 6);
diff --git a/util/libssl.num b/util/libssl.num
index c81feb263e..4a2ca8ded1 100644
--- a/util/libssl.num
+++ b/util/libssl.num
@@ -626,3 +626,4 @@ SSL_CTX_ech_set1_outer_alpn_protos      625	4_0_0	EXIST::FUNCTION:ECH
 SSL_set1_ech_config_list                626	4_0_0	EXIST::FUNCTION:ECH
 SSL_get0_sigalg                         627	4_0_0	EXIST::FUNCTION:
 SSL_get0_shared_sigalg                  628	4_0_0	EXIST::FUNCTION:
+SSL_send_fatal_alert                    ?	4_2_0	EXIST::FUNCTION: