Ejemplo n.º 1
0
def handle_censys(query, limit, offset):
    global UID
    global SECRET
    UID = ConfigFileParser().censys_UID()
    SECRET = ConfigFileParser().censys_SECRET()
    msg = '[+] Trying to login with credentials in config file: {}.'.format(
        paths.CONFIG_PATH)
    colorprint.green(msg)
    if not can_auto_login():
        err_msg = '[-] Automatic authorization failed.\n[*] Please input your censys API Key (https://censys.io/account/api).'
        colorprint.cyan(err_msg)
        UID = input('[*] UID > ').strip()
        SECRET = input('[*] SECRET > ').strip()
        if not can_auto_login():
            err_msg = "[-] authorization failed"
            colorprint.red(err_msg)
            sys.exit()

    page_start = int(offset / 100) + 1
    page_stop = page_start + int(limit / 100) + 1

    for page in range(page_start, page_stop):
        get_ip(query, page)

        # the last loop dont need sleep
        if page < page_stop - 1:
            time.sleep(3)
Ejemplo n.º 2
0
def engine_register(args):
    # if the engine mode is conflicting
    if args.engine_thread and args.engine_gevent:
        colorprint.red(
            "Cannot use Multi-Threaded mode and Coroutine mode at the same time"
        )
        colorprint.red(
            'Use [-eT] to set Multi-Threaded mode or [-eG] to set Coroutine mode'
        )
        sys.exit()

    # else if engine mode is Multi-Threaded mode
    elif args.engine_thread:
        conf.engine_mode = "multi_threaded"

    # else if engine mode is Coroutine mode
    else:
        conf.engine_mode = 'coroutine'

    # set concurrent num
    if args.concurrent_num > 1000 or args.concurrent_num < 1:
        warn_msg = "setting concurrent num {}. Maybe it's too much, continue? [y/N] (default y): ".format(
            args.concurrent_num)
        colorprint.cyan(warn_msg, end='')
        flag = input()
        if flag.lower() in ('y', 'yes', ''):
            conf.concurrent_num = args.concurrent_num
        else:
            msg = '[-] User quit!'
            colorprint.cyan(msg)
            sys.exit()
    conf.concurrent_num = args.concurrent_num
Ejemplo n.º 3
0
def engine_register(args):
    # if the engine mode is conflicting
    if args.engine_thread and args.engine_gevent:
        colorprint.red(
            "Cannot use Multi-Threaded mode and Coroutine mode at the same time"
        )
        colorprint.red(
            'Use [-eT] to set Multi-Threaded mode or [-eG] to set Coroutine mode'
        )
        sys.exit()

    # else if engine mode is Multi-Threaded mode
    elif args.engine_thread:
        conf.engine_mode = "multi_threaded"
        # set threads num
        if args.thread_num > 200 or args.thread_num < 1:
            msg = '[*] Invalid input in [-t](range: 1 to 200), has changed to default(30)'
            colorprint.cyan(msg)
            conf.thread_num = 30
            return
        conf.thread_num = args.thread_num

    # else if engine mode is Coroutine mode
    else:
        conf.engine_mode = 'coroutine'
Ejemplo n.º 4
0
def handle_censys(query, limit, offset):
    global UID
    global SECRET
    UID = ConfigFileParser().censys_UID()
    SECRET = ConfigFileParser().censys_SECRET()
    if not can_auto_login():
        err_msg = '[-] Automatic authorization failed.\n\
                   [*] Please input your Shodan API Key (https://account.shodan.io/).'

        colorprint.cyan(err_msg)
        UID = input('[*] UID > ').strip()
        SECRET = input('[*] UID > ').strip()
        if not can_auto_login(UID, SECRET):
            err_msg = "[-] authorization failed"
            colorprint.red(err_msg)
        else:
            pass
    else:

        page_start = int(offset / 160) + 1
        page_stop = page_start + int(limit / 160) + 1

        for page in range(page_start, page_stop):
            ip_list = get_ip(query, page)

            # the last loop dont need sleep
            if page < page_stop - 1:
                time.sleep(3)
Ejemplo n.º 5
0
def handle_fofa(query, limit, offset=0):
    try:
        msg = '[+] Trying to login with credentials in config file: {}.'.format(
            paths.CONFIG_PATH)
        colorprint.green(msg)
        email = ConfigFileParser().fofa_email()
        key = ConfigFileParser().fofa_key()
        #print(key)
        if check(email, key):
            pass
        else:
            raise Exception(
                "Automatic authorization failed")  # will go to except block
    except Exception as e:
        logger.debug(e)
        msg = '[*] Automatic authorization failed.'
        colorprint.cyan(msg)
        msg = '[*] Please input your FoFa Email and API Key below.'
        colorprint.cyan(msg)
        email = input("[*] Fofa Email: ").strip()
        key = input('[*] Fofa API Key: ').strip()
        if not check(email, key):
            msg = '[-] Fofa API authorization failed, Please re-run it and enter a valid key.'
            colorprint.red(msg)
            sys.exit()

    query = base64.b64encode(query.encode('utf-8')).decode('utf-8')

    # count how many result to search
    size = limit + offset

    url = f"https://fofa.so/api/v1/search/all?email={email}&key={key}&qbase64={query}&size={size}"
    try:
        response = request.get(url).text
        resp = json.loads(response)
        if not resp["error"]:
            for item in resp.get('results')[offset:]:
                #print(type(item[0]))
                if 'https:' not in item[0]:
                    try:
                        requests.get("http://" + item[0],
                                     timeout=5,
                                     verify=False)
                        conf.target.add("http://" + item[0])
                        print("http://" + item[0])
                    except:
                        pass

                else:
                    try:
                        requests.get(item[0], timeout=5, verify=False)
                        conf.target.add(item[0])
                        print(item[0])
                    except:
                        pass

    except Exception as e:
        colorprint.red(e)
        sys.exit()
Ejemplo n.º 6
0
 def _get_option(section, option):
     try:
         cf = ConfigParser()
         cf.read(paths.CONFIG_PATH)
         return cf.get(section=section, option=option)
     except:
         colorprint.cyan(
             'Missing essential options, please check your config-file.')
         return ''
Ejemplo n.º 7
0
 def manual_login(self):
     msg = '[*] Please input your ZoomEye Email and Password below.'
     colorprint.cyan(msg)
     self.username = input('[*] ZoomEye Username(Email): ').strip()
     self.password = input('[*] ZoomEye Password: '******'[-] Error ZoomEye username or password.'
         colorprint.red(msg)
         sys.exit()
Ejemplo n.º 8
0
    def login(self):
        msg = '[+] Trying to login with credentials in config file: %s.' % paths.CONFIG_PATH
        colorprint.green(msg)
        self.api_key = ConfigFileParser().shodan_apikey()

        if not self.api_key:
            msg = '[*] Automatic authorization failed.'
            colorprint.cyan(msg)
            msg = '[*] Please input your Shodan API Key (https://account.shodan.io/).'
            colorprint.cyan(msg)
            self.api_key = input('[*] API KEY > ').strip()
Ejemplo n.º 9
0
    def auto_login(self):
        msg = '[+] Trying to login with credentials in config file: %s.' % paths.CONFIG_PATH
        colorprint.green(msg)
        try:
            self.username = ConfigFileParser().ZoomEyeEmail()
            self.password = ConfigFileParser().ZoomEyePassword()
        except:
            pass

        if bool(self.username and self.password):
            if self.get_token():
                return

        msg = '[*] Automatic authorization failed.'
        colorprint.cyan(msg)
        self.manual_login()
Ejemplo n.º 10
0
def handle_fofa(query, limit, offset=0):
    try:
        msg = '[+] Trying to login with credentials in config file: {}.'.format(
            paths.CONFIG_PATH)
        colorprint.green(msg)
        email = ConfigFileParser().fofa_email()
        key = ConfigFileParser().fofa_key()
        if check(email, key):
            pass
        else:
            raise Exception(
                "Automatic authorization failed")  # will go to except block
    except Exception as e:
        logger.debug(e)
        msg = '[*] Automatic authorization failed.'
        colorprint.cyan(msg)
        msg = '[*] Please input your FoFa Email and API Key below.'
        colorprint.cyan(msg)
        email = input("[*] Fofa Email: ").strip()
        key = input('[*] Fofa API Key: ').strip()
        if not check(email, key):
            msg = '[-] Fofa API authorization failed, Please re-run it and enter a valid key.'
            colorprint.red(msg)
            sys.exit()

    query = base64.b64encode(query.encode('utf-8')).decode('utf-8')

    # count how many result to search
    size = limit + offset

    url = f"https://fofa.info/api/v1/search/all?email={email}&key={key}&qbase64={query}&size={size}&fields=host,ip,protocol,port"
    try:
        response = request.get(url).text
        resp = json.loads(response)
        if not resp["error"]:
            for item in resp.get('results')[offset:]:
                host = item[0]
                protocol = item[2]
                # 下面根据host,ip, protocal, port来组装,一般用host就够了,但是对于http/https还需要处理一下
                if protocol == "https" or protocol == "http":
                    if not host.startswith("http"):
                        host = protocol + "://" + host
                conf.target.add(host)

    except Exception as e:
        colorprint.red(e)
        sys.exit()
Ejemplo n.º 11
0
def handle_google(query, limit, offset=0):
    key = ConfigFileParser().google_developer_key()
    engine = ConfigFileParser().google_engine()
    if not key or not engine:
        msg = "[-] Please config your 'developer_key' and 'search_enging' at saucerfram.conf"
        colorprint.red(msg)
        sys.exit()
    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'))
        colorprint.green(msg)

        ans = set()
        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.add(url.get('link'))
        for t in ans:
            conf.target.put(t)

    except SocketError:
        colorprint.red(
            '[-] Unable to connect Google, maybe agent/proxy error.')
        sys.exit()
    except ServerHttpDenied as e:
        colorprint.cyan('[-] It seems like Google-Server denied this request.')
        colorprint.red(e)
        sys.exit()
Ejemplo n.º 12
0
def handle_fofa(query, limit, offset=0):
    try:
        msg = '[+] Trying to login with credentials in config file: %s.' % paths.CONFIG_PATH
        colorprint.green(msg)
        email = ConfigFileParser().fofa_email()
        key = ConfigFileParser().fofa_key()
        if check(email, key):
            pass
        else:
            raise SystemExit  # will go to except block
    except Exception as e:
        logger.debug(e)
        msg = '[*] Automatic authorization failed.'
        colorprint.cyan(msg)
        msg = '[*] Please input your FoFa Email and API Key below.'
        colorprint.cyan(msg)
        email = input("[*] Fofa Email: ").strip()
        key = input('[*] Fofa API Key: ').strip()
        if not check(email, key):
            msg = '[-] Fofa API authorization failed, Please re-run it and enter a valid key.'
            colorprint.red(msg)
            sys.exit()

    query = base64.b64encode(query)

    request = "https://fofa.so/api/v1/search/all?email={0}&key={1}&qbase64={2}".format(
        email, key, query)
    try:
        response = requests.get(request)
        resp = response.readlines()[0]
        resp = json.loads(resp)
        if resp["error"] is None:
            for item in resp.get('results'):
                conf.target.append(item[0])
            if resp.get('size') >= 100:
                colorprint.cyan(
                    "{0} items found! just 100 returned....".format(
                        resp.get('size')))
    except Exception as e:
        colorprint.red(e)
        sys.exit()
Ejemplo n.º 13
0
def target_register(args):

    # init target queue
    conf.target = set()

    # single target to queue
    if args.target_single:
        msg = '[+] Load target : {}'.format(args.target_single)
        colorprint.green(msg)
        conf.target.add(args.target_single)

    # file target to queue
    if args.target_file:
        if not os.path.isfile(args.target_file):
            msg = '[-] TargetFile not found: {}'.format(args.target_file)
            colorprint.red(msg)
            sys.exit()
        msg = '[+] Load targets from : {}'.format(args.target_file)
        colorprint.green(msg)
        with open(args.target_file, 'r', encoding='utf8') as f:
            targets = f.readlines()
            for target in targets:
                conf.target.add(target.strip('\n'))

    # range of ip target to queue .e.g. 192.168.1.1-192.168.1.100
    if args.target_range:
        try:
            lists = gen_ip(args.target_range)
            if (len(lists)) > 100000:
                warn_msg = "[*] Loading {} targets, Maybe it's too much, continue? [y/N]".format(
                    (len(lists)))
                colorprint.cyan(warn_msg, end='')
                flag = input()
                if flag in ('Y', 'y', 'yes', 'YES', 'Yes'):
                    pass
                else:
                    msg = '[-] User quit!'
                    colorprint.cyan(msg)
                    sys.exit()

            msg = '[+] Load targets from : {}'.format(args.target_range)
            colorprint.green(msg)

            # save to conf
            for target in lists:
                conf.target.add(target)

        except:  # Exception as e:
            # colorprint.red(e)
            err_msg = "Invalid input in [-iR], Example: -iR 192.168.1.1-192.168.1.100"
            colorprint.red(err_msg)
            sys.exit()

    # ip/mask e.g. 192.168.1.2/24
    if args.target_network:
        try:
            ip_range = ipaddress.ip_network(args.target_network, strict=False)
            for ip in ip_range.hosts():
                conf.target.add(ip)

        except:  #  Exception as e:
            # colorprint.red(e)
            msg = "[-] Invalid input in [-iN], Example: -iN 192.168.1.0/24"
            colorprint.red(msg)
            sys.exit()

        msg = '[+] Load targets from : {}'.format(args.target_network)
        colorprint.green(msg)

    # set search limit of api
    if args.api_limit <= 0:
        err_msg = 'Invalid input in [-limit] (can not be negative number)'
        colorprint.red(err_msg)
        sys.exit()
    if args.api_limit > 10000:
        warn_msg = "Loading {} targets, Maybe it's too much, continue? [y/N]".format(
            args.api_limit)
        colorprint.cyan(warn_msg)
        flag = input()
        if flag in ('Y', 'y', 'yes', 'YES', 'Yes'):
            pass
        else:
            msg = 'User quit!'
            colorprint.cyan(msg)
            sys.exit()
    conf.limit = args.api_limit

    # set search offset of api
    if args.api_offset < 0:
        warn_msg = "Wrong offset setting, would you like to set it to 0? [y/N]".format(
            args.api_limit)
        colorprint.cyan(warn_msg)
        flag = input()
        if flag in ('Y', 'y', 'yes', 'YES', 'Yes'):
            args.api_offset = 0
        else:
            msg = 'User quit!'
            colorprint.cyan(msg)
            sys.exit()
    conf.offset = args.api_offset

    if args.zoomeye_dork:
        from lib.api.zoomeye.zoomeye import handle_zoomeye
        # verify search_type for zoomeye
        if args.search_type not in ['web', 'host']:
            msg = '[-] Invalid value in [--search-type], show usage with [-h]'
            colorprint.red(msg)
            sys.exit()
        conf.search_type = args.search_type
        handle_zoomeye(query=args.zoomeye_dork,
                       limit=conf.limit,
                       type=conf.search_type,
                       offset=conf.offset)

    if args.fofa_dork:
        from lib.api.fofa.fofa import handle_fofa
        handle_fofa(query=args.fofa_dork, limit=conf.limit, offset=conf.offset)

    if args.shodan_dork:
        from lib.api.shodan.shodan import handle_shodan
        handle_shodan(query=args.shodan_dork,
                      limit=conf.limit,
                      offset=conf.offset)

    if args.censys_dork:
        from lib.api.censys.censys import handle_censys
        handle_censys(query=args.censys_dork,
                      limit=conf.limit,
                      offset=conf.offset)

    # verify targets number
    if len(conf.target) == 0:
        err_msg = 'No targets found\nPlease load targets with [-iU|-iF|-iR|-iN] or use API with [-aZ|-aS|-aG|-aF]'
        colorprint.red(err_msg)
        sys.exit()
Ejemplo n.º 14
0
"""
Copyright (c) saucerman (https://saucer-man.com)
See the file 'LICENSE' for copying permission
"""

import sys
import json
import base64
from lib.utils.config import ConfigFileParser
from lib.core.common import colorprint
from lib.core.data import paths, conf, logger
try:
    import requests
except ImportError:
    colorprint.red("[-] Can't import requests")
    colorprint.cyan("[*] Try pip install requests")
    sys.exit()


def check(email, key):  # verify email and key
    if email and key:
        auth_url = "https://fofa.so/api/v1/info/my?email={0}&key={1}".format(
            email, key)
        try:
            response = requests.get(auth_url)
            if response.code == 200:
                return True
        except Exception as e:
            return False
    return False
Ejemplo n.º 15
0
See the file 'LICENSE' for copying permission
"""

import sys
from lib.core.common import colorprint
from lib.core.enums import PROXY_TYPE
from lib.utils.config import ConfigFileParser
from lib.core.data import conf
from httplib2 import Http, ProxyInfo
from socket import error as SocketError
try:
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError as ServerHttpDenied
except:
    colorprint.red("[-] Can't import googleapiclient")
    colorprint.cyan("[*] Try pip install google-api-python-client")
    sys.exit()


def _initHttpClient():
    if conf.google_proxy:
        proxy_str = conf.google_proxy
    elif ConfigFileParser().google_proxy():
        proxy_str = ConfigFileParser().google_proxy()
    else:
        proxy_str = None

    if not proxy_str:
        return Http()

    msg = 'Proxy: %s' % proxy_str