From af74399bdb21a1a3084ea3a33989c015d33383e6 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Tue, 5 Aug 2025 19:35:01 +0200 Subject: [PATCH 1/5] add ldap3 Kerberos authentication function --- nxc/protocols/ldap.py | 98 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 3 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index f5762b18af..63ff964127 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -3,9 +3,10 @@ import hashlib import hmac import os +import ldap3 from errno import EHOSTUNREACH, ETIMEDOUT, ENETUNREACH from binascii import hexlify -from datetime import datetime +from datetime import datetime, timezone from re import sub, IGNORECASE from zipfile import ZipFile from termcolor import colored @@ -25,15 +26,20 @@ SAM_MACHINE_ACCOUNT, ) from impacket.krb5 import constants -from impacket.krb5.kerberosv5 import getKerberosTGS, SessionKeyDecryptionError +from impacket.krb5.kerberosv5 import getKerberosTGS, SessionKeyDecryptionError, getKerberosTGT from impacket.krb5.ccache import CCache -from impacket.krb5.types import Principal, KerberosException +from impacket.krb5.types import Principal, KerberosException, Ticket, KerberosTime +from impacket.krb5.asn1 import TGS_REP, AP_REQ, Authenticator, seq_set from impacket.ldap import ldap as ldap_impacket from impacket.ldap import ldaptypes from impacket.ldap import ldapasn1 as ldapasn1_impacket from impacket.ldap.ldap import LDAPFilterSyntaxError from impacket.smbconnection import SessionError from impacket.ntlm import getNTLMSSPType1 +from impacket.spnego import SPNEGO_NegTokenInit, TypesMech + +from pyasn1.codec.ber import decoder as der_decoder, encoder as ber_encoder +from pyasn1.type.univ import noValue from nxc.config import process_secret, host_info_colors from nxc.connection import connection @@ -488,6 +494,92 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", ) return False + def ldap3_kerberos_login(self, user: str, password: str = "", lmhash: str = "", nthash: str = "", aes_key: str = "", kdcHost: str | None = None, useCache: bool = True) -> tuple[bool, ldap3.Connection | None]: + target, domain = self.host, self.domain + + # Hashes hex → bytes + if lmhash or nthash: + lmhash = bytes.fromhex(lmhash.zfill(len(lmhash) + len(lmhash) % 2)) + nthash = bytes.fromhex(nthash.zfill(len(nthash) + len(nthash) % 2)) + + TGT = TGS = None + if useCache: + try: + ccache = CCache.loadFile(os.getenv("KRB5CCNAME")) + if not domain: + domain = ccache.principal.realm["data"].decode() + spn = f"ldap/{target.upper()}@{domain.upper()}" + if creds := ccache.getCredential(spn): + TGS = creds.toTGS(spn) + elif creds := ccache.getCredential(f"krbtgt/{domain.upper()}@{domain.upper()}"): + TGT = creds.toTGT() + except Exception: + pass + + # TGT + princ = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + if not TGT: + tgt_blob, cipher, _, sessionKey = getKerberosTGT( + princ, password, domain, lmhash, nthash, aes_key, kdcHost + ) + TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": sessionKey} + else: + cipher, sessionKey = TGT["cipher"], TGT["sessionKey"] + # TGS for ldap/ + host_fqdn = getattr(self, "hostname", None) or target + if "." not in host_fqdn: + host_fqdn = f"{host_fqdn}.{domain}" + spn_princ = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) + if not TGS: + tgs_blob, cipher, _, sessionKey = getKerberosTGS( + spn_princ, domain, kdcHost, TGT["KDC_REP"], cipher, sessionKey + ) + TGS = {"KDC_REP": tgs_blob, "cipher": cipher, "sessionKey": sessionKey} + else: + cipher, sessionKey = TGS["cipher"], TGS["sessionKey"] + # SPNEGO → AP_REQ + blob = SPNEGO_NegTokenInit(); blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] + tgs_rep = der_decoder.decode(TGS["KDC_REP"], asn1Spec=TGS_REP())[0] + ticket = Ticket(); ticket.from_asn1(tgs_rep["ticket"]) + + apReq = AP_REQ() + apReq["pvno"] = 5 + apReq["msg-type"] = int(constants.ApplicationTagNumbers.AP_REQ.value) + apReq["ap-options"] = constants.encodeFlags([]) + seq_set(apReq, "ticket", ticket.to_asn1) + + auth = Authenticator() + auth["authenticator-vno"] = 5 + auth["crealm"] = domain + seq_set(auth, "cname", princ.components_to_asn1) + now = datetime.now(timezone.utc) + auth["ctime"] = KerberosTime.to_asn1(now) + auth["cusec"] = now.microsecond + enc_auth = cipher.encrypt(sessionKey, 11, ber_encoder.encode(auth), None) + + apReq["authenticator"] = noValue + apReq["authenticator"]["etype"] = cipher.enctype + apReq["authenticator"]["cipher"] = enc_auth + blob["MechToken"] = ber_encoder.encode(apReq) + + # Bind SASL / GSS-SPNEGO + server = ldap3.Server(target, port=self.args.port, get_info=ldap3.ALL) + conn = ldap3.Connection(server, authentication=ldap3.SASL, sasl_mechanism="GSS-SPNEGO", auto_bind=False) + if conn.closed: + conn.open(read_server_info=False) + + req = ldap3.operation.bind.bind_operation(conn.version, ldap3.SASL, user, None, "GSS-SPNEGO", blob.getData()) + conn.sasl_in_progress = True + resp = conn.post_send_single_response(conn.send("bindRequest", req, None)) + conn.sasl_in_progress = False + + if resp[0]["result"] != 0: + return False, None + + conn.bound = True + self.ldap_connection = conn + return True, conn + def plaintext_login(self, domain, username, password): self.username = username self.password = password From 6e4d6f8e394600199e34cfaf5201a4d0bac64313 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 9 Aug 2025 00:00:46 +0200 Subject: [PATCH 2/5] Update Function --- nxc/protocols/ldap.py | 270 +++++++++++++++++++++++++++++++++++------- 1 file changed, 224 insertions(+), 46 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 63ff964127..067e140a1f 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -494,51 +494,171 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", ) return False - def ldap3_kerberos_login(self, user: str, password: str = "", lmhash: str = "", nthash: str = "", aes_key: str = "", kdcHost: str | None = None, useCache: bool = True) -> tuple[bool, ldap3.Connection | None]: - target, domain = self.host, self.domain + def create_ldap3_connection(self): + """ + Return an ldap3.Connection. + + - NTLM bind requires a plaintext password. + - If LM/NT hashes are provided (no password), switch to Kerberos automatically. + - Kerberos path: try LDAP:389, fallback to LDAPS:636 on strongerAuthRequired. + """ + target = self.host + domain = (self.domain or "").upper() + user = self.username or "" + pwd = getattr(self, "password", "") or "" + lmhash = getattr(self, "lmhash", "") or "" + nthash = getattr(self, "nthash", "") or "" + aeskey = getattr(self, "aesKey", "") or "" + kdc = getattr(self, "kdcHost", None) + port = int(getattr(self.args, "port", 389)) + port_explicit = bool(getattr(self.args, "port_explicitly_set", False)) + + explicit_k = bool(getattr(self.args, "kerberos", False)) + hash_only = (not pwd) and (bool(nthash) or bool(lmhash)) + aes_only = (not pwd) and bool(aeskey) + use_k = explicit_k or hash_only or aes_only + use_cc = bool(getattr(self.args, "use_kcache", False)) + + if hash_only and not explicit_k: + self.logger.display("No -k supplied: switching to Kerberos because ldap3 NTLM doesn’t support hash-only auth.") + + if not use_k: + def _ntlm_bind(ssl: bool, bind_port: int): + try: + self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" + self.logger.extra["port"] = str(bind_port) + server = ldap3.Server( + target, + port=bind_port, + use_ssl=ssl, + get_info=ldap3.NONE, + ) + user_ntlm = f"{domain}\\{user}" if domain else user + conn = ldap3.Connection( + server, + user=user_ntlm, + password=pwd, + authentication=ldap3.NTLM, + auto_bind=True, + ) + return conn, {"result": 0} + except Exception as e: + return None, e + + # port test order + primary_port = port + try_order = [(primary_port, primary_port == 636)] + if not port_explicit: + if primary_port == 389: + try_order.append((636, True)) + else: + try_order.append((389, False)) + + conn = None + last_err = None + for bind_port, use_ssl in try_order: + c, r = _ntlm_bind(use_ssl, bind_port) + if c and getattr(c, "bound", False): + conn = c + break + last_err = r + if port_explicit: + break - # Hashes hex → bytes - if lmhash or nthash: - lmhash = bytes.fromhex(lmhash.zfill(len(lmhash) + len(lmhash) % 2)) - nthash = bytes.fromhex(nthash.zfill(len(nthash) + len(nthash) % 2)) + if not conn: + self.logger.fail(f"NTLM bind failed: {last_err}") + return None + + self.ldap_connection = conn - TGT = TGS = None - if useCache: try: - ccache = CCache.loadFile(os.getenv("KRB5CCNAME")) - if not domain: - domain = ccache.principal.realm["data"].decode() - spn = f"ldap/{target.upper()}@{domain.upper()}" - if creds := ccache.getCredential(spn): - TGS = creds.toTGS(spn) - elif creds := ccache.getCredential(f"krbtgt/{domain.upper()}@{domain.upper()}"): - TGT = creds.toTGT() + self.check_if_admin() + except Exception: + pass + try: + self.db.add_credential("plaintext", domain or self.targetDomain, user, pwd) + except Exception: + pass + try: + if not self.args.local_auth and user: + add_user_bh(user, domain or self.targetDomain, self.logger, self.config) + if getattr(self, "admin_privs", False): + add_user_bh(f"{self.hostname}$", domain or self.targetDomain, self.logger, self.config) except Exception: pass - # TGT - princ = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value) - if not TGT: - tgt_blob, cipher, _, sessionKey = getKerberosTGT( - princ, password, domain, lmhash, nthash, aes_key, kdcHost - ) - TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": sessionKey} - else: - cipher, sessionKey = TGT["cipher"], TGT["sessionKey"] - # TGS for ldap/ + self.logger.info(f"ldap3 NTLM bind over {'LDAPS:636' if conn.server.port == 636 else f'LDAP:{conn.server.port}'} established") + return conn + + # Build FQDN for SPN host_fqdn = getattr(self, "hostname", None) or target - if "." not in host_fqdn: + if "." not in host_fqdn and domain: host_fqdn = f"{host_fqdn}.{domain}" - spn_princ = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) + + TGT = None + TGS = None + from_cache = False + + if use_cc: + try: + ccname = os.getenv("KRB5CCNAME") + if not ccname: + self.logger.error("KRB5CCNAME environment variable is not set") + return None + ccache = CCache.loadFile(ccname) + + if not domain: + domain = ccache.principal.realm["data"].decode().upper() + + spn_candidates = [ + f"ldap/{host_fqdn.lower()}@{domain}", + f"ldap/{host_fqdn.upper()}@{domain}", + ] + creds = None + for spn in spn_candidates: + creds = ccache.getCredential(spn) + if creds: + TGS = creds.toTGS(spn) + break + + if not TGS: + kt = ccache.getCredential(f"krbtgt/{domain}@{domain}") + if kt: + TGT = kt.toTGT() + + if not TGS and not TGT: + self.logger.fail("Kerberos cache selected (--use-kcache) but no usable TGT/TGS found in cache.") + return None + + from_cache = True + except Exception as e: + self.logger.fail(f"Failed to read Kerberos cache (--use-kcache): {e}") + return None + + # Prepare creds for TGT acquisition if needed + princ = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + lm_b = bytes.fromhex(lmhash.zfill(len(lmhash) + len(lmhash) % 2)) if lmhash else b"" + nt_b = bytes.fromhex(nthash.zfill(len(nthash) + len(nthash) % 2)) if nthash else b"" + + if not TGT and not TGS: + tgt_blob, cipher, _, sessionKey = getKerberosTGT(princ, pwd, domain, lm_b, nt_b, aeskey, kdc) + TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": sessionKey} + else : + cipher = (TGT or TGS)["cipher"] + sessionKey = (TGT or TGS)["sessionKey"] + + # Ensure we have a TGS for ldap/ if not TGS: + spn_princ = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) tgs_blob, cipher, _, sessionKey = getKerberosTGS( - spn_princ, domain, kdcHost, TGT["KDC_REP"], cipher, sessionKey + spn_princ, domain, kdc, TGT["KDC_REP"], TGT["cipher"], TGT["sessionKey"] ) TGS = {"KDC_REP": tgs_blob, "cipher": cipher, "sessionKey": sessionKey} - else: - cipher, sessionKey = TGS["cipher"], TGS["sessionKey"] - # SPNEGO → AP_REQ - blob = SPNEGO_NegTokenInit(); blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] + + # Build AP_REQ (SPNEGO) + blob = SPNEGO_NegTokenInit() + blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] + tgs_rep = der_decoder.decode(TGS["KDC_REP"], asn1Spec=TGS_REP())[0] ticket = Ticket(); ticket.from_asn1(tgs_rep["ticket"]) @@ -555,30 +675,88 @@ def ldap3_kerberos_login(self, user: str, password: str = "", lmhash: str = "", now = datetime.now(timezone.utc) auth["ctime"] = KerberosTime.to_asn1(now) auth["cusec"] = now.microsecond - enc_auth = cipher.encrypt(sessionKey, 11, ber_encoder.encode(auth), None) + enc_auth = cipher.encrypt(sessionKey, 11, ber_encoder.encode(auth), None) apReq["authenticator"] = noValue apReq["authenticator"]["etype"] = cipher.enctype apReq["authenticator"]["cipher"] = enc_auth blob["MechToken"] = ber_encoder.encode(apReq) - # Bind SASL / GSS-SPNEGO - server = ldap3.Server(target, port=self.args.port, get_info=ldap3.ALL) - conn = ldap3.Connection(server, authentication=ldap3.SASL, sasl_mechanism="GSS-SPNEGO", auto_bind=False) - if conn.closed: - conn.open(read_server_info=False) + # Helper GSS-SPNEGO bind + def _gss_bind(ssl: bool, bind_port: int): + try: + self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" + self.logger.extra["port"] = str(bind_port) + server = ldap3.Server( + target, + port=bind_port, + use_ssl=ssl, + get_info=ldap3.NONE, + ) + conn = ldap3.Connection( + server, + authentication=ldap3.SASL, + sasl_mechanism="GSS-SPNEGO", + auto_bind=False, + ) + if conn.closed: + conn.open(read_server_info=False) + req = ldap3.operation.bind.bind_operation(conn.version, ldap3.SASL, user, None, "GSS-SPNEGO", blob.getData()) + conn.sasl_in_progress = True + resp = conn.post_send_single_response(conn.send("bindRequest", req, None)) + conn.sasl_in_progress = False + return conn, resp + except Exception as e: + return None, e - req = ldap3.operation.bind.bind_operation(conn.version, ldap3.SASL, user, None, "GSS-SPNEGO", blob.getData()) - conn.sasl_in_progress = True - resp = conn.post_send_single_response(conn.send("bindRequest", req, None)) - conn.sasl_in_progress = False + primary_port = port + try_order = [(primary_port, primary_port == 636)] + if not port_explicit: + if primary_port == 389: + try_order.append((636, True)) + else: + try_order.append((389, False)) - if resp[0]["result"] != 0: - return False, None + conn = None + last_resp = None + for bind_port, use_ssl in try_order: + c, r = _gss_bind(use_ssl, bind_port) + conn, last_resp = c, r + + ok = False + if isinstance(r, list) and r and isinstance(r[0], dict): + ok = (r[0].get("result", None) == 0) + + if ok: + break + if port_explicit: + break + + if not (isinstance(last_resp, list) and last_resp and isinstance(last_resp[0], dict) and last_resp[0].get("result", 1) == 0): + self.logger.fail(f"ldap3 Kerberos bind failed: {last_resp[0] if isinstance(last_resp, list) and last_resp else last_resp}") + return None conn.bound = True self.ldap_connection = conn - return True, conn + + # whoami if username is empty (ccache case) + try: + if not user: + w = conn.extend.standard.who_am_i() + if isinstance(w, str) and w.startswith("u:"): + uval = w[2:] + if "\\" in uval: + dom, usr = uval.split("\\", 1) + self.username = usr + if not domain: + domain = dom.upper() + else: + self.username = uval + except Exception: + pass + + self.logger.info("ldap3 Kerberos connection established") + return conn def plaintext_login(self, domain, username, password): self.username = username From 65c15fae4b3ad486e242ea85186bf8c3d612e4a2 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Fri, 15 Aug 2025 02:01:51 +0200 Subject: [PATCH 3/5] Update: use self.* attributes directly --- nxc/protocols/ldap.py | 117 +++++++++++++++++------------------------- 1 file changed, 47 insertions(+), 70 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 067e140a1f..afa1ea74bd 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -502,24 +502,13 @@ def create_ldap3_connection(self): - If LM/NT hashes are provided (no password), switch to Kerberos automatically. - Kerberos path: try LDAP:389, fallback to LDAPS:636 on strongerAuthRequired. """ - target = self.host - domain = (self.domain or "").upper() - user = self.username or "" - pwd = getattr(self, "password", "") or "" - lmhash = getattr(self, "lmhash", "") or "" - nthash = getattr(self, "nthash", "") or "" - aeskey = getattr(self, "aesKey", "") or "" - kdc = getattr(self, "kdcHost", None) - port = int(getattr(self.args, "port", 389)) - port_explicit = bool(getattr(self.args, "port_explicitly_set", False)) - - explicit_k = bool(getattr(self.args, "kerberos", False)) - hash_only = (not pwd) and (bool(nthash) or bool(lmhash)) - aes_only = (not pwd) and bool(aeskey) - use_k = explicit_k or hash_only or aes_only - use_cc = bool(getattr(self.args, "use_kcache", False)) - - if hash_only and not explicit_k: + + hash_only = (not self.password) and (bool(self.nthash) or bool(self.lmhash)) + aes_only = (not self.password) and bool(self.aesKey) + use_k = self.kerberos or hash_only or aes_only + use_cc = getattr(self, "use_kcache", False) + + if hash_only and not self.kerberos: self.logger.display("No -k supplied: switching to Kerberos because ldap3 NTLM doesn’t support hash-only auth.") if not use_k: @@ -528,16 +517,16 @@ def _ntlm_bind(ssl: bool, bind_port: int): self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" self.logger.extra["port"] = str(bind_port) server = ldap3.Server( - target, + self.host, port=bind_port, use_ssl=ssl, get_info=ldap3.NONE, ) - user_ntlm = f"{domain}\\{user}" if domain else user + user_ntlm = f"{self.domain}\\{self.username}" if self.domain else (self.username or "") conn = ldap3.Connection( server, user=user_ntlm, - password=pwd, + password=self.password, authentication=ldap3.NTLM, auto_bind=True, ) @@ -546,10 +535,10 @@ def _ntlm_bind(ssl: bool, bind_port: int): return None, e # port test order - primary_port = port - try_order = [(primary_port, primary_port == 636)] + port_explicit = getattr(self, "port_explicitly_set", False) + try_order = [(self.port, self.port == 636)] if not port_explicit: - if primary_port == 389: + if self.port == 389: try_order.append((636, True)) else: try_order.append((389, False)) @@ -570,34 +559,19 @@ def _ntlm_bind(ssl: bool, bind_port: int): return None self.ldap_connection = conn - - try: - self.check_if_admin() - except Exception: - pass - try: - self.db.add_credential("plaintext", domain or self.targetDomain, user, pwd) - except Exception: - pass - try: - if not self.args.local_auth and user: - add_user_bh(user, domain or self.targetDomain, self.logger, self.config) - if getattr(self, "admin_privs", False): - add_user_bh(f"{self.hostname}$", domain or self.targetDomain, self.logger, self.config) - except Exception: - pass - - self.logger.info(f"ldap3 NTLM bind over {'LDAPS:636' if conn.server.port == 636 else f'LDAP:{conn.server.port}'} established") + self.logger.info( + f"ldap3 NTLM bind over {'LDAPS:636' if conn.server.port == 636 else f'LDAP:{conn.server.port}'} established" + ) return conn # Build FQDN for SPN - host_fqdn = getattr(self, "hostname", None) or target - if "." not in host_fqdn and domain: - host_fqdn = f"{host_fqdn}.{domain}" + realm = (self.domain or "").upper() + host_fqdn = (self.hostname or self.host) or "" + if "." not in host_fqdn and realm: + host_fqdn = f"{host_fqdn}.{realm}" TGT = None TGS = None - from_cache = False if use_cc: try: @@ -607,12 +581,12 @@ def _ntlm_bind(ssl: bool, bind_port: int): return None ccache = CCache.loadFile(ccname) - if not domain: - domain = ccache.principal.realm["data"].decode().upper() + if not realm: + realm = ccache.principal.realm["data"].decode().upper() spn_candidates = [ - f"ldap/{host_fqdn.lower()}@{domain}", - f"ldap/{host_fqdn.upper()}@{domain}", + f"ldap/{host_fqdn.lower()}@{realm}", + f"ldap/{host_fqdn.upper()}@{realm}", ] creds = None for spn in spn_candidates: @@ -622,28 +596,28 @@ def _ntlm_bind(ssl: bool, bind_port: int): break if not TGS: - kt = ccache.getCredential(f"krbtgt/{domain}@{domain}") + kt = ccache.getCredential(f"krbtgt/{realm}@{realm}") if kt: TGT = kt.toTGT() if not TGS and not TGT: self.logger.fail("Kerberos cache selected (--use-kcache) but no usable TGT/TGS found in cache.") return None - - from_cache = True except Exception as e: self.logger.fail(f"Failed to read Kerberos cache (--use-kcache): {e}") return None # Prepare creds for TGT acquisition if needed - princ = Principal(user, type=constants.PrincipalNameType.NT_PRINCIPAL.value) - lm_b = bytes.fromhex(lmhash.zfill(len(lmhash) + len(lmhash) % 2)) if lmhash else b"" - nt_b = bytes.fromhex(nthash.zfill(len(nthash) + len(nthash) % 2)) if nthash else b"" + princ = Principal(self.username or "", type=constants.PrincipalNameType.NT_PRINCIPAL.value) + lm_b = bytes.fromhex(self.lmhash.zfill(len(self.lmhash) + len(self.lmhash) % 2)) if self.lmhash else b"" + nt_b = bytes.fromhex(self.nthash.zfill(len(self.nthash) + len(self.nthash) % 2)) if self.nthash else b"" if not TGT and not TGS: - tgt_blob, cipher, _, sessionKey = getKerberosTGT(princ, pwd, domain, lm_b, nt_b, aeskey, kdc) + tgt_blob, cipher, _, sessionKey = getKerberosTGT( + princ, self.password, realm, lm_b, nt_b, self.aesKey, self.kdcHost + ) TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": sessionKey} - else : + else: cipher = (TGT or TGS)["cipher"] sessionKey = (TGT or TGS)["sessionKey"] @@ -651,16 +625,17 @@ def _ntlm_bind(ssl: bool, bind_port: int): if not TGS: spn_princ = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) tgs_blob, cipher, _, sessionKey = getKerberosTGS( - spn_princ, domain, kdc, TGT["KDC_REP"], TGT["cipher"], TGT["sessionKey"] + spn_princ, realm, self.kdcHost, TGT["KDC_REP"], TGT["cipher"], TGT["sessionKey"] ) TGS = {"KDC_REP": tgs_blob, "cipher": cipher, "sessionKey": sessionKey} - # Build AP_REQ (SPNEGO) + # Build AP_REQ SPNEGO blob = SPNEGO_NegTokenInit() blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] tgs_rep = der_decoder.decode(TGS["KDC_REP"], asn1Spec=TGS_REP())[0] - ticket = Ticket(); ticket.from_asn1(tgs_rep["ticket"]) + ticket = Ticket() + ticket.from_asn1(tgs_rep["ticket"]) apReq = AP_REQ() apReq["pvno"] = 5 @@ -670,7 +645,7 @@ def _ntlm_bind(ssl: bool, bind_port: int): auth = Authenticator() auth["authenticator-vno"] = 5 - auth["crealm"] = domain + auth["crealm"] = realm seq_set(auth, "cname", princ.components_to_asn1) now = datetime.now(timezone.utc) auth["ctime"] = KerberosTime.to_asn1(now) @@ -688,7 +663,7 @@ def _gss_bind(ssl: bool, bind_port: int): self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" self.logger.extra["port"] = str(bind_port) server = ldap3.Server( - target, + self.host, port=bind_port, use_ssl=ssl, get_info=ldap3.NONE, @@ -701,7 +676,9 @@ def _gss_bind(ssl: bool, bind_port: int): ) if conn.closed: conn.open(read_server_info=False) - req = ldap3.operation.bind.bind_operation(conn.version, ldap3.SASL, user, None, "GSS-SPNEGO", blob.getData()) + req = ldap3.operation.bind.bind_operation( + conn.version, ldap3.SASL, (self.username or ""), None, "GSS-SPNEGO", blob.getData() + ) conn.sasl_in_progress = True resp = conn.post_send_single_response(conn.send("bindRequest", req, None)) conn.sasl_in_progress = False @@ -709,10 +686,10 @@ def _gss_bind(ssl: bool, bind_port: int): except Exception as e: return None, e - primary_port = port - try_order = [(primary_port, primary_port == 636)] + port_explicit = getattr(self, "port_explicitly_set", False) + try_order = [(self.port, self.port == 636)] if not port_explicit: - if primary_port == 389: + if self.port == 389: try_order.append((636, True)) else: try_order.append((389, False)) @@ -741,15 +718,15 @@ def _gss_bind(ssl: bool, bind_port: int): # whoami if username is empty (ccache case) try: - if not user: + if not self.username: w = conn.extend.standard.who_am_i() if isinstance(w, str) and w.startswith("u:"): uval = w[2:] if "\\" in uval: dom, usr = uval.split("\\", 1) self.username = usr - if not domain: - domain = dom.upper() + if not self.domain: + self.domain = dom.upper() else: self.username = uval except Exception: From 6bcb6e623b5a1cc922ad4912b8024e7679e64af7 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 13 Dec 2025 21:48:10 +0100 Subject: [PATCH 4/5] add Ldap3Connection wrapper class for reusable ldap3 connections --- nxc/protocols/ldap.py | 276 +++--------------------- nxc/protocols/ldap/ldap3_conn.py | 350 +++++++++++++++++++++++++++++++ 2 files changed, 381 insertions(+), 245 deletions(-) create mode 100644 nxc/protocols/ldap/ldap3_conn.py diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index afa1ea74bd..b1ceeef8d7 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -3,10 +3,9 @@ import hashlib import hmac import os -import ldap3 from errno import EHOSTUNREACH, ETIMEDOUT, ENETUNREACH from binascii import hexlify -from datetime import datetime, timezone +from datetime import datetime from re import sub, IGNORECASE from zipfile import ZipFile from termcolor import colored @@ -26,20 +25,15 @@ SAM_MACHINE_ACCOUNT, ) from impacket.krb5 import constants -from impacket.krb5.kerberosv5 import getKerberosTGS, SessionKeyDecryptionError, getKerberosTGT +from impacket.krb5.kerberosv5 import getKerberosTGS, SessionKeyDecryptionError from impacket.krb5.ccache import CCache -from impacket.krb5.types import Principal, KerberosException, Ticket, KerberosTime -from impacket.krb5.asn1 import TGS_REP, AP_REQ, Authenticator, seq_set +from impacket.krb5.types import Principal, KerberosException from impacket.ldap import ldap as ldap_impacket from impacket.ldap import ldaptypes from impacket.ldap import ldapasn1 as ldapasn1_impacket from impacket.ldap.ldap import LDAPFilterSyntaxError from impacket.smbconnection import SessionError from impacket.ntlm import getNTLMSSPType1 -from impacket.spnego import SPNEGO_NegTokenInit, TypesMech - -from pyasn1.codec.ber import decoder as der_decoder, encoder as ber_encoder -from pyasn1.type.univ import noValue from nxc.config import process_secret, host_info_colors from nxc.connection import connection @@ -52,6 +46,7 @@ from nxc.helpers.ntlm_parser import parse_challenge from nxc.helpers.misc import get_bloodhound_info from nxc.paths import CONFIG_PATH, NXC_PATH +from nxc.protocols.ldap.ldap3_conn import Ldap3Connection ldap_error_status = { "1": "STATUS_NOT_SUPPORTED", @@ -163,6 +158,7 @@ def __init__(self, args, db, host): self.no_ntlm = False self.sid_domain = "" self.scope = None + self.ldap3_conn = None connection.__init__(self, args, db, host) @@ -494,246 +490,36 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", ) return False - def create_ldap3_connection(self): - """ - Return an ldap3.Connection. - - - NTLM bind requires a plaintext password. - - If LM/NT hashes are provided (no password), switch to Kerberos automatically. - - Kerberos path: try LDAP:389, fallback to LDAPS:636 on strongerAuthRequired. - """ - - hash_only = (not self.password) and (bool(self.nthash) or bool(self.lmhash)) - aes_only = (not self.password) and bool(self.aesKey) - use_k = self.kerberos or hash_only or aes_only - use_cc = getattr(self, "use_kcache", False) - - if hash_only and not self.kerberos: - self.logger.display("No -k supplied: switching to Kerberos because ldap3 NTLM doesn’t support hash-only auth.") - - if not use_k: - def _ntlm_bind(ssl: bool, bind_port: int): - try: - self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" - self.logger.extra["port"] = str(bind_port) - server = ldap3.Server( - self.host, - port=bind_port, - use_ssl=ssl, - get_info=ldap3.NONE, - ) - user_ntlm = f"{self.domain}\\{self.username}" if self.domain else (self.username or "") - conn = ldap3.Connection( - server, - user=user_ntlm, - password=self.password, - authentication=ldap3.NTLM, - auto_bind=True, - ) - return conn, {"result": 0} - except Exception as e: - return None, e - - # port test order - port_explicit = getattr(self, "port_explicitly_set", False) - try_order = [(self.port, self.port == 636)] - if not port_explicit: - if self.port == 389: - try_order.append((636, True)) - else: - try_order.append((389, False)) - - conn = None - last_err = None - for bind_port, use_ssl in try_order: - c, r = _ntlm_bind(use_ssl, bind_port) - if c and getattr(c, "bound", False): - conn = c - break - last_err = r - if port_explicit: - break - - if not conn: - self.logger.fail(f"NTLM bind failed: {last_err}") - return None - - self.ldap_connection = conn - self.logger.info( - f"ldap3 NTLM bind over {'LDAPS:636' if conn.server.port == 636 else f'LDAP:{conn.server.port}'} established" - ) - return conn - - # Build FQDN for SPN - realm = (self.domain or "").upper() - host_fqdn = (self.hostname or self.host) or "" - if "." not in host_fqdn and realm: - host_fqdn = f"{host_fqdn}.{realm}" - - TGT = None - TGS = None - - if use_cc: - try: - ccname = os.getenv("KRB5CCNAME") - if not ccname: - self.logger.error("KRB5CCNAME environment variable is not set") - return None - ccache = CCache.loadFile(ccname) - - if not realm: - realm = ccache.principal.realm["data"].decode().upper() - - spn_candidates = [ - f"ldap/{host_fqdn.lower()}@{realm}", - f"ldap/{host_fqdn.upper()}@{realm}", - ] - creds = None - for spn in spn_candidates: - creds = ccache.getCredential(spn) - if creds: - TGS = creds.toTGS(spn) - break - - if not TGS: - kt = ccache.getCredential(f"krbtgt/{realm}@{realm}") - if kt: - TGT = kt.toTGT() - - if not TGS and not TGT: - self.logger.fail("Kerberos cache selected (--use-kcache) but no usable TGT/TGS found in cache.") - return None - except Exception as e: - self.logger.fail(f"Failed to read Kerberos cache (--use-kcache): {e}") - return None + def get_ldap3_connection(self): + if self.ldap3_conn: + return self.ldap3_conn - # Prepare creds for TGT acquisition if needed - princ = Principal(self.username or "", type=constants.PrincipalNameType.NT_PRINCIPAL.value) - lm_b = bytes.fromhex(self.lmhash.zfill(len(self.lmhash) + len(self.lmhash) % 2)) if self.lmhash else b"" - nt_b = bytes.fromhex(self.nthash.zfill(len(self.nthash) + len(self.nthash) % 2)) if self.nthash else b"" - - if not TGT and not TGS: - tgt_blob, cipher, _, sessionKey = getKerberosTGT( - princ, self.password, realm, lm_b, nt_b, self.aesKey, self.kdcHost - ) - TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": sessionKey} - else: - cipher = (TGT or TGS)["cipher"] - sessionKey = (TGT or TGS)["sessionKey"] - - # Ensure we have a TGS for ldap/ - if not TGS: - spn_princ = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) - tgs_blob, cipher, _, sessionKey = getKerberosTGS( - spn_princ, realm, self.kdcHost, TGT["KDC_REP"], TGT["cipher"], TGT["sessionKey"] - ) - TGS = {"KDC_REP": tgs_blob, "cipher": cipher, "sessionKey": sessionKey} - - # Build AP_REQ SPNEGO - blob = SPNEGO_NegTokenInit() - blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] - - tgs_rep = der_decoder.decode(TGS["KDC_REP"], asn1Spec=TGS_REP())[0] - ticket = Ticket() - ticket.from_asn1(tgs_rep["ticket"]) - - apReq = AP_REQ() - apReq["pvno"] = 5 - apReq["msg-type"] = int(constants.ApplicationTagNumbers.AP_REQ.value) - apReq["ap-options"] = constants.encodeFlags([]) - seq_set(apReq, "ticket", ticket.to_asn1) - - auth = Authenticator() - auth["authenticator-vno"] = 5 - auth["crealm"] = realm - seq_set(auth, "cname", princ.components_to_asn1) - now = datetime.now(timezone.utc) - auth["ctime"] = KerberosTime.to_asn1(now) - auth["cusec"] = now.microsecond - - enc_auth = cipher.encrypt(sessionKey, 11, ber_encoder.encode(auth), None) - apReq["authenticator"] = noValue - apReq["authenticator"]["etype"] = cipher.enctype - apReq["authenticator"]["cipher"] = enc_auth - blob["MechToken"] = ber_encoder.encode(apReq) - - # Helper GSS-SPNEGO bind - def _gss_bind(ssl: bool, bind_port: int): - try: - self.logger.extra["protocol"] = "LDAPS" if ssl else "LDAP" - self.logger.extra["port"] = str(bind_port) - server = ldap3.Server( - self.host, - port=bind_port, - use_ssl=ssl, - get_info=ldap3.NONE, - ) - conn = ldap3.Connection( - server, - authentication=ldap3.SASL, - sasl_mechanism="GSS-SPNEGO", - auto_bind=False, - ) - if conn.closed: - conn.open(read_server_info=False) - req = ldap3.operation.bind.bind_operation( - conn.version, ldap3.SASL, (self.username or ""), None, "GSS-SPNEGO", blob.getData() - ) - conn.sasl_in_progress = True - resp = conn.post_send_single_response(conn.send("bindRequest", req, None)) - conn.sasl_in_progress = False - return conn, resp - except Exception as e: - return None, e - - port_explicit = getattr(self, "port_explicitly_set", False) - try_order = [(self.port, self.port == 636)] - if not port_explicit: - if self.port == 389: - try_order.append((636, True)) - else: - try_order.append((389, False)) - - conn = None - last_resp = None - for bind_port, use_ssl in try_order: - c, r = _gss_bind(use_ssl, bind_port) - conn, last_resp = c, r - - ok = False - if isinstance(r, list) and r and isinstance(r[0], dict): - ok = (r[0].get("result", None) == 0) - - if ok: - break - if port_explicit: - break + ldap3_wrapper = Ldap3Connection( + host=self.host, + port=self.port, + hostname=self.hostname, + domain=self.domain, + username=self.username, + password=self.password, + lmhash=self.lmhash, + nthash=self.nthash, + aesKey=getattr(self, "aesKey", ""), + kdcHost=self.kdcHost, + kerberos=getattr(self, "kerberos", False), + use_kcache=getattr(self, "use_kcache", False), + port_explicitly_set=getattr(self, "port_explicitly_set", False), + logger=self.logger, + ) - if not (isinstance(last_resp, list) and last_resp and isinstance(last_resp[0], dict) and last_resp[0].get("result", 1) == 0): - self.logger.fail(f"ldap3 Kerberos bind failed: {last_resp[0] if isinstance(last_resp, list) and last_resp else last_resp}") - return None + self.ldap3_conn = ldap3_wrapper.create_conn() - conn.bound = True - self.ldap_connection = conn + # Sync back username/domain if resolved from ccache + if ldap3_wrapper.username and not self.username: + self.username = ldap3_wrapper.username + if ldap3_wrapper.domain and not self.domain: + self.domain = ldap3_wrapper.domain - # whoami if username is empty (ccache case) - try: - if not self.username: - w = conn.extend.standard.who_am_i() - if isinstance(w, str) and w.startswith("u:"): - uval = w[2:] - if "\\" in uval: - dom, usr = uval.split("\\", 1) - self.username = usr - if not self.domain: - self.domain = dom.upper() - else: - self.username = uval - except Exception: - pass - - self.logger.info("ldap3 Kerberos connection established") - return conn + return self.ldap3_conn def plaintext_login(self, domain, username, password): self.username = username diff --git a/nxc/protocols/ldap/ldap3_conn.py b/nxc/protocols/ldap/ldap3_conn.py new file mode 100644 index 0000000000..5f37e3254f --- /dev/null +++ b/nxc/protocols/ldap/ldap3_conn.py @@ -0,0 +1,350 @@ +import os +from datetime import datetime, timezone + +import ldap3 +import ldap3.operation.bind + +from impacket.krb5 import constants +from impacket.krb5.kerberosv5 import getKerberosTGS, getKerberosTGT +from impacket.krb5.ccache import CCache +from impacket.krb5.types import Principal, KerberosTime, Ticket +from impacket.krb5.asn1 import TGS_REP, AP_REQ, Authenticator, seq_set +from impacket.spnego import SPNEGO_NegTokenInit, TypesMech + +from pyasn1.codec.ber import decoder as der_decoder, encoder as ber_encoder +from pyasn1.type.univ import noValue + + +class Ldap3Connection: + """ + Wrapper class for creating ldap3.Connection instances. + + Supports: + - NTLM authentication (plaintext password or pass-the-hash) + - Kerberos authentication (password, hash, aesKey, or ccache) + - Automatic fallback from LDAP:389 to LDAPS:636 when required + """ + + def __init__( + self, + host: str, + port: int, + hostname: str, + domain: str, + username: str, + password: str = "", + lmhash: str = "", + nthash: str = "", + aesKey: str = "", + kdcHost: str | None = None, + kerberos: bool = False, + use_kcache: bool = False, + port_explicitly_set: bool = False, + logger=None, + ): + self.host = host + self.port = port + self.hostname = hostname + self.domain = domain + self.username = username + self.password = password + self.lmhash = lmhash + self.nthash = nthash + self.aesKey = aesKey + self.kdcHost = kdcHost + self.kerberos = kerberos + self.use_kcache = use_kcache + self.port_explicitly_set = port_explicitly_set + self.logger = logger + + self._connection = None + + def _log_info(self, msg): + if self.logger: + self.logger.info(msg) + + def _log_debug(self, msg): + if self.logger: + self.logger.debug(msg) + + def _log_fail(self, msg): + if self.logger: + self.logger.fail(msg) + + def _log_error(self, msg): + if self.logger: + self.logger.error(msg) + + def _log_display(self, msg): + if self.logger: + self.logger.display(msg) + + def _set_protocol_info(self, protocol: str, port: str): + if self.logger and hasattr(self.logger, "extra"): + self.logger.extra["protocol"] = protocol + self.logger.extra["port"] = port + + def create_conn(self): + if self.kerberos or self.use_kcache: + return self._kerberos_connect() + + return self._ntlm_connect() + + def _do_ntlm_bind(self, ssl: bool, bind_port: int): + try: + self._set_protocol_info("LDAPS" if ssl else "LDAP", str(bind_port)) + server = ldap3.Server( + self.host, + port=bind_port, + use_ssl=ssl, + get_info=ldap3.NONE, + ) + user_ntlm = f"{self.domain}\\{self.username}" if self.domain else (self.username or "") + + # Determine authentication secret: password or hash + if self.password: + auth_secret = self.password + elif self.nthash: + # Pass-the-hash: ldap3 NTLM accepts "LMHASH:NTHASH" as password + lmhash = self.lmhash if self.lmhash else "aad3b435b51404eeaad3b435b51404ee" + auth_secret = f"{lmhash}:{self.nthash}" + else: + auth_secret = "" + + conn = ldap3.Connection( + server, + user=user_ntlm, + password=auth_secret, + authentication=ldap3.NTLM, + auto_bind=True, + ) + return conn, {"result": 0} + except Exception as e: + return None, e + + def _ntlm_connect(self): + # Build list of (port, use_ssl) tuples to try + ports_to_try = [(self.port, self.port == 636)] + if not self.port_explicitly_set: + fallback_port = (636, True) if self.port == 389 else (389, False) + ports_to_try.append(fallback_port) + + connection = None + last_error = None + + for bind_port, use_ssl in ports_to_try: + bound_connection, bind_result = self._do_ntlm_bind(use_ssl, bind_port) + if bound_connection and getattr(bound_connection, "bound", False): + connection = bound_connection + break + last_error = bind_result + if self.port_explicitly_set: + break + + if not connection: + self._log_fail(f"NTLM bind failed: {last_error}") + return None + + self._connection = connection + protocol_info = "LDAPS:636" if connection.server.port == 636 else f"LDAP:{connection.server.port}" + self._log_info(f"ldap3 NTLM bind over {protocol_info} established") + return connection + + def _kerberos_connect(self): + # Build FQDN for SPN + realm = (self.domain or "").upper() + host_fqdn = (self.hostname or self.host) or "" + if "." not in host_fqdn and realm: + host_fqdn = f"{host_fqdn}.{realm}" + + TGT = None + TGS = None + + if self.use_kcache: + result = self._load_from_ccache(realm, host_fqdn) + if result is None: + return None + TGT, TGS, realm = result + + # Prepare creds for TGT acquisition if needed + user_principal = Principal(self.username or "", type=constants.PrincipalNameType.NT_PRINCIPAL.value) + lmhash_bytes = bytes.fromhex(self.lmhash.zfill(len(self.lmhash) + len(self.lmhash) % 2)) if self.lmhash else b"" + nthash_bytes = bytes.fromhex(self.nthash.zfill(len(self.nthash) + len(self.nthash) % 2)) if self.nthash else b"" + + if not TGT and not TGS: + tgt_blob, cipher, _, session_key = getKerberosTGT(user_principal, self.password, realm, lmhash_bytes, nthash_bytes, self.aesKey, self.kdcHost) + TGT = {"KDC_REP": tgt_blob, "cipher": cipher, "sessionKey": session_key} + else: + cipher = (TGT or TGS)["cipher"] + session_key = (TGT or TGS)["sessionKey"] + + # Ensure we have a ST for ldap/ + if not TGS: + service_principal = Principal(f"ldap/{host_fqdn}", type=constants.PrincipalNameType.NT_SRV_INST.value) + tgs_blob, cipher, _, session_key = getKerberosTGS(service_principal, realm, self.kdcHost, TGT["KDC_REP"], TGT["cipher"], TGT["sessionKey"]) + TGS = {"KDC_REP": tgs_blob, "cipher": cipher, "sessionKey": session_key} + + # Build AP_REQ SPNEGO blob + spnego_blob = self._build_spnego_blob(TGS, user_principal, realm, cipher, session_key) + + return self._gss_spnego_bind(spnego_blob, realm, host_fqdn) + + def _load_from_ccache(self, realm, host_fqdn): + try: + ccname = os.getenv("KRB5CCNAME") + if not ccname: + self._log_error("KRB5CCNAME environment variable is not set") + return None + ccache = CCache.loadFile(ccname) + + if not realm: + realm = ccache.principal.realm["data"].decode().upper() + + spn_candidates = [ + f"ldap/{host_fqdn.lower()}@{realm}", + f"ldap/{host_fqdn.upper()}@{realm}", + ] + TGS = None + for spn in spn_candidates: + creds = ccache.getCredential(spn) + if creds: + TGS = creds.toTGS(spn) + break + + TGT = None + if not TGS: + krbtgt_credential = ccache.getCredential(f"krbtgt/{realm}@{realm}") + if krbtgt_credential: + TGT = krbtgt_credential.toTGT() + + if not TGS and not TGT: + self._log_fail("Kerberos cache selected (--use-kcache) but no usable TGT/TGS found in cache.") + return None + + return TGT, TGS, realm + except Exception as e: + self._log_fail(f"Failed to read Kerberos cache (--use-kcache): {e}") + return None + + def _build_spnego_blob(self, TGS, user_principal, realm, cipher, session_key): + spnego_token = SPNEGO_NegTokenInit() + spnego_token["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]] + + tgs_rep = der_decoder.decode(TGS["KDC_REP"], asn1Spec=TGS_REP())[0] + ticket = Ticket() + ticket.from_asn1(tgs_rep["ticket"]) + + apReq = AP_REQ() + apReq["pvno"] = 5 + apReq["msg-type"] = int(constants.ApplicationTagNumbers.AP_REQ.value) + apReq["ap-options"] = constants.encodeFlags([]) + seq_set(apReq, "ticket", ticket.to_asn1) + + auth = Authenticator() + auth["authenticator-vno"] = 5 + auth["crealm"] = realm + seq_set(auth, "cname", user_principal.components_to_asn1) + now = datetime.now(timezone.utc) + auth["ctime"] = KerberosTime.to_asn1(now) + auth["cusec"] = now.microsecond + + enc_auth = cipher.encrypt(session_key, 11, ber_encoder.encode(auth), None) + apReq["authenticator"] = noValue + apReq["authenticator"]["etype"] = cipher.enctype + apReq["authenticator"]["cipher"] = enc_auth + spnego_token["MechToken"] = ber_encoder.encode(apReq) + + return spnego_token + + def _do_gss_bind(self, use_ssl: bool, bind_port: int, spnego_blob): + try: + self._set_protocol_info("LDAPS" if use_ssl else "LDAP", str(bind_port)) + ldap_server = ldap3.Server( + self.host, + port=bind_port, + use_ssl=use_ssl, + get_info=ldap3.NONE, + ) + ldap_connection = ldap3.Connection( + ldap_server, + authentication=ldap3.SASL, + sasl_mechanism="GSS-SPNEGO", + auto_bind=False, + ) + if ldap_connection.closed: + ldap_connection.open(read_server_info=False) + + bind_request = ldap3.operation.bind.bind_operation( + ldap_connection.version, ldap3.SASL, (self.username or ""), None, "GSS-SPNEGO", spnego_blob.getData() + ) + ldap_connection.sasl_in_progress = True + bind_response = ldap_connection.post_send_single_response(ldap_connection.send("bindRequest", bind_request, None)) + ldap_connection.sasl_in_progress = False + + return ldap_connection, bind_response + except Exception as error: + return None, error + + def _gss_spnego_bind(self, spnego_blob, realm, host_fqdn): + # Build list of (port, use_ssl) tuples to try + ports_to_try = [(self.port, self.port == 636)] + if not self.port_explicitly_set: + fallback_port = (636, True) if self.port == 389 else (389, False) + ports_to_try.append(fallback_port) + + connection = None + last_response = None + + for bind_port, use_ssl in ports_to_try: + bound_connection, bind_response = self._do_gss_bind(use_ssl, bind_port, spnego_blob) + connection = bound_connection + last_response = bind_response + + bind_successful = False + if isinstance(bind_response, list) and bind_response and isinstance(bind_response[0], dict): + bind_successful = (bind_response[0].get("result", None) == 0) + + if bind_successful: + break + if self.port_explicitly_set: + break + + # Check if bind was successful + is_valid_response = isinstance(last_response, list) and last_response and isinstance(last_response[0], dict) + bind_succeeded = is_valid_response and last_response[0].get("result", 1) == 0 + + if not bind_succeeded: + error_detail = last_response[0] if is_valid_response else last_response + self._log_fail(f"ldap3 Kerberos bind failed: {error_detail}") + return None + + connection.bound = True + self._connection = connection + + # Resolve username from whoami if not set (ccache case) + self._resolve_username_from_whoami(connection) + + self._log_info("ldap3 Kerberos connection established") + return connection + + def _resolve_username_from_whoami(self, ldap_connection): + try: + if not self.username: + whoami_response = ldap_connection.extend.standard.who_am_i() + if isinstance(whoami_response, str) and whoami_response.startswith("u:"): + # Response format is "u:DOMAIN\\username" or "u:username" + identity_string = whoami_response[2:] + if "\\" in identity_string: + domain_part, username_part = identity_string.split("\\", 1) + self.username = username_part + if not self.domain: + self.domain = domain_part.upper() + else: + self.username = identity_string + except Exception: + pass + + @property + def connection(self): + """Return the current connection.""" + return self._connection \ No newline at end of file From dad75bae7593516d9da224e206fce508870f668b Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sat, 13 Dec 2025 21:49:56 +0100 Subject: [PATCH 5/5] ruff fix --- nxc/protocols/ldap/ldap3_conn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nxc/protocols/ldap/ldap3_conn.py b/nxc/protocols/ldap/ldap3_conn.py index 5f37e3254f..7f10b17c77 100644 --- a/nxc/protocols/ldap/ldap3_conn.py +++ b/nxc/protocols/ldap/ldap3_conn.py @@ -347,4 +347,4 @@ def _resolve_username_from_whoami(self, ldap_connection): @property def connection(self): """Return the current connection.""" - return self._connection \ No newline at end of file + return self._connection