class ModulesChecks: def __init__(self): self.badges = Badges() self.importer = Importer() self.local_storage = LocalStorage() self.modules = Modules() def perform_check(self): fail = False all_modules = self.local_storage.get("modules") if all_modules: for database in all_modules.keys(): self.badges.output_process("Checking modules from " + database + " database...") modules = all_modules[database] for category in modules.keys(): for platform in modules[category].keys(): for module in modules[category][platform].keys(): try: _ = self.importer.import_module( modules[category][platform][module] ['Path']) self.badges.output_success( self.modules.get_full_name( category, platform, module) + ': OK') except Exception: self.badges.output_error( self.modules.get_full_name( category, platform, module) + ': FAIL') fail = True return fail
class PayloadsTests: def __init__(self): self.badges = Badges() self.importer = Importer() self.local_storage = LocalStorage() self.payloads = Payloads() def perform_test(self): fail = False all_payloads = self.local_storage.get("payloads") if all_payloads: for database in all_payloads.keys(): self.badges.output_process("Testing payloads from " + database + " database...") payloads = all_payloads[database] for platform in payloads.keys(): for architecture in payloads[platform].keys(): for payload in payloads[platform][architecture].keys(): try: _ = self.importer.import_payload( payloads[platform][architecture][payload] ['Path']) self.badges.output_success( self.payloads.get_full_name( platform, architecture, payload) + ': OK') except Exception: self.badges.output_error( self.payloads.get_full_name( platform, architecture, payload) + ': FAIL') fail = True return fail
class Handler(http.server.SimpleHTTPRequestHandler): def log_request(self, fmt, *args): pass def do_GET(self): self.badges = Badges() self.badges.output_success( f"Connection from {self.client_address[0]}!") self.badges.output_process("Sending payload stage...") self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(self.payload, "utf8")) self.badges.output_success("Payload sent successfully!")
class PluginsChecks: def __init__(self): self.badges = Badges() self.importer = Importer() self.local_storage = LocalStorage() def perform_check(self): fail = False all_plugins = self.local_storage.get("plugins") if all_plugins: for database in all_plugins.keys(): self.badges.output_process("Checking plugins from " + database + " database...") plugins = all_plugins[database] for plugin in plugins.keys(): try: _ = self.importer.import_plugin(plugins[plugin]['Path']) self.badges.output_success(plugin + ': OK') except Exception: self.badges.output_error(plugin + ': FAIL') fail = True return fail
class PerformTests: def __init__(self): self.badges = Badges() self.importer = Importer() self.modules_tests = ModulesTests() self.plugins_tests = PluginsTests() self.payloads_tests = PayloadsTests() def perform_tests(self): self.importer.import_database() statuses = list() self.badges.output_process("Performing modules test...") statuses.append(self.modules_tests.perform_test()) self.badges.output_process("Performing plugins test...") statuses.append(self.plugins_tests.perform_test()) self.badges.output_process("Performing payloads test...") statuses.append(self.payloads_tests.perform_test()) for status in statuses: if status: self.badges.output_error("Not all tests passed!") sys.exit(1) self.badges.output_success("All tests passed!")
class TCP: def __init__(self): self.badges = Badges() self.exceptions = Exceptions() @staticmethod def get_local_host(): try: server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.connect(("192.168.1.1", 80)) local_host = server.getsockname()[0] server.close() local_host = local_host except Exception: local_host = "127.0.0.1" return local_host @staticmethod def tcp_request(host, port, data, buffer_size=1024, timeout=10): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, int(port))) sock.send(data.encode()) output = sock.recv(buffer_size) sock.close() return output.decode().strip() @staticmethod def check_tcp_port(host, port, timeout=10): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) if sock.connect_ex((host, int(port))) == 0: sock.close() return True sock.close() return False def connect(self, remote_host, remote_port, timeout=None): address = remote_host + ':' + str(remote_port) self.badges.output_process("Connecting to " + address + "...") try: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.settimeout(timeout) server.connect((remote_host, int(remote_port))) self.badges.output_process("Establishing connection...") except socket.timeout: self.badges.output_warning("Connection timeout.") raise self.exceptions.GlobalException except Exception: self.badges.output_error("Failed to connect to " + address + "!") raise self.exceptions.GlobalException return server def listen(self, local_host, local_port, timeout=None): try: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.settimeout(timeout) server.bind((local_host, int(local_port))) server.listen(1) self.badges.output_process("Listening on port " + str(local_port) + "...") client, address = server.accept() self.badges.output_process("Connecting to " + address[0] + "...") self.badges.output_process("Establishing connection...") server.close() except socket.timeout: self.badges.output_warning("Timeout waiting for connection.") server.close() raise self.exceptions.GlobalException except Exception: self.badges.output_error("Failed to listen on port " + str(local_port) + "!") raise self.exceptions.GlobalException return client, address[0]
class HTTPClient: def __init__(self): self.badges = Badges() self.handler = Handler def start_server(self, host, port, payload, forever=True): try: self.badges.output_process( f"Starting http server on port {str(port)}...") httpd = socketserver.TCPServer((host, int(port)), self.handler) self.badges.output_process("Serving payload on http server...") httpd.RequestHandlerClass.payload = payload if forever: while True: self.badges.output_process("Listening for connections...") httpd.handle_request() else: self.badges.output_process("Listening for connections...") httpd.handle_request() except Exception: self.badges.output_error( f"Failed to start http server on port {str(port)}!") def http_request(self, method, host, port, path, ssl=False, session=requests, **kwargs): kwargs.setdefault("timeout", HTTP_TIMEOUT) kwargs.setdefault("verify", False) kwargs.setdefault("allow_redirects", True) if not ssl: ssl = int(port) in [443] url = self.normalize_url(host, port, path, ssl) try: return getattr(session, method.lower())(url, **kwargs) except (requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema): self.badges.output_error("Invalid URL format: {}!".format(url)) except requests.exceptions.ConnectionError: self.badges.output_error("Connection error: {}!".format(url)) except requests.RequestException as e: self.badges.output_error(e) except socket.error as e: self.badges.output_error(e) return None @staticmethod def normalize_url(host, port, path, ssl=False): if ssl: url = "https://" else: url = "http://" url += "{}:{}{}".format(host, port, path) return url
class Sessions: def __init__(self): self.badges = Badges() self.local_storage = LocalStorage() def add_session(self, session_platform, session_type, session_host, session_port, session_object): if not self.local_storage.get("sessions"): self.local_storage.set("sessions", dict()) session_id = 0 if session_platform in self.local_storage.get("sessions").keys(): sessions = self.local_storage.get("sessions") session_id = len(sessions[session_platform]) sessions[session_platform][int(session_id)] = { 'type': session_type, 'host': session_host, 'port': session_port, 'object': session_object } else: sessions = { session_platform: { int(session_id): { 'type': session_type, 'host': session_host, 'port': session_port, 'object': session_object } } } self.local_storage.update("sessions", sessions) return session_id def check_session_exist(self, session_platform, session_id): sessions = self.local_storage.get("sessions") if sessions: if session_platform in sessions.keys(): if int(session_id) in sessions[session_platform].keys(): return True return False def spawn_interactive_connection(self, session_platform, session_id): sessions = self.local_storage.get("sessions") if self.check_session_exist(session_platform, session_id): self.badges.output_process("Interacting with session " + str(session_id) + "...") self.badges.output_success("Interactive connection spawned!") self.badges.output_information("Type commands below.\n") sessions[session_platform][int(session_id)]['object'].interact() else: self.badges.output_error("Invalid session given!") def close_session(self, session_platform, session_id): sessions = self.local_storage.get("sessions") if self.check_session_exist(session_platform, session_id): try: sessions[session_platform][int(session_id)]['object'].close() del sessions[session_platform][int(session_id)] if not sessions[session_platform]: del sessions[session_platform] self.local_storage.update("sessions", sessions) except Exception: self.badges.output_error("Failed to close session!") else: self.badges.output_error("Invalid session given!") def get_session(self, session_platform, session_type, session_id): sessions = self.local_storage.get("sessions") if self.check_session_exist(session_platform, session_id): if session_type == sessions[session_platform][int( session_id)]['type']: return sessions[session_platform][int(session_id)]['object'] self.badges.output_error("Session with invalid type!") return None return None
class Execute: def __init__(self): self.fmt = FMT() self.badges = Badges() self.local_storage = LocalStorage() self.modules = Modules() def execute_command(self, commands, arguments): if commands: if not self.execute_builtin_method(commands, arguments): if not self.execute_core_command(commands, arguments): if not self.execute_module_command(commands, arguments): if not self.execute_plugin_command( commands, arguments): self.badges.output_error("Unrecognized command: " + commands[0] + "!") def execute_from_file(self, input_file): if os.path.exists(input_file): file = open(input_file, 'r') file_text = file.read().split('\n') file.close() for line in file_text: commands = self.fmt.format_commands(line) arguments = commands[1:] self.execute_command(commands, arguments) def execute_builtin_method(self, commands, arguments): if commands[0][0] == '!': if len(commands[0]) > 1: commands[0] = commands[0].replace('!', '', 1) self.execute_system(commands) else: self.badges.output_usage("!<command>") return True return False def execute_system(self, commands): self.badges.output_process("Executing system command: " + commands[0] + "\n") try: subprocess.call(commands) except Exception: self.badges.output_error("Unrecognized system command: " + commands[0] + "!") def execute_core_command(self, commands, arguments): if commands[0] in self.local_storage.get("commands").keys(): command = self.local_storage.get("commands")[commands[0]] if (len(commands) - 1) < command.details['MinArgs']: self.badges.output_usage(command.details['Usage']) else: command.run(len(arguments), arguments) return True return False def execute_module_command(self, commands, arguments): if self.modules.check_current_module(): if hasattr(self.modules.get_current_module_object(), "commands"): if commands[0] in self.modules.get_current_module_object( ).commands.keys(): command_object = self.modules.get_current_module_object() command = self.modules.get_current_module_object( ).commands[commands[0]] self.parse_and_execute_command(commands, command, arguments, command_object) return True return False def execute_plugin_command(self, commands, arguments): if self.local_storage.get("loaded_plugins"): for plugin in self.local_storage.get("loaded_plugins").keys(): if hasattr( self.local_storage.get("loaded_plugins")[plugin], "commands"): for label in self.local_storage.get( "loaded_plugins")[plugin].commands.keys(): if commands[0] in self.local_storage.get( "loaded_plugins")[plugin].commands[label].keys( ): command_object = self.local_storage.get( "loaded_plugins")[plugin] command = command_object.commands[label][ commands[0]] self.parse_and_execute_command( commands, command, arguments, command_object) return True return False def parse_and_execute_command(self, commands, command, arguments, command_object): if hasattr(command_object, commands[0]): if (len(commands) - 1) < command['MinArgs']: self.badges.output_usage(command['Usage']) else: getattr(command_object, commands[0])(len(arguments), arguments) else: self.badges.output_error("Failed to execute command!")
class Modules: def __init__(self): self.types = Types() self.badges = Badges() self.sessions = Sessions() self.payloads = Payloads() self.local_storage = LocalStorage() self.importer = Importer() def check_exist(self, name): if self.check_style(name): all_modules = self.local_storage.get("modules") if all_modules: for database in all_modules.keys(): modules = all_modules[database] category = self.get_category(name) platform = self.get_platform(name) if category in modules.keys(): if platform in modules[category].keys(): module = self.get_name(name) if module in modules[category][platform].keys(): return True return False def check_imported(self, name): imported_modules = self.local_storage.get("imported_modules") if imported_modules: if name in imported_modules.keys(): return True return False @staticmethod def check_style(name): if len(name.split('/')) >= 3: return True return False def check_current_module(self): if self.local_storage.get("current_module"): if len(self.local_storage.get("current_module")) > 0: return True return False def get_module_object(self, category, platform, name): module_full_name = self.get_full_name(category, platform, name) if self.check_exist(module_full_name): database = self.get_database(module_full_name) return self.local_storage.get( "modules")[database][category][platform][name] return None def get_current_module_object(self): if self.check_current_module(): return self.local_storage.get_array( "current_module", self.local_storage.get("current_module_number")) return None def get_current_module_platform(self): if self.check_current_module(): return self.local_storage.get_array( "current_module", self.local_storage.get( "current_module_number")).details['Platform'] return None def get_current_module_name(self): if self.check_current_module(): return self.local_storage.get_array( "current_module", self.local_storage.get( "current_module_number")).details['Module'] return None def get_database(self, name): if self.check_style(name): all_modules = self.local_storage.get("modules") if all_modules: for database in all_modules.keys(): modules = all_modules[database] category = self.get_category(name) platform = self.get_platform(name) if category in modules.keys(): if platform in modules[category].keys(): module = self.get_name(name) if module in modules[category][platform].keys(): return database return None def get_category(self, name): if self.check_style(name): return name.split('/')[0] return None def get_platform(self, name): if self.check_style(name): return name.split('/')[1] return None def get_name(self, name): if self.check_style(name): return os.path.join(*(name.split(os.path.sep)[2:])) return None @staticmethod def get_full_name(category, platform, name): return category + '/' + platform + '/' + name def compare_types(self, value_type, value): if value_type and not value_type.lower == 'all': if value_type.lower() == 'mac': if not self.types.is_mac(value): self.badges.output_error( "Invalid value, expected valid MAC!") return False if value_type.lower() == 'ip': if not self.types.is_ip(value): self.badges.output_error( "Invalid value, expected valid IP!") return False if value_type.lower() == 'ipv4': if not self.types.is_ipv4(value): self.badges.output_error( "Invalid value, expected valid IPv4!") return False if value_type.lower() == 'ipv6': if not self.types.is_ipv6(value): self.badges.output_error( "Invalid value, expected valid IPv6!") return False if value_type.lower() == 'ipv4_range': if not self.types.is_ipv4_range(value): self.badges.output_error( "Invalid value, expected valid IPv4 range!") return False if value_type.lower() == 'ipv6_range': if not self.types.is_ipv6_range(value): self.badges.output_error( "Invalid value, expected valid IPv6 range!") return False if value_type.lower() == 'port': if not self.types.is_port(value): self.badges.output_error( "Invalid value, expected valid port!") return False if value_type.lower() == 'port_range': if not self.types.is_port_range(value): self.badges.output_error( "Invalid value, expected valid port range!") return False if value_type.lower() == 'number': if not self.types.is_number(value): self.badges.output_error( "Invalid value, expected valid number!") return False if value_type.lower() == 'integer': if not self.types.is_integer(value): self.badges.output_error( "Invalid value, expected valid integer!") return False if value_type.lower() == 'float': if not self.types.is_float(value): self.badges.output_error( "Invalid value, expected valid float!") return False if value_type.lower() == 'boolean': if not self.types.is_boolean(value): self.badges.output_error( "Invalid value, expected valid boolean!") return False if value_type.lower() == 'session': module_platform = self.get_current_module_platform() if not self.sessions.check_exist(module_platform, value): return False return True def set_current_module_option(self, option, value): if self.check_current_module(): current_module = self.get_current_module_object() if not hasattr(current_module, "options") and not hasattr( current_module, "payload"): self.badges.output_warning("Module has no options.") return if hasattr(current_module, "payload") and option.lower() == "payload": if self.payloads.check_exist(value): module_name = self.get_current_module_name() platform = self.payloads.get_platform(value) architecture = self.payloads.get_architecture(value) name = self.payloads.get_name(value) payload = self.payloads.get_payload_object( platform, architecture, name) module_payload = current_module.payload valid = 0 if module_payload['Types'] is None or payload[ 'Type'] in module_payload['Types']: valid += 1 if module_payload['Categories'] is None or payload[ 'Category'] in module_payload['Categories']: valid += 1 if module_payload['Platforms'] is None or payload[ 'Platform'] in module_payload['Platforms']: valid += 1 if module_payload['Architectures'] is None or payload[ 'Architecture'] in module_payload['Architectures']: valid += 1 if valid == 4: if not self.payloads.add_payload( module_name, platform, architecture, name): self.badges.output_error( "Invalid payload, expected valid payload!") return self.badges.output_information(option + " ==> " + value) self.local_storage.set_module_payload( "current_module", self.local_storage.get("current_module_number"), value) return self.badges.output_error( "Incompatible payload type, category or platform!") return self.badges.output_error( "Invalid payload, expected valid payload!") return if hasattr(current_module, "options"): if option in current_module.options.keys(): value_type = current_module.options[option]['Type'] if self.compare_types(value_type, value): self.badges.output_information(option + " ==> " + value) self.local_storage.set_module_option( "current_module", self.local_storage.get("current_module_number"), option, value) return if hasattr(current_module, "payload"): current_payload = self.payloads.get_current_payload() if current_payload and hasattr(current_payload, "options"): if option in current_payload.options.keys(): value_type = current_payload.options[option]['Type'] if self.compare_types(value_type, value): self.badges.output_information(option + " ==> " + value) self.local_storage.set_payload_option( current_module.details['Module'], current_payload.details['Payload'], option, value) else: self.badges.output_error("Unrecognized option!") else: self.badges.output_error("Unrecognized option!") else: self.badges.output_warning("No module selected.") def import_module(self, category, platform, name): modules = self.get_module_object(category, platform, name) try: module_object = self.importer.import_module(modules['Path']) if not self.local_storage.get("imported_modules"): self.local_storage.set("imported_modules", dict()) self.local_storage.update( "imported_modules", {self.get_full_name(category, platform, name): module_object}) except Exception: return None return module_object def add_module(self, category, platform, name): modules = self.get_module_object(category, platform, name) not_installed = list() for dependence in modules['Dependencies']: if not self.importer.import_check(dependence): not_installed.append(dependence) if not not_installed: imported_modules = self.local_storage.get("imported_modules") full_name = self.get_full_name(category, platform, name) if self.check_imported(full_name): module_object = imported_modules[full_name] self.add_to_global(module_object) else: module_object = self.import_module(category, platform, name) if module_object: if hasattr(module_object, "payload"): payload_name = module_object.payload['Value'] platform = self.payloads.get_platform(payload_name) architecture = self.payloads.get_architecture( payload_name) name = self.payloads.get_name(payload_name) self.badges.output_process("Using default payload " + payload_name + "...") if self.payloads.check_exist(payload_name): if self.payloads.add_payload( full_name, platform, architecture, name): self.add_to_global(module_object) return self.badges.output_error("Invalid default payload!") return self.add_to_global(module_object) else: self.badges.output_error( "Failed to select module from database!") else: self.badges.output_error( "Module depends this dependencies which is not installed:") for dependence in not_installed: self.badges.output_empty(" * " + dependence) def add_to_global(self, module_object): if self.check_current_module(): self.local_storage.add_array("current_module", '') self.local_storage.set( "current_module_number", self.local_storage.get("current_module_number") + 1) self.local_storage.set_array( "current_module", self.local_storage.get("current_module_number"), module_object) else: self.local_storage.set("current_module", []) self.local_storage.set("current_module_number", 0) self.local_storage.add_array("current_module", '') self.local_storage.set_array( "current_module", self.local_storage.get("current_module_number"), module_object)
class Jobs: def __init__(self): self.exceptions = Exceptions() self.tables = Tables() self.badges = Badges() self.local_storage = LocalStorage() self.modules = Modules() self.job_process = None def stop_dead(self): jobs = self.local_storage.get("jobs") if jobs: for job_id in list(jobs): if not jobs[job_id]['job_process'].is_alive(): self.delete_job(job_id) def check_jobs(self): if not self.local_storage.get("jobs"): return True return False def check_module_job(self, module_name): jobs = self.local_storage.get("jobs") if jobs: for job_id in jobs.keys(): if jobs[job_id]['module_name'] == module_name: return True return False def exit_jobs(self): if self.check_jobs(): return True self.badges.output_warning("You have some running jobs.") if self.badges.input_question("Exit anyway? [y/N] ").lower() in [ 'yes', 'y' ]: self.badges.output_process("Stopping all jobs...") self.stop_all_jobs() return True return False def stop_all_jobs(self): if not self.check_jobs(): for job_id in list(self.local_storage.get("jobs").keys()): self.delete_job(job_id) def stop_job(self, job): if job.is_alive(): exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(job.ident), exc) if res == 0: raise self.exceptions.GlobalException if res > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(job.ident, None) raise self.exceptions.GlobalException def start_job(self, job_function, job_arguments): self.job_process = threading.Thread(target=job_function, args=job_arguments) self.job_process.setDaemon(True) self.job_process.start() def delete_job(self, job_id): if not self.check_jobs(): job_id = int(job_id) if job_id in list(self.local_storage.get("jobs").keys()): try: self.stop_job( self.local_storage.get("jobs")[job_id]['job_process']) self.local_storage.delete_element("jobs", job_id) except Exception: self.badges.output_error("Failed to stop job!") else: self.badges.output_error("Invalid job id!") else: self.badges.output_error("Invalid job id!") def create_job(self, job_name, module_name, job_function, job_arguments=()): self.start_job(job_function, job_arguments) if not self.local_storage.get("jobs"): self.local_storage.set("jobs", dict()) job_id = len(self.local_storage.get("jobs")) job_data = { job_id: { 'job_name': job_name, 'module_name': module_name, 'job_process': self.job_process } } self.local_storage.update("jobs", job_data) return job_id