From 7638abd38a13f9d2b5c769eb12c70eacf49b3806 Mon Sep 17 00:00:00 2001
From: Joseph Sutton <josephsutton@catalyst.net.nz>
Date: Tue, 7 Jun 2022 17:37:34 +1200
Subject: [PATCH 12/15] CVE-2022-32743 dsdb/modules/acl: Account for
 sAMAccountName without $

If we have an account without a trailing $, we should ensure the
servicePrincipalName matches the entire sAMAccountName. We should not
allow a match against the sAMAccountName prefix of length
strlen(samAccountName) - 1, as that could conflict with a different
account.

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

Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
---
 source4/dsdb/samdb/ldb_modules/acl.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/source4/dsdb/samdb/ldb_modules/acl.c b/source4/dsdb/samdb/ldb_modules/acl.c
index a26d0ba..82f6ec3 100644
--- a/source4/dsdb/samdb/ldb_modules/acl.c
+++ b/source4/dsdb/samdb/ldb_modules/acl.c
@@ -543,6 +543,7 @@ static int acl_validate_spn_value(TALLOC_CTX *mem_ctx,
 	char *instanceName;
 	char *serviceType;
 	char *serviceName;
+	size_t account_name_len;
 	const char *forest_name = samdb_forest_name(ldb, mem_ctx);
 	const char *base_domain = samdb_default_domain_name(ldb, mem_ctx);
 	struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"),
@@ -616,11 +617,18 @@ static int acl_validate_spn_value(TALLOC_CTX *mem_ctx,
 			}
 		}
 	}
+
+	account_name_len = strlen(samAccountName);
+	if (account_name_len && samAccountName[account_name_len - 1] == '$') {
+		/* Account for the '$' character. */
+		--account_name_len;
+	}
+
 	/* instanceName can be samAccountName without $ or dnsHostName
 	 * or "ntds_guid._msdcs.forest_domain for DC objects */
-	if (strlen(instanceName) == (strlen(samAccountName) - 1)
+	if (strlen(instanceName) == account_name_len
 	    && strncasecmp(instanceName, samAccountName,
-			   strlen(samAccountName) - 1) == 0) {
+			   account_name_len) == 0) {
 		goto success;
 	}
 	if ((dnsHostName != NULL) &&
-- 
1.8.3.1

