From fc06cdeb11963e348e9787bb95689f9be064a506 Mon Sep 17 00:00:00 2001
From: tb <>
Date: Mon, 15 Mar 2021 15:59:04 +0000
Subject: Don't leave stale sequence numbers behind in ssl3_clear()

A TLS client doing session reuse in a certain way could run into
a use-after-free. Set the sequence numbers inside ssl3_clear() to
make sure this points at valid memory and do the initialization of
the record layer a bit earlier so that this works as desired.
Additionally, explicitly clear the sequence numbers in ssl3_free()
which would have turned the use-after-free into a NULL dereference.

Issue reported by Ilya Chipitsine.

Fix from jsing

This is errata/6.8/017_libssl.patch.sig
---
 src/lib/libssl/s3_lib.c  | 11 ++++++++++-
 src/lib/libssl/ssl_lib.c |  7 +++----
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/src/lib/libssl/s3_lib.c b/src/lib/libssl/s3_lib.c
index 91bfb5f3b6..97dd2005c2 100644
--- a/src/lib/libssl/s3_lib.c
+++ b/src/lib/libssl/s3_lib.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: s3_lib.c,v 1.198 2020/09/17 15:42:14 jsing Exp $ */
+/* $OpenBSD: s3_lib.c,v 1.198.4.1 2021/03/15 15:59:04 tb Exp $ */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
@@ -1577,6 +1577,10 @@ ssl3_free(SSL *s)
 
 	free(S3I(s)->alpn_selected);
 
+	/* Clear reference to sequence numbers. */
+	tls12_record_layer_clear_read_state(s->internal->rl);
+	tls12_record_layer_clear_write_state(s->internal->rl);
+
 	freezero(S3I(s), sizeof(*S3I(s)));
 	freezero(s->s3, sizeof(*s->s3));
 
@@ -1649,6 +1653,11 @@ ssl3_clear(SSL *s)
 	s->internal->packet_length = 0;
 	s->version = TLS1_VERSION;
 
+	tls12_record_layer_set_read_seq_num(s->internal->rl,
+	    S3I(s)->read_sequence);
+	tls12_record_layer_set_write_seq_num(s->internal->rl,
+	    S3I(s)->write_sequence);
+
 	S3I(s)->hs.state = SSL_ST_BEFORE|((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
 }
 
diff --git a/src/lib/libssl/ssl_lib.c b/src/lib/libssl/ssl_lib.c
index 1cf64d1301..d7d3d0c051 100644
--- a/src/lib/libssl/ssl_lib.c
+++ b/src/lib/libssl/ssl_lib.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: ssl_lib.c,v 1.234.4.1 2021/02/03 07:06:13 tb Exp $ */
+/* $OpenBSD: ssl_lib.c,v 1.234.4.2 2021/03/15 15:59:04 tb Exp $ */
 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  * All rights reserved.
  *
@@ -253,6 +253,8 @@ SSL_new(SSL_CTX *ctx)
 		goto err;
 	if ((s->internal = calloc(1, sizeof(*s->internal))) == NULL)
 		goto err;
+	if ((s->internal->rl = tls12_record_layer_new()) == NULL)
+		goto err;
 
 	s->internal->min_version = ctx->internal->min_version;
 	s->internal->max_version = ctx->internal->max_version;
@@ -341,9 +343,6 @@ SSL_new(SSL_CTX *ctx)
 	if (!s->method->internal->ssl_new(s))
 		goto err;
 
-	if ((s->internal->rl = tls12_record_layer_new()) == NULL)
-		goto err;
-
 	s->references = 1;
 	s->server = (ctx->method->internal->ssl_accept == ssl_undefined_function) ? 0 : 1;
 
-- 
cgit v1.2.3-55-g6feb