Skip to content

Add DNS Module - #761

Open
lodos2005 wants to merge 4 commits into
Pennyw0rth:mainfrom
lodos2005:main
Open

lodos2005 wants to merge 4 commits into
Pennyw0rth:mainfrom
lodos2005:main

Conversation

@lodos2005

@lodos2005 lodos2005 commented Jun 27, 2025 •

Copy link
Copy Markdown
Contributor

Description

This pull request introduces a new module, dns, for managing DNS records within an Active Directory-integrated DNS environment directly via LDAP. It provides administrators and pentesters with a powerful command-line tool to perform various DNS operations, from creating and deleting records to querying existing zones, without leaving the NetExec console.
This module is inspired by the functionality of dnstool.py from krbrelayx by @dirkjanm and is designed to be a robust and user-friendly addition to NetExec's capabilities.

Key Features

  • Comprehensive Record Management: Full CRUD (Create, Read, Update, Delete) operations for 'A' records.
  • Multiple Actions: Supports add, modify, query, remove (tombstone), ldapdelete (direct deletion), and resurrect.
  • Zone Enumeration: Ability to list all DNS zones in DomainDnsZones, ForestDnsZones, or the legacy System partition.
  • Flexible Targeting: Allows specifying the target record, data, zone, and DNS partition.
  • Support for Multiple Records: The ALLOWMULTIPLE option permits adding multiple A records for a single hostname.
  • User-Friendly: Includes a comprehensive built-in help menu (-o HELP) and short aliases (A, R, D, etc.) for all options for faster use.

Help Usage
dns-help

Query Usage
dns-query

Forest Query Usage
dns-forestquery

Add Usage
dns-add

Forest Add Usage
dns-forestadd

Add AllowMultiple Usage
dns-allowmultiple

Modify Usage
dns-modify

Remove Usage
dns-remove

Ldap Remove Usage
dns-ldapremove

List
dns-list

List-DN
dns-listdn

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • This requires a third party update (such as Impacket, Dploot, lsassy, etc)

Setup guide for the review

Please provide guidance on what setup is needed to test the introduced changes, such as your locally running machine Python version & OS, as well as the target(s) you tested against, including software versions.
In particular:

  • Bug Fix: Please provide a short description on how to trigger the bug, to make the bug reproducable for the reviewer.
  • Added Feature/Enhancement: Please specify what setup is needed in order to test the changes. E.g. is additional software needed? GPO changes required? Specific registry settings that need to be changed?

Screenshots (if appropriate):

Screenshots are always nice to have and can give a visual representation of the change.
If appropriate include before and after screenshot(s) to show which results are to be expected.

Checklist:

  • I have ran Ruff against my changes (via poetry: poetry run python -m ruff check . --preview, use --fix to automatically fix what it can)
  • I have added or updated the tests/e2e_commands.txt file if necessary
  • New and existing e2e tests pass locally with my changes
  • If reliant on changes of third party dependencies, such as Impacket, dploot, lsassy, etc, I have linked the relevant PRs in those projects
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (PR here: https://github.com/Pennyw0rth/NetExec-Wiki)

Comment thread nxc/modules/dns.py Resolved
@Marshall-Hallenbeck Marshall-Hallenbeck added enhancement New feature or request good first issue Good for newcomers new module labels Jun 27, 2025
@NeffIsBack NeffIsBack removed the enhancement New feature or request label Jun 29, 2025
@NeffIsBack

NeffIsBack commented Jun 29, 2025 •

Copy link
Copy Markdown
Member

Thanks for the PR!

Could you PR all of the structs to impacket? That is probably the better place instead of that NetExec builds its own lib. Also other people can use them if needed.
Don't worry about getting the changes merged, we currently use our forked version and can just merge what we need

@lodos2005

Copy link
Copy Markdown
Contributor Author

fortra/impacket#1994
I sent the PR. I'll refactor the code again.

@NeffIsBack

Copy link
Copy Markdown
Member

@lodos2005 any update on this? Could you also replace ldap3 with impackets LDAP as we now have CRUD methods?

@NeffIsBack NeffIsBack added this to the v1.6.0 milestone Mar 22, 2026
@NeffIsBack

Copy link
Copy Markdown
Member

@lodos2005 r u there?

Add dns Modüle

Signed-off-by: Hakan Yavuz <lodos05@gmail.com>
Add DNS module

Signed-off-by: Hakan Yavuz <lodos05@gmail.com>
@lodos2005
lodos2005 force-pushed the main branch 2 times, most recently from 77a39ff to 3317931 Compare September 12, 2026 21:28
- Use impacket.dnsp.ADIDNSManager for the full record lifecycle instead
  of a hand-rolled LDAP layer, dropping the ldap3 dependency and all
  locally defined MS-DNSP structures (requires fortra/impacket#1994)
- Reuse the already authenticated connection.ldap_connection so
  hash and Kerberos logins work like every other module
- Replace the built-in help screen with a concise options docstring
  including usage examples, short aliases are parsed via a single map
- Derive the default action before validation so RECORD+DATA adds,
  RECORD queries and no options lists zones as documented
- Add the required CATEGORY attribute

Signed-off-by: Hakan Yavuz <lodos05@gmail.com>
@lodos2005

lodos2005 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

heyyy @NeffIsBack, lodosisback. deeply sorry for the late response. i refactored code , this now depends on fortra/impacket#1994 and ldap3 is gone (uses impacket's own LDAP CRUD via connection.ldap_connection) and some improvement

@NeffIsBack

Copy link
Copy Markdown
Member

heyyy @NeffIsBack, lodosisback. deeply sorry for the late response. i refactored code , this now depends on fortra/impacket#1994 and ldap3 is gone (uses impacket's own LDAP CRUD via connection.ldap_connection) and some improvement

Welcome back :)
So this would be ready for a review?

@lodos2005

Copy link
Copy Markdown
Contributor Author

heyyy @NeffIsBack, lodosisback. deeply sorry for the late response. i refactored code , this now depends on fortra/impacket#1994 and ldap3 is gone (uses impacket's own LDAP CRUD via connection.ldap_connection) and some improvement

Welcome back :) So this would be ready for a review?

yep exactly

@NeffIsBack NeffIsBack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few thoughts:

  • We should just implement the logic manually instead of relying on a helper logic of impacket. The logic there looks fairly simple and then we have direct control over it.
  • If you run into issues because parse_result_attributes returns a decoded string but you need raw bytes, feel free to add exceptions for that attribute in the parsing function.
  • Please try to decrease line lengths by keeping e.g. logging calls one-liners. Imo makes it more readable.

Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
Comment thread nxc/modules/dns.py Resolved
- Drop the impacket.dnsp dependency: the MS-DNSP structures and all
  record handling now live in the module, built on impacket's LDAP
  CRUD methods over the already authenticated connection
- Add a dnsRecord exception to parse_result_attributes so raw record
  bytes are returned instead of a lossy string decode
- Move the option/action constants inside the class, abort from
  options() by returning False, keep logging calls one-liners and
  split active/tombstoned records with a plain loop
- Validate the DATA IPv4 address before writing records

Tested against an AD lab with password, NTLM hash, Kerberos, ccache
and certificate authentication.

Signed-off-by: Hakan Yavuz <lodos05@gmail.com>
@lodos2005

Copy link
Copy Markdown
Contributor Author

Thanks for the review @NeffIsBack — all addressed in f1b3456! The module is now fully self-contained (no impacket.dnsp dependency, so CI import error gone), dnsRecord returns raw bytes via a parse_result_attributes exception, and all style points are applied (class constants, return False aborts, one-liner logging, simple tombstone loop). Tested with password/hash/Kerberos/ccache/certificate auth against an AD lab. Anything else, just ping me!

@NeffIsBack NeffIsBack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code already looking quite good. Shouldn't be much to adjust anymore

Comment thread nxc/modules/dns.py
Comment on lines +13 to +133
RECORD_TYPE_MAPPING = {
0: "ZERO",
1: "A",
2: "NS",
5: "CNAME",
6: "SOA",
33: "SRV",
65281: "WINS",
}


class DNS_RECORD(Structure):
"""
dnsRecord - used in LDAP
[MS-DNSP] section 2.3.2.2
"""

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_COUNT_NAME(Structure):
"""
DNS_COUNT_NAME, used for FQDNs in LDAP communication
[MS-DNSP] section 2.2.2.2.2
"""

structure = (
("Length", "B-RawName"),
("LabelCount", "B"),
("RawName", ":"),
)

def toFqdn(self):
ind = 0
labels = []
for _i in range(self["LabelCount"]):
nextlen = struct.unpack("B", self["RawName"][ind:ind + 1])[0]
labels.append(self["RawName"][ind + 1:ind + 1 + nextlen].decode("utf-8"))
ind += nextlen + 1
# For the final dot
labels.append("")
return ".".join(labels)


class DNS_RPC_RECORD_A(Structure):
"""
DNS_RPC_RECORD_A
[MS-DNSP] section 2.2.2.2.4.1
"""

structure = (("address", ":"),)

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

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


class DNS_RPC_RECORD_NODE_NAME(Structure):
"""
DNS_RPC_RECORD_NODE_NAME
[MS-DNSP] section 2.2.2.2.4.2
"""

structure = (("nameNode", ":", DNS_COUNT_NAME),)


class DNS_RPC_RECORD_SRV(Structure):
"""
DNS_RPC_RECORD_SRV
[MS-DNSP] section 2.2.2.2.4.18
"""

structure = (
("wPriority", ">H"),
("wWeight", ">H"),
("wPort", ">H"),
("nameTarget", ":", DNS_COUNT_NAME),
)


class DNS_RPC_RECORD_SOA(Structure):
"""
DNS_RPC_RECORD_SOA
[MS-DNSP] section 2.2.2.2.4.3
"""

structure = (
("dwSerialNo", ">L"),
("dwRefresh", ">L"),
("dwRetry", ">L"),
("dwExpire", ">L"),
("dwMinimumTtl", ">L"),
("namePrimaryServer", ":", DNS_COUNT_NAME),
("zoneAdminEmail", ":", DNS_COUNT_NAME),
)


class DNS_RPC_RECORD_TS(Structure):
"""
DNS_RPC_RECORD_TS (Tombstone Record)
[MS-DNSP] section 2.2.2.2.4.23
"""

structure = (("entombedTime", "<Q"),)

def toDatetime(self):
microseconds = self["entombedTime"] / 10.0
return datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=microseconds)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's import these from impacket tho. No logic, but structures should be defined there. Just assume they exist, I will merge and switch to our fork if needed.

Comment thread nxc/modules/dns.py
Comment on lines +146 to +147
opsec_safe = True
multiple_hosts = True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those should be removed, they don't exist anymore

Comment thread nxc/modules/dns.py
"""
options = {self.ALIASES.get(key.upper(), key.upper()): value for key, value in module_options.items()}

self.action = options.get("ACTION", "").lower()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just add "list" as the fallback so it is the default

Comment thread nxc/modules/dns.py
Comment on lines +192 to +199
# Derive the default action before validating it
if not self.action:
if self.record and self.data:
self.action = "add"
elif self.record:
self.action = "query"
else:
self.action = "list"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not assume any action if the user doesn't explicitly specify it. Since we have a default that is fine imo

Comment thread nxc/modules/dns.py
Comment on lines +223 to +224
rootdse = parse_result_attributes(self.ldap.search(searchBase="", searchFilter="(objectClass=*)", attributes=["schemaNamingContext"], scope=ldapasn1.Scope("baseObject")))
self.schema_root = rootdse[0]["schemaNamingContext"] if rootdse else ""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's query that in enum_host_info() since we do the exact same call there.

Comment thread nxc/modules/dns.py
Comment on lines +221 to +222
self.dns_server = getattr(connection.args, "dns_server", None) or connection.host
self.dns_timeout = getattr(connection.args, "dns_timeout", None) or 3

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need getattr, it is always available since it's not proto dependent.

Comment thread nxc/modules/dns.py
return serial + 1
return int(datetime.datetime.now().timestamp())

def _query_soa_serial(self, zone):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add some comments, this is hard to understand :D

Comment thread nxc/modules/dns.py
if not self.allow_multiple:
for data in entry["records"]:
existing = DNS_RECORD(data)
if existing["Type"] == 1:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please replace the "1" everywhere with some "A record" constant. Imo this would improve readability a lot. Same for other records if you find something else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants