From 1b38a28bcaebdae0128518605a422a194747a60f Mon Sep 17 00:00:00 2001
From: Joseph Sutton <josephsutton@catalyst.net.nz>
Date: Fri, 27 May 2022 19:17:02 +1200
Subject: [PATCH 57/99] CVE-2022-2031 s4:kpasswd: Account for missing target
 principal

This field is supposed to be optional.

BUG: https://bugzilla.samba.org/show_bug.cgi?id=15047
BUG: https://bugzilla.samba.org/show_bug.cgi?id=15049
BUG: https://bugzilla.samba.org/show_bug.cgi?id=15074

Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Reviewed-by: Andreas Schneider <asn@samba.org>
---
 source4/kdc/kpasswd-service-mit.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/source4/kdc/kpasswd-service-mit.c b/source4/kdc/kpasswd-service-mit.c
index 2117c1c1696..b53c1a4618a 100644
--- a/source4/kdc/kpasswd-service-mit.c
+++ b/source4/kdc/kpasswd-service-mit.c
@@ -143,16 +143,18 @@ static krb5_error_code kpasswd_set_password(struct kdc_server *kdc,
 		return KRB5_KPASSWD_HARDERROR;
 	}
 
-	target_realm = smb_krb5_principal_get_realm(
-		mem_ctx, context, target_principal);
-	code = krb5_unparse_name_flags(context,
-				       target_principal,
-				       KRB5_PRINCIPAL_UNPARSE_NO_REALM,
-				       &target_name);
-	if (code != 0) {
-		DBG_WARNING("Failed to parse principal\n");
-		*error_string = "String conversion failed";
-		return KRB5_KPASSWD_HARDERROR;
+	if (target_principal != NULL) {
+		target_realm = smb_krb5_principal_get_realm(
+			mem_ctx, context, target_principal);
+		code = krb5_unparse_name_flags(context,
+					       target_principal,
+					       KRB5_PRINCIPAL_UNPARSE_NO_REALM,
+					       &target_name);
+		if (code != 0) {
+			DBG_WARNING("Failed to parse principal\n");
+			*error_string = "String conversion failed";
+			return KRB5_KPASSWD_HARDERROR;
+		}
 	}
 
 	if ((target_name != NULL && target_realm == NULL) ||
-- 
2.25.1
