From 4a96c6b7265838b044dab4a2a6150c246297bc89 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Fri, 31 May 2024 11:18:27 +0100
Subject: [PATCH 2/9] More correctly handle a selected_len of 0 when processing
 NPN

In the case where the NPN callback returns with SSL_TLEXT_ERR_OK, but
the selected_len is 0 we should fail. Previously this would fail with an
internal_error alert because calling OPENSSL_malloc(selected_len) will
return NULL when selected_len is 0. We make this error detection more
explicit and return a handshake failure alert.

Follow on from CVE-2024-5535

Reviewed-by: Neil Horman <nhorman@openssl.org>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/24718)

(cherry picked from commit 4279c89a726025c758db3dafb263b17e52211304)

Upstream-Status: Backport from [https://github.com/openssl/openssl/commit/159921152fd4aa91e4c849fd281ad93ac0d0d0ba]
CVE: CVE-2024-5535
Signed-off-by: Siddharth Doshi <sdoshi@mvista.com>
---
 ssl/statem/extensions_clnt.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ssl/statem/extensions_clnt.c b/ssl/statem/extensions_clnt.c
index 842be07..a07dc62 100644
--- a/ssl/statem/extensions_clnt.c
+++ b/ssl/statem/extensions_clnt.c
@@ -1536,7 +1536,8 @@ int tls_parse_stoc_npn(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
                                   PACKET_data(pkt),
                                   PACKET_remaining(pkt),
                                   s->ctx->ext.npn_select_cb_arg) !=
-             SSL_TLSEXT_ERR_OK) {
+                                  SSL_TLSEXT_ERR_OK
+            || selected_len == 0) {
         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_EXTENSION);
         return 0;
     }
-- 
2.25.1

