Beispiel #1
0
    def __init__(self, username, password, host='127.0.0.1', port=8008):
        self.string_tools = StringTools()

        self.fmt = FMT()
        self.execute = Execute()

        self.jobs = Jobs()
        self.options = Options()
        self.modules = Modules()
        self.payloads = Payloads()
        self.sessions = Sessions()
        self.config = Config()

        self.host = host
        self.port = int(port)

        self.username = username
        self.password = password

        self.token = self.string_tools.random_string(32)
Beispiel #2
0
class HatSploitCommand(Command):
    jobs = Jobs()
    sessions = Sessions()

    details = {
        'Category': "core",
        'Name': "exit",
        'Authors': [
            'Ivan Nikolsky (enty8080) - command developer'
        ],
        'Description': "Exit HatSploit Framework.",
        'Usage': "exit",
        'MinArgs': 0
    }

    def run(self, argc, argv):
        if self.jobs.exit_jobs() and self.sessions.close_sessions():
            sys.exit(0)
Beispiel #3
0
class HatSploitCommand(Command):
    sessions = Sessions()
    show = Show()

    details = {
        'Category': "sessions",
        'Name': "sessions",
        'Authors': [
            'Ivan Nikolsky (enty8080) - command developer'
        ],
        'Description': "Manage opened sessions.",
        'Usage': "sessions <option> [arguments]",
        'MinArgs': 1,
        'Options': {
            '-l': ['', "List all opened sessions."],
            '-i': ['<id>', "Interact with specified session."],
            '-d': ['<id> <remote_file> <local_path>', "Download file from session."],
            '-u': ['<id> <local_file> <remote_path>', "Upload file to session."],
            '-c': ['<id>', "Close specified session."],
            '--auto-interaction': ['[on|off]', "Interact with session after opening."]
        }
    }

    def run(self, argc, argv):
        if argv[1] == '-l':
            self.show.show_sessions()
        elif argv[1] == '-c':
            self.sessions.close_session(argv[2])
        elif argv[1] == '-i':
            self.sessions.interact_with_session(argv[2])
        elif argv[1] == '-d':
            self.sessions.session_download(argv[2], argv[3], argv[4])
        elif argv[1] == '-u':
            self.sessions.session_upload(argv[2], argv[3], argv[4])
        elif argv[1] == '--auto-interaction':
            if argv[2] == 'on':
                self.sessions.enable_auto_interaction()
            elif argv[2] == 'off':
                self.sessions.disable_auto_interaction()
Beispiel #4
0
class Handler:
    blinder = Blinder()
    post = Post()
    post_tools = PostTools()
    server_handle = Handle()

    sessions = Sessions()
    modules = Modules()
    jobs = Jobs()
    types = TypeTools()
    badges = Badges()
    local_storage = LocalStorage()

    def do_job(self, payload_type, target, args):
        if payload_type == 'one_side':
            target(*args)
        else:
            self.jobs.create_job(
                None,
                None,
                target,
                args,
                True
            )

    def ensure_linemax(self, payload, linemax):
        min_size = 10000
        max_size = 100000

        if len(payload) >= max_size and linemax not in range(min_size, max_size):
            self.badges.print_process(f"Ensuring payload size ({str(len(payload))} bytes)...")
            linemax = max_size

        return linemax

    def send(self, sender, payload, args={}):
        if isinstance(payload, bytes):
            self.badges.print_process(f"Sending payload stage ({str(len(payload))} bytes)...")
        else:
            self.badges.print_process("Sending command payload stage...")

        self.post_tools.post_command(sender, payload, args)

    def open_session(self, host, port, session_platform, session_architecture, session_type, session, action=None):
        session_id = self.sessions.add_session(session_platform, session_architecture, session_type,
                                               host, port, session)
        time = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")

        self.badges.print_success(f"{session_type.title()} session {str(session_id)} opened at {time}!")

        if action:
            action()

        if self.local_storage.get("auto_interaction"):
            self.sessions.interact_with_session(session_id)

    def module_handle(self, host=None, sender=None, args={}, concat=None, location=None,
                      background=None, method=None, timeout=None, linemax=100, ensure=False,
                      on_session=None):
        module = self.modules.get_current_module_object()
        rhost = host

        options = module.handler
        payload = module.payload

        if 'BLINDER' in options:
            if options['BLINDER'].lower() in ['yes', 'y']:
                if sender is not None:
                    self.handle(
                        sender=sender,
                        args=args,
                        blinder=True
                    )

                    return True

        stage = payload['Payload'] if method != 'raw' else payload['Raw']

        if payload['Details']['Type'] == 'bind_tcp':
            host = options['RBHOST']
            port = options['RBPORT']

        elif payload['Details']['Type'] == 'reverse_tcp':
            host = options['LHOST']
            port = options['LPORT']

        else:
            host, port = None, None

        if 'Session' in payload['Details']:
            session = payload['Details']['Session']
        else:
            session = None

        if 'Arguments' in payload['Details']:
            arguments = payload['Details']['Arguments']
        else:
            arguments = None

        platform = payload['Details']['Platform']
        architecture = payload['Details']['Architecture']

        if platform in self.types.platforms:
            module_platform = module.details['Platform']

            if module_platform not in self.types.platforms:
                platform = module_platform

        return self.handle(
            payload=stage,
            sender=sender,

            host=host,
            port=port,

            rhost=rhost,

            payload_category=payload['Details']['Category'],
            payload_type=payload['Details']['Type'],

            args=args,
            concat=concat,
            location=location,
            background=background,

            method=method,
            timeout=timeout,
            linemax=linemax,

            platform=platform,
            architecture=architecture,

            ensure=ensure,
            blinder=False,

            session=session,
            arguments=arguments,
            on_session=on_session
        )

    def handle(self, payload=None, sender=None, host=None, port=None, rhost=None, payload_category='stager',
               payload_type='one_side', args={}, concat=None, location=None, background=None,
               method=None, timeout=None, linemax=100, platform='generic', architecture='generic',
               ensure=False, blinder=False, session=None, arguments=None, on_session=None):

        if blinder:
            self.blinder.shell(sender, args)
            return True

        if not self.send_payload(
            payload=payload,
            sender=sender,

            payload_category=payload_category,
            payload_type=payload_type,

            args=args,
            concat=concat,
            location=location,
            background=background,

            method=method,
            linemax=linemax,

            platform=platform,
            ensure=ensure,
            arguments=arguments
        ):
            self.badges.print_error("Failed to send payload stage!")
            return False

        remote = self.handle_session(
            host=host,
            port=port,

            payload_type=payload_type,
            session=session,
            timeout=timeout
        )

        if not remote:
            self.badges.print_warning("Payload sent but no session was opened.")
            return True

        session_type = remote[0].details['Type']

        remote[0].details['Post'] = method
        remote[0].details['Platform'] = platform
        remote[0].details['Architecture'] = architecture

        if remote[1] not in ('127.0.0.1', '0.0.0.0'):
            rhost = remote[1]

        self.open_session(rhost, port, platform, architecture, session_type, remote[0], on_session)
        return True

    def module_handle_session(self, payload_type='one_side', session=None, timeout=None):
        module = self.modules.get_current_module_object()

        options = module.handler
        session = session if session is not None else HatSploitSession

        if payload_type == 'reverse_tcp':
            new_session, host = self.server_handle.listen_session(
                options['LHOST'],
                options['LPORT'],
                session, timeout
            )

            if not new_session and not host:
                return None

        elif payload_type == 'bind_tcp':
            host = options['RBHOST']

            new_session = self.server_handle.connect_session(
                options['RBHOST'],
                options['RBPORT'],
                session, timeout
            )

            if not new_session:
                return None

        else:
            return None

        return new_session, host

    def handle_session(self, host=None, port=None, payload_type='one_side', session=None, timeout=None):
        session = session if session is not None else HatSploitSession

        if payload_type == 'reverse_tcp':
            if not host or not port:
                return None

            new_session, host = self.server_handle.listen_session(host, port, session, timeout)

            if not new_session and not host:
                return None

        elif payload_type == 'bind_tcp':
            if not host or not port:
                return None

            new_session = self.server_handle.connect_session(host, port, session, timeout)

            if not new_session:
                return None

        elif payload_type == 'one_side':
            return None

        else:
            self.badges.print_error("Invalid payload type!")
            return None

        return new_session, host

    def send_payload(self, payload=None, sender=None, payload_category='stager', payload_type='one_side',
                     args={}, concat=None, location=None, background=None, method=None, linemax=100,
                     platform='generic', ensure=False, arguments=None):
        if payload is None:
            self.badges.print_error("Payload stage is not found!")
            return False

        if sender is None:
            self.badges.print_error("No sender found!")
            return False

        if ensure:
            linemax = self.ensure_linemax(payload['Payload'], linemax)

        if payload_category == 'stager':
            self.badges.print_process(f"Sending payload stage ({str(len(payload))} bytes)...")

            if method != 'raw':
                self.do_job(
                    payload_type,
                    self.post.post,
                    [
                        platform,
                        sender,
                        payload,
                        args,
                        arguments,
                        method,
                        location,
                        concat,
                        background,
                        linemax
                    ]
                )

                return True

        if payload_category == 'singler' or method == 'raw':
            self.do_job(
                payload_type,
                self.send,
                [
                    sender,
                    payload,
                    args
                ]
            )

        else:
            self.badges.print_error("Invalid payload category!")
            return False

        return True
Beispiel #5
0
class Console:
    exceptions = Exceptions()
    execute = Execute()
    loader = Loader()

    fmt = FMT()
    badges = Badges()

    completer = Completer()
    banner = Banner()
    tip = Tip()

    loot = Loot()

    config = Config()
    jobs = Jobs()
    options = Options()
    sessions = Sessions()
    modules = Modules()
    payloads = Payloads()
    local_storage = LocalStorage()

    history = config.path_config['history_path']
    prompt = config.core_config['details']['prompt']

    handler_options = {
        'Module': {},
        'Payload': {}
    }

    completion = None

    def check_install(self):
        if os.path.exists(self.config.path_config['root_path']):
            workspace = self.config.path_config['user_path']
            loot = self.config.path_config['loot_path']

            if not os.path.isdir(workspace):
                self.badges.print_process(f"Creating workspace at {workspace}...")
                os.mkdir(workspace)

            if not os.path.isdir(loot):
                self.loot.create_loot()

            return True
        self.badges.print_error("HatSploit is not installed!")
        self.badges.print_information("Consider running installation.")
        return False

    def start_hsf(self):
        try:
            self.loader.load_all()
        except Exception:
            sys.exit(1)

    def update_events(self):
        current_module = self.modules.get_current_module_object()
        current_payload = self.payloads.get_current_payload()

        self.jobs.stop_dead()
        self.sessions.close_dead()

        self.options.add_handler_options(current_module, current_payload)

    def launch_menu(self):
        while True:
            try:
                if not self.modules.check_current_module():
                    prompt = f'({self.prompt})> '
                else:
                    current_module = self.modules.get_current_module_object()

                    category = current_module.details['Category']
                    name = current_module.details['Name']

                    prompt = f'({self.prompt}: {category}: %red{name}%end)> '
                commands = self.badges.input_empty(prompt)

                self.update_events()
                self.execute.execute_command(commands)
                self.update_events()

                if self.local_storage.get("history"):
                    readline.write_history_file(self.history)

            except (KeyboardInterrupt, EOFError, self.exceptions.GlobalException):
                pass
            except Exception as e:
                self.badges.print_error(f"An error occurred: {str(e)}!")

    def enable_history_file(self):
        if not os.path.exists(self.history):
            open(self.history, 'w').close()
        readline.read_history_file(self.history)

    def launch_history(self):
        readline.set_auto_history(False)

        using_history = self.local_storage.get("history")
        if using_history:
            readline.set_auto_history(True)
            self.enable_history_file()

        readline.set_completer(self.completer.completer)
        readline.set_completer_delims(" \t\n;")

        readline.parse_and_bind("tab: complete")

    def launch_shell(self):
        version = self.config.core_config['details']['version']
        codename = self.config.core_config['details']['codename']

        if self.config.core_config['console']['clear']:
            self.badges.print_empty("%clear", end='')

        if self.config.core_config['console']['banner']:
            self.banner.print_random_banner()

        if self.config.core_config['console']['header']:
            plugins = self.local_storage.get("plugins")
            modules = self.local_storage.get("modules")
            payloads = self.local_storage.get("payloads")

            plugins_total = 0
            modules_total = 0
            payloads_total = 0

            if payloads:
                for database in payloads:
                    payloads_total += len(payloads[database])
            if plugins:
                for database in plugins:
                    plugins_total += len(plugins[database])
            if modules:
                for database in modules:
                    modules_total += len(modules[database])

            header = ""
            header += "%end"
            if codename:
                header += f"    --=( %yellowHatSploit Framework {version} {codename}%end\n"
            else:
                header += f"    --=( %yellowHatSploit Framework {version}%end\n"
            header += "--==--=( Developed by EntySec (%linehttps://entysec.netlify.app/%end)\n"
            header += f"    --=( {modules_total} modules | {payloads_total} payloads | {plugins_total} plugins"
            header += "%end"

            self.badges.print_empty(header)

        if self.config.core_config['console']['tip']:
            self.tip.print_random_tip()

    def shell(self):
        self.start_hsf()
        self.launch_history()
        self.launch_shell()
        self.launch_menu()

    def script(self, input_files, do_shell=False):
        self.start_hsf()
        self.launch_shell()

        for input_file in input_files:
            if os.path.exists(input_file):
                file = open(input_file, 'r')
                file_text = file.read().split('\n')
                file.close()

                for line in file_text:
                    commands = self.fmt.format_commands(line)

                    self.add_handler_options()
                    self.jobs.stop_dead()

                    self.execute.execute_command(commands)

        if do_shell:
            self.launch_history()
            self.launch_menu()
Beispiel #6
0
class API:
    def __init__(self, username, password, host='127.0.0.1', port=8008):
        self.string_tools = StringTools()

        self.fmt = FMT()
        self.execute = Execute()

        self.jobs = Jobs()
        self.options = Options()
        self.modules = Modules()
        self.payloads = Payloads()
        self.sessions = Sessions()
        self.config = Config()

        self.host = host
        self.port = int(port)

        self.username = username
        self.password = password

        self.token = self.string_tools.random_string(32)

    def run(self):
        cli.show_server_banner = lambda *_: None
        rest_api = Flask("HatSploit")

        log = logging.getLogger("werkzeug")
        log.setLevel(logging.ERROR)

        @rest_api.before_request
        def validate_token():
            if request.path not in ['/login', '/']:
                token = request.form['token']

                if token != self.token:
                    return make_response('', 401)

                current_module = self.modules.get_current_module_object()
                current_payload = self.payloads.get_current_payload()

                self.jobs.stop_dead()
                self.sessions.close_dead()

                self.options.add_handler_options(current_module,
                                                 current_payload)

        @rest_api.route('/', methods=['GET', 'POST'])
        def api():
            version = self.config.core_config['details']['version']
            codename = self.config.core_config['details']['codename']

            response = "HatSploit REST API server\n"
            response += f"Version: {version}\n"

            if codename:
                response += f"Codename: {codename}\n"

            return make_response(f"<pre>{response}</pre>", 200)

        @rest_api.route('/login', methods=['POST'])
        def login_api():
            username = request.form['username']
            password = request.form['password']

            if username == self.username and password == self.password:
                return jsonify(token=self.token)
            return make_response('', 401)

        @rest_api.route('/execute', methods=['POST'])
        def commands_api():
            command = request.form['command']
            commands = self.fmt.format_commands(command)

            self.execute.execute_command(commands)

        @rest_api.route('/payloads', methods=['POST'])
        def payloads_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'list':
                data = {}
                all_payloads = self.payloads.get_payloads()
                number = 0

                for database in sorted(all_payloads):
                    payloads = all_payloads[database]

                    for payload in sorted(payloads):
                        data.update({
                            number: {
                                'Category': payloads[payload]['Category'],
                                'Payload': payloads[payload]['Payload'],
                                'Rank': payloads[payload]['Rank'],
                                'Name': payloads[payload]['Name'],
                                'Platform': payloads[payload]['Platform']
                            }
                        })

                        number += 1

                return jsonify(data)
            return make_response('', 200)

        @rest_api.route('/modules', methods=['POST'])
        def modules_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'list':
                data = {}
                all_modules = self.modules.get_modules()
                number = 0

                for database in sorted(all_modules):
                    modules = all_modules[database]

                    for module in sorted(modules):
                        data.update({
                            number: {
                                'Category': modules[module]['Category'],
                                'Module': modules[module]['Module'],
                                'Rank': modules[module]['Rank'],
                                'Name': modules[module]['Name'],
                                'Platform': modules[module]['Platform']
                            }
                        })

                        number += 1

                return jsonify(data)

            if action == 'options':
                data = {}
                current_module = self.modules.get_current_module_object()

                if current_module:
                    options = current_module.options

                    for option in sorted(options):
                        value, required = options[option]['Value'], options[
                            option]['Required']
                        if required:
                            required = 'yes'
                        else:
                            required = 'no'
                        if not value and value != 0:
                            value = ""
                        data.update({
                            option: {
                                'Value': value,
                                'Required': required,
                                'Description': options[option]['Description']
                            }
                        })

                    if hasattr(current_module, "payload"):
                        current_payload = self.payloads.get_current_payload()

                        if hasattr(current_payload, "options"):
                            options = current_payload.options

                            for option in sorted(options):
                                value, required = options[option][
                                    'Value'], options[option]['Required']
                                if required:
                                    required = 'yes'
                                else:
                                    required = 'no'
                                if not value and value != 0:
                                    value = ""
                                data.update({
                                    option: {
                                        'Value':
                                        value,
                                        'Required':
                                        required,
                                        'Description':
                                        options[option]['Description']
                                    }
                                })

                return jsonify(data)

            if action == 'use':
                self.modules.use_module(request.form['module'])

            if action == 'set':
                self.modules.set_current_module_option(request.form['option'],
                                                       request.form['value'])

            if action == 'run':
                current_module = self.modules.get_current_module_object()

                if current_module:
                    self.jobs.create_job(current_module.details['Name'],
                                         current_module.details['Module'],
                                         self.modules.run_current_module)

            return make_response('', 200)

        @rest_api.route('/sessions', methods=['POST'])
        def sessions_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'close':
                session = request.form['session']
                self.sessions.close_session(session)

            elif action == 'list':
                data = {}
                sessions = self.sessions.get_all_sessions()
                fetch = 'all'

                if 'fetch' in request.form:
                    fetch = request.form['fetch']

                if sessions:
                    for session in sessions:
                        if fetch == 'all':
                            data.update({
                                session: {
                                    'platform':
                                    sessions[session]['platform'],
                                    'architecture':
                                    sessions[session]['architecture'],
                                    'type':
                                    sessions[session]['type'],
                                    'host':
                                    sessions[session]['host'],
                                    'port':
                                    sessions[session]['port']
                                }
                            })
                        elif fetch == sessions[session]['platform']:
                            data.update({
                                session: {
                                    'platform':
                                    sessions[session]['platform'],
                                    'architecture':
                                    sessions[session]['architecture'],
                                    'type':
                                    sessions[session]['type'],
                                    'host':
                                    sessions[session]['host'],
                                    'port':
                                    sessions[session]['port']
                                }
                            })

                return jsonify(data)

            elif action == 'execute':
                session = request.form['session']
                session = self.sessions.get_session(session)

                if session:
                    if request.form['output'].lower() in ['yes', 'y']:
                        output = session.send_command(request.form['command'],
                                                      output=True)
                        return jsonify(output=output)

                    session.send_command(request.form['command'])

            elif action == 'download':
                if 'local_path' in request.form:
                    local_path = request.form['local_path']
                else:
                    local_path = self.config.path_config['loot_path']

                self.sessions.session_download(request.form['session'],
                                               request.form['remote_file'],
                                               local_path)

            elif action == 'upload':
                self.session.session_upload(request.form['session'],
                                            request.form['local_file'],
                                            request.form['remote_path'])

            return make_response('', 200)

        rest_api.run(host=self.host, port=self.port)
Beispiel #7
0
class Modules:
    types = TypeTools()
    badges = Badges()
    sessions = Sessions()
    payloads = Payloads()
    local_storage = LocalStorage()
    importer = Importer()

    def get_modules(self):
        return self.local_storage.get("modules")

    def get_imported_modules(self):
        return self.local_storage.get("imported_modules")

    def modules_completer(self, text):
        modules = self.get_modules()
        matches = []

        if modules:
            for database in modules:
                for module in modules[database]:
                    if module.startswith(text):
                        matches.append(module)

        return matches

    def check_exist(self, name):
        all_modules = self.get_modules()
        if all_modules:
            for database in all_modules:
                modules = all_modules[database]

                if name in modules:
                    return True
        return False

    def check_imported(self, name):
        imported_modules = self.get_imported_modules()
        if imported_modules:
            if name in imported_modules:
                return True
        return False

    def check_current_module(self):
        if self.local_storage.get("current_module"):
            if len(self.local_storage.get("current_module")) > 0:
                return True
        return False

    def check_if_already_used(self, module):
        if self.check_current_module():
            if module == self.get_current_module_name():
                return True
        return False

    def get_module_object(self, name):
        if self.check_exist(name):
            database = self.get_database(name)
            return self.get_modules()[database][name]
        return None

    def get_current_module_object(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get("current_module_number"))
        return None

    def get_current_module_platform(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get(
                    "current_module_number")).details['Platform']
        return None

    def get_current_module_name(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get(
                    "current_module_number")).details['Module']
        return None

    def get_database(self, name):
        all_modules = self.get_modules()
        if all_modules:
            for database in all_modules:
                modules = all_modules[database]

                if name in modules:
                    return database
        return None

    def compare_type(self, name, value, checker, module=True):
        value = str(value)

        if value.startswith('file:') and len(value) > 5 and module:
            file = value.split(':')[1]

            if not os.path.isfile(file):
                self.badges.print_error(f"Local file: {file}: does not exist!")
                return False

            with open(file, 'r') as f:
                for line in f.read().split('\n'):
                    if line.strip():
                        if not checker(line.strip()):
                            self.badges.print_error(
                                f"File contains invalid value, expected valid {name}!"
                            )
                            return False
            return True

        if not checker(value):
            self.badges.print_error(f"Invalid value, expected valid {name}!")
            return False

        return True

    def compare_session(self, value_type, value):
        session = value_type.lower().replace(' ', '')
        session = session.split('->')

        session_platforms = []
        session_platform = self.get_current_module_platform()
        session_type = "shell"

        if len(session) == 2:
            if session[1].startswith('[') and session[1].endswith(']'):
                session_platforms = session[1][1:-1].split(',')
            else:
                session_type = session[1]

        elif len(session) == 3:
            if session[1].startswith('[') and session[1].endswith(']'):
                session_platforms = session[1][1:-1].split(',')
            else:
                session_type = session[1]

            if session[2].startswith('[') and session[2].endswith(']'):
                session_platforms = session[2][1:-1].split(',')
            else:
                session_type = session[2]

        if not session_platforms:
            if not self.sessions.check_exist(value, session_platform,
                                             session_type):
                self.badges.print_error(
                    "Invalid value, expected valid session!")
                return False
        else:
            session = 0
            for platform in session_platforms:
                if self.sessions.check_exist(value, platform.strip(),
                                             session_type):
                    session = 1
                    break

            if not session:
                self.badges.print_error(
                    "Invalid value, expected valid session!")
                return False

        return True

    def compare_types(self, value_type, value, module=True):
        if value_type and not value_type.lower == 'all':
            if value_type.lower() == 'mac':
                return self.compare_type("MAC", value, self.types.is_mac,
                                         module)

            if value_type.lower() == 'ip':
                return self.compare_type("IP", value, self.types.is_ip, module)

            if value_type.lower() == 'ipv4':
                return self.compare_type("IPv4", value, self.types.is_ipv4,
                                         module)

            if value_type.lower() == 'ipv6':
                return self.compare_type("IPv6", value, self.types.is_ipv6,
                                         module)

            if value_type.lower() == 'ipv4_range':
                return self.compare_type("IPv4 range", value,
                                         self.types.is_ipv4_range, module)

            if value_type.lower() == 'ipv6_range':
                return self.compare_type("IPv6 range", value,
                                         self.types.is_ipv6_range, module)

            if value_type.lower() == 'port':
                return self.compare_type("port", value, self.types.is_port,
                                         module)

            if value_type.lower() == 'port_range':
                return self.compare_type("port range", value,
                                         self.types.is_port_range, module)

            if value_type.lower() == 'number':
                return self.compare_type("number", value, self.types.is_number,
                                         module)

            if value_type.lower() == 'integer':
                return self.compare_type("integer", value,
                                         self.types.is_integer, module)

            if value_type.lower() == 'float':
                return self.compare_type("float", value, self.types.is_float,
                                         module)

            if value_type.lower() == 'boolean':
                return self.compare_type("boolean", value,
                                         self.types.is_boolean, module)

            if value_type.lower() == 'payload':
                current_module = self.get_current_module_object()
                module_name = self.get_current_module_name()
                module_payload = current_module.payload

                categories = module_payload['Categories']
                types = module_payload['Types']
                platforms = module_payload['Platforms']
                architectures = module_payload['Architectures']

                if self.payloads.check_module_compatible(
                        value, categories, types, platforms, architectures):
                    if self.payloads.add_payload(module_name, value):
                        return True

                self.badges.print_error(
                    "Invalid valud, expected valid payload!")
                return False

            if 'session' in value_type.lower():
                value = str(value)

                if value.startswith('file:') and len(value) > 5 and module:
                    file = value.split(':')[1]

                    if not os.path.isfile(file):
                        self.badges.print_error(
                            f"Local file: {file}: does not exist!")
                        return False

                    with open(file, 'r') as f:
                        for line in f.read().split('\n'):
                            if line.strip():
                                if not self.compare_session(
                                        value_type, line.strip()):
                                    self.badges.print_error(
                                        f"File contains invalid value, expected valid session!"
                                    )
                                    return False
                    return True

                return self.compare_session(value_type, value)

        return True

    def set_current_module_option(self, option, value):
        if self.check_current_module():
            current_module = self.get_current_module_object()

            if not hasattr(current_module, "options") and not hasattr(
                    current_module, "payload"):
                self.badges.print_warning("Module has no options.")
                return

            if hasattr(current_module, "options"):
                if option in current_module.options:
                    value_type = current_module.options[option]['Type']

                    if value_type == 'payload':
                        payloads_shorts = self.local_storage.get(
                            "payload_shorts")

                        if payloads_shorts:
                            if value.isdigit():
                                payload_number = int(value)

                                if payload_number in payloads_shorts:
                                    value = payloads_shorts[payload_number]

                    if self.compare_types(value_type, value):
                        self.badges.print_information(option + " ==> " + value)

                        if option.lower() == 'blinder':
                            if value.lower() in ['y', 'yes']:
                                current_module.payload['Value'] = None

                        if value_type == 'payload':
                            self.local_storage.set_module_payload(
                                "current_module",
                                self.local_storage.get(
                                    "current_module_number"), value)
                        else:
                            self.local_storage.set_module_option(
                                "current_module",
                                self.local_storage.get(
                                    "current_module_number"), option, value)
                    return

            if hasattr(current_module, "payload"):
                current_payload = self.payloads.get_current_payload()
                if current_payload and hasattr(current_payload, "options"):
                    if option in current_payload.options:
                        value_type = current_payload.options[option]['Type']

                        if self.compare_types(value_type, value, False):
                            self.badges.print_information(option + " ==> " +
                                                          value)
                            self.local_storage.set_payload_option(
                                current_module.details['Module'],
                                current_payload.details['Payload'], option,
                                value)
                    else:
                        self.badges.print_error("Unrecognized option!")
                else:
                    self.badges.print_error("Unrecognized option!")
            else:
                self.badges.print_error("Unrecognized option!")
        else:
            self.badges.print_warning("No module selected.")

    def import_module(self, name):
        modules = self.get_module_object(name)
        try:
            module_object = self.importer.import_module(modules['Path'])
            if not self.get_imported_modules():
                self.local_storage.set("imported_modules", {})
            self.local_storage.update("imported_modules",
                                      {name: module_object})
        except Exception:
            return None
        return module_object

    def add_module(self, name):
        imported_modules = self.get_imported_modules()

        if self.check_imported(name):
            module_object = imported_modules[name]
            self.add_to_global(module_object)
        else:
            module_object = self.import_module(name)
            if module_object:
                if hasattr(module_object, "payload"):
                    payload_name = module_object.payload['Value']

                    if payload_name:
                        self.badges.print_process(
                            f"Using default payload {payload_name}...")

                        if self.payloads.check_exist(payload_name):
                            if self.payloads.add_payload(name, payload_name):
                                self.add_to_global(module_object)
                            return

                        self.badges.print_error("Invalid default payload!")
                        return

                self.add_to_global(module_object)
            else:
                self.badges.print_error(
                    "Failed to select module from database!")

    def add_to_global(self, module_object):
        if self.check_current_module():
            self.local_storage.add_array("current_module", '')
            self.local_storage.set(
                "current_module_number",
                self.local_storage.get("current_module_number") + 1)
            self.local_storage.set_array(
                "current_module",
                self.local_storage.get("current_module_number"), module_object)
        else:
            self.local_storage.set("current_module", [])
            self.local_storage.set("current_module_number", 0)
            self.local_storage.add_array("current_module", '')
            self.local_storage.set_array(
                "current_module",
                self.local_storage.get("current_module_number"), module_object)

    def use_module(self, module):
        modules_shorts = self.local_storage.get("module_shorts")

        if modules_shorts:
            if module.isdigit():
                module_number = int(module)

                if module_number in modules_shorts:
                    module = modules_shorts[module_number]

        if not self.check_if_already_used(module):
            if self.check_exist(module):
                self.add_module(module)
            else:
                self.badges.print_error("Invalid module!")

    def go_back(self):
        if self.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)

    def entry_to_module(self, current_module):
        values = []

        for option in current_module.options:
            opt = current_module.options[option]
            val = str(opt['Value'])

            if val.startswith('file:') and len(val) > 5:
                file = val[5:]

                with open(file, 'r') as f:
                    vals = f.read().strip()
                    values.append(vals.split('\n'))

        if not values:
            current_module.run()
            return

        if not all(len(value) == len(values[0]) for value in values):
            self.badges.print_error(
                "All files should contain equal number of values!")
            return

        save = copy.deepcopy(current_module.options)
        for i in range(0, len(values[0])):
            count = 0

            for option in current_module.options:
                opt = current_module.options[option]
                val = str(opt['Value'])

                if val.startswith('file:') and len(val) > 5:
                    current_module.options[option]['Value'] = values[count][i]
                    count += 1

            try:
                current_module.run()
            except (KeyboardInterrupt, EOFError):
                pass

            current_module.options = save
            save = copy.deepcopy(current_module.options)

    def validate_options(self, module_object):
        current_module = module_object
        missed = ""

        if hasattr(current_module, "options"):
            for option in current_module.options:
                current_option = current_module.options[option]
                if not current_option['Value'] and current_option[
                        'Value'] != 0 and current_option['Required']:
                    missed += option + ', '

        return missed

    def run_current_module(self):
        if self.check_current_module():
            current_module = self.get_current_module_object()
            current_module_name = self.get_current_module_name()

            current_payload = self.payloads.get_current_payload()
            payload_data = {}

            missed = self.validate_options(current_module)
            if current_payload:
                missed += self.payloads.validate_options(current_payload)

            if missed:
                self.badges.print_error(
                    f"These options are failed to validate: {missed[:-2]}!")
            else:
                try:
                    if current_payload:
                        payload_data = self.payloads.run_payload(
                            current_payload)
                        for entry in payload_data:
                            current_module.payload[entry] = payload_data[entry]

                    self.badges.print_empty()
                    self.entry_to_module(current_module)

                    self.badges.print_success(
                        f"{current_module_name.split('/')[0].title()} module completed!"
                    )
                except (KeyboardInterrupt, EOFError):
                    self.badges.print_warning(
                        f"{current_module_name.split('/')[0].title()} module interrupted."
                    )

                except Exception as e:
                    self.badges.print_error(
                        f"An error occurred in module: {str(e)}!")
                    self.badges.print_error(
                        f"{current_module_name.split('/')[0].title()} module failed!"
                    )

                if current_payload:
                    for entry in payload_data:
                        del current_module.payload[entry]
        else:
            self.badges.print_warning("No module selected.")
Beispiel #8
0
class Show:
    jobs = Jobs()
    loot = Loot()
    local_storage = LocalStorage()
    modules = Modules()
    payloads = Payloads()
    sessions = Sessions()

    colors = Colors()
    badges = Badges()
    tables = Tables()

    def show_custom_commands(self, handler):
        commands_data = {}
        headers = ("Command", "Description")
        commands = handler

        for command in sorted(commands):
            label = commands[command].details['Category']
            commands_data[label] = []
        for command in sorted(commands):
            label = commands[command].details['Category']
            commands_data[label].append(
                (command, commands[command].details['Description']))
        for label in sorted(commands_data):
            self.tables.print_table(label.title() + " Commands", headers,
                                    *commands_data[label])

    def show_interface_commands(self):
        if self.local_storage.get("commands"):
            self.show_custom_commands(self.local_storage.get("commands"))
        else:
            self.badges.print_warning("No commands available.")

    def show_plugin_commands(self):
        for plugin in self.local_storage.get("loaded_plugins"):
            loaded_plugin = self.local_storage.get("loaded_plugins")[plugin]
            if hasattr(loaded_plugin, "commands"):
                commands_data = {}
                headers = ("Command", "Description")
                commands = loaded_plugin.commands
                for label in sorted(commands):
                    commands_data[label] = []
                    for command in sorted(commands[label]):
                        commands_data[label].append(
                            (command, commands[label][command]['Description']))
                for label in sorted(commands_data):
                    self.tables.print_table(label.title() + " Commands",
                                            headers, *commands_data[label])

    def show_module_commands(self):
        current_module = self.modules.get_current_module_object()
        if hasattr(current_module, "commands"):
            commands_data = []
            headers = ("Command", "Description")
            commands = current_module.commands
            for command in sorted(commands):
                commands_data.append(
                    (command, commands[command]['Description']))
            self.tables.print_table("Module Commands", headers, *commands_data)

    def show_all_commands(self):
        self.show_interface_commands()
        if self.modules.check_current_module():
            self.show_module_commands()
        if self.local_storage.get("loaded_plugins"):
            self.show_plugin_commands()

    def show_jobs(self):
        if self.local_storage.get("jobs"):
            jobs_data = []
            headers = ("ID", "Name", "Module")
            jobs = self.local_storage.get("jobs")
            for job_id in jobs:
                jobs_data.append((job_id, jobs[job_id]['job_name'],
                                  jobs[job_id]['module_name']))
            self.tables.print_table("Active Jobs", headers, *jobs_data)
        else:
            self.badges.print_warning("No running jobs available.")

    def show_loot(self):
        loots = self.loot.list_loot()
        if loots:
            headers = ("Loot", "Path", "Time")
            self.tables.print_table("Collected Loot", headers, *loots)
        else:
            self.badges.print_warning("No loot collected yet.")

    def show_module_databases(self):
        if self.local_storage.get("connected_module_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_module_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Module Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No module database connected.")

    def show_payload_databases(self):
        if self.local_storage.get("connected_payload_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_payload_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Payload Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No payload database connected.")

    def show_plugin_databases(self):
        if self.local_storage.get("connected_plugin_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_plugin_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Plugin Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No plugin database connected.")

    def show_plugins(self):
        all_plugins = self.local_storage.get("plugins")
        headers = ("Number", "Plugin", "Name")
        plugins_shorts = {}

        for database in sorted(all_plugins):
            number = 0
            plugins_data = []
            plugins = all_plugins[database]

            for plugin in sorted(plugins):
                plugins_data.append((number, plugins[plugin]['Plugin'],
                                     plugins[plugin]['Name']))
                plugins_shorts.update({number: plugins[plugin]['Plugin']})
                number += 1

            self.tables.print_table(f"Plugins ({database})", headers,
                                    *plugins_data)
            self.local_storage.set("plugin_shorts", plugins_shorts)

    def show_modules(self, category=None):
        all_modules = self.local_storage.get("modules")
        headers = ("Number", "Category", "Module", "Rank", "Name")
        modules_shorts = {}

        for database in sorted(all_modules):
            number = 0
            modules_data = []
            modules = all_modules[database]

            for module in sorted(modules):
                if category:
                    if category == modules[module]['Category']:
                        modules_data.append(
                            (number, modules[module]['Category'],
                             modules[module]['Module'],
                             modules[module]['Rank'], modules[module]['Name']))
                        modules_shorts.update(
                            {number: modules[module]['Module']})
                        number += 1
                else:
                    modules_data.append(
                        (number, modules[module]['Category'],
                         modules[module]['Module'], modules[module]['Rank'],
                         modules[module]['Name']))
                    modules_shorts.update({number: modules[module]['Module']})
                    number += 1

            if category:
                self.tables.print_table(
                    f"{category.title()} Modules ({database})", headers,
                    *modules_data)
            else:
                self.tables.print_table(f"Modules ({database})", headers,
                                        *modules_data)

            self.local_storage.set("module_shorts", modules_shorts)

    def show_payloads(self, category=None):
        all_payloads = self.local_storage.get("payloads")
        headers = ("Number", "Category", "Payload", "Rank", "Name")
        payloads_shorts = {}

        for database in sorted(all_payloads):
            number = 0
            payloads_data = []
            payloads = all_payloads[database]

            for payload in sorted(payloads):
                if category:
                    if category == payloads[payload]['Category']:
                        payloads_data.append(
                            (number, payloads[payload]['Category'],
                             payloads[payload]['Payload'],
                             payloads[payload]['Rank'],
                             payloads[payload]['Name']))
                        payloads_shorts.update(
                            {number: payloads[payload]['Payload']})
                        number += 1
                else:
                    payloads_data.append(
                        (number, payloads[payload]['Category'],
                         payloads[payload]['Payload'],
                         payloads[payload]['Rank'], payloads[payload]['Name']))
                    payloads_shorts.update(
                        {number: payloads[payload]['Payload']})
                    number += 1

            if category:
                self.tables.print_table(
                    f"{category.title()} Payloads ({database})", headers,
                    *payloads_data)
            else:
                self.tables.print_table(f"Payloads ({database})", headers,
                                        *payloads_data)

            self.local_storage.set("payload_shorts", payloads_shorts)

    def show_search_plugins(self, keyword):
        all_plugins = self.local_storage.get("plugins")
        plugins_shorts = {}

        if all_plugins:
            headers = ("Number", "Plugin", "Name")
            for database in all_plugins:
                number = 0
                plugins_data = []
                plugins = all_plugins[database]

                for plugin in sorted(plugins):
                    if keyword in plugins[plugin][
                            'Plugin'] or keyword in plugins[plugin]['Name']:
                        name = plugins[plugin]['Plugin'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = plugins[plugin]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        plugins_data.append((number, name, description))
                        plugins_shorts.update(
                            {number: plugins[plugin]['Plugin']})

                        number += 1
                if plugins_data:
                    self.tables.print_table(f"Plugins ({database})", headers,
                                            *plugins_data)
                    self.local_storage.set("plugin_shorts", plugins_shorts)

    def show_search_modules(self, keyword):
        all_modules = self.local_storage.get("modules")
        modules_shorts = {}

        if all_modules:
            headers = ("Number", "Module", "Rank", "Name")
            for database in all_modules:
                number = 0
                modules_data = []
                modules = all_modules[database]

                for module in sorted(modules):
                    if keyword in modules[module][
                            'Module'] or keyword in modules[module]['Name']:
                        name = modules[module]['Module'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = modules[module]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        modules_data.append(
                            (number, name, modules[module]['Rank'],
                             description))
                        modules_shorts.update(
                            {number: modules[module]['Module']})

                        number += 1
                if modules_data:
                    self.tables.print_table(f"Modules ({database})", headers,
                                            *modules_data)
                    self.local_storage.set("module_shorts", modules_shorts)

    def show_search_payloads(self, keyword):
        all_payloads = self.local_storage.get("payloads")
        payloads_shorts = {}

        if all_payloads:
            headers = ("Number", "Category", "Payload", "Rank", "Name")
            for database in all_payloads:
                number = 0
                payloads_data = []
                payloads = all_payloads[database]

                for payload in sorted(payloads):
                    if keyword in payloads[payload][
                            'Payload'] or keyword in payloads[payload]['Name']:
                        name = payloads[payload]['Payload'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = payloads[payload]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        payloads_data.append(
                            (number, payloads[payload]['Category'], name,
                             payloads[payload]['Rank'], description))
                        payloads_shorts.update(
                            {number: payloads[payload]['Payload']})

                        number += 1
                if payloads_data:
                    self.tables.print_table(f"Payloads ({database})", headers,
                                            *payloads_data)
                    self.local_storage.set("payload_shorts", payloads_shorts)

    def show_sessions(self):
        sessions = self.local_storage.get("sessions")
        if sessions:
            sessions_data = []
            headers = ("ID", "Platform", "Architecture", "Type", "Host",
                       "Port")
            for session_id in sessions:
                session_platform = sessions[session_id]['platform']
                session_architecture = sessions[session_id]['architecture']
                session_type = sessions[session_id]['type']
                host = sessions[session_id]['host']
                port = sessions[session_id]['port']

                sessions_data.append(
                    (session_id, session_platform, session_architecture,
                     session_type, host, port))
            self.tables.print_table("Opened Sessions", headers, *sessions_data)
        else:
            self.badges.print_warning("No opened sessions available.")

    def show_module_information(self, current_module_details):
        current_module = current_module_details

        authors = ""
        for author in current_module['Authors']:
            authors += author + ", "
        authors = authors[:-2]

        self.badges.print_information("Module information:")
        self.badges.print_empty("")

        if current_module['Name']:
            self.badges.print_empty("         Name: " + current_module['Name'])
        if current_module['Module']:
            self.badges.print_empty("       Module: " +
                                    current_module['Module'])
        if authors:
            self.badges.print_empty("      Authors: ")
            for author in current_module['Authors']:
                self.badges.print_empty("               " + author)
        if current_module['Description']:
            self.badges.print_empty("  Description: " +
                                    current_module['Description'])
        if current_module['Rank']:
            self.badges.print_empty("         Rank: " + current_module['Rank'])

        self.badges.print_empty("")

    def show_options(self):
        current_module = self.modules.get_current_module_object()

        if not current_module:
            self.badges.print_warning("No module selected.")
            return

        if not hasattr(current_module, "options") and not hasattr(
                current_module, "payload"):
            self.badges.print_warning("Module has no options.")
            return

        if not hasattr(current_module, "options") and not hasattr(
                self.payloads.get_current_payload(), "options"):
            self.badges.print_warning("Module has no options.")
            return

        if hasattr(current_module, "options"):
            options_data = []
            headers = ("Option", "Value", "Required", "Description")
            options = current_module.options

            for option in sorted(options):
                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.tables.print_table(
                f"Module Options ({current_module.details['Module']})",
                headers, *options_data)

        if hasattr(current_module, "payload"):
            if hasattr(self.payloads.get_current_payload(), "options"):
                options_data = []
                headers = ("Option", "Value", "Required", "Description")
                current_payload = self.payloads.get_current_payload()
                if current_payload:
                    for option in sorted(current_payload.options):
                        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.tables.print_table(
                        f"Payload Options ({current_payload.details['Payload']})",
                        headers, *options_data)