From be4c33a1452aa2cd2fa6a420a1d443aef4233243 Mon Sep 17 00:00:00 2001
From: Volker Lendecke <vl@samba.org>
Date: Wed, 17 Jun 2026 08:24:47 +0200
Subject: [PATCH 19/23] CVE-2026-58218: dns_server: Fix an error path memleak

We talloc the new key off "dns->tkeys", which is long-lived. On any
error we never free'd that again. Probably not remotely triggerable,
this is only setting up the gensec context.

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

Signed-off-by: Volker Lendecke <vl@samba.org>
Reviewed-by: Douglas Bagnall <dbagnall@samba.org>
---
 source4/dns_server/dns_query.c | 25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)

--- a/source4/dns_server/dns_query.c
+++ b/source4/dns_server/dns_query.c
@@ -666,18 +666,18 @@ static NTSTATUS create_tkey(struct dns_s
 	struct dns_server_tkey *k = talloc_zero(store, struct dns_server_tkey);
 
 	if (k == NULL) {
-		return NT_STATUS_NO_MEMORY;
+		goto nomem;
 	}
 
 	k->name = talloc_strdup(k, name);
 
 	if (k->name  == NULL) {
-		return NT_STATUS_NO_MEMORY;
+		goto nomem;
 	}
 
 	k->algorithm = talloc_strdup(k, algorithm);
 	if (k->algorithm == NULL) {
-		return NT_STATUS_NO_MEMORY;
+		goto nomem;
 	}
 
 	/*
@@ -695,8 +695,7 @@ static NTSTATUS create_tkey(struct dns_s
 						&k->gensec);
 	if (!NT_STATUS_IS_OK(status)) {
 		DEBUG(1, ("Failed to start GENSEC server code: %s\n", nt_errstr(status)));
-		*tkey = NULL;
-		return status;
+		goto fail;
 	}
 
 	gensec_want_feature(k->gensec, GENSEC_FEATURE_SIGN);
@@ -706,8 +705,7 @@ static NTSTATUS create_tkey(struct dns_s
 	if (!NT_STATUS_IS_OK(status)) {
 		DEBUG(1, ("Failed to set remote address into GENSEC: %s\n",
 			  nt_errstr(status)));
-		*tkey = NULL;
-		return status;
+		goto fail;
 	}
 
 	status = gensec_set_local_address(k->gensec,
@@ -715,8 +713,7 @@ static NTSTATUS create_tkey(struct dns_s
 	if (!NT_STATUS_IS_OK(status)) {
 		DEBUG(1, ("Failed to set local address into GENSEC: %s\n",
 			  nt_errstr(status)));
-		*tkey = NULL;
-		return status;
+		goto fail;
 	}
 
 	status = gensec_start_mech_by_oid(k->gensec, GENSEC_OID_SPNEGO);
@@ -724,8 +721,7 @@ static NTSTATUS create_tkey(struct dns_s
 	if (!NT_STATUS_IS_OK(status)) {
 		DEBUG(1, ("Failed to start GENSEC server code: %s\n",
 			  nt_errstr(status)));
-		*tkey = NULL;
-		return status;
+		goto fail;
 	}
 
 	TALLOC_FREE(store->tkeys[store->next_idx]);
@@ -736,6 +732,13 @@ static NTSTATUS create_tkey(struct dns_s
 
 	*tkey = k;
 	return NT_STATUS_OK;
+
+nomem:
+	status = NT_STATUS_NO_MEMORY;
+fail:
+	TALLOC_FREE(k);
+	*tkey = NULL;
+	return status;
 }
 
 static NTSTATUS accept_gss_ticket(TALLOC_CTX *mem_ctx,
