From 5a62eb5734d50fe556934aefa3bac5698372f00e Mon Sep 17 00:00:00 2001
From: Joseph Sutton <josephsutton@catalyst.net.nz>
Date: Mon, 15 Aug 2022 16:53:45 +1200
Subject: [PATCH 11/15] CVE-2022-3437 source4/heimdal: Avoid undefined
 behaviour in _gssapi_verify_pad()

By decrementing 'pad' only when we know it's safe, we ensure we can't
stray backwards past the start of a buffer, which would be undefined
behaviour.

In the previous version of the loop, 'i' is the number of bytes left to
check, and 'pad' is the current byte we're checking. 'pad' was
decremented at the end of each loop iteration. If 'i' was 1 (so we
checked the final byte), 'pad' could potentially be pointing to the
first byte of the input buffer, and the decrement would put it one
byte behind the buffer.

That would be undefined behaviour.

The patch changes it so that 'pad' is the byte we previously checked,
which allows us to ensure that we only decrement it when we know we
have a byte to check.

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
---
 source4/heimdal/lib/gssapi/krb5/decapsulate.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/source4/heimdal/lib/gssapi/krb5/decapsulate.c b/source4/heimdal/lib/gssapi/krb5/decapsulate.c
index 86085f56950..4e3fcd659e9 100644
--- a/source4/heimdal/lib/gssapi/krb5/decapsulate.c
+++ b/source4/heimdal/lib/gssapi/krb5/decapsulate.c
@@ -193,13 +193,13 @@ _gssapi_verify_pad(gss_buffer_t wrapped_token,
     if (wrapped_token->length < 1)
 	return GSS_S_BAD_MECH;
 
-    pad = (u_char *)wrapped_token->value + wrapped_token->length - 1;
-    padlength = *pad;
+    pad = (u_char *)wrapped_token->value + wrapped_token->length;
+    padlength = pad[-1];
 
     if (padlength > datalen)
 	return GSS_S_BAD_MECH;
 
-    for (i = padlength; i > 0 && *pad == padlength; i--, pad--)
+    for (i = padlength; i > 0 && *--pad == padlength; i--)
 	;
     if (i != 0)
 	return GSS_S_BAD_MIC;
-- 
2.25.1
