Skip to content
Open
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
10 changes: 7 additions & 3 deletions nxc/helpers/klist.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ def __init__(self, connection):
self.logger = connection.logger
self.bias_minutes = 0

def run(self, command):
# klist prints non-ASCII names, and a NBSP before ':' on French Windows, in the target's OEM codepage; force UTF-8 on both ends so parsing is locale-independent
return self.connection.execute(f"chcp 65001 > nul & {command}", True, codec="utf-8")
Comment on lines +35 to +36

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This breaks --klist/--klist-dump with --exec-method atexec and smbexec, which work on main: atexec puts the command unescaped in the task XML, so the & makes it invalid, and smbexec echoes the command into a batch file, so the > and & split the echo.

$ nxc smb 10.4.10.22 -u Administrator -p NgtI75cKV+Pu -d north.sevenkingdoms.local --klist --exec-method atexec
SMB                      10.4.10.22      445    CASTELBLACK      [-] TSCH SessionError: code: 0x8004131a - SCHED_E_MALFORMEDXML - The task XML is malformed.
SMB                      10.4.10.22      445    CASTELBLACK      [-] Failed to enumerate Kerberos sessions
$ nxc smb 10.4.10.22 -u Administrator -p NgtI75cKV+Pu -d north.sevenkingdoms.local --klist --exec-method smbexec
SMB                      10.4.10.22      445    CASTELBLACK      [-] SMBEXEC: Could not retrieve output file, it may have been detected by AV. Please increase the number of tries with the option '--get-output-tries'. If it is still failing, try the 'wmi' protocol or another exec method
SMB                      10.4.10.22      445    CASTELBLACK      [-] Failed to enumerate Kerberos sessions

On main both list [+] Found 4 TGT(s). Quoting the command fixes smbexec:

Suggested change
# klist prints non-ASCII names, and a NBSP before ':' on French Windows, in the target's OEM codepage; force UTF-8 on both ends so parsing is locale-independent
return self.connection.execute(f"chcp 65001 > nul & {command}", True, codec="utf-8")
# klist prints in the target's OEM codepage: switch it to UTF-8 (quoted so smbexec's echo keeps & and >)
return self.connection.execute(f'cmd /c "chcp 65001 > nul & {command}"', True, codec="utf-8")

and atexec needs the XML escaping that impacket's atexec.py already does. This also fixes -x '(whoami & hostname)' on atexec, which fails on main with the same SCHED_E_MALFORMEDXML:

--- a/nxc/protocols/smb/atexec.py
+++ b/nxc/protocols/smb/atexec.py
@@ -5,2 +5,3 @@
 from time import sleep
+from xml.sax.saxutils import escape
@@ -92 +93 @@
-        full_command = f"{random.choice(random_cmd_arg)} {command}"
+        full_command = f"{random.choice(random_cmd_arg)} {escape(command)}"

With both, atexec, smbexec, wmiexec, mmcexec and winrm list the same 4 TGTs as main, and the code page is still switched on each (-x 'cmd /c "chcp 65001 > nul & chcp"' gives Active code page: 65001):

$ nxc smb 10.4.10.22 -u Administrator -p NgtI75cKV+Pu -d north.sevenkingdoms.local --klist --exec-method atexec
SMB                      10.4.10.22      445    CASTELBLACK      [+] Found 4 TGT(s)
SMB                      10.4.10.22      445    CASTELBLACK        [1] NORTH\sql_svc       0x17f09  (expires 2026-11-19 06:00:49 UTC)
SMB                      10.4.10.22      445    CASTELBLACK        [2] NORTH\CASTELBLACK$  0x3e4  (expires 2026-11-19 04:37:42 UTC)
SMB                      10.4.10.22      445    CASTELBLACK        [3] NORTH\robb.stark    0x6a769  (expires 2026-11-19 00:05:03 UTC)
SMB                      10.4.10.22      445    CASTELBLACK        [4] NORTH\CASTELBLACK$  0x3e7  (expires 2026-11-18 22:47:09 UTC)


def display(self):
tgts = self.load_tgts()
if tgts is None:
Expand Down Expand Up @@ -66,7 +70,7 @@ def dump(self, selection):

def load_tgts(self):
"""Returns None when klist itself could not run, a (possibly empty) list otherwise."""
output = self.connection.execute("klist sessions", True)
output = self.run("klist sessions")
if not output:
self.logger.fail("Failed to enumerate Kerberos sessions")
return None
Expand Down Expand Up @@ -109,7 +113,7 @@ def target_utc_bias(self):
klist prints local wallclock with no zone, so without this the ccache times and the
expiry check are off by the target's UTC offset whenever it differs from ours.
"""
output = self.connection.execute(r'reg query "HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v ActiveTimeBias', True)
output = self.run(r'reg query "HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v ActiveTimeBias')
match = re.search(r"ActiveTimeBias\s+REG_DWORD\s+0x([0-9a-fA-F]+)", output) if output else None
if not match:
self.logger.debug("Could not read ActiveTimeBias, assuming target is in UTC")
Expand All @@ -123,7 +127,7 @@ def collect_tgts(self, sessions):
now = datetime.now(UTC).timestamp()
tgts = []
for logon_hex, account in sessions:
tgt_text = self.connection.execute(f"klist tgt -li {logon_hex}", True)
tgt_text = self.run(f"klist tgt -li {logon_hex}")
if not tgt_text:
self.logger.debug(f"{account} ({logon_hex}): no output from klist tgt")
continue
Expand Down
5 changes: 3 additions & 2 deletions nxc/protocols/smb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,7 +1014,7 @@ def trigger_winreg(self):
return False

@requires_admin
def execute(self, payload=None, get_output=False, methods=None) -> str:
def execute(self, payload=None, get_output=False, methods=None, codec=None) -> str:
"""
Executes a command on the target host using CMD.exe and the specified method(s).

Expand All @@ -1023,6 +1023,7 @@ def execute(self, payload=None, get_output=False, methods=None) -> str:
payload (str): The command to execute
get_output (bool): Whether to get the output of the command (can be useful for AV evasion)
methods (list): The method(s) to use for command execution
codec (str): Decode the output with this codec instead of the --codec default

Returns:
-------
Expand Down Expand Up @@ -1130,7 +1131,7 @@ def execute(self, payload=None, get_output=False, methods=None) -> str:
output = exec_method.execute(payload, get_output)
try:
if not isinstance(output, str):
output = output.decode(self.args.codec)
output = output.decode(codec or self.args.codec)
except UnicodeDecodeError:
self.logger.debug("Decoding error detected, consider running chcp.com at the target, map the result with https://docs.python.org/3/library/codecs.html#standard-encodings")
output = output.decode("cp437")
Expand Down
4 changes: 2 additions & 2 deletions nxc/protocols/winrm.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,12 +253,12 @@ def hash_login(self, domain, username, ntlm_hash):
self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {e!s}")
return False

def execute(self, payload=None, get_output=False, shell_type="cmd"):
def execute(self, payload=None, get_output=False, shell_type="cmd", codec=None):
Comment thread
azoxlpf marked this conversation as resolved.
Dismissed
if not payload:
payload = self.args.execute

try:
result = self.conn.execute_cmd(payload, encoding=self.args.codec) if shell_type == "cmd" else self.conn.execute_ps(payload)
result = self.conn.execute_cmd(payload, encoding=codec or self.args.codec) if shell_type == "cmd" else self.conn.execute_ps(payload)
except Exception as e:
# Reference: https://github.com/diyan/pywinrm/issues/275
if hasattr(e, "code") and e.code == 5:
Expand Down
Loading