예제 #1
0
    def loadAutoScript(self):
        payloadFile = 'NotThing'
        try:
            payloadFile = open("autoTmpScript.rc",'r')    #automate file
        except:
            print_status('Don\'t have autoTmpScript.rc')
        if payloadFile != 'NotThing':            
            for mycommand in payloadFile.readlines():
                mycommand = mycommand.strip()

                print_status('%s'%(mycommand))
                if not len(mycommand) or mycommand.startswith('#'):
                    continue
                try:
                    command, args = self.parse_line(mycommand)
                    if not command:
                        continue
                    command_handler = self.get_command_handler(command)
                    command_handler(args)
                except RoutersploitException as err:
                    print_error(err)
                except EOFError:
                    print_info()
                    print_status("routersploit stopped")
                    break
                except KeyboardInterrupt:
                    print_info()
                finally:
                    printer_queue.join()
예제 #2
0
    def __handle_if_noninteractive(self, argv):
        noninteractive = False
        module = ""
        set_opts = []

        try:
            opts, args = getopt.getopt(argv, "hxm:s:", ["module=", "set="])
        except getopt.GetoptError:
            print_info("{} -m <module> -s \"<option> <value>\"".format(sys.argv[0]))
            sys.exit(2)

        for opt, arg in opts:
            if opt == "-h":
                print_info("{} -x -m <module> -s \"<option> <value>\"".format(sys.argv[0]))
                sys.exit(0)
            elif opt == "-x":
                noninteractive = True
            elif opt in ("-m", "--module"):
                module = arg
            elif opt in ("-s", "--set"):
                set_opts.append(arg)

        if noninteractive:
            self.command_use(module)

            for opt in set_opts:
                self.command_set(opt)

            self.command_exploit()

            sys.exit(0)
예제 #3
0
    def run(self):
        print_status("Generating payload")
        try:
            data = self.generate()
        except OptionValidationError as e:
            print_error(e)
            return

        if self.output == "elf":
            with open(self.filepath, 'wb+') as f:
                print_status("Building ELF payload")
                content = self.generate_elf(data)
                print_success("Saving file {}".format(self.filepath))
                f.write(content)
        elif self.output == "c":
            print_success("Bulding payload for C")
            content = self.generate_c(data)
            print_info(content)
        elif self.output == "python":
            print_success("Building payload for python")
            content = self.generate_python(data)
            print_info(content)
        else:
            raise OptionValidationError(
                "No such option as {}".format(self.output)
            )
예제 #4
0
 def _wrapper(self, *args, **kwargs):
     try:
         if args[1].count(" ") == space_number:
             return []
     except Exception as err:
         print_info(err)
     return wrapped_function(self, *args, **kwargs)
예제 #5
0
    def run(self):
        print_status("Generating payload")
        try:
            data = self.generate()
        except OptionValidationError as e:
            print_error(e)
            return

        if self.output == "elf":
            with open(self.filepath, "wb+") as f:
                print_status("Building ELF payload")
                content = self.generate_elf(data)
                print_success("Saving file {}".format(self.filepath))
                f.write(content)
        elif self.output == "c":
            print_success("Bulding payload for C")
            content = self.generate_c(data)
            print_info(content)
        elif self.output == "python":
            print_success("Building payload for python")
            content = self.generate_python(data)
            print_info(content)
        else:
            raise OptionValidationError(
                "No such option as {}".format(self.output)
            )

        return content
예제 #6
0
    def __handle_if_noninteractive(self, argv):
        noninteractive = False
        module = ""
        set_opts = []

        try:
            opts, args = getopt.getopt(argv, "hxm:s:", ["module=", "set="])
        except getopt.GetoptError:
            print_info("{} -m <module> -s \"<option> <value>\"".format(sys.argv[0]))
            sys.exit(2)

        for opt, arg in opts:
            if opt == "-h":
                print_info("{} -x -m <module> -s \"<option> <value>\"".format(sys.argv[0]))
                sys.exit(0)
            elif opt == "-x":
                noninteractive = True
            elif opt in ("-m", "--module"):
                module = arg
            elif opt in ("-s", "--set"):
                set_opts.append(arg)

        if noninteractive:
            self.command_use(module)

            for opt in set_opts:
                self.command_set(opt)

            self.command_exploit()

            sys.exit(0)
예제 #7
0
 def _wrapper(self, *args, **kwargs):
     try:
         if args[1].count(" ") == space_number:
             return []
     except Exception as err:
         print_info(err)
     return wrapped_function(self, *args, **kwargs)
예제 #8
0
 def command_run(self, *args, **kwargs):
     print_status("Running module...")
     try:
         self.current_module.run()
     except KeyboardInterrupt:
         print_info()
         print_error("Operation cancelled by user")
     except Exception:
         print_error(traceback.format_exc(sys.exc_info()))
예제 #9
0
 def command_run(self, *args, **kwargs):
     print_status("Running module...")
     try:
         self.current_module.run()
     except KeyboardInterrupt:
         print_info()
         print_error("Operation cancelled by user")
     except Exception:
         print_error(traceback.format_exc(sys.exc_info()))
예제 #10
0
파일: payloads.py 프로젝트: bambeero1/Jail
    def run(self):
        print_status("Generating payload")

        payload = self.generate()
        if self.encoder:
            payload = self.encoder.encode(payload)

        if self.fmt:
            payload = self.fmt.format(payload)

        print_info(payload)
        return payload
예제 #11
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

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

        for module in self.modules:
            if keyword in module:
                module = humanize_path(module)
                print_info(
                    "{}\033[31m{}\033[0m{}".format(*module.partition(keyword)))
예제 #12
0
    def run(self):
        print_status("Generating payload")

        payload = self.generate()
        if self.encoder:
            payload = self.encoder.encode(payload)

        if self.fmt:
            payload = self.fmt.format(payload)

        print_info(payload)
        return payload
예제 #13
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

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

        for module in self.modules:
            if keyword in module:
                module = humanize_path(module)
                print_info(
                    "{}\033[31m{}\033[0m{}".format(*module.partition(keyword))
                )
예제 #14
0
    def _show_devices(self, *args, **kwargs):  # TODO: cover with tests
        try:
            devices = self.current_module._Exploit__info__['devices']

            print_info("\nTarget devices:")
            i = 0
            for device in devices:
                if isinstance(device, dict):
                    print_info("   {} - {}".format(i, device['name']))
                else:
                    print_info("   {} - {}".format(i, device))
                i += 1
            print_info()
        except KeyError:
            print_info("\nTarget devices are not defined")
예제 #15
0
    def _show_devices(self, *args, **kwargs):  # TODO: cover with tests
        try:
            devices = self.current_module._Exploit__info__['devices']

            print_info("\nTarget devices:")
            i = 0
            for device in devices:
                if isinstance(device, dict):
                    print_info("   {} - {}".format(i, device['name']))
                else:
                    print_info("   {} - {}".format(i, device))
                i += 1
            print_info()
        except KeyError:
            print_info("\nTarget devices are not defined")
예제 #16
0
    def nonInteractive(self, argv):
        """ Execute specific command and return result without launching the interactive CLI

        :return:

        """
        module = ""
        set_opts = []

        try:
            opts, args = getopt.getopt(argv[1:], "hm:s:",
                                       ["help=", "module=", "set="])
        except getopt.GetoptError:
            print_info("{} -m <module> -s \"<option> <value>\"".format(
                argv[0]))
            printer_queue.join()
            return

        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print_info("{} -m <module> -s \"<option> <value>\"".format(
                    argv[0]))
                printer_queue.join()
                return
            elif opt in ("-m", "--module"):
                module = arg
            elif opt in ("-s", "--set"):
                set_opts.append(arg)

        if not len(module):
            print_error('A module is required when running non-interactively')
            printer_queue.join()
            return

        self.command_use(module)

        for opt in set_opts:
            self.command_set(opt)

        self.command_exploit()

        # Wait for results if needed
        printer_queue.join()

        return
예제 #17
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        while True:
            try:
                command, args, kwargs = self.parse_line(input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args, **kwargs)
            except RoutersploitException as err:
                print_error(err)
            except (EOFError, KeyboardInterrupt, SystemExit):
                print_info()
                print_error("RouterSploit stopped")
                break
            finally:
                printer_queue.join()
예제 #18
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        payloadFile = 0

        # add a function
        # let me test iot automate
        self.loadAutoScript()
        while True:
            try:
                command, args = self.parse_line(input(self.prompt))
                print_status('%s :: %s'%(command,args))
                
                if not command:
                    continue
                command_handler = self.get_command_handler(command)

                command_handler(args)
            except RoutersploitException as err:
                print_error(err)
            except EOFError:
                print_info()
                print_status("routersploit stopped")
                break
            except KeyboardInterrupt:
                print_info()
            finally:
                printer_queue.join()
예제 #19
0
    def _show_options(self, *args, **kwargs):
        target_names = ["target", "port", "ssl", "rhost", "rport", "lhost", "lport"]
        target_opts = [opt for opt in self.current_module.options if opt in target_names]
        module_opts = [opt for opt in self.current_module.options if opt not in target_opts]
        headers = ("Name", "Current settings", "Description")

        print_info("\nTarget options:")
        print_table(headers, *self.get_opts(*target_opts))

        if module_opts:
            print_info("\nModule options:")
            print_table(headers, *self.get_opts(*module_opts))

        print_info()
예제 #20
0
    def _show_options(self, *args, **kwargs):
        target_names = ["target", "port", "ssl", "rhost", "rport", "lhost", "lport"]
        target_opts = [opt for opt in self.current_module.options if opt in target_names]
        module_opts = [opt for opt in self.current_module.options if opt not in target_opts]
        headers = ("Name", "Current settings", "Description")

        print_info("\nTarget options:")
        print_table(headers, *self.get_opts(*target_opts))

        if module_opts:
            print_info("\nModule options:")
            print_table(headers, *self.get_opts(*module_opts))

        print_info()
예제 #21
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        while True:
            try:
                command, args = self.parse_line(input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args)
            except RoutersploitException as err:
                print_error(err)
            except EOFError:
                print_info()
                print_status("routersploit stopped")
                break
            except KeyboardInterrupt:
                print_info()
            finally:
                printer_queue.join()
    def start(self):
        """ exploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        while True:
            try:
                command, args = self.parse_line(input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args)
            except RoutersploitException as err:
                print_error(err)
            except EOFError:
                print_info()
                print_status(" stopped")
                break
            except KeyboardInterrupt:
                print_info()
            finally:
                printer_queue.join()
예제 #23
0
    def command_search(self, *args, **kwargs):
        mod_type = ''
        mod_detail = ''
        mod_vendor = ''
        existing_modules = [
            name for _, name, _ in pkgutil.iter_modules([MODULES_DIR])
        ]
        devices = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'exploits')])
        ]
        languages = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'encoders')])
        ]
        payloads = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'payloads')])
        ]

        try:
            keyword = args[0].strip("'\"").lower()
        except IndexError:
            keyword = ''

        if not (len(keyword) or len(kwargs.keys())):
            print_error(
                "Please specify at least search keyword. e.g. 'search cisco'")
            print_error(
                "You can specify options. e.g. 'search type=exploits device=routers vendor=linksys WRT100 rce'"
            )
            return

        for (key, value) in kwargs.items():
            if key == 'type':
                if value not in existing_modules:
                    print_error("Unknown module type.")
                    return
                # print_info(' - Type  :\t{}'.format(value))
                mod_type = "{}.".format(value)
            elif key in ['device', 'language', 'payload']:
                if key == 'device' and (value not in devices):
                    print_error("Unknown exploit type.")
                    return
                elif key == 'language' and (value not in languages):
                    print_error("Unknown encoder language.")
                    return
                elif key == 'payload' and (value not in payloads):
                    print_error("Unknown payload type.")
                    return
                # print_info(' - {}:\t{}'.format(key.capitalize(), value))
                mod_detail = ".{}.".format(value)
            elif key == 'vendor':
                # print_info(' - Vendor:\t{}'.format(value))
                mod_vendor = ".{}.".format(value)

        for module in self.modules:
            if mod_type not in str(module):
                continue
            if mod_detail not in str(module):
                continue
            if mod_vendor not in str(module):
                continue
            if not all(word in str(module) for word in keyword.split()):
                continue

            found = humanize_path(module)

            if len(keyword):
                for word in keyword.split():
                    found = found.replace(word,
                                          "\033[31m{}\033[0m".format(word))

            print_info(found)
예제 #24
0
 def command_help(self, *args, **kwargs):
     print_info(self.global_help)
     if self.current_module:
         print_info("\n", self.module_help)
예제 #25
0
 def __show_modules(self, root=''):
     for module in [
             module for module in self.modules if module.startswith(root)
     ]:
         print_info(module.replace('.', os.sep))
예제 #26
0
 def _show_info(self, *args, **kwargs):
     pprint_dict_in_order(
         self.module_metadata,
         ("name", "description", "devices", "authors", "references"),
     )
     print_info()
예제 #27
0
    def start(self, argv):
        """ Routersploit main entry point. Starting interpreter loop. """

        printer_queue.join()
        try:
            command, args = self.parse_line("use scanners/routers/router_scan")
            if not command:
                return -1
            command_handler = self.get_command_handler(command)
            command_handler(args)
        except RoutersploitException as err:
            print_error(err)
        except EOFError:
            print_info()
            print_status("routersploit stopped")
            return -1
        except KeyboardInterrupt:
            print_info()
        finally:
            printer_queue.join()

        try:
            command, args = self.parse_line("set target " + argv)
            if not command:
                return -1
            command_handler = self.get_command_handler(command)
            command_handler(args)
        except RoutersploitException as err:
            print_error(err)
        except EOFError:
            print_info()
            print_status("routersploit stopped")
            return -1
        except KeyboardInterrupt:
            print_info()
        finally:
            printer_queue.join()

        try:
            command, args = self.parse_line("run")
            if not command:
                return -1
            command_handler = self.get_command_handler(command)
            command_handler(args)
        except RoutersploitException as err:
            print_error(err)
        except EOFError:
            print_info()
            print_status("routersploit stopped")
            return -1
        except KeyboardInterrupt:
            print_info()
        finally:
            printer_queue.join()
예제 #28
0
def shell(exploit, architecture="", method="", payloads=None, **params):
    available_payloads = {}
    payload = None
    options = []

    if architecture and method:
        path = "routersploit/modules/payloads/{}/".format(architecture)

        # get all payloads for given architecture
        all_payloads = [f.split(".")[0] for f in listdir(path) if isfile(join(path, f)) and f.endswith(".py") and f != "__init__.py"]

        payload_path = path.replace("/", ".")
        for p in all_payloads:
            module = getattr(importlib.import_module("{}{}".format(payload_path, p)), 'Exploit')

            # if method/arch is cmd then filter out payloads
            if method is "cmd":
                if getattr(module, "cmd") in payloads:
                    available_payloads[p] = module
            else:
                available_payloads[p] = module

    print_info()
    print_success("Welcome to cmd. Commands are sent to the target via the execute method.")
    print_status("For further exploitation use 'show payloads' and 'set payload <payload>' commands.")
    print_info()

    while True:
        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 = input(cmd_str)

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

        elif cmd == "show payloads":
            if not available_payloads:
                print_error("There are no available payloads for this exploit")
                continue

            print_status("Available payloads:")
            headers = ("Payload", "Name", "Description")
            data = []
            for p in available_payloads.keys():
                data.append((p, available_payloads[p]._Exploit__info__["name"], available_payloads[p]._Exploit__info__["description"]))

            print_table(headers, *data)

        elif cmd.startswith("set payload "):
            if not available_payloads:
                print_error("There are no available payloads for this exploit")
                continue

            c = cmd.split(" ")

            if c[2] in available_payloads.keys():
                payload = available_payloads[c[2]]()

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

                if payload.handler == "bind_tcp":
                    options.append(["rhost", 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_info("{} => {}".format(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:
                        print_error("Exploit failed to transfer payload")
                        continue

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

                elif method == "cmd":
                    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))
예제 #29
0
 def _show_info(self, *args, **kwargs):
     pprint_dict_in_order(
         self.module_metadata,
         ("name", "description", "devices", "authors", "references"),
     )
     print_info()
예제 #30
0
 def run(self):
     print_status("Generating payload")
     print_info(
         self.generate()
     )
예제 #31
0
 def __show_modules(self, root=''):
     for module in [module for module in self.modules if module.startswith(root)]:
         print_info(module.replace('.', os.sep))
예제 #32
0
 def command_help(self, *args, **kwargs):
     print_info(self.global_help)
     if self.current_module:
         print_info("\n", self.module_help)