Beispiel #1
0
def HookRegister(args):
    if args.proxy_ip:
        msg = 'Use proxy: %s' % args.proxy_ip
        outputscreen.info(msg)
        conf.PROXY_MODE = 'PROXY'
        conf.INPUT_TARGET_PROXY = args.proxy_ip
    elif args.proxy_pool_ip:
        proxy_pool_file = os.path.join(paths.DATA_PATH, 'Proxy_pool',
                                       'proxy_pool.txt')
        if os.path.exists(proxy_pool_file):
            msg = 'Use proxy ip file: proxy_pool.txt'
            outputscreen.info(msg)
            conf.PROXY_MODE = "RANDOM_PROXY"
            conf.PROXY_IP_PATH = proxy_pool_file
        else:
            outputscreen.error(
                "读取代理文件出错,请确保代理文件名为proxy_pool.txt,每行一条代理,格式如: 124.225.223.101:80"
            )
            sys.exit()
    else:
        conf.PROXY_MODE = ''
    if args.user_agent:
        msg = "Use User-Agent: %s" % args.user_agent
        outputscreen.info(msg)
        conf.UA_MODE = 'UA'
        conf.INPUT_TARGET_UA = args.user_agent
    else:
        conf.UA_MODE = ''
    if args.set_cookie:
        msg = "Use Cookie: %s" % args.set_cookie
        outputscreen.info(msg)
        conf.COOKIE_MODE = 'COOKIE'
        conf.INPUT_TARGET_COOKIE = args.set_cookie
    else:
        conf.COOKIE_MODE = ''
Beispiel #2
0
def _initHttpClient():
    if conf.GOOGLE_PROXY:
        proxy_str = conf.GOOGLE_PROXY
    elif ConfigFileParser().GoogleProxy():
        proxy_str = ConfigFileParser().GoogleProxy()
    else:
        proxy_str = None

    if not proxy_str:
        return Http()

    msg = 'Proxy: %s' % proxy_str
    outputscreen.info(msg)
    proxy = proxy_str.strip().split(' ')
    if len(proxy) != 3:
        msg = 'SyntaxError in GoogleProxy string, Please check your args or config file.'
        sys.exit(outputscreen.error(msg))
    if proxy[0].lower() == 'http':
        type = PROXY_TYPE.HTTP
    elif proxy[0].lower() == 'sock5':
        type = PROXY_TYPE.SOCKS5
    elif proxy[0].lower() == 'sock4':
        type = PROXY_TYPE.SOCKS4
    else:
        msg = 'Invalid proxy-type in GoogleProxy string, Please check your args or config file.'
        sys.exit(outputscreen.error(msg))
    try:
        port = int(proxy[2])
    except ValueError:
        msg = 'Invalid port in GoogleProxy string, Please check your args or config file.'
        sys.exit(outputscreen.error(msg))
    else:
        http_client = Http(proxy_info=ProxyInfo(type, proxy[1], port))
    return http_client
Beispiel #3
0
def run():
    initEngine()
    # 多线程模式
    if conf.thread_mode:
        outputscreen.info('Threading mode')
        for i in range(th.thread_num):
            t = threading.Thread(target=scan, name=str(i))
            t.setDaemon(True)
            t.start()
            # It can quit with Ctrl-C
        try:
            while 1:
                if th.thread_count > 0 and th.is_continue:
                    time.sleep(0.01)
                else:
                    break
        except KeyboardInterrupt as e:
            outputscreen.nerror('User quit!')
            th.is_continue = False
    # 协程模式
    elif conf.gevent_mode:
        from gevent import monkey
        monkey.patch_all()
        import gevent
        outputscreen.info('Coroutine mode')
        while th.target.qsize() > 0 and th.is_continue:
            try:
                gevent.joinall([gevent.spawn(scan) for i in range(0, th.thread_num) if th.target.qsize() > 0])
            except KeyboardInterrupt:
                sys.exit(outputscreen.error('Ctrl+C quit!'))
        #     th.is_continue = False
    # except KeyboardInterrupt:
    #     sys.exit(outputscreen.error('[-] Ctrl+C quit!'))
    if 'errmsg' in th:
        outputscreen.error(th.errmsg)
Beispiel #4
0
def ApiRegister(args):
    search_type = args.search_type
    google_proxy = args.google_proxy
    api_limit = args.api_limit
    offset = args.api_offset
    if not 'API_MODE' in conf:
        return
    if not conf.API_DORK:
        msg = 'Empty API dork, show usage with [-h]'
        sys.exit(outputscreen.error(msg))

    if offset < 0:
        msg = 'Invalid value in [--offset], show usage with [-h]'
        sys.exit(outputscreen.error(msg))
    else:
        conf.API_OFFSET = offset
    if api_limit <= 0:
        msg = 'Invalid value in [--limit], show usage with [-h]'
        sys.exit(outputscreen.error(msg))
    else:
        conf.API_LIMIT = api_limit
    if conf.API_MODE is 'Zoomeye':
        if search_type not in ['web', 'host']:
            msg = 'Invalid value in [--search-type], show usage with [-h]'
            sys.exit(outputscreen.error(msg))
        else:
            conf.ZOOMEYE_SEARCH_TYPE = search_type

    elif conf.API_MODE is 'Google':
        conf.GOOGLE_PROXY = google_proxy
Beispiel #5
0
def check_environment():
    try:
        os.path.isdir(module_path())
    except Exception:
        err_msg = "your system does not properly handle non-ASCII paths. "
        err_msg += "Please move the pocsuite's directory to the other location"
        outputscreen.error(err_msg)
        raise SystemExit
Beispiel #6
0
def main():
    check_environment()
    paths.ROOT_PATH = module_path()
    setPaths()
    try:
        banner()
        cmdLineOptions.update(cmdLineParser().__dict__)
        initOptions(cmdLineOptions)
    except:
        err_msg = 'I think you entered the wrong parameter...'
        sys.exit(outputscreen.error(err_msg))

    try:
        loadPayload()
        setModule()
        patch_session()
        _disable_warnings()
        # print('cmdLineOptions', cmdLineOptions, '\n')
        # print('conf', conf, '\n')
    except AttributeError:
        raise
        # print('xxxxxxxxxx')
        # exit()

    run()
    if th.found_count and conf.OUT_FILE_STATUS:
        outputscreen.resuccess('Report generated successfully -> %s' % conf.OUT_FILE_NAME)
    else:
        outputscreen.nerror('本次扫描未产生报告')
Beispiel #7
0
def load_file_mode():
    subs = []
    try:
        with open(conf.INPUT_FILE_PATH) as p:
            lines = p.readlines()
        for line in lines:
            line = line.strip()
            subs.append(line)
        # 去重排序
        subs = sorted(list(set(subs)))
        for su in subs:
            for name, exp in conf.MODULE_PLUGIN.items():
                sub = su.strip()
                if '://' not in sub:
                    sub = 'http://' + sub
                if sub:
                    module = dict()
                    module["sub"] = sub
                    module["name"] = name
                    module["poc"] = exp
                    conf.queue.put(module)
    except FileNotFoundError:
        err_msg = "The %s was not found" % conf.INPUT_FILE_PATH
        sys.exit(outputscreen.error(err_msg))
    except:
        raise
Beispiel #8
0
def loadPayload():
    conf.MODULE_PLUGIN = dict()
    # 遍历脚本,脚本名和路径对应 name->path
    for i in range(0, len(conf.MODULE_NAME)):
        name = conf.MODULE_NAME[i]
        path = conf.MODULE_FILE_PATH[i]
        try:
            spec = importlib.util.spec_from_file_location(name, path)
            module_obj = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module_obj)
            for each in ['poc']:
                if not hasattr(module_obj, each):
                    error_msg = "[Warning] Can't find essential method:'%s()' in current %s,Please modify your script/PoC." % (
                        each, name)
                    outputscreen.error(error_msg)
                else:
                    conf.MODULE_PLUGIN[name] = module_obj
        except:
            raise
Beispiel #9
0
def _initial():
    z = ZoomEye()
    z.auto_login()
    info = z.resources_info().get('resources')
    if info:
        msg = 'Available ZoomEye search: (search:%s)' % (info.get(
            'search', 'NO FOUND'))
        outputscreen.info(msg)
    else:
        msg = 'ZoomEye API authorization failed, Please re-run it and enter a new token.'
        sys.exit(outputscreen.error(msg))
    return z
Beispiel #10
0
def GoogleSearch(query, limit, offset=0):
    key = ConfigFileParser().GoogleDeveloperKey()
    engine = ConfigFileParser().GoogleEngine()
    if not key or not engine:
        msg = "Please config your 'developer_key' and 'search_enging' at toolkit.conf"
        sys.exit(outputscreen.error(msg))
    try:
        service = build("customsearch",
                        "v1",
                        http=_initHttpClient(),
                        developerKey=key)

        result_info = service.cse().list(q=query, cx=engine).execute()
        msg = 'Max query results: %s' % str(
            result_info.get('searchInformation', {}).get('totalResults'))
        outputscreen.info(msg)

        ans = list()
        limit += offset
        for i in range(int(offset / 10), int((limit + 10 - 1) / 10)):
            result = service.cse().list(q=query,
                                        cx=engine,
                                        num=10,
                                        start=i * 10 + 1).execute()
            if 'items' in result:
                for url in result.get('items'):
                    ans.append(url.get('link'))
        return ans
    except SocketError:
        sys.exit(
            outputscreen.error(
                'Unable to connect Google, maybe agent/proxy error.'))
    except ApiNameOrVersion:
        msg = '使用-As加载的脚本超过12个会有这个未知的bug,还不知道怎么解决QAQ,先使用-s吧。'
        sys.exit(outputscreen.error(msg))
    except ServerHttpDenied:
        outputscreen.warning(
            'It seems like Google-Server denied this request.')
        sys.exit()
Beispiel #11
0
def TargetRegister(args):
    """
    加载目标
    :param args:
    :return:
    """
    msg = 'Initialize targets...'
    outputscreen.warning(msg)
    # 单一目标
    if args.target_single:
        msg = 'Load target: %s' % args.target_single
        outputscreen.info(msg)
        conf.TARGET_MODE = 'SINGLE'
        conf.INPUT_TARGET_URL = args.target_single
    # 目标为文件
    elif args.target_file:
        msg = 'Load targets from: %s' % args.target_file
        outputscreen.info(msg)
        conf.TARGET_MODE = 'FILE'
        conf.INPUT_FILE_PATH = args.target_file
    # 目标为Zoomeye搜索后的IP或web
    elif args.zoomeye_dork:
        msg = 'Load targets from Zoomeye_Api: %s' % args.zoomeye_dork
        outputscreen.info(msg)
        conf.TARGET_MODE = 'API'
        conf.API_MODE = 'Zoomeye'
        conf.API_DORK = args.zoomeye_dork
    elif args.google_dork:
        msg = 'Load targets from Google_Api: %s' % args.google_dork
        outputscreen.info(msg)
        conf.TARGET_MODE = 'API'
        conf.API_MODE = 'Google'
        conf.API_DORK = args.google_dork
    # 目标为IP段
    else:
        err_msg = 'No target or target file is specified!'
        outputscreen.error(err_msg)
        sys.exit()
Beispiel #12
0
 def manual_login(self):
     msg = 'Please input your ZoomEye Email and Password below.'
     outputscreen.info(msg)
     try:
         from lib.core.data import conf, cmdLineOptions
         self.username = input('[!] ZoomEye Username(Email): ').strip()
         self.password = getpass.getpass(
             prompt='[!] ZoomEye Password: '******'[!] ZoomEye Password: '******'User quit!'))
     self.get_token()
     if not self.get_token():
         msg = 'Invalid ZoomEye username or password.'
         sys.exit(outputscreen.error(msg))
Beispiel #13
0
def loadfakeuseragent():
    """
    随机UA头
    :return:
    """
    ua_list = []
    ua_file = paths.UA_LIST_PATH
    if os.path.isfile(ua_file):
        with open(ua_file) as u:
            ua = u.readlines()
        for a in ua:
            a = a.strip()
            ua_list.append(a)
        return random.choice(ua_list)
    else:
        sys.exit(outputscreen.error('NO found %s' % ua_file))
Beispiel #14
0
 def get_token(self):
     # Please access https://www.zoomeye.org/api/doc#login
     # data = '{{"username": "******", "password": "******"}}'.format(self.username,self.password)
     data = {'username': self.username, 'password': self.password}
     data = json.dumps(data)
     resp = requests.post(
         self.zoomeye_login_api,
         data=data,
     )
     if resp.status_code == 200 and 'access_token' in resp.text:
         self.token = json.loads(resp.text)['access_token']
         return self.token
     if resp.status_code == 400 and '400 Unknown Virtual Host' in resp.text:
         msg = '使用-As加载的脚本超过12个会有这个未知的bug,还不知道怎么解决QAQ,先使用-s吧。'
         sys.exit(outputscreen.error(msg))
     return False
Beispiel #15
0
def load_api_mode():
    conf.API_OUTPUT = os.path.join(paths.DATA_PATH, conf.API_MODE)
    if not os.path.exists(conf.API_OUTPUT):
        os.mkdir(conf.API_OUTPUT)
    output = conf.API_OUTPUT
    dork = conf.API_DORK
    limit = conf.API_LIMIT
    offset = conf.API_OFFSET
    if conf.API_MODE is 'Zoomeye':
        anslist = ZoomEyeSearch(query=dork,
                                limit=limit,
                                type=conf.ZOOMEYE_SEARCH_TYPE,
                                offset=offset)
    if conf.API_MODE is 'Google':
        anslist = GoogleSearch(query=dork, limit=limit, offset=conf.API_OFFSET)
    if anslist:
        tmpIpFile = os.path.join(output,
                                 '%s.txt' % (time.strftime('%Y%m%d%H%M%S')))
        with open(tmpIpFile, 'w') as fp:
            for each in anslist:
                if isinstance(each, list):  # for ZoomEye web type
                    each = each[0]
                fp.write(each + '\n')
        with open(tmpIpFile) as tm:
            for target in tm.readlines():
                for name, exp in conf.MODULE_PLUGIN.items():
                    sub = target.strip()
                    if '://' not in sub:
                        sub = 'http://' + sub
                    if sub:
                        module = dict()
                        module["sub"] = sub
                        module["name"] = name
                        module["poc"] = exp
                        conf.queue.put(module)
    else:
        msg = '%s Api 未找到符合 %s 的目标' % (conf.API_MODE, dork)
        sys.exit(outputscreen.error(msg))
Beispiel #16
0
def ScriptsRegister(args):
    script_name = args.script_name
    all_scripts = args.all_scripts
    pocs_path = paths.POCS_PATH
    # 存放脚本文件名
    script_name_list = []
    # 存放脚本文件路径
    script_path_list = []
    # 判断script是否存在,不存在为0
    flag = 0
    # script列表的长度,flag=len_script_name时退出查找文件的循环
    len_script_name = len(script_name)
    if not (script_name or all_scripts):
        err_msg = 'Use -s/-As load script/scripts'
        outputscreen.error(err_msg)
        sys.exit()
    # 设置单个或多个poc的路径,type(script_name)=list
    if script_name:
        for root, dirs, files in os.walk(pocs_path):
            """
                root :所指的是当前正在遍历的目录的地址
                dirs :当前文件夹中所有目录名字的 list (不包括子目录)
                files :当前文件夹中所有的文件 (不包括子目录中的文件)
            """
            for file in files:
                # 文件名
                file_name = os.path.splitext(file)[0]
                # 文件后缀
                file_suffix = os.path.splitext(file)[1]
                # 路径
                file_path = os.path.join(root, file)
                file_abs_path = os.path.abspath(file)
                # 文件父目录
                file_parent = os.path.dirname(file_path)

                # print("file : {0}".format(file))
                # print("file_name : {0}".format(file_name))
                # # print("file_suffix : {0}".format(file_suffix))
                # print("file_path : {0}".format(file_path))
                # # print("file_parent : {0}".format(file_parent))

                for target_file in script_name:
                    if target_file == file_name:
                        flag += 1
                        script_name_list.append(file_name)
                        script_path_list.append(file_path)
            if flag == len_script_name:
                break
            conf.MODULE_NAME = script_name_list
            conf.MODULE_FILE_PATH = script_path_list
            # print('flagxxxxxxxxxxxxx',flag)
        if flag == 0:
            outputscreen.error('Script not %s exist, please check spelling' %
                               script_name)
            sys.exit()
        else:
            msg = 'Load script:%s' % conf.MODULE_NAME
            outputscreen.info(msg)
    # 同种类型下的所有poc,eg.struts2_all包含003-053的全部poc
    if all_scripts:
        for root, dirs, files in os.walk(pocs_path):
            for di in dirs:
                if all_scripts == di:
                    file_path = os.path.join(root, di)
                    file_name_list = list(
                        map(
                            lambda filename: '{}'.format(filename),
                            filter(
                                lambda filename: False
                                if '__' in filename else True,
                                os.listdir(file_path))))
                    for sn in file_name_list:
                        if sn[-3:] == '.py':
                            script_name_list.append(sn)
                    for file_name in file_name_list:
                        script_path = os.path.join(file_path, file_name)
                        # print('script_path', script_path)
                        flag += 1
                        if file_name[-3:] == '.py':
                            script_path_list.append(script_path)
                    conf.MODULE_NAME = script_name_list
                    conf.MODULE_FILE_PATH = script_path_list
        if flag == 0:
            outputscreen.error('File not %s exist. please check spelling' %
                               all_scripts)
            sys.exit()
        else:
            msg = 'Load script:%s' % conf.MODULE_NAME
            outputscreen.info(msg)