From 5d0aba426b076094f74c5910a7e7bf7c0026148b Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Wed, 29 May 2024 16:17:48 +0800
Subject: [PATCH] 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 #24395)

Reference:https://github.com/openssl/openssl/commit/2d05959073c4bf8803401668b9df85931a08e020
Conflict:Context Adaptation

(cherry picked from commit d146349)
---
 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 81d20ad..71b0413 100644
--- a/ssl/record/rec_layer_s3.c
+++ b/ssl/record/rec_layer_s3.c
@@ -248,6 +248,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, SSL_F_SSL3_READ_N, 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 fa597c2..b8b91d1 100644
--- a/ssl/record/ssl3_buffer.c
+++ b/ssl/record/ssl3_buffer.c
@@ -179,5 +179,7 @@ int ssl3_release_read_buffer(SSL *s)
     b = RECORD_LAYER_get_rbuf(&s->rlayer);
     OPENSSL_free(b->buf);
     b->buf = NULL;
+    s->rlayer.packet = NULL;
+    s->rlayer.packet_length = 0;
     return 1;
 }
-- 
2.27.0

