Ejemplo n.º 1
0
def listener_worker():
    s = get_tcp_listener(ipv6=conf.ipv6, listen_port=int(conf.connect_back_port))
    while True:
        try:
            conn, address = s.accept()
            conn.setblocking(1)
            client = AttribDict()
            client.conn = conn
            client.address = address
            kb.data.clients.append(client)
            info_msg = "new connection established from {0}".format(
                desensitization(address[0]) if conf.ppt else address[0])
            logger.log(CUSTOM_LOGGING.SUCCESS, info_msg)
        except Exception:
            pass
Ejemplo n.º 2
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, desensitization(ip) if conf.ppt else 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(
                        desensitization(conf.connect_back_host) if conf.ppt else conf.connect_back_host))
                    break
            except Exception:
                data_to_stdout("wrong number, choose again\n")
Ejemplo n.º 3
0
def start():
    runtime_check()
    tasks_count = kb.task_queue.qsize()
    info_msg = "pocsusite got a total of {0} tasks".format(tasks_count)
    logger.info(info_msg)
    logger.debug("pocsuite will open {} threads".format(conf.threads))

    try:
        run_threads(conf.threads, task_run)
        logger.info("Scan completed,ready to print")
    finally:
        task_done()

    if conf.mode == "shell" and not conf.api:
        info_msg = "connect back ip: {0}    port: {1}".format(
            desensitization(conf.connect_back_host) if conf.ppt else conf.connect_back_host, conf.connect_back_port)
        logger.info(info_msg)
        info_msg = "watting for shell connect to pocsuite"
        logger.info(info_msg)
        if conf.console_mode:
            handle_listener_connection_for_console()
        else:
            handle_listener_connection()
Ejemplo n.º 4
0
    def execute(self,
                target,
                headers=None,
                params=None,
                mode='verify',
                verbose=True):
        self.target = target
        self.url = parse_target_url(
            target
        ) if self.current_protocol == POC_CATEGORY.PROTOCOL.HTTP else self.build_url(
        )
        self.headers = headers
        if isinstance(params, dict) or isinstance(params, str):
            self.params = params
        else:
            self.params = {}
        self.mode = mode
        self.verbose = verbose
        self.expt = (0, 'None')
        # TODO
        output = None

        try:
            output = self._execute()

        except NotImplementedError as e:
            self.expt = (ERROR_TYPE_ID.NOTIMPLEMENTEDERROR, e)
            logger.log(
                CUSTOM_LOGGING.ERROR,
                'POC: {0} not defined "{1}" mode'.format(self.name, self.mode))
            output = Output(self)

        except ConnectTimeout as e:
            self.expt = (ERROR_TYPE_ID.CONNECTTIMEOUT, e)
            while conf.retry > 0:
                logger.debug('POC: {0} timeout, start it over.'.format(
                    self.name))
                try:
                    output = self._execute()
                    break
                except ConnectTimeout:
                    logger.debug('POC: {0} time-out retry failed!'.format(
                        self.name))
                conf.retry -= 1
            else:
                msg = "connect target '{0}' failed!".format(
                    desensitization(target) if conf.ppt else target)
                logger.error(msg)
                output = Output(self)

        except HTTPError as e:
            self.expt = (ERROR_TYPE_ID.HTTPERROR, e)
            logger.warn('POC: {0} HTTPError occurs, start it over.'.format(
                self.name))
            output = Output(self)

        except ConnectionError as e:
            self.expt = (ERROR_TYPE_ID.CONNECTIONERROR, e)
            msg = "connect target '{0}' failed!".format(
                desensitization(target) if conf.ppt else target)
            logger.error(msg)
            output = Output(self)

        except TooManyRedirects as e:
            self.expt = (ERROR_TYPE_ID.TOOMANYREDIRECTS, e)
            logger.debug(str(e))
            output = Output(self)

        except BaseException as e:
            self.expt = (ERROR_TYPE_ID.OTHER, e)
            logger.error("PoC has raised a exception")
            logger.error(str(traceback.format_exc()))
            # logger.exception(e)
            output = Output(self)
        if output:
            output.params = self.params
        return output
Ejemplo n.º 5
0
def task_run():
    while not kb.task_queue.empty() and kb.thread_continue:
        target, poc_module = kb.task_queue.get()
        if not conf.console_mode:
            poc_module = copy.deepcopy(kb.registered_pocs[poc_module])
        poc_name = poc_module.name

        # for hide some infomations
        if conf.ppt:
            info_msg = "running poc:'{0}' target '{1}'".format(
                poc_name, desensitization(target))
        else:
            info_msg = "running poc:'{0}' target '{1}'".format(
                poc_name, target)

        logger.info(info_msg)

        # hand user define parameters
        if hasattr(poc_module, "_options"):
            for item in kb.cmd_line:
                value = cmd_line_options.get(item, "")
                if item in poc_module.options:
                    poc_module.set_option(item, value)
                    info_msg = "Parameter {0} => {1}".format(item, value)
                    logger.info(info_msg)
            # check must be option
            for opt, v in poc_module.options.items():
                # check conflict in whitelist
                if opt in CMD_PARSE_WHITELIST:
                    info_msg = "Poc:'{0}' You can't customize this variable '{1}' because it is already taken up by the pocsuite.".format(
                        poc_name, opt)
                    logger.error(info_msg)
                    raise SystemExit

                if v.require and v.value == "":
                    info_msg = "Poc:'{poc}' Option '{key}' must be set,please add parameters '--{key}'".format(
                        poc=poc_name, key=opt)
                    logger.error(info_msg)
                    raise SystemExit

        try:
            result = poc_module.execute(target,
                                        headers=conf.http_headers,
                                        mode=conf.mode,
                                        verbose=False)
        except PocsuiteValidationException as ex:
            info_msg = "Poc:'{}' PocsuiteValidationException:{}".format(
                poc_name, ex)
            logger.error(info_msg)
            result = None

        if not isinstance(result, Output) and not None:
            _result = Output(poc_module)
            if result:
                if isinstance(result, bool):
                    _result.success({})
                elif isinstance(result, str):
                    _result.success({"Info": result})
                elif isinstance(result, dict):
                    _result.success(result)
                else:
                    _result.success({"Info": repr(result)})
            else:
                _result.fail('target is not vulnerable')

            result = _result

        if not result:
            continue

        if not conf.quiet:
            result.show_result()

        result_status = "success" if result.is_success() else "failed"
        if result_status == "success" and kb.comparison:
            kb.comparison.change_success(target, True)

        output = AttribDict(result.to_dict())
        if conf.ppt:
            # hide some information
            target = desensitization(target)

        output.update({
            'target': target,
            'poc_name': poc_name,
            'created': time.strftime("%Y-%m-%d %X", time.localtime()),
            'status': result_status
        })
        result_plugins_handle(output)
        kb.results.append(output)
Ejemplo n.º 6
0
def task_run():
    while not kb.task_queue.empty() and kb.thread_continue:
        target, poc_module = kb.task_queue.get()
        if not conf.console_mode:
            poc_module = copy.deepcopy(kb.registered_pocs[poc_module])
        poc_name = poc_module.name

        if conf.pcap:
            # start capture flow
            import os
            import logging

            os.environ["MPLBACKEND"] = "Agg"
            logging.getLogger("scapy").setLevel(logging.ERROR)

            from pocsuite3.lib.utils.pcap_sniffer import Sniffer
            from scapy.utils import wrpcap
            sniffer = Sniffer(urlparse(target).hostname)
            if sniffer.use_pcap:
                if not sniffer.is_admin:
                    logger.warn(
                        "Please use administrator privileges, and the poc will continue to execute without fetching the packet"
                    )
                    conf.pcap = False
                else:
                    sniffer.start()
                    # let scapy start for a while
                    time.sleep(1)
            else:
                logger.warn(
                    "No libpcap is detected, and the poc will continue to execute without fetching the packet"
                )
                conf.pcap = False

        # for hide some infomations
        if conf.ppt:
            info_msg = "running poc:'{0}' target '{1}'".format(
                poc_name, desensitization(target))
        else:
            info_msg = "running poc:'{0}' target '{1}'".format(
                poc_name, target)

        logger.info(info_msg)

        # hand user define parameters
        if hasattr(poc_module, "_options"):
            for item in kb.cmd_line:
                value = cmd_line_options.get(item, "")
                if item in poc_module.options:
                    poc_module.set_option(item, value)
                    info_msg = "Parameter {0} => {1}".format(item, value)
                    logger.info(info_msg)
            # check must be option
            for opt, v in poc_module.options.items():
                # check conflict in whitelist
                if opt in CMD_PARSE_WHITELIST:
                    info_msg = "Poc:'{0}' You can't customize this variable '{1}' because it is already taken up by the pocsuite.".format(
                        poc_name, opt)
                    logger.error(info_msg)
                    raise SystemExit

                if v.require and v.value == "":
                    info_msg = "Poc:'{poc}' Option '{key}' must be set,please add parameters '--{key}'".format(
                        poc=poc_name, key=opt)
                    logger.error(info_msg)
                    raise SystemExit

        try:
            result = poc_module.execute(target,
                                        headers=conf.http_headers,
                                        mode=conf.mode,
                                        verbose=False)
        except PocsuiteValidationException as ex:
            info_msg = "Poc:'{}' PocsuiteValidationException:{}".format(
                poc_name, ex)
            logger.error(info_msg)
            result = None

        if not isinstance(result, Output) and not None:
            _result = Output(poc_module)
            if result:
                if isinstance(result, bool):
                    _result.success({})
                elif isinstance(result, str):
                    _result.success({"Info": result})
                elif isinstance(result, dict):
                    _result.success(result)
                else:
                    _result.success({"Info": repr(result)})
            else:
                _result.fail('target is not vulnerable')

            result = _result

        if not result:
            continue

        if not conf.quiet:
            result.show_result()

        result_status = "success" if result.is_success() else "failed"
        if result_status == "success" and kb.comparison:
            kb.comparison.change_success(target, True)

        output = AttribDict(result.to_dict())
        if conf.ppt:
            # hide some information
            target = desensitization(target)

        output.update({
            'target': target,
            'poc_name': poc_name,
            'created': time.strftime("%Y-%m-%d %X", time.localtime()),
            'status': result_status
        })
        result_plugins_handle(output)
        kb.results.append(output)
        if conf.pcap:
            sniffer.join(20)
            if not sniffer.is_alive():
                filename = urlparse(target).hostname + time.strftime(
                    '_%Y_%m_%d_%H%M%S.pcap')
                logger.info(f"pcap data has been saved in: {filename}")
                wrpcap(filename, sniffer.pcap.results)
            else:
                logger.error("Thread terminates timeout. Failed to save pcap")