From 2d05959073c4bf8803401668b9df85931a08e020 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Wed, 24 Apr 2024 11:33:41 +0100
Subject: [PATCH 2/5] Set rlayer.packet to NULL after we've finished using it

In order to ensure we do not have a UAF we reset the rlayer.packet pointer
to NULL after we free it.

CVE-2024-4741

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

(cherry picked from commit d146349171101dec3a876c13eb7a6dea32ba62ba)
---
 ssl/record/rec_layer_s3.c | 6 ++++++
 ssl/record/ssl3_buffer.c  | 2 ++
 2 files changed, 8 insertions(+)

diff --git a/ssl/record/rec_layer_s3.c b/ssl/record/rec_layer_s3.c
index 1569997bea..779e998bb6 100644
--- a/ssl/record/rec_layer_s3.c
+++ b/ssl/record/rec_layer_s3.c
@@ -230,6 +230,12 @@ int ssl3_read_n(SSL *s, size_t n, size_t max, int extend, int clearold,
         /* ... now we can act as if 'extend' was set */
     }
 
+    if (!ossl_assert(s->rlayer.packet != NULL)) {
+        /* does not happen */
+        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
+        return -1;
+    }
+
     len = s->rlayer.packet_length;
     pkt = rb->buf + align;
     /*
diff --git a/ssl/record/ssl3_buffer.c b/ssl/record/ssl3_buffer.c
index 97b0c26ced..1a10a7c0b8 100644
--- a/ssl/record/ssl3_buffer.c
+++ b/ssl/record/ssl3_buffer.c
@@ -191,5 +191,7 @@ int ssl3_release_read_buffer(SSL *s)
         OPENSSL_cleanse(b->buf, b->len);
     OPENSSL_free(b->buf);
     b->buf = NULL;
+    s->rlayer.packet = NULL;
+    s->rlayer.packet_length = 0;
     return 1;
 }
-- 
2.33.0

