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
1 change: 1 addition & 0 deletions nxc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def gen_cli_args():
output_group = output_parser.add_argument_group("Output Options")
output_group.add_argument("--no-progress", action="store_true", help="do not displaying progress bar during scan")
output_group.add_argument("--log", metavar="LOG", help="export result into a custom file")
output_group.add_argument("-j", "--json", action="store_true", help="output results as JSON lines")
log_level = output_group.add_mutually_exclusive_group()
log_level.add_argument("--verbose", action="store_true", help="enable verbose output")
log_level.add_argument("--debug", action="store_true", help="enable debug level information")
Expand Down
25 changes: 24 additions & 1 deletion nxc/logger.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import json
from logging import LogRecord
from logging.handlers import RotatingFileHandler
import os.path
Expand All @@ -18,6 +19,7 @@ def parse_debug_args():
debug_parser = argparse.ArgumentParser(add_help=False)
debug_parser.add_argument("--debug", action="store_true")
debug_parser.add_argument("--verbose", action="store_true")
debug_parser.add_argument("-j", "--json", action="store_true")
args, _ = debug_parser.parse_known_args()
return args

Expand Down Expand Up @@ -69,6 +71,8 @@ def no_debug(func):
"""
@functools.wraps(func)
def wrapper(self, msg, *args, **kwargs):
if self.json_output:
return func(self, msg, *args, **kwargs)
if self.logger.getEffectiveLevel() >= logging.INFO:
return func(self, msg, *args, **kwargs)
else:
Expand All @@ -81,6 +85,7 @@ def wrapper(self, msg, *args, **kwargs):

class NXCAdapter(logging.LoggerAdapter):
def __init__(self, extra=None, merge_extra=False):
self.json_output = parse_debug_args().json
logging.basicConfig(
format="%(message)s",
datefmt="[%X]",
Expand Down Expand Up @@ -113,7 +118,7 @@ def format(self, msg, *args, **kwargs):

This is used instead of process() since process() applies to _all_ messages, including debug calls
"""
if self.extra is None:
if self.json_output or self.extra is None:
return f"{msg}", kwargs

if "module_name" in self.extra and len(self.extra["module_name"]) > 11:
Expand All @@ -128,9 +133,21 @@ def format(self, msg, *args, **kwargs):

return (f"{module_name:<24} {self.extra['host']:<15} {self.extra['port']:<6} {self.extra['hostname'] if self.extra['hostname'] else 'NONE':<16} {msg}", kwargs)

def emit_json(self, event_type, message):
record = {
"timestamp": datetime.now().isoformat(),
"type": event_type,
"message": str(message),
}
if self.extra:
record.update({key: value for key, value in self.extra.items() if value is not None})
nxc_console.print(json.dumps(record, default=str))

@no_debug
def display(self, msg, *args, **kwargs):
"""Display text to console, formatted for nxc"""
if self.json_output:
return self.emit_json("display", msg)
msg, kwargs = self.format(f"{colored('[*]', 'blue', attrs=['bold'])} {msg}", kwargs)
text = Text.from_ansi(msg)
nxc_console.print(text, *args, **kwargs)
Expand All @@ -139,6 +156,8 @@ def display(self, msg, *args, **kwargs):
@no_debug
def success(self, msg, color="green", *args, **kwargs):
"""Prints some sort of success to the user"""
if self.json_output:
return self.emit_json("success", msg)
msg, kwargs = self.format(f"{colored('[+]', color, attrs=['bold'])} {msg}", kwargs)
text = Text.from_ansi(msg)
nxc_console.print(text, *args, **kwargs)
Expand All @@ -147,6 +166,8 @@ def success(self, msg, color="green", *args, **kwargs):
@no_debug
def highlight(self, msg, *args, **kwargs):
"""Prints a completely yellow highlighted message to the user"""
if self.json_output:
return self.emit_json("highlight", msg)
msg, kwargs = self.format(f"{colored(msg, 'yellow', attrs=['bold'])}", kwargs)
text = Text.from_ansi(msg)
nxc_console.print(text, *args, **kwargs)
Expand All @@ -155,6 +176,8 @@ def highlight(self, msg, *args, **kwargs):
@no_debug
def fail(self, msg, color="red", *args, **kwargs):
"""Prints a failure (may or may not be an error) - e.g. login creds didn't work"""
if self.json_output:
return self.emit_json("fail", msg)
msg, kwargs = self.format(f"{colored('[-]', color, attrs=['bold'])} {msg}", kwargs)
text = Text.from_ansi(msg)
nxc_console.print(text, *args, **kwargs)
Expand Down
9 changes: 8 additions & 1 deletion nxc/protocols/wmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ def proto_logger(self):
"protocol": "WMI",
"host": self.host,
"port": self.port,
"hostname": self.hostname
"hostname": self.hostname,
"server_os": self.server_os,
}
)

Expand Down Expand Up @@ -163,13 +164,19 @@ def enum_host_info(self):
self.remoteName = sanitize_dns(dns_hostname, self.logger) if self.kerberos else self.host
self.server_os = ntlm_info["os_version"]
self.logger.extra["hostname"] = self.hostname
self.logger.extra["server_os"] = self.server_os
else:
self.hostname = self.host
if self.args.local_auth:
self.domain = self.hostname
if self.args.domain:
self.domain = self.args.domain

try:
self.db.add_host(self.host, self.hostname, domain=self.domain, os=self.server_os)
except Exception as e:
self.logger.debug(f"Error adding host {self.host} into db: {e!s}")

if not self.kdcHost and self.domain:
result = self.resolver(self.domain)
self.kdcHost = result["host"] if result else None
Expand Down
11 changes: 10 additions & 1 deletion nxc/protocols/wmi/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ class Host(Base):
ip = Column(String)
hostname = Column(String)
port = Column(Integer)
domain = Column(String)
os = Column(String)

__table_args__ = (
PrimaryKeyConstraint("id"),
UniqueConstraint("ip"),
)

class DpapiSecret(Base):
Expand Down Expand Up @@ -79,7 +82,7 @@ def reflect_tables(self):
self.DpapiSecretsTable = self.reflect_table(self.DpapiSecret)
self.DpapiBackupkeyTable = self.reflect_table(self.DpapiBackupKey)

def add_host(self, ip, hostname, port):
def add_host(self, ip, hostname, port=None, domain=None, os=None):
"""Check if this host has already been added to the database, if not, add it in."""
hosts = []
updated_ids = []
Expand All @@ -93,6 +96,8 @@ def add_host(self, ip, hostname, port):
"ip": ip,
"hostname": hostname,
"port": port,
"domain": domain,
"os": os if os is not None else "",
}
hosts = [new_host]
# update existing hosts data
Expand All @@ -106,6 +111,10 @@ def add_host(self, ip, hostname, port):
host_data["hostname"] = hostname
if port is not None:
host_data["port"] = port
if domain is not None:
host_data["domain"] = domain
if os is not None:
host_data["os"] = os
if host_data not in hosts:
hosts.append(host_data)
updated_ids.append(host_data["id"])
Expand Down
Loading