diff --git a/nxc/cli.py b/nxc/cli.py index 99e52bd74a..c0ab195717 100755 --- a/nxc/cli.py +++ b/nxc/cli.py @@ -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") diff --git a/nxc/logger.py b/nxc/logger.py index 182686d0b9..c42e9e8ee8 100755 --- a/nxc/logger.py +++ b/nxc/logger.py @@ -1,4 +1,5 @@ import logging +import json from logging import LogRecord from logging.handlers import RotatingFileHandler import os.path @@ -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 @@ -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: @@ -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]", @@ -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: @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/nxc/protocols/wmi.py b/nxc/protocols/wmi.py index daba36f9a4..08741d3678 100644 --- a/nxc/protocols/wmi.py +++ b/nxc/protocols/wmi.py @@ -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, } ) @@ -163,6 +164,7 @@ 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: @@ -170,6 +172,11 @@ def enum_host_info(self): 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 diff --git a/nxc/protocols/wmi/database.py b/nxc/protocols/wmi/database.py index ef54caba10..71dfaa83fb 100644 --- a/nxc/protocols/wmi/database.py +++ b/nxc/protocols/wmi/database.py @@ -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): @@ -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 = [] @@ -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 @@ -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"])