From cbd4f5b3650737c796f38c285fb37c61ecfe38b6 Mon Sep 17 00:00:00 2001
From: Andrew Bartlett <abartlet@samba.org>
Date: Tue, 1 Nov 2022 12:34:57 +1300
Subject: [PATCH 08/54] CVE-2022-37966 selftest: Allow krb5 tests to run
 against an IP by using the target_hostname binding string

This makes it easier to test against a server that is not accessible via DNS.

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

Signed-off-by: Andrew Bartlett <abartlet@samba.org>
Reviewed-by: Stefan Metzmacher <metze@samba.org>
(cherry picked from commit c7cd6889177e8c705bb637172a60a5cf26734a3f)

Conflict: NA
Reference: https://attachments.samba.org/attachment.cgi?id=17695
---
 python/samba/drs_utils.py                | 12 ++++++++++--
 python/samba/tests/krb5/kdc_base_test.py |  3 ++-
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/python/samba/drs_utils.py b/python/samba/drs_utils.py
index 6399e5f7fbcb..955d0f571f87 100644
--- a/python/samba/drs_utils.py
+++ b/python/samba/drs_utils.py
@@ -41,12 +41,13 @@ class drsException(Exception):
         return "drsException: " + self.value
 
 
-def drsuapi_connect(server, lp, creds):
+def drsuapi_connect(server, lp, creds, ip=None):
     """Make a DRSUAPI connection to the server.
 
     :param server: the name of the server to connect to
     :param lp: a samba line parameter object
     :param creds: credential used for the connection
+    :param ip: Forced target server name
     :return: A tuple with the drsuapi bind object, the drsuapi handle
                 and the supported extensions.
     :raise drsException: if the connection fails
@@ -55,7 +56,14 @@ def drsuapi_connect(server, lp, creds):
     binding_options = "seal"
     if lp.log_level() >= 9:
         binding_options += ",print"
-    binding_string = "ncacn_ip_tcp:%s[%s]" % (server, binding_options)
+
+    # Allow forcing the IP
+    if ip is not None:
+        binding_options += f",target_hostname={server}"
+        binding_string = f"ncacn_ip_tcp:{ip}[{binding_options}]"
+    else:
+        binding_string = "ncacn_ip_tcp:%s[%s]" % (server, binding_options)
+
     try:
         drsuapiBind = drsuapi.drsuapi(binding_string, lp, creds)
         (drsuapiHandle, bindSupportedExtensions) = drs_DsBind(drsuapiBind)
diff --git a/python/samba/tests/krb5/kdc_base_test.py b/python/samba/tests/krb5/kdc_base_test.py
index 0733c5c96752..adf67fe7241a 100644
--- a/python/samba/tests/krb5/kdc_base_test.py
+++ b/python/samba/tests/krb5/kdc_base_test.py
@@ -514,7 +514,8 @@ class KDCBaseTest(RawKerberosTest):
         dns_hostname = samdb.host_dns_name()
         (bind, handle, _) = drsuapi_connect(dns_hostname,
                                             self.get_lp(),
-                                            admin_creds)
+                                            admin_creds,
+                                            ip=self.dc_host)
 
         req = drsuapi.DsGetNCChangesRequest8()
 
-- 
2.34.1
