From ebac8bf0478e19849f83af6d44b73d7ab3afd25b Mon Sep 17 00:00:00 2001
From: Joseph Sutton <josephsutton@catalyst.net.nz>
Date: Mon, 15 Aug 2022 16:53:55 +1200
Subject: [PATCH 12/15] CVE-2022-3437 source4/heimdal: Check the result of
 _gsskrb5_get_mech()

We should make sure that the result of 'total_len - mech_len' won't
overflow, and that we don't memcmp() past the end of the buffer.

BUG: https://bugzilla.samba.org/show_bug.cgi?id=15134

Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>

Conflict: NA
Reference: https://download.samba.org/pub/samba/patches/security/samba-4.15.11-security-2022-10-25.patch
---
 selftest/knownfail.d/heimdal-des-overflow     | 1 -
 source4/heimdal/lib/gssapi/krb5/decapsulate.c | 4 ++++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/selftest/knownfail.d/heimdal-des-overflow b/selftest/knownfail.d/heimdal-des-overflow
index 23acbb43d31..68b304530db 100644
--- a/selftest/knownfail.d/heimdal-des-overflow
+++ b/selftest/knownfail.d/heimdal-des-overflow
@@ -3,7 +3,6 @@
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_missing_8_bytes.none
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_missing_payload.none
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_truncated_header_0.none
-^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_truncated_header_1.none
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_with_padding_truncated_0.none
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_with_padding_truncated_1.none
 ^samba.unittests.auth.heimdal_gensec_unwrap_des.test_unwrap_with_seal_missing_payload.none
diff --git a/source4/heimdal/lib/gssapi/krb5/decapsulate.c b/source4/heimdal/lib/gssapi/krb5/decapsulate.c
index 4e3fcd659e9..031a621eabc 100644
--- a/source4/heimdal/lib/gssapi/krb5/decapsulate.c
+++ b/source4/heimdal/lib/gssapi/krb5/decapsulate.c
@@ -80,6 +80,10 @@ _gssapi_verify_mech_header(u_char **str,
 
     if (mech_len != mech->length)
 	return GSS_S_BAD_MECH;
+    if (mech_len > total_len)
+	return GSS_S_BAD_MECH;
+    if (p - *str > total_len - mech_len)
+	return GSS_S_BAD_MECH;
     if (ct_memcmp(p,
 		  mech->elements,
 		  mech->length) != 0)
-- 
2.25.1
