Skip to content

Commit 6b31e55

Browse files
authored
Merge pull request #8 from blacklanternsecurity/upstream-sync-2026-11-13
Sync with upstream Pennyw0rth/NetExec (214 commits)
2 parents e8bc438 + c5fdc75 commit 6b31e55

52 files changed

Lines changed: 1630 additions & 1374 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,5 @@ docs/_build/
6464

6565
# PyBuilder
6666
target/
67+
nxc/.DS_Store
68+
.DS_Store

‎AGENTS.md‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,45 @@
77

88
# Coding style
99

10+
- Never add a comment or docstring at the top of a Python file unless that file already has a top-of-file comment or docstring.
11+
- In parenthesized Python import blocks, group multiple imported names on each line instead of placing every name on its own line.
12+
- Keep function and method call arguments on one line when practical, including `raise` and log calls; format object literals for readability.
13+
- Keep comments short and precise. Use block form for docstrings and other long text.
1014
- Assume ordinary LDAP searches and LDAP response parsing do not raise exceptions; do not wrap them in `try`/`except`.
1115
- Always bind caught exceptions as `e`, not `error` or another name.
1216
- Do not prefix function or method names with underscores; preserve required Python special methods such as `__init__`.
1317
- Do not assume the host runs Linux; keep code and paths cross-platform unless the task explicitly targets one operating system.
18+
- Keep implementations as short and concise as practical. Prefer direct control flow and shared error handling over wrappers, redundant branches, or defensive boilerplate.
19+
- Avoid stub variables that merely hold a value for one immediate use. Pass data directly unless a local name improves clarity, prevents repeated work, or represents meaningful state.
20+
- Do not use `.warning()` logging. Use `.fail()` when logic or an operation fails.
21+
- If unsure about anything, ask for clarification before proceeding.
22+
23+
# NetExec protocol structure
24+
25+
- Protocol implementations must follow the lifecycle defined by `proto_flow()` in `nxc/connection.py`.
26+
- Keep connection setup in `create_conn_obj()`, target enumeration in `enum_host_info()`, host information output in `print_host_info()`, authentication in the login methods, and cleanup in `disconnect()`.
27+
- Keep protocol-specific behavior in the appropriate lifecycle methods and let `proto_flow()` control their order and dispatch command arguments and modules.
1428

1529
# NetExec module structure
1630

1731
- In files under `nxc/modules/`, do not define variables, constants, or helper functions at module scope.
1832
- Keep all module-specific state, constants, and helper methods inside the `NXCModule` class.
1933
- Module scope should contain only imports and the `NXCModule` class definition.
20-
- When a module must terminate for invalid options, import `exit` with `from sys import exit` and call `exit(...)`; do not use `import sys` with `sys.exit(...)`.
34+
- When module options are invalid, log the reason with `context.log.fail()` and `return False` from `options()`; do not call `exit()`.
2135
- Do not over-validate module options. Check only that required arguments are present, mutually exclusive arguments are not combined, or a value would otherwise cause the module to fail before performing its normal lookup or operation.
2236
- Do not validate whether user-supplied object names, identifiers, or similar values are semantically correct when the underlying protocol lookup can handle them; let a misspecified value produce the normal "not found" result.
23-
- Avoid stub variables that merely hold a value for one immediate use. Pass data directly unless a local name improves clarity, prevents repeated work, or represents meaningful state.
24-
- Keep module implementations as short and concise as practical. Prefer direct control flow and shared error handling over wrappers, redundant branches, or defensive boilerplate.
25-
- Do not optimize module code for line length; long lines are acceptable when they keep straightforward logic together.
26-
- Do not use `.warning()` logging in NetExec modules. Use `.fail()` when logic or an operation fails.
27-
- Run `ruff check .` after every coding session.
2837

2938
# Development and validation
3039

3140
- To verify that a module works, run the module's actual NetExec command instead of pytest or compilation checks.
32-
- Record every module-verification command in `tests/e2e_commands.txt`.
41+
- Record every module-verification command in `tests/e2e_commands.txt` using the file's placeholders (`TARGET_HOST`, `LOGIN_USERNAME`, `LOGIN_PASSWORD`, `KERBEROS`), never real targets or credentials.
3342
- Do not run compilation checks.
3443
- Run Ruff after completing a coding session.
3544

3645
# Filesystem and source conventions
3746

3847
- Assume that the underlying operating system and its storage are fully secure. Files and other data produced by NetExec may intentionally contain readable plaintext credentials; do not add encryption, redaction, restrictive permission handling, or permission warnings unless explicitly requested.
39-
- Before opening, creating, writing, renaming, moving, or deleting a file or directory, sanitize every path component derived from untrusted data and verify that the resulting path cannot traverse outside its intended base directory.
48+
- Before opening, creating, writing, renaming, moving, or deleting a file or directory, sanitize every path component derived from untrusted data with `sanitize_path_component()` from `nxc/helpers/path.py` and verify that the resulting path cannot traverse outside its intended base directory.
4049
- Place every file and directory produced by NetExec under `NXC_PATH` by default, using `TMP_PATH` for temporary artifacts. An explicit user-provided output path or task requirement may override this default.
4150
- `NXC_PATH` defaults to `~/.nxc` but may be overridden by the environment. Import and use `NXC_PATH` or its derived path constants instead of hardcoding `~/.nxc`.
42-
- Place imports at the top of files unless explicitly instructed otherwise.
51+
- Place imports at the top of files unless explicitly instructed otherwise; only a heavy, rarely used dependency on a hot path, such as protocol loading, may be imported where it is used.

‎Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ clean:
1313
find . -name '.pytest_cache' -exec rm -rf {} +
1414

1515
tests:
16-
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics --exclude nxc/data/*
16+
ruff check .
1717

1818
requirements:
1919
poetry export --without-hashes -f requirements.txt -o requirements.txt

‎netexec.spec‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,12 @@ a = Analysis(
3232
'impacket.dcerpc.v5.rprn',
3333
'impacket.dcerpc.v5.even',
3434
'impacket.dcerpc.v5.even6',
35+
'impacket.dcerpc.v5.tsts',
3536
'impacket.dpapi_ng',
3637
'impacket.tds',
3738
'impacket.version',
3839
'impacket.ldap.ldap',
39-
'jwt',
40+
'impacket.krb5.kpasswd',
4041
'nxc.connection',
4142
'nxc.protocols.smb.wmiexec',
4243
'nxc.protocols.smb.atexec',
@@ -48,9 +49,12 @@ a = Analysis(
4849
'nxc.parsers.ldap_results',
4950
'nxc.helpers.bash',
5051
'nxc.helpers.bloodhound',
52+
'nxc.helpers.dpapi',
5153
'nxc.helpers.even6_parser',
54+
'nxc.helpers.firefox',
5255
'nxc.helpers.msada_guids',
5356
'nxc.helpers.negotiate_parser',
57+
'nxc.helpers.smb',
5458
'paramiko',
5559
'pefile',
5660
'pypsrp.client',
@@ -84,9 +88,16 @@ a = Analysis(
8488
'dploot.triage.cng',
8589
'dploot.lib.target',
8690
'dploot.lib.smb',
91+
'dploot.lib.network.mssql',
92+
'dploot.lib.network.winrm',
93+
'dsinternals.common.cryptography.X509Certificate2',
94+
'dsinternals.common.data.DNWithBinary',
95+
'dsinternals.common.data.hello.KeyCredential',
96+
'dsinternals.system.DateTime',
97+
'dsinternals.system.Guid',
98+
'lxml.objectify',
8799
'pyasn1_modules.rfc5652',
88100
'unicrypto.backends.pycryptodomex',
89-
'dateutil.relativedelta',
90101
'sspilib.raw._text',
91102
],
92103
hookspath=['./nxc/.hooks'],

‎nxc/connection.py‎

Lines changed: 14 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,6 @@
2020
from nxc.logger import nxc_logger, NXCAdapter
2121
from nxc.context import Context
2222
from nxc.paths import NXC_PATH
23-
from nxc.protocols.ldap.laps import laps_search
24-
from nxc.helpers.pfx import pfx_auth
25-
26-
from impacket.dcerpc.v5 import transport
27-
from impacket.krb5.ccache import CCache
2823

2924
sem = BoundedSemaphore(1)
3025
fail_lock = Lock()
@@ -102,37 +97,6 @@ def _decorator(self, *args, **kwargs):
10297
return wraps(func)(_decorator)
10398

10499

105-
def dcom_FirewallChecker(iInterface, remoteHost, timeout):
106-
stringBindings = iInterface.get_cinstance().get_string_bindings()
107-
for strBinding in stringBindings:
108-
if strBinding["wTowerId"] == 7:
109-
if strBinding["aNetworkAddr"].find("[") >= 0:
110-
binding, _, bindingPort = strBinding["aNetworkAddr"].partition("[")
111-
bindingPort = "[" + bindingPort
112-
else:
113-
binding = strBinding["aNetworkAddr"]
114-
bindingPort = ""
115-
116-
if binding.upper().find(iInterface.get_target().upper()) >= 0:
117-
stringBinding = "ncacn_ip_tcp:" + strBinding["aNetworkAddr"][:-1]
118-
break
119-
elif iInterface.is_fqdn() and binding.upper().find(iInterface.get_target().upper().partition(".")[0]) >= 0:
120-
stringBinding = f"ncacn_ip_tcp:{iInterface.get_target()}{bindingPort}"
121-
if "stringBinding" not in locals():
122-
return True, None
123-
try:
124-
rpctransport = transport.DCERPCTransportFactory(stringBinding)
125-
rpctransport.setRemoteHost(remoteHost)
126-
rpctransport.set_connect_timeout(timeout)
127-
rpctransport.connect()
128-
rpctransport.disconnect()
129-
except Exception as e:
130-
nxc_logger.debug(f"Exception while connecting to {stringBinding}: {e}")
131-
return False, stringBinding
132-
else:
133-
return True, stringBinding
134-
135-
136100
class connection:
137101
def __init__(self, args, db, target):
138102
self.args = args
@@ -146,16 +110,19 @@ def __init__(self, args, db, target):
146110
# Authentication info
147111
self.password = ""
148112
self.username = ""
113+
self.certificate_auth = bool(self.args.pfx_cert or self.args.pfx_base64 or self.args.pem_cert)
149114
self.kerberos = bool(self.args.kerberos or
150115
self.args.use_kcache or
151116
self.args.aesKey or
117+
(self.certificate_auth and not (self.protocol == "ldap" and self.args.schannel)) or # PKINIT yields a TGT, while Schannel binds the certificate to the LDAP channel itself
152118
(hasattr(self.args, "delegate") and self.args.delegate) or
153119
(hasattr(self.args, "generate_st") and self.args.generate_st) or
154120
(hasattr(self.args, "no_preauth_targets") and self.args.no_preauth_targets))
155121
self.aesKey = None if not self.args.aesKey else self.args.aesKey[0]
156122
self.use_kcache = None if not self.args.use_kcache else self.args.use_kcache
157123
self.admin_privs = False
158124
self.failed_logins = 0
125+
self.has_reusable_secret = not (self.protocol == "ldap" and self.args.schannel) # a Schannel bind authenticates the LDAP connection only, leaving no secret for a second channel
159126

160127
# Network info
161128
self.domain = None
@@ -259,7 +226,7 @@ def proto_flow(self):
259226
self.output_filename = os.path.join(base_log_dir, filename_pattern)
260227

261228
self.print_host_info()
262-
if self.login() or (self.username == "" and self.password == "" and self.protocol != "mssql"):
229+
if self.login() or (self.username == "" and self.password == "" and self.protocol != "mssql" and not self.certificate_auth): # a failed certificate auth is not a null session
263230
self.logger.debug("Calling command arguments")
264231
self.call_cmd_args()
265232
if self.args.module:
@@ -561,20 +528,27 @@ def login(self):
561528
if self.args.use_kcache:
562529
self.logger.debug("Trying to authenticate using Kerberos cache")
563530
with sem:
531+
from impacket.krb5.ccache import CCache
564532
username = self.args.username[0] if len(self.args.username) else CCache.parseFile()[1]
565533
password = self.args.password[0] if len(self.args.password) else ""
566534
return self.kerberos_login(self.domain, username, password, "", "", self.kdcHost, True)
567535

568-
if self.args.pfx_cert or self.args.pfx_base64 or self.args.pem_cert:
536+
if self.certificate_auth:
569537
self.logger.debug("Trying to authenticate using Certificate pfx")
570-
if not self.args.username:
538+
if self.args.protocol == "ldap" and self.args.schannel:
539+
# Schannel maps the certificate to an account server-side, so the supplied username is ignored
540+
with sem:
541+
return self.plaintext_login(self.domain, "", "")
542+
if not username:
571543
self.logger.fail("You must specify a username when using certificate authentication")
572544
return False
573545
with sem:
574-
return pfx_auth(self)
546+
from nxc.helpers.pfx import pfx_auth
547+
return pfx_auth(self, domain[0], username[0])
575548

576549
if hasattr(self.args, "laps") and self.args.laps:
577550
self.logger.debug("Trying to authenticate using LAPS")
551+
from nxc.protocols.ldap.laps import laps_search
578552
username[0], secret[0], domain[0] = laps_search(self, username, secret, cred_type, domain, self.dns_server)
579553
cred_type = ["plaintext"]
580554
if not (username[0] or secret[0] or domain[0]):

0 commit comments

Comments
 (0)