def load_all_method_args(language, API=False):
    module_names = []
    modules_args = {}
    # get module names
    for _lib in glob(os.path.dirname(inspect.getfile(lib)) + '/*/*/engine.py'):
        _lib = _lib.replace('/', '.').replace('\\', '.')
        if '.lib.brute.' in _lib or '.lib.scan.' in _lib or '.lib.vuln.' in _lib:
            _lib = 'lib.' + _lib.rsplit('.lib.')[-1].rsplit('.py')[0]
            if _lib not in module_names:
                module_names.append(_lib)
    # get args
    res = ""
    for imodule in module_names:
        try:
            extra_requirements_dict = getattr(
                __import__(imodule, fromlist=['extra_requirements_dict']),
                'extra_requirements_dict')
        except:
            __die_failure(messages(language, 112).format(imodule))
        imodule_args = extra_requirements_dict()
        modules_args[imodule] = []
        for imodule_arg in imodule_args:
            if API:
                res += imodule_arg + "=" + ",".join(
                    map(str, imodule_args[imodule_arg])) + "\n"
            modules_args[imodule].append(imodule_arg)
    if API:
        return res
    for imodule in modules_args:
        info(
            imodule.rsplit('.')[2] + '_' + imodule.rsplit('.')[1] + ' --> ' +
            ", ".join(modules_args[imodule]))
    return module_names
Exemple #2
0
def build_graph(graph_flag, language, data, _HOST, _USERNAME, _PASSWORD, _PORT,
                _TYPE, _DESCRIPTION):
    """
    build a graph

    Args:
        graph_flag: graph name
        language: language
        data: events in JSON type
        _HOST: host key used in JSON
        _USERNAME: username key used in JSON
        _PASSWORD: password key used in JSON
        _PORT: port key used in JSON
        _TYPE: type key used in JSON
        _DESCRIPTION: description key used in JSON

    Returns:
        graph in HTML type
    """
    info(messages(language, 88))
    try:
        start = getattr(
            __import__('lib.graph.{0}.engine'.format(
                graph_flag.rsplit('_graph')[0]),
                       fromlist=['start']), 'start')
    except:
        __die_failure(messages(language, 98).format(graph_flag))

    info(messages(language, 89))
    return start(graph_flag, language, data, _HOST, _USERNAME, _PASSWORD,
                 _PORT, _TYPE, _DESCRIPTION)
Exemple #3
0
def check(language):
    """
    check if framework compatible with the OS
    Args:
        language: language

    Returns:
        True if compatible otherwise None
    """
    # from core.color import finish
    from core.alert import messages
    if "linux" in os_name() or "darwin" in os_name():
        pass
        # os.system("clear")
    elif "win32" == os_name() or "win64" == os_name():
        # if language != "en":
        #    from core.color import finish
        #    from core.alert import error
        #   error("please use english language on windows!")
        #    finish()
        #    sys.exit(1)
        # os.system("cls")
        pass
    else:
        __die_failure(messages(language, "error_platform"))
    if version() is 2 or version() is 3:
        pass
    else:
        __die_failure(messages(language, "python_version_error"))
    logo()
    return True
Exemple #4
0
def load_all_method_args(language, API=False):
    module_names = []
    modules_args = {}
    # get module names
    for lib in glob('lib/*/*/engine.py'):
        lib = lib.replace('/', '.').replace('\\', '.').rsplit('.py')[0]
        if lib.rsplit('.')[1] != 'graph' and lib not in module_names:
            module_names.append(lib)
    # get args
    res = ""
    for imodule in module_names:
        try:
            extra_requirements_dict = getattr(
                __import__(imodule, fromlist=['extra_requirements_dict']),
                'extra_requirements_dict')
        except:
            __die_failure(messages(language, 112).format(imodule))
        imodule_args = extra_requirements_dict()
        modules_args[imodule] = []
        for imodule_arg in imodule_args:
            if API:
                res += imodule_arg + "=" + ",".join(
                    map(str, imodule_args[imodule_arg])) + "\n"
            modules_args[imodule].append(imodule_arg)
    if API:
        return res
    for imodule in modules_args:
        info(
            imodule.rsplit('.')[2] + '_' + imodule.rsplit('.')[1] + ' --> ' +
            ", ".join(modules_args[imodule]))
    return module_names
Exemple #5
0
def check(language):
    """
    check if framework compatible with the OS
    Args:
        language: language

    Returns:
        True if compatible otherwise None
    """
    # from core.color import finish
    if 'linux' in os_name() or 'darwin' in os_name():
        pass
        # os.system('clear')
    elif 'win32' == os_name() or 'win64' == os_name():
        # if language != 'en':
        #    from core.color import finish
        #    from core.alert import error
        #   error('please use english language on windows!')
        #    finish()
        #    sys.exit(1)
        # os.system('cls')
        pass
    else:
        __die_failure(messages(language, "error_platform"))
    if version() is 2 or version() is 3:
        pass
    else:
        __die_failure(messages(language, "python_version_error"))
    logo()
    return True
Exemple #6
0
def __check_external_modules():
    external_modules = [
        "argparse", "netaddr", "requests", "paramiko", "texttable", "socks",
        "win_inet_pton", "flask"
    ]
    for module in external_modules:
        try:
            __import__(module)
        except:
            __die_failure("pip install -r requirements.txt ---> " + module +
                          " not installed!")
    return True
Exemple #7
0
def build_graph(graph_flag, language, data, _HOST, _USERNAME, _PASSWORD, _PORT, _TYPE, _DESCRIPTION):
    info(messages(language, 88))
    try:
        start = getattr(
            __import__('lib.graph.{0}.engine'.format(graph_flag.rsplit('_graph')[0]),
                       fromlist=['start']),
            'start')
    except:
        __die_failure(messages(language, 98).format(graph_flag))

    info(messages(language, 89))
    return start(graph_flag, language, data, _HOST, _USERNAME, _PASSWORD, _PORT, _TYPE, _DESCRIPTION)
Exemple #8
0
def start_attack(target, num, total, scan_method, users, passwds, timeout_sec,
                 thread_number, ports, log_in_file, time_sleep, language,
                 verbose_level, socks_proxy, retries, ping_flag, methods_args,
                 scan_id, scan_cmd):
    info(messages(language, 45).format(str(target), str(num), str(total)))
    # Calling Engines
    try:
        start = getattr(
            __import__('lib.{0}.{1}.engine'.format(
                scan_method.rsplit('_')[-1],
                '_'.join(scan_method.rsplit('_')[:-1])),
                       fromlist=['start']), 'start')
    except:
        __die_failure(messages(language, 46).format(scan_method))
    start(target, users, passwds, ports, timeout_sec, thread_number, num,
          total, log_in_file, time_sleep, language, verbose_level, socks_proxy,
          retries, ping_flag, methods_args, scan_id, scan_cmd)
    return 0
Exemple #9
0
def __process_it(api_host, api_port, api_debug_mode, api_access_key,
                 api_client_white_list, api_client_white_list_ips,
                 api_access_log, api_access_log_filename, api_cert,
                 api_cert_key, language):
    """
    a function to run flask in a subprocess to make kill signal in a better way!

    Args:
        api_host: host/IP to bind address
        api_port: bind port
        api_debug_mode: debug mode flag
        api_access_key: API access key
        api_client_white_list: clients while list flag
        api_client_white_list_ips: clients white list IPs
        api_access_log: access log flag
        api_access_log_filename: access log filename
        api_cert: SSL certificate
        api_cert_key: SSL Private key

        language: language
    """
    app.config["OWASP_NETTACKER_CONFIG"] = {
        "api_access_key": api_access_key,
        "api_client_white_list": api_client_white_list,
        "api_client_white_list_ips": api_client_white_list_ips,
        "api_access_log": api_access_log,
        "api_access_log_filename": api_access_log_filename,
        "api_cert": api_cert,
        "api_cert_key": api_cert_key,
        "language": language
    }
    try:
        if api_cert:
            if api_cert_key:
                app.run(host=api_host,
                        port=api_port,
                        debug=api_debug_mode,
                        ssl_context=(api_cert, api_cert_key),
                        threaded=True)
            else:
                __die_failure(messages(language, "api_cert_key"))

        if api_cert_key:
            if api_cert:
                app.run(host=api_host,
                        port=api_port,
                        debug=api_debug_mode,
                        ssl_context=(api_cert, api_cert_key),
                        threaded=True)
            else:
                __die_failure(messages(language, "api_cert"))

        else:
            app.run(host=api_host,
                    port=api_port,
                    debug=api_debug_mode,
                    ssl_context="adhoc",
                    threaded=True)
    except Exception as e:
        __die_failure(messages(language, "wrong_values"))
Exemple #10
0
def check(language):
    from core.color import finish
    if 'linux' in os_name() or 'darwin' in os_name():
        pass
        # os.system('clear')
    elif 'win32' == os_name() or 'win64' == os_name():
        # if language != 'en':
        #    from core.color import finish
        #    from core.alert import error
        #   error('please use english language on windows!')
        #    finish()
        #    sys.exit(1)
        # os.system('cls')
        pass
    else:
        __die_failure(messages(language, 47))
    if version() is 2 or version() is 3:
        pass
    else:
        __die_failure(messages(language, 48))
    logo()
    return
Exemple #11
0
def check_for_requirements(start_api_server):
    """
    check if requirements exist

    Returns:
        True if exist otherwise False
    """
    from core.alert import messages
    from config import api_configuration
    # check external required modules
    try:
        import pymongo
        import netaddr
        import flask
        del netaddr
        del flask
    except Exception as _:
        __die_failure("pip install -r requirements.txt")
    # check mongodb
    try:
        connection = pymongo.MongoClient(
            api_configuration()["api_database"],
            serverSelectionTimeoutMS=api_configuration()
            ["api_database_connection_timeout"])
        connection.list_database_names()
    except Exception as _:
        __die_failure("cannot connect to mongodb")
    # check if its honeypot server not api server
    if not start_api_server:
        # check docker
        try:
            subprocess.check_output(["docker", "--help"],
                                    stderr=subprocess.PIPE)
        except Exception as _:
            __die_failure(messages("en", "docker_error"))
        # check tshark
        try:
            subprocess.check_output(["tshark", "--help"],
                                    stderr=subprocess.PIPE)
        except Exception as _:
            __die_failure("please install tshark first!")
    return True
def __check_external_modules():
    external_modules = [
        "argparse", "netaddr", "requests", "paramiko", "texttable", "socks",
        "win_inet_pton", "flask", "sqlite3"
    ]
    for module in external_modules:
        try:
            __import__(module)
        except:
            __die_failure("pip install -r requirements.txt ---> " + module +
                          " not installed!")

    default_config = _builder(_core_config(), _core_default_config())

    if not os.path.exists(default_config["home_path"]):
        try:
            os.mkdir(default_config["home_path"])
            os.mkdir(default_config["tmp_path"])
            os.mkdir(default_config["results_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["home_path"]))
    if not os.path.exists(default_config["tmp_path"]):
        try:
            os.mkdir(default_config["tmp_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["results_path"]))
    if not os.path.exists(default_config["results_path"]):
        try:
            os.mkdir(default_config["results_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["results_path"]))
    if not os.path.isfile(default_config["api_db_name"]):
        try:
            copyfile(
                os.path.dirname(inspect.getfile(api)) + '/database.sqlite3',
                default_config["api_db_name"])
            if not os.path.isfile(default_config["api_db_name"]):
                __die_failure("cannot access the directory {0}".format(
                    default_config["api_db_name"]))
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["api_db_name"]))
    return True
Exemple #13
0
def start(target, users, passwds, ports, timeout_sec, thread_number, num,
          total, log_in_file, time_sleep, language, verbose_level, socks_proxy,
          retries, methods_args, scan_id, scan_cmd):  # Main function
    if target_type(target) != 'SINGLE_IPv4' or target_type(
            target) != 'DOMAIN' or target_type(
                target) != 'HTTP' or target_type(target) != 'SINGLE_IPv6':
        # rand useragent
        user_agent_list = [
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5",
            "Googlebot/2.1 ( http://www.googlebot.com/bot.html)",
            "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Ubuntu/10.04"
            " Chromium/9.0.595.0 Chrome/9.0.595.0 Safari/534.13",
            "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.2; WOW64; .NET CLR 2.0.50727)",
            "Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51",
            "Mozilla/5.0 (compatible; 008/0.83; http://www.80legs.com/webcrawler.html) Gecko/2008032620",
            "Debian APT-HTTP/1.3 (0.8.10.3)",
            "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
            "Googlebot/2.1 (+http://www.googlebot.com/bot.html)",
            "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)",
            "YahooSeeker/1.2 (compatible; Mozilla 4.0; MSIE 5.5; yahooseeker at yahoo-inc dot com ; "
            "http://help.yahoo.com/help/us/shop/merchant/)",
            "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)",
            "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
            "msnbot/1.1 (+http://search.msn.com/msnbot.htm)"
        ]
        user_agent = {'User-agent': random.choice(user_agent_list)}
        limit = 1000
        # requirements check
        new_extra_requirements = extra_requirements_dict()
        if methods_args is not None:
            for extra_requirement in extra_requirements_dict():
                if extra_requirement in methods_args:
                    new_extra_requirements[extra_requirement] = methods_args[
                        extra_requirement]
        extra_requirements = new_extra_requirements
        random_agent_flag = True
        if extra_requirements["wordpress_dos_cve_2018_6389_vuln_random_agent"][
                0] != "True":
            random_agent_flag = False
        if extra_requirements["wordpress_dos_cve_2018_6389_vuln_no_limit"][
                0] != "False":
            limit = -1
        threads = []
        total_req = limit
        filepath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        thread_tmp_filename = '{}/tmp/thread_tmp_'.format(
            load_file_path()) + ''.join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(20))
        __log_into_file(thread_tmp_filename, 'w', '1', language)
        trying = 0
        if target_type(target) == 'SINGLE_IPv4' or target_type(
                target) == 'DOMAIN':
            url = 'http://{0}/'.format(target)
        else:
            if target.count(':') > 1:
                __die_failure(messages(language, "insert_port_message"))
            http = target.rsplit('://')[0]
            host = target_to_host(target)
            path = "/".join(
                target.replace('http://', '').replace('https://',
                                                      '').rsplit('/')[1:])
            url = http + '://' + host + '/' + path
        if test(url, retries, timeout_sec, user_agent, socks_proxy,
                verbose_level, trying, total_req, total, num, language, False,
                log_in_file, scan_id, scan_cmd, thread_tmp_filename) is not 0:
            warn(messages(language, "open_error").format(url))
            return
        info(messages(language, "DOS_send").format(target))
        n = 0
        t = threading.Thread(
            target=test,
            args=(url, retries, timeout_sec, user_agent, socks_proxy,
                  verbose_level, trying, total_req, total, num, language, True,
                  log_in_file, scan_id, scan_cmd, thread_tmp_filename))
        t.start()
        keyboard_interrupt_flag = False
        while (n != limit):
            n += 1
            if random_agent_flag:
                user_agent = {'User-agent': random.choice(user_agent_list)}
            t = threading.Thread(target=send_dos,
                                 args=(url, user_agent, timeout_sec,
                                       log_in_file, language, time_sleep,
                                       thread_tmp_filename, retries,
                                       socks_proxy, scan_id, scan_cmd))
            threads.append(t)
            t.start()
            trying += 1
            if verbose_level > 3:
                info(
                    messages(language, "trying_message").format(
                        trying, total_req, num, total, target_to_host(target),
                        port, 'wordpress_dos_cve_2018_6389_vuln'))
            try:
                if int(open(thread_tmp_filename).read().rsplit()[0]) is 0:
                    if limit is not -1:
                        break
            except Exception:
                pass
            while 1:
                try:
                    if threading.activeCount() >= thread_number:
                        time.sleep(0.01)
                    else:
                        break
                except KeyboardInterrupt:
                    keyboard_interrupt_flag = True
                    break
            if keyboard_interrupt_flag:
                break
        # wait for threads
        kill_switch = 0
        kill_time = int(timeout_sec / 0.1) if int(timeout_sec /
                                                  0.1) is not 0 else 1
        while 1:
            time.sleep(0.1)
            kill_switch += 1
            try:
                if threading.activeCount() is 2 or kill_switch is kill_time:
                    break
            except KeyboardInterrupt:
                break
        thread_write = int(open(thread_tmp_filename).read().rsplit()[0])
        if thread_write is 1:
            info(
                messages(language, "no_vulnerability_found").format(
                    "wordpress_dos_cve_2018_6389_vuln"))
            if verbose_level is not 0:
                data = json.dumps({
                    'HOST':
                    target,
                    'USERNAME':
                    '',
                    'PASSWORD':
                    '',
                    'PORT':
                    '',
                    'TYPE':
                    'wordpress_dos_cve_2018_6389_vuln',
                    'DESCRIPTION':
                    messages(language, "no_vulnerability_found").format(
                        "wordpress_dos_cve_2018_6389_vuln"),
                    'TIME':
                    now(),
                    'CATEGORY':
                    "scan",
                    'SCAN_ID':
                    scan_id,
                    'SCAN_CMD':
                    scan_cmd
                })
                __log_into_file(log_in_file, 'a', data, language)
        os.remove(thread_tmp_filename)
    else:
        warn(
            messages(language, "input_target_error").format(
                'wordpress_dos_cve_2018_6389_vuln', target))
Exemple #14
0
def start_attack(target, num, total, scan_method, users, passwds, timeout_sec,
                 thread_number, ports, log_in_file, time_sleep, language,
                 verbose_level, socks_proxy, retries, ping_flag, methods_args,
                 scan_id, scan_cmd):
    """
    start new attack for each target

    Args:
        target: target
        num: number of process
        total: number of total processes
        scan_method: module name
        users: usernames
        passwds: passwords
        timeout_sec: timeout seconds
        thread_number: thread number
        ports: port numbers
        log_in_file: output filename
        time_sleep: time sleep
        language: language
        verbose_level: verbose level number
        socks_proxy: socks proxy
        retries: number of retries
        ping_flag: ping before scan flag
        methods_args: module name
        scan_id: scan hash id
        scan_cmd: scan cmd

    Returns:
        True of success otherwise None
    """
    if verbose_level >= 1:
        info(
            messages(language, "start_attack").format(str(target), str(num),
                                                      str(total)))
    if ping_flag:
        if socks_proxy is not None:
            socks_version = socks.SOCKS5 if socks_proxy.startswith(
                'socks5://') else socks.SOCKS4
            socks_proxy = socks_proxy.rsplit('://')[1]
            if '@' in socks_proxy:
                socks_username = socks_proxy.rsplit(':')[0]
                socks_password = socks_proxy.rsplit(':')[1].rsplit('@')[0]
                socks.set_default_proxy(
                    socks_version,
                    str(socks_proxy.rsplit('@')[1].rsplit(':')[0]),
                    int(socks_proxy.rsplit(':')[-1]),
                    username=socks_username,
                    password=socks_password)
                socket.socket = socks.socksocket
                socket.getaddrinfo = getaddrinfo
            else:
                socks.set_default_proxy(socks_version,
                                        str(socks_proxy.rsplit(':')[0]),
                                        int(socks_proxy.rsplit(':')[1]))
                socket.socket = socks.socksocket
                socket.getaddrinfo = getaddrinfo
        if do_one_ping(target, timeout_sec, 8) is None:
            if verbose_level >= 3:
                warn(
                    messages(language,
                             "skipping_target").format(target, scan_method))
            return None
    # Calling Engines
    try:
        start = getattr(
            __import__('lib.{0}.{1}.engine'.format(
                scan_method.rsplit('_')[-1],
                '_'.join(scan_method.rsplit('_')[:-1])),
                       fromlist=['start']), 'start')
    except:
        __die_failure(
            messages(language, "module_not_available").format(scan_method))
    start(target, users, passwds, ports, timeout_sec, thread_number, num,
          total, log_in_file, time_sleep, language, verbose_level, socks_proxy,
          retries, methods_args, scan_id, scan_cmd)
    return True
def check_all_required(
        targets, targets_list, thread_number, thread_number_host, log_in_file,
        scan_method, exclude_method, users, users_list, passwds, passwds_list,
        timeout_sec, ports, parser, module_names, language, verbose_level,
        show_version, check_update, socks_proxy, retries, graph_flag,
        help_menu_flag, methods_args, method_args_list, wizard_mode, profile,
        start_api, api_host, api_port, api_debug_mode, api_access_key,
        api_client_white_list, api_client_white_list_ips, api_access_log,
        api_access_log_filename):
    # Checking Requirements
    # import libs
    from core import compatible
    # Check Help Menu
    if help_menu_flag:
        parser.print_help()
        write("\n\n")
        write(messages(language, 3))
        __die_success()
    # Check if method args list called
    if method_args_list:
        from core.load_modules import load_all_method_args
        load_all_method_args(language)
        __die_success()
    # Check version
    if show_version:
        from core import color
        info(
            messages(language,
                     84).format(color.color("yellow"), compatible.__version__,
                                color.color("reset"), color.color("cyan"),
                                compatible.__code_name__, color.color("reset"),
                                color.color("green")))
        __die_success()
    # API mode
    if start_api:
        from api.engine import _start_api
        from core.targets import target_type
        from core.ip import _generate_IPRange

        try:
            api_port = int(api_port)
        except:
            __die_failure(messages(language, 154))
        if api_client_white_list:
            if type(api_client_white_list_ips) != type([]):
                api_client_white_list_ips = list(
                    set(api_client_white_list_ips.rsplit(",")))
            hosts = []
            for data in api_client_white_list_ips:
                if target_type(data) == "SINGLE_IPv4":
                    if data not in hosts:
                        hosts.append(data)
                elif target_type(data) == "RANGE_IPv4":
                    for cidr in _generate_IPRange(data):
                        for ip in cidr:
                            if ip not in hosts:
                                hosts.append(ip)
                elif target_type(data) == "CIDR_IPv4":
                    for ip in _generate_IPRange(data):
                        if ip not in hosts:
                            hosts.append(str(ip))
                else:
                    __die_failure(messages(language, 155))
            api_client_white_list_ips = hosts[:]
        if api_access_log:
            try:
                f = open(api_access_log_filename, 'a')
            except:
                __die_failure(
                    messages(language, 40).format(api_access_log_filename))
        _start_api(api_host, api_port, api_debug_mode, api_access_key,
                   api_client_white_list, api_client_white_list_ips,
                   api_access_log, api_access_log_filename, language)
    # Wizard mode
    if wizard_mode:
        (targets, thread_number, thread_number_host,
         log_in_file, scan_method, exclude_method, users,
         passwds, timeout_sec, ports, verbose_level,
         socks_proxy, retries, graph_flag) = \
            __wizard(
                targets, thread_number, thread_number_host,
                log_in_file, module_names, exclude_method, users,
                passwds, timeout_sec, ports, verbose_level,
                socks_proxy, retries, load_all_graphs(), language
            )
    # Select a Profile
    if profile is not None:
        _all_profiles = _builder(_profiles(), default_profiles())
        if scan_method is None:
            scan_method = ""
        else:
            scan_method += ","
        if profile == "all":
            profile = ",".join(_all_profiles)
        tmp_sm = scan_method
        for pr in profile.rsplit(","):
            try:
                for sm in _all_profiles[pr]:
                    if sm not in tmp_sm.rsplit(","):
                        tmp_sm += sm + ","
            except:
                __die_failure(messages(language, 137).format(pr))
        if tmp_sm[-1] == ",":
            tmp_sm = tmp_sm[0:-1]
        scan_method = ",".join(list(set(tmp_sm.rsplit(","))))
    # Check Socks
    if socks_proxy is not None:
        e = False
        if socks_proxy.startswith("socks://"):
            socks_flag = 5
            socks_proxy = socks_proxy.replace("socks://", "")
        elif socks_proxy.startswith("socks5://"):
            socks_flag = 5
            socks_proxy = socks_proxy.replace("socks5://", "")
        elif socks_proxy.startswith("socks4://"):
            socks_flag = 4
            socks_proxy = socks_proxy.replace("socks4://", "")
        else:
            socks_flag = 5
        if "://" in socks_proxy:
            socks_proxy = socks_proxy.rsplit("://")[1].rsplit("/")[0]
        try:
            if len(socks_proxy.rsplit(":")) < 2 or len(
                    socks_proxy.rsplit(":")) > 3:
                e = True
            elif len(socks_proxy.rsplit(":")) is 2 and socks_proxy.rsplit(
                    ":")[1] == "":
                e = True
            elif len(socks_proxy.rsplit(":")) is 3 and socks_proxy.rsplit(
                    ":")[2] == "":
                e = True
        except:
            e = True
        if e:
            __die_failure(messages(language, 63))
        if socks_flag is 4:
            socks_proxy = "socks4://" + socks_proxy
        if socks_flag is 5:
            socks_proxy = "socks5://" + socks_proxy
    # Check update
    if check_update:
        from core.update import _update
        _update(compatible.__version__, compatible.__code_name__, language,
                socks_proxy)
        __die_success()
    # Check the target(s)
    if targets is None and targets_list is None:
        parser.print_help()
        write("\n")
        __die_failure(messages(language, 26))
    else:
        if targets is not None:
            targets = list(set(targets.rsplit(",")))
        elif targets_list is not None:
            try:
                targets = list(set(open(targets_list, "rb").read().rsplit()))
            except:
                __die_failure(messages(language, 27).format(targets_list))
    # Check thread number
    if thread_number > 101 or thread_number_host > 101:
        warn(messages(language, 28))
    # Check timeout number
    if timeout_sec is not None and timeout_sec >= 15:
        warn(messages(language, 29).format(timeout_sec))
    # Check scanning method
    if scan_method is not None and scan_method == "all":
        scan_method = module_names
        scan_method.remove("all")
    elif scan_method is not None and scan_method not in module_names:
        if "*_" in scan_method:
            scan_method = scan_method.rsplit(",")
            tmp_scan_method = scan_method[:]
            for sm in scan_method:
                if sm.startswith("*_"):
                    scan_method.remove(sm)
                    found_flag = False
                    for mn in module_names:
                        if mn.endswith("_" + sm.rsplit("*_")[1]):
                            scan_method.append(mn)
                            found_flag = True
                    if found_flag is False:
                        __die_failure(messages(language, 117).format(sm))
            scan_method = ",".join(scan_method)
        if "," in scan_method:
            scan_method = scan_method.rsplit(",")
            for sm in scan_method:
                if sm not in module_names:
                    __die_failure(messages(language, 30).format(sm))
                if sm == "all":
                    scan_method = module_names
                    scan_method.remove("all")
                    break
        else:
            __die_failure(messages(language, 31).format(scan_method))
    elif scan_method is None:
        __die_failure(messages(language, 41))
    else:
        scan_method = scan_method.rsplit()
    # Check for exluding scanning method
    if exclude_method is not None:
        exclude_method = exclude_method.rsplit(",")
        for exm in exclude_method:
            if exm in scan_method:
                if "all" == exm:
                    __die_failure(messages(language, 32))
                else:
                    scan_method.remove(exm)
                    if len(scan_method) is 0:
                        __die_failure(messages(language, 33))
            else:
                __die_failure(messages(language, 34).format(exm))
    # Check port(s)
    if type(ports) is not list and ports is not None and "-" in ports:
        ports = ports.rsplit("-")
        ports = range(int(ports[0]), int(ports[1]) + 1)
    elif type(ports) is not list and ports is not None:
        ports = ports.rsplit(",")
    # Check user list
    if users is not None:
        users = list(set(users.rsplit(",")))
    elif users_list is not None:
        try:
            users = list(set(
                open(users_list).read().rsplit("\n")))  # fix later
        except:
            __die_failure(messages(language, 37).format(targets_list))
    # Check password list
    if passwds is not None:
        passwds = list(set(passwds.rsplit(",")))
    if passwds_list is not None:
        try:
            passwds = list(set(
                open(passwds_list).read().rsplit("\n")))  # fix later
        except:
            __die_failure(messages(language, 39).format(targets_list))
    # Check output file
    try:
        tmpfile = open(log_in_file, "w")
    except:
        __die_failure(messages(language, 40).format(log_in_file))
    # Check Graph
    if graph_flag is not None:
        if graph_flag not in load_all_graphs():
            __die_failure(messages(language, 97).format(graph_flag))
        if not (log_in_file.endswith(".html") or log_in_file.endswith(".htm")):
            warn(messages(language, 87))
            graph_flag = None
    # Check Methods ARGS
    if methods_args is not None:
        new_methods_args = {}
        methods_args = methods_args.rsplit("&")
        for imethod_args in methods_args:
            if len(imethod_args.rsplit("=")) is 2:
                if imethod_args.rsplit("=")[1].startswith("read_from_file:"):
                    try:
                        read_data = list(
                            set(
                                open(
                                    imethod_args.rsplit("=read_from_file:")
                                    [1]).read().rsplit("\n")))
                    except:
                        __die_failure(messages(language, 36))
                    new_methods_args[imethod_args.rsplit("=")[0]] = read_data
                else:
                    new_methods_args[imethod_args.rsplit(
                        "=")[0]] = imethod_args.rsplit("=")[1].rsplit(",")
            else:
                new_methods_args[imethod_args.rsplit("=")[0]] = ""
        methods_args = new_methods_args
    # Return the values
    return [
        targets, targets_list, thread_number, thread_number_host, log_in_file,
        scan_method, exclude_method, users, users_list, passwds, passwds_list,
        timeout_sec, ports, parser, module_names, language, verbose_level,
        show_version, check_update, socks_proxy, retries, graph_flag,
        help_menu_flag, methods_args, method_args_list, wizard_mode, profile,
        start_api, api_host, api_port, api_debug_mode, api_access_key,
        api_client_white_list, api_client_white_list_ips, api_access_log,
        api_access_log_filename
    ]
def load_all_args(module_names, graph_names):
    # Language Options
    # import libs
    default_config = _builder(_core_config(), _core_default_config())
    _all_profiles = [key for key in _builder(_profiles(), default_profiles())]
    _all_profiles.append("all")
    language_list = [lang for lang in messages(-1, 0)]
    if "-L" in sys.argv or "--language" in sys.argv:
        try:
            index = sys.argv.index("-L") + 1
        except:
            index = sys.argv.index("--language") + 1
    else:
        index = -1
    if index is -1:
        language = "en"
    else:
        _error_flag = False
        try:
            language = sys.argv[index]
        except:
            _error_flag = True
        if _error_flag or language not in language_list:
            __die_failure("Please select one of these languages {0}".format(
                language_list))

    # Check if compatible
    check(language)
    finish()
    # Start Parser
    parser = argparse.ArgumentParser(prog="Nettacker", add_help=False)

    # parser = OptionParser(usage=messages(language, 1),
    #                      description=messages(language, 2),
    #                      epilog=messages(language, 3))

    # Engine Options
    engineOpt = parser.add_argument_group(messages(language, 4),
                                          messages(language, 5))
    engineOpt.add_argument("-L",
                           "--language",
                           action="store",
                           dest="language",
                           default=default_config["language"],
                           help=messages(language, 6).format(language_list))
    engineOpt.add_argument("-v",
                           "--verbose",
                           action="store",
                           dest="verbose_level",
                           default=default_config["verbose_level"],
                           help=messages(language, 59))
    engineOpt.add_argument("-V",
                           "--version",
                           action="store_true",
                           default=default_config["show_version"],
                           dest="show_version",
                           help=messages(language, 60))
    engineOpt.add_argument("-c",
                           "--update",
                           action="store_true",
                           default=default_config["check_update"],
                           dest="check_update",
                           help=messages(language, 61))
    engineOpt.add_argument("-o",
                           "--output",
                           action="store",
                           default=default_config["log_in_file"],
                           dest="log_in_file",
                           help=messages(language, 11))
    engineOpt.add_argument("--graph",
                           action="store",
                           default=default_config["graph_flag"],
                           dest="graph_flag",
                           help=messages(language, 86).format(graph_names))
    engineOpt.add_argument("-h",
                           "--help",
                           action="store_true",
                           default=default_config["help_menu_flag"],
                           dest="help_menu_flag",
                           help=messages(language, 2))
    engineOpt.add_argument("-W",
                           "--wizard",
                           action="store_true",
                           default=default_config["wizard_mode"],
                           dest="wizard_mode",
                           help=messages(language, 107))
    engineOpt.add_argument("--profile",
                           action="store",
                           default=default_config["profile"],
                           dest="profile",
                           help=messages(language, 136).format(_all_profiles))

    # Target Options
    target = parser.add_argument_group(messages(language, 12),
                                       messages(language, 13))
    target.add_argument("-i",
                        "--targets",
                        action="store",
                        dest="targets",
                        default=default_config["targets"],
                        help=messages(language, 14))
    target.add_argument("-l",
                        "--targets-list",
                        action="store",
                        dest="targets_list",
                        default=default_config["targets_list"],
                        help=messages(language, 15))

    # Exclude Module Name
    exclude_names = module_names[:]
    exclude_names.remove("all")

    # Methods Options
    method = parser.add_argument_group(messages(language, 142),
                                       messages(language, 16))
    method.add_argument("-m",
                        "--method",
                        action="store",
                        dest="scan_method",
                        default=default_config["scan_method"],
                        help=messages(language, 17).format(module_names))
    method.add_argument("-x",
                        "--exclude",
                        action="store",
                        dest="exclude_method",
                        default=default_config["exclude_method"],
                        help=messages(language, 18).format(exclude_names))
    method.add_argument("-u",
                        "--usernames",
                        action="store",
                        dest="users",
                        default=default_config["users"],
                        help=messages(language, 19))
    method.add_argument("-U",
                        "--users-list",
                        action="store",
                        dest="users_list",
                        default=default_config["users_list"],
                        help=messages(language, 20))
    method.add_argument("-p",
                        "--passwords",
                        action="store",
                        dest="passwds",
                        default=default_config["passwds"],
                        help=messages(language, 21))
    method.add_argument("-P",
                        "--passwords-list",
                        action="store",
                        dest="passwds_list",
                        default=default_config["passwds_list"],
                        help=messages(language, 22))
    method.add_argument("-g",
                        "--ports",
                        action="store",
                        dest="ports",
                        default=default_config["ports"],
                        help=messages(language, 23))
    method.add_argument("-T",
                        "--timeout",
                        action="store",
                        dest="timeout_sec",
                        default=default_config["timeout_sec"],
                        type=float,
                        help=messages(language, 24))
    method.add_argument("-w",
                        "--time-sleep",
                        action="store",
                        dest="time_sleep",
                        default=default_config["time_sleep"],
                        type=float,
                        help=messages(language, 25))
    method.add_argument("-r",
                        "--range",
                        action="store_true",
                        default=default_config["check_ranges"],
                        dest="check_ranges",
                        help=messages(language, 7))
    method.add_argument("-s",
                        "--sub-domains",
                        action="store_true",
                        default=default_config["check_subdomains"],
                        dest="check_subdomains",
                        help=messages(language, 8))
    method.add_argument("-t",
                        "--thread-connection",
                        action="store",
                        default=default_config["thread_number"],
                        type=int,
                        dest="thread_number",
                        help=messages(language, 9))
    method.add_argument("-M",
                        "--thread-hostscan",
                        action="store",
                        default=default_config["thread_number_host"],
                        type=int,
                        dest="thread_number_host",
                        help=messages(language, 10))
    method.add_argument("-R",
                        "--socks-proxy",
                        action="store",
                        dest="socks_proxy",
                        default=default_config["socks_proxy"],
                        help=messages(language, 62))
    method.add_argument("--retries",
                        action="store",
                        dest="retries",
                        type=int,
                        default=default_config["retries"],
                        help=messages(language, 64))
    method.add_argument("--ping-before-scan",
                        action="store_true",
                        dest="ping_flag",
                        default=default_config["ping_flag"],
                        help=messages(language, 99))
    method.add_argument("--method-args",
                        action="store",
                        dest="methods_args",
                        default=default_config["methods_args"],
                        help=messages(language, 35))
    method.add_argument("--method-args-list",
                        action="store_true",
                        dest="method_args_list",
                        default=default_config["method_args_list"],
                        help=messages(language, 111))

    # API Options
    api = parser.add_argument_group(messages(language, 143),
                                    messages(language, 144))
    api.add_argument("--start-api",
                     action="store_true",
                     dest="start_api",
                     default=default_config["start_api"],
                     help=messages(language, 145))
    api.add_argument("--api-host",
                     action="store",
                     dest="api_host",
                     default=default_config["api_host"],
                     help=messages(language, 146))
    api.add_argument("--api-port",
                     action="store",
                     dest="api_port",
                     default=default_config["api_port"],
                     help=messages(language, 147))
    api.add_argument("--api-debug-mode",
                     action="store_true",
                     dest="api_debug_mode",
                     default=default_config["api_debug_mode"],
                     help=messages(language, 148))
    api.add_argument("--api-access-key",
                     action="store",
                     dest="api_access_key",
                     default=default_config["api_access_key"],
                     help=messages(language, 149))
    api.add_argument("--api-client-white-list",
                     action="store_true",
                     dest="api_client_white_list",
                     default=default_config["api_client_white_list"],
                     help=messages(language, 150))
    api.add_argument("--api-client-white-list-ips",
                     action="store",
                     dest="api_client_white_list_ips",
                     default=default_config["api_client_white_list_ips"],
                     help=messages(language, 151))
    api.add_argument("--api-access-log",
                     action="store_true",
                     dest="api_access_log",
                     default=default_config["api_access_log"],
                     help=messages(language, 152))
    api.add_argument("--api-access-log-filename",
                     action="store",
                     dest="api_access_log_filename",
                     default=default_config["api_access_log_filename"],
                     help=messages(language, 153))

    # Return Options
    return [
        parser,
        parser.parse_args(), default_config["startup_check_for_update"]
    ]
def check_all_required(targets, targets_list, thread_number, thread_number_host,
                       log_in_file, scan_method, exclude_method, users, users_list,
                       passwds, passwds_list, timeout_sec, ports, parser, module_names,
                       language, verbose_level, show_version, check_update, socks_proxy,
                       retries, graph_flag, help_menu_flag, methods_args, method_args_list,
                       wizard_mode, profile):
    # Checking Requirements
    # import libs
    from core import compatible
    # Check Help Menu
    if help_menu_flag:
        parser.print_help()
        write('\n\n')
        write(messages(language, 3))
        __die_success()
    # Check if method args list called
    if method_args_list:
        from core.load_modules import load_all_method_args
        load_all_method_args(language)
        __die_success()
    # Check version
    if show_version:
        from core import color
        info(messages(language, 84).format(color.color('yellow'), compatible.__version__, color.color('reset'),
                                           color.color('cyan'), compatible.__code_name__, color.color('reset'),
                                           color.color('green')))
        __die_success()
    # Wizard mode
    if wizard_mode:
        (targets, thread_number, thread_number_host,
         log_in_file, scan_method, exclude_method, users,
         passwds, timeout_sec, ports, verbose_level,
         socks_proxy, retries, graph_flag) = \
            __wizard(
                targets, thread_number, thread_number_host,
                log_in_file, module_names, exclude_method, users,
                passwds, timeout_sec, ports, verbose_level,
                socks_proxy, retries, load_all_graphs(), language
            )
    # Select a Profile
    if profile is not None:
        _all_profiles = _builder(get_profiles(), all_profiles())
        if scan_method is None:
            scan_method = ''
        else:
            scan_method += ','
        if profile == 'all':
            profile = ','.join(_all_profiles)
        tmp_sm = scan_method
        for pr in profile.rsplit(','):
            try:
                for sm in _all_profiles[pr]:
                    if sm not in tmp_sm.rsplit(','):
                        tmp_sm += sm + ','
            except:
                __die_failure(messages(language, 137).format(pr))
        if tmp_sm[-1] == ',':
            tmp_sm = tmp_sm[0:-1]
        scan_method = ','.join(list(set(tmp_sm.rsplit(','))))
    # Check Socks
    if socks_proxy is not None:
        e = False
        if socks_proxy.startswith('socks://'):
            socks_flag = 5
            socks_proxy = socks_proxy.replace('socks://', '')
        elif socks_proxy.startswith('socks5://'):
            socks_flag = 5
            socks_proxy = socks_proxy.replace('socks5://', '')
        elif socks_proxy.startswith('socks4://'):
            socks_flag = 4
            socks_proxy = socks_proxy.replace('socks4://', '')
        else:
            socks_flag = 5
        if '://' in socks_proxy:
            socks_proxy = socks_proxy.rsplit('://')[1].rsplit('/')[0]
        try:
            if len(socks_proxy.rsplit(':')) < 2 or len(socks_proxy.rsplit(':')) > 3:
                e = True
            elif len(socks_proxy.rsplit(':')) is 2 and socks_proxy.rsplit(':')[1] == '':
                e = True
            elif len(socks_proxy.rsplit(':')) is 3 and socks_proxy.rsplit(':')[2] == '':
                e = True
        except:
            e = True
        if e:
            __die_failure(messages(language, 63))
        if socks_flag is 4:
            socks_proxy = 'socks4://' + socks_proxy
        if socks_flag is 5:
            socks_proxy = 'socks5://' + socks_proxy
    # Check update
    if check_update:
        from core.update import _update
        _update(compatible.__version__, compatible.__code_name__, language, socks_proxy)
        __die_success()
    # Check the target(s)
    if targets is None and targets_list is None:
        parser.print_help()
        write("\n")
        __die_failure(messages(language, 26))
    else:
        if targets is not None:
            targets = list(set(targets.rsplit(",")))
        elif targets_list is not None:
            try:
                targets = list(set(open(targets_list, "rb").read().rsplit()))
            except:
                __die_failure(messages(language, 27).format(targets_list))
    # Check thread number
    if thread_number > 100 or thread_number_host > 100:
        warn(messages(language, 28))
    # Check timeout number
    if timeout_sec is not None and timeout_sec >= 15:
        warn(messages(language, 29).format(timeout_sec))
    # Check scanning method
    if scan_method is not None and scan_method == "all":
        scan_method = module_names
        scan_method.remove("all")
    elif scan_method is not None and scan_method not in module_names:
        if "*_" in scan_method:
            scan_method = scan_method.rsplit(',')
            tmp_scan_method = scan_method[:]
            for sm in scan_method:
                if sm.startswith('*_'):
                    scan_method.remove(sm)
                    found_flag = False
                    for mn in module_names:
                        if mn.endswith('_' + sm.rsplit('*_')[1]):
                            scan_method.append(mn)
                            found_flag = True
                    if found_flag is False:
                        __die_failure(messages(language, 117).format(sm))
            scan_method = ','.join(scan_method)
        if "," in scan_method:
            scan_method = scan_method.rsplit(",")
            for sm in scan_method:
                if sm not in module_names:
                    __die_failure(messages(language, 30).format(sm))
                if sm == "all":
                    scan_method = module_names
                    scan_method.remove("all")
                    break
        else:
            __die_failure(messages(language, 31).format(scan_method))
    elif scan_method is None:
        __die_failure(messages(language, 41))
    else:
        scan_method = scan_method.rsplit()
    # Check for exluding scanning method
    if exclude_method is not None:
        exclude_method = exclude_method.rsplit(",")
        for exm in exclude_method:
            if exm in scan_method:
                if "all" == exm:
                    __die_failure(messages(language, 32))
                else:
                    scan_method.remove(exm)
                    if len(scan_method) is 0:
                        __die_failure(messages(language, 33))
            else:
                __die_failure(messages(language, 34).format(exm))
    # Check port(s)
    if type(ports) is not list and ports is not None and "-" in ports:
        ports = ports.rsplit("-")
        ports = range(int(ports[0]), int(ports[1]) + 1)
    elif type(ports) is not list and ports is not None:
        ports = ports.rsplit(",")
    # Check user list
    if users is not None:
        users = list(set(users.rsplit(",")))
    elif users_list is not None:
        try:
            users = list(set(open(users_list).read().rsplit("\n")))  # fix later
        except:
            __die_failure(messages(language, 37).format(targets_list))
    # Check password list
    if passwds is not None:
        passwds = list(set(passwds.rsplit(",")))
    if passwds_list is not None:
        try:
            passwds = list(set(open(passwds_list).read().rsplit("\n")))  # fix later
        except:
            __die_failure(messages(language, 39).format(targets_list))
    # Check output file
    try:
        tmpfile = open(log_in_file, "w")
    except:
        __die_failure(messages(language, 40).format(log_in_file))
    # Check Graph
    if graph_flag is not None:
        if graph_flag not in load_all_graphs():
            __die_failure(messages(language, 97).format(graph_flag))
        if not (log_in_file.endswith('.html') or log_in_file.endswith('.htm')):
            warn(messages(language, 87))
            graph_flag = None
    # Check Methods ARGS
    if methods_args is not None:
        new_methods_args = {}
        methods_args = methods_args.rsplit('&')
        for imethod_args in methods_args:
            if len(imethod_args.rsplit('=')) is 2:
                if imethod_args.rsplit('=')[1].startswith('read_from_file:'):
                    try:
                        read_data = list(set(open(imethod_args.rsplit('=read_from_file:')[1]).read().rsplit('\n')))
                    except:
                        __die_failure(messages(language, 36))
                    new_methods_args[imethod_args.rsplit('=')[0]] = read_data
                else:
                    new_methods_args[imethod_args.rsplit('=')[0]] = imethod_args.rsplit('=')[1].rsplit(',')
            else:
                new_methods_args[imethod_args.rsplit('=')[0]] = ""
        methods_args = new_methods_args
    # Return the values
    return [targets, targets_list, thread_number, thread_number_host,
            log_in_file, scan_method, exclude_method, users, users_list,
            passwds, passwds_list, timeout_sec, ports, parser, module_names,
            language, verbose_level, show_version, check_update, socks_proxy,
            retries, graph_flag, help_menu_flag, methods_args, method_args_list,
            wizard_mode, profile]
Exemple #18
0
def analysis(
    targets,
    check_ranges,
    check_subdomains,
    subs_temp,
    range_temp,
    log_in_file,
    time_sleep,
    language,
    verbose_level,
    retries,
    socks_proxy,
    enumerate_flag,
):
    """
    analysis and calulcate targets.

    Args:
        targets: targets
        check_ranges: check IP range flag
        check_subdomains: check subdomain flag
        subs_temp: subdomain temp filename
        range_temp: IP range tmp filename
        log_in_file: output filename
        time_sleep: time to sleep
        language: language
        verbose_level: verbose level number
        retries: retries number
        socks_proxy: socks proxy
        enumerate_flag: enumerate flag

    Returns:
        a generator
    """
    __log_into_file(range_temp, "a", "", language)
    __log_into_file(subs_temp, "a", "", language)

    for target in targets:
        if target_type(target) == "SINGLE_IPv4":
            if check_ranges:
                if not enumerate_flag:
                    info(messages(language, "checking_range").format(target))
                IPs = IPRange(getIPRange(target), range_temp, language)
                if type(IPs) == netaddr.ip.IPNetwork:
                    for IPm in IPs:
                        yield IPm
                elif type(IPs) == list:
                    for IPm in IPs:
                        for IP in IPm:
                            yield IP
            else:
                if not enumerate_flag:
                    info(messages(language, "target_submitted").format(target))
                yield target
        elif target_type(target) == "SINGLE_IPv6":
            yield target

        elif (target_type(target) == "RANGE_IPv4"
              or target_type(target) == "CIDR_IPv4"):
            IPs = IPRange(target, range_temp, language)
            if not enumerate_flag:
                info(messages(language, "checking").format(target))
            if type(IPs) == netaddr.ip.IPNetwork:
                for IPm in IPs:
                    yield IPm
            elif type(IPs) == list:
                for IPm in IPs:
                    for IP in IPm:
                        yield IP

        elif target_type(target) == "DOMAIN":
            if check_subdomains:
                if check_ranges:
                    if enumerate_flag:
                        info(messages(language, "checking").format(target))
                    sub_domains = (json.loads(open(subs_temp).read())
                                   if len(open(subs_temp).read()) > 2 else
                                   __get_subs(target, 3, "", 0, language, 0,
                                              socks_proxy, 3, 0, 0))
                    if len(open(subs_temp).read()) == 0:
                        __log_into_file(subs_temp, "a",
                                        json.dumps(sub_domains), language)
                    if target not in sub_domains:
                        sub_domains.append(target)
                    for target in sub_domains:
                        if not enumerate_flag:
                            info(
                                messages(language,
                                         "target_submitted").format(target))
                        yield target
                        n = 0
                        err = 0
                        IPs = []
                        while True:
                            try:
                                IPs.append(socket.gethostbyname(target))
                                err = 0
                                n += 1
                                if n == 12:
                                    break
                            except Exception:
                                err += 1
                                if err == 3 or n == 12:
                                    break
                        IPz = list(set(IPs))
                        for IP in IPz:
                            if not enumerate_flag:
                                info(
                                    messages(language,
                                             "checking_range").format(IP))
                            IPs = IPRange(getIPRange(IP), range_temp, language)
                            if type(IPs) == netaddr.ip.IPNetwork:
                                for IPm in IPs:
                                    yield IPm
                            elif type(IPs) == list:
                                for IPm in IPs:
                                    for IPn in IPm:
                                        yield IPn
                else:
                    if enumerate_flag:
                        info(messages(language, "checking").format(target))
                    sub_domains = (json.loads(open(subs_temp).read())
                                   if len(open(subs_temp).read()) > 2 else
                                   __get_subs(target, 3, "", 0, language, 0,
                                              socks_proxy, 3, 0, 0))
                    if len(open(subs_temp).read()) == 0:
                        __log_into_file(subs_temp, "a",
                                        json.dumps(sub_domains), language)
                    if target not in sub_domains:
                        sub_domains.append(target)
                    for target in sub_domains:
                        if not enumerate_flag:
                            info(
                                messages(language,
                                         "target_submitted").format(target))
                        yield target
            else:
                if check_ranges:
                    if not enumerate_flag:
                        info(messages(language, "checking").format(target))
                    yield target
                    n = 0
                    err = 0
                    IPs = []
                    while True:
                        try:
                            IPs.append(socket.gethostbyname(target))
                            err = 0
                            n += 1
                            if n == 12:
                                break
                        except Exception:
                            err += 1
                            if err == 3 or n == 12:
                                break
                    IPz = list(set(IPs))
                    for IP in IPz:
                        if not enumerate_flag:
                            info(
                                messages(language,
                                         "checking_range").format(IP))
                        IPs = IPRange(getIPRange(IP), range_temp, language)
                        if type(IPs) == netaddr.ip.IPNetwork:
                            for IPm in IPs:
                                yield IPm
                        elif type(IPs) == list:
                            for IPm in IPs:
                                for IPn in IPm:
                                    yield IPn
                else:
                    if not enumerate_flag:
                        info(
                            messages(language,
                                     "target_submitted").format(target))
                    yield target

        elif target_type(target) == "HTTP":
            if not enumerate_flag:
                info(messages(language, "checking").format(target))
            yield target
            if check_ranges:
                if "http://" == target[:7].lower():
                    target = target[7:].rsplit("/")[0]
                if "https://" == target[:8].lower():
                    target = target[8:].rsplit("/")[0]
                yield target
                IPs = []
                while True:
                    try:
                        IPs.append(socket.gethostbyname(target))
                        err = 0
                        n += 1
                        if n == 12:
                            break
                    except Exception:
                        err += 1
                        if err == 3 or n == 12:
                            break
                IPz = list(set(IPs))
                for IP in IPz:
                    if not enumerate_flag:
                        info(messages(language, "checking_range").format(IP))
                    IPs = IPRange(getIPRange(IP), range_temp, language)
                    if type(IPs) == netaddr.ip.IPNetwork:
                        for IPm in IPs:
                            yield IPm
                    elif type(IPs) == list:
                        for IPm in IPs:
                            for IPn in IPm:
                                yield IPn

        else:
            __die_failure(messages(language, "unknown_target").format(target))
Exemple #19
0
def check_all_required(targets, targets_list, thread_number, thread_number_host,
                       log_in_file, scan_method, exclude_method, users, users_list,
                       passwds, passwds_list, timeout_sec, ports, parser, module_names, language, verbose_level,
                       show_version, check_update, socks_proxy, retries, graph_flag, help_menu_flag, methods_args,
                       method_args_list, wizard_mode, profile, start_api, api_host, api_port, api_debug_mode,
                       api_access_key, api_client_white_list, api_client_white_list_ips, api_access_log,
                       api_access_log_filename, api_cert, api_cert_key):
    """
    check all rules and requirements for ARGS

    Args:
        targets: targets from CLI
        targets_list: targets_list from CLI
        thread_number: thread numbers from CLI
        thread_number_host: thread number for hosts from CLI
        log_in_file: output file from CLI
        scan_method: modules from CLI
        exclude_method: exclude modules from CLI
        users: usernames from CLI
        users_list: username file from CLI
        passwds: passwords from CLI
        passwds_list: passwords file from CLI
        timeout_sec: timeout seconds from CLI
        ports: ports from CLI
        parser: parser (argparse)
        module_names: all module names
        language: language from CLI
        verbose_level: verbose level from CLI
        show_version: show version flag from CLI
        check_update: check for update flag from CLI
        socks_proxy: socks proxy from CLI
        retries: retries from from CLI
        graph_flag: graph name from CLI
        help_menu_flag: help menu flag from CLI
        methods_args: modules ARGS flag from CLI
        method_args_list: modules ARGS from CLI
        wizard_mode: wizard mode flag from CLI
        profile: profiles from CLI
        start_api: start API flag from CLI
        api_host: API host from CLI
        api_port: API port from CLI
        api_debug_mode: API debug mode flag from CLI
        api_access_key: API access key from CLI
        api_client_white_list: API client white list flag from CLI
        api_client_white_list_ips: API client white list IPs from CLI
        api_access_log: API access log log flag from CLI
        api_access_log_filename: API access log filename from CLI

    Returns:
        all ARGS with applied rules
    """
    # Checking Requirements
    # import libs
    from core import compatible

    # Check Help Menu
    if help_menu_flag:
        parser.print_help()
        write("\n\n")
        write(messages(language, "license"))
        __die_success()
    # Check if method args list called
    if method_args_list:
        from core.load_modules import load_all_method_args

        load_all_method_args(language)
        __die_success()
    # Check version
    if show_version:
        from core import color

        info(
            messages(language, "current_version").format(
                color.color("yellow"),
                compatible.__version__,
                color.color("reset"),
                color.color("cyan"),
                compatible.__code_name__,
                color.color("reset"),
                color.color("green"),
            )
        )
        __die_success()
    # API mode
    if start_api:
        from api.engine import _start_api
        from core.targets import target_type
        from core.ip import _generate_IPRange

        try:
            api_port = int(api_port)
        except Exception:
            __die_failure(messages(language, "API_port_int"))
        if api_client_white_list:
            if type(api_client_white_list_ips) != type([]):
                api_client_white_list_ips = list(
                    set(api_client_white_list_ips.rsplit(","))
                )
            hosts = []
            for data in api_client_white_list_ips:
                if target_type(data) == "SINGLE_IPv4":
                    if data not in hosts:
                        hosts.append(data)
                elif target_type(data) == "RANGE_IPv4":
                    for cidr in _generate_IPRange(data):
                        for ip in cidr:
                            if ip not in hosts:
                                hosts.append(ip)
                elif target_type(data) == "CIDR_IPv4":
                    for ip in _generate_IPRange(data):
                        if ip not in hosts:
                            hosts.append(str(ip))
                else:
                    __die_failure(messages(language, "unknown_ip_input"))
            api_client_white_list_ips = hosts[:]
        if api_access_log:
            try:
                open(api_access_log_filename, "a")
            except Exception:
                write_to_api_console(
                    " * "
                    + messages(language, "file_write_error").format(
                        api_access_log_filename
                    )
                    + "\n"
                )
                __die_failure("")

        _start_api(api_host, api_port, api_debug_mode, api_access_key, api_client_white_list,
                   api_client_white_list_ips, api_access_log, api_access_log_filename, api_cert, api_cert_key, language)
    # Wizard mode
    if wizard_mode:
        (
            targets,
            thread_number,
            thread_number_host,
            log_in_file,
            scan_method,
            exclude_method,
            users,
            passwds,
            timeout_sec,
            ports,
            verbose_level,
            socks_proxy,
            retries,
            graph_flag,
        ) = __wizard(
            targets,
            thread_number,
            thread_number_host,
            log_in_file,
            module_names,
            exclude_method,
            users,
            passwds,
            timeout_sec,
            ports,
            verbose_level,
            socks_proxy,
            retries,
            load_all_graphs(),
            language,
        )
    # Check the target(s)
    if targets is None and targets_list is None:
        parser.print_help()
        write("\n")
        __die_failure(messages(language, "error_target"))
    # Select a Profile
    if scan_method is None and profile is None:
        __die_failure(messages(language, "scan_method_select"))
    if profile is not None:
        if scan_method is None:
            scan_method = ""
        else:
            scan_method += ","
        _all_profiles = _builder(_profiles(), default_profiles())
        if "all" in profile.rsplit(","):
            profile = ",".join(_all_profiles)
        tmp_sm = scan_method
        for pr in profile.rsplit(","):
            try:
                for sm in _all_profiles[pr]:
                    if sm not in tmp_sm.rsplit(","):
                        tmp_sm += sm + ","
            except Exception:
                __die_failure(messages(language, "profile_404").format(pr))
        if tmp_sm[-1] == ",":
            tmp_sm = tmp_sm[0:-1]
        scan_method = ",".join(list(set(tmp_sm.rsplit(","))))
    # Check Socks
    if socks_proxy is not None:
        e = False
        if socks_proxy.startswith("socks://"):
            socks_flag = 5
            socks_proxy = socks_proxy.replace("socks://", "")
        elif socks_proxy.startswith("socks5://"):
            socks_flag = 5
            socks_proxy = socks_proxy.replace("socks5://", "")
        elif socks_proxy.startswith("socks4://"):
            socks_flag = 4
            socks_proxy = socks_proxy.replace("socks4://", "")
        else:
            socks_flag = 5
        if "://" in socks_proxy:
            socks_proxy = socks_proxy.rsplit("://")[1].rsplit("/")[0]
        try:
            if (
                len(socks_proxy.rsplit(":")) < 2
                or len(socks_proxy.rsplit(":")) > 3
            ):
                e = True
            elif (
                len(socks_proxy.rsplit(":")) == 2
                and socks_proxy.rsplit(":")[1] == ""
            ):
                e = True
            elif (
                len(socks_proxy.rsplit(":")) == 3
                and socks_proxy.rsplit(":")[2] == ""
            ):
                e = True
        except Exception:
            e = True
        if e:
            __die_failure(messages(language, "valid_socks_address"))
        if socks_flag == 4:
            socks_proxy = "socks4://" + socks_proxy
        if socks_flag == 5:
            socks_proxy = "socks5://" + socks_proxy
    # Check update
    if check_update and _update_check(language):
        from core.update import _update

        _update(
            compatible.__version__,
            compatible.__code_name__,
            language,
            socks_proxy,
        )
        __die_success()
    else:
        if targets is not None:
            targets = list(set(targets.rsplit(",")))
        elif targets_list is not None:
            try:
                targets = list(set(open(targets_list, "rb").read().rsplit()))
            except Exception:
                __die_failure(
                    messages(language, "error_target_file").format(
                        targets_list
                    )
                )
    # Check thread number
    if thread_number > 101 or thread_number_host > 101:
        warn(messages(language, "thread_number_warning"))
    # Check timeout number
    if timeout_sec is not None and timeout_sec >= 15:
        warn(messages(language, "set_timeout").format(timeout_sec))
    # Check scanning method
    if scan_method is not None and "all" in scan_method.rsplit(","):
        scan_method = module_names
        scan_method.remove("all")
    elif (
        scan_method is not None
        and len(scan_method.rsplit(",")) == 1
        and "*_" not in scan_method
    ):
        if scan_method in module_names:
            scan_method = scan_method.rsplit()
        else:
            __die_failure(
                messages(language, "scan_module_not_found").format(scan_method)
            )
    else:
        if scan_method is not None:
            if scan_method not in module_names:
                if "*_" in scan_method or "," in scan_method:
                    scan_method = scan_method.rsplit(",")
                    scan_method_tmp = scan_method[:]
                    for sm in scan_method_tmp:
                        scan_method_error = True
                        if sm.startswith("*_"):
                            scan_method.remove(sm)
                            found_flag = False
                            for mn in module_names:
                                if mn.endswith("_" + sm.rsplit("*_")[1]):
                                    scan_method.append(mn)
                                    scan_method_error = False
                                    found_flag = True
                            if found_flag is False:
                                __die_failure(
                                    messages(
                                        language, "module_pattern_404"
                                    ).format(sm)
                                )
                        elif sm == "all":
                            scan_method = module_names
                            scan_method_error = False
                            scan_method.remove("all")
                            break
                        elif sm in module_names:
                            scan_method_error = False
                        elif sm not in module_names:
                            __die_failure(
                                messages(
                                    language, "scan_module_not_found"
                                ).format(sm)
                            )
                else:
                    scan_method_error = True
            if scan_method_error:
                __die_failure(
                    messages(language, "scan_module_not_found").format(
                        scan_method
                    )
                )
        else:
            __die_failure(messages(language, "scan_method_select"))
    scan_method = list(set(scan_method))
    # Check for exluding scanning method
    if exclude_method is not None:
        exclude_method = exclude_method.rsplit(",")
        for exm in exclude_method:
            if exm in scan_method:
                if "all" == exm:
                    __die_failure(messages(language, "error_exclude_all"))
                else:
                    scan_method.remove(exm)
                    if len(scan_method) == 0:
                        __die_failure(messages(language, "error_exclude_all"))
            else:
                __die_failure(
                    messages(language, "exclude_module_error").format(exm)
                )
    # Check port(s)
    if type(ports) is not list and ports is not None:
        tmp_ports = []
        for port in ports.rsplit(","):
            try:
                if "-" not in port:
                    if int(port) not in tmp_ports:
                        tmp_ports.append(int(port))
                else:
                    t_ports = range(
                        int(port.rsplit("-")[0]), int(port.rsplit("-")[1]) + 1
                    )
                    for p in t_ports:
                        if p not in tmp_ports:
                            tmp_ports.append(p)
            except Exception:
                __die_failure(messages(language, "ports_int"))
        if len(tmp_ports) == 0:
            ports = None
        else:
            ports = tmp_ports[:]
    # Check user list
    if users is not None:
        users = list(set(users.rsplit(",")))
    elif users_list is not None:
        try:
            # fix later
            users = list(set(open(users_list).read().rsplit("\n")))
        except Exception:
            __die_failure(
                messages(language, "error_username").format(targets_list)
            )
    # Check password list
    if passwds is not None:
        passwds = list(set(passwds.rsplit(",")))
    if passwds_list is not None:
        try:
            passwds = list(
                set(open(passwds_list).read().rsplit("\n"))
            )  # fix later
        except Exception:
            __die_failure(
                messages(language, "error_password_file").format(targets_list)
            )
    # Check output file
    try:
        open(log_in_file, "w")
    except Exception:
        __die_failure(
            messages(language, "file_write_error").format(log_in_file)
        )
    # Check Graph
    if graph_flag is not None:
        if graph_flag not in load_all_graphs():
            __die_failure(
                messages(language, "graph_module_404").format(graph_flag)
            )
        if not (log_in_file.endswith(".html") or log_in_file.endswith(".htm")):
            warn(messages(language, "graph_output"))
            graph_flag = None
    # Check Methods ARGS
    if methods_args is not None:
        new_methods_args = {}
        methods_args = methods_args.rsplit("&")
        for imethod_args in methods_args:
            if len(imethod_args.rsplit("=")) == 2:
                if imethod_args.rsplit("=")[1].startswith("read_from_file:"):
                    try:
                        read_data = list(
                            set(
                                open(
                                    imethod_args.rsplit("=read_from_file:")[1]
                                )
                                .read()
                                .rsplit("\n")
                            )
                        )
                    except Exception:
                        __die_failure(messages(language, "error_reading_file"))
                    new_methods_args[imethod_args.rsplit("=")[0]] = read_data
                else:
                    new_methods_args[
                        imethod_args.rsplit("=")[0]
                    ] = imethod_args.rsplit("=")[1].rsplit(",")
            else:
                new_methods_args[imethod_args] = ["True"]
        methods_args = new_methods_args
    # Return the values

    return [targets, targets_list, thread_number, thread_number_host,
            log_in_file, scan_method, exclude_method, users, users_list,
            passwds, passwds_list, timeout_sec, ports, parser, module_names, language, verbose_level,
            show_version, check_update, socks_proxy, retries, graph_flag, help_menu_flag, methods_args,
            method_args_list, wizard_mode, profile, start_api, api_host, api_port, api_debug_mode,
            api_access_key, api_client_white_list, api_client_white_list_ips, api_access_log,
            api_access_log_filename, api_cert, api_cert_key]
Exemple #20
0
def start(target, users, passwds, ports, timeout_sec, thread_number, num,
          total, log_in_file, time_sleep, language, verbose_level, socks_proxy,
          retries, ping_flag, methods_args, scan_id,
          scan_cmd):  # Main function
    if target_type(target) != 'SINGLE_IPv4' or target_type(
            target) != 'DOMAIN' or target_type(
                target) != 'HTTP' or target_type(target) != 'SINGLE_IPv6':
        # rand useragent
        user_agent_list = [
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5",
            "Googlebot/2.1 ( http://www.googlebot.com/bot.html)",
            "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Ubuntu/10.04"
            " Chromium/9.0.595.0 Chrome/9.0.595.0 Safari/534.13",
            "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.2; WOW64; .NET CLR 2.0.50727)",
            "Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51",
            "Mozilla/5.0 (compatible; 008/0.83; http://www.80legs.com/webcrawler.html) Gecko/2008032620",
            "Debian APT-HTTP/1.3 (0.8.10.3)",
            "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
            "Googlebot/2.1 (+http://www.googlebot.com/bot.html)",
            "Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)",
            "YahooSeeker/1.2 (compatible; Mozilla 4.0; MSIE 5.5; yahooseeker at yahoo-inc dot com ; "
            "http://help.yahoo.com/help/us/shop/merchant/)",
            "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)",
            "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
            "msnbot/1.1 (+http://search.msn.com/msnbot.htm)"
        ]
        http_methods = ["GET", "HEAD"]
        user_agent = {'User-agent': random.choice(user_agent_list)}

        # requirements check
        new_extra_requirements = extra_requirements_dict()
        if methods_args is not None:
            for extra_requirement in extra_requirements_dict():
                if extra_requirement in methods_args:
                    new_extra_requirements[extra_requirement] = methods_args[
                        extra_requirement]
        extra_requirements = new_extra_requirements
        if extra_requirements["dir_scan_http_method"][0] not in http_methods:
            warn(messages(language, 110))
            extra_requirements["dir_scan_http_method"] = ["GET"]
        if ports is None:
            ports = extra_requirements["dir_scan_ports"]
        random_agent_flag = True
        if extra_requirements["dir_scan_random_agent"][0] == "False":
            random_agent_flag = False
        if ping_flag:
            if socks_proxy is not None:
                socks_version = socks.SOCKS5 if socks_proxy.startswith(
                    'socks5://') else socks.SOCKS4
                socks_proxy = socks_proxy.rsplit('://')[1]
                if '@' in socks_proxy:
                    socks_username = socks_proxy.rsplit(':')[0]
                    socks_password = socks_proxy.rsplit(':')[1].rsplit('@')[0]
                    socks.set_default_proxy(
                        socks_version,
                        str(socks_proxy.rsplit('@')[1].rsplit(':')[0]),
                        int(socks_proxy.rsplit(':')[-1]),
                        username=socks_username,
                        password=socks_password)
                    socket.socket = socks.socksocket
                    socket.getaddrinfo = getaddrinfo
                else:
                    socks.set_default_proxy(socks_version,
                                            str(socks_proxy.rsplit(':')[0]),
                                            int(socks_proxy.rsplit(':')[1]))
                    socket.socket = socks.socksocket
                    socket.getaddrinfo = getaddrinfo
            warn(messages(language, 100).format(target, 'heartbleed_vuln'))
            if do_one_ping(target, timeout_sec, 8) is None:
                return None
        threads = []
        max = thread_number
        total_req = len(extra_requirements["dir_scan_list"]) * len(ports)
        thread_tmp_filename = 'tmp/thread_tmp_' + ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(20))
        thread_write = open(thread_tmp_filename, 'w')
        thread_write.write('1')
        thread_write.close()
        trying = 0
        for port in ports:
            port = int(port)
            if target_type(target) == 'SINGLE_IPv4' or target_type(
                    target) == 'DOMAIN':
                url = 'http://{0}:{1}/'.format(target, str(port))
            else:
                if target.count(':') > 1:
                    __die_failure(messages(language, 105))
                http = target.rsplit('://')[0]
                host = target_to_host(target)
                path = "/".join(
                    target.replace('http://', '').replace('https://',
                                                          '').rsplit('/')[1:])
                url = http + '://' + host + ':' + str(port) + '/' + path
            if test(url, retries, timeout_sec, user_agent,
                    extra_requirements["dir_scan_http_method"][0], socks_proxy,
                    verbose_level, trying, total_req, total, num, port,
                    language) is 0:
                for idir in extra_requirements["dir_scan_list"]:
                    # check target type
                    if target_type(target) == 'SINGLE_IPv4' or target_type(
                            target) == 'DOMAIN':
                        url = 'http://{0}:{1}/{2}'.format(
                            target, str(port), idir)
                    else:
                        http = target.rsplit('://')[0]
                        host = target_to_host(target)
                        path = "/".join(
                            target.replace('http://',
                                           '').replace('https://',
                                                       '').rsplit('/')[1:])
                        url = http + '://' + host + ':' + str(
                            port) + '/' + path + '/' + idir

                    if random_agent_flag:
                        user_agent = {
                            'User-agent': random.choice(user_agent_list)
                        }
                    t = threading.Thread(
                        target=check,
                        args=(url, user_agent, timeout_sec, log_in_file,
                              language, time_sleep, thread_tmp_filename,
                              retries,
                              extra_requirements["dir_scan_http_method"][0],
                              socks_proxy, scan_id, scan_cmd))
                    threads.append(t)
                    t.start()
                    trying += 1
                    if verbose_level is not 0:
                        info(
                            messages(language,
                                     72).format(trying, total_req, num, total,
                                                target_to_host(target), port,
                                                'dir_scan'))
                    while 1:
                        try:
                            if threading.activeCount() >= max:
                                time.sleep(0.01)
                            else:
                                break
                        except KeyboardInterrupt:
                            break
                            break
            else:
                warn(messages(language, 109).format(url))

        # wait for threads
        kill_switch = 0
        kill_time = int(timeout_sec / 0.1) if int(timeout_sec /
                                                  0.1) is not 0 else 1
        while 1:
            time.sleep(0.1)
            kill_switch += 1
            try:
                if threading.activeCount() is 1 or kill_switch is kill_time:
                    break
            except KeyboardInterrupt:
                break
        thread_write = int(open(thread_tmp_filename).read().rsplit()[0])
        if thread_write is 1:
            info(
                messages(language, 108).format(target,
                                               ",".join(map(str, ports))))
            if verbose_level is not 0:
                save = open(log_in_file, 'a')
                save.write(
                    json.dumps({
                        'HOST': target,
                        'USERNAME': '',
                        'PASSWORD': '',
                        'PORT': '',
                        'TYPE': 'dir_scan',
                        'DESCRIPTION': messages(language, 94),
                        'TIME': now(),
                        'CATEGORY': "scan",
                        'SCAN_ID': scan_id,
                        'SCAN_CMD': scan_cmd
                    }) + '\n')
                save.close()
        os.remove(thread_tmp_filename)
    else:
        warn(messages(language, 69).format('dir_scan', target))
Exemple #21
0
def load_all_args(module_names, graph_names):
    """
    create the ARGS and help menu

    Args:
        module_names: all module names
        graph_names: all graph names

    Returns:
        the parser, the ARGS
    """
    # Language Options
    # import libs
    default_config = _builder(_core_config(), _core_default_config())
    _all_profiles = [key for key in _builder(_profiles(), default_profiles())]
    _all_profiles.append("all")
    language_list = [lang for lang in messages(-1, 0)]
    if "-L" in sys.argv or "--language" in sys.argv:
        try:
            index = sys.argv.index("-L") + 1
        except Exception:
            index = sys.argv.index("--language") + 1
    else:
        index = -1
    if index == -1:
        language = "en"
    else:
        _error_flag = False
        try:
            language = sys.argv[index]
        except Exception:
            _error_flag = True
        if _error_flag or language not in language_list:
            __die_failure(
                "Please select one of these languages {0}".format(
                    language_list
                )
            )

    # Check if compatible
    check(language)
    finish()
    # Start Parser
    parser = argparse.ArgumentParser(prog="Nettacker", add_help=False)

    # parser = OptionParser(usage=messages(language,"options"),
    #                      description=messages(language,"help_menu"),
    #                      epilog=messages(language,"license"))

    # Engine Options
    engineOpt = parser.add_argument_group(
        messages(language, "engine"), messages(language, "engine_input")
    )
    engineOpt.add_argument(
        "-L",
        "--language",
        action="store",
        dest="language",
        default=default_config["language"],
        help=messages(language, "select_language").format(language_list),
    )
    engineOpt.add_argument(
        "-v",
        "--verbose",
        action="store",
        type=int,
        dest="verbose_level",
        default=default_config["verbose_level"],
        help=messages(language, "verbose_level"),
    )
    engineOpt.add_argument(
        "-V",
        "--version",
        action="store_true",
        default=default_config["show_version"],
        dest="show_version",
        help=messages(language, "software_version"),
    )
    engineOpt.add_argument(
        "-c",
        "--update",
        action="store_true",
        default=default_config["check_update"],
        dest="check_update",
        help=messages(language, "check_updates"),
    )
    engineOpt.add_argument(
        "-o",
        "--output",
        action="store",
        default=default_config["log_in_file"],
        dest="log_in_file",
        help=messages(language, "save_logs"),
    )
    engineOpt.add_argument(
        "--graph",
        action="store",
        default=default_config["graph_flag"],
        dest="graph_flag",
        help=messages(language, "available_graph").format(graph_names),
    )
    engineOpt.add_argument(
        "-h",
        "--help",
        action="store_true",
        default=default_config["help_menu_flag"],
        dest="help_menu_flag",
        help=messages(language, "help_menu"),
    )
    engineOpt.add_argument(
        "-W",
        "--wizard",
        action="store_true",
        default=default_config["wizard_mode"],
        dest="wizard_mode",
        help=messages(language, "wizard_mode"),
    )
    engineOpt.add_argument(
        "--profile",
        action="store",
        default=default_config["profile"],
        dest="profile",
        help=messages(language, "select_profile").format(_all_profiles),
    )

    # Target Options
    target = parser.add_argument_group(
        messages(language, "target"), messages(language, "target_input")
    )
    target.add_argument(
        "-i",
        "--targets",
        action="store",
        dest="targets",
        default=default_config["targets"],
        help=messages(language, "target_list"),
    )
    target.add_argument(
        "-l",
        "--targets-list",
        action="store",
        dest="targets_list",
        default=default_config["targets_list"],
        help=messages(language, "read_target"),
    )

    # Exclude Module Name
    exclude_names = module_names[:]
    exclude_names.remove("all")

    # Methods Options
    method = parser.add_argument_group(
        messages(language, "Method"), messages(language, "scan_method_options")
    )
    method.add_argument(
        "-m",
        "--method",
        action="store",
        dest="scan_method",
        default=default_config["scan_method"],
        help=messages(language, "choose_scan_method").format(module_names),
    )
    method.add_argument(
        "-x",
        "--exclude",
        action="store",
        dest="exclude_method",
        default=default_config["exclude_method"],
        help=messages(language, "exclude_scan_method").format(exclude_names),
    )
    method.add_argument(
        "-u",
        "--usernames",
        action="store",
        dest="users",
        default=default_config["users"],
        help=messages(language, "username_list"),
    )
    method.add_argument(
        "-U",
        "--users-list",
        action="store",
        dest="users_list",
        default=default_config["users_list"],
        help=messages(language, "username_from_file"),
    )
    method.add_argument(
        "-p",
        "--passwords",
        action="store",
        dest="passwds",
        default=default_config["passwds"],
        help=messages(language, "password_seperator"),
    )
    method.add_argument(
        "-P",
        "--passwords-list",
        action="store",
        dest="passwds_list",
        default=default_config["passwds_list"],
        help=messages(language, "read_passwords"),
    )
    method.add_argument(
        "-g",
        "--ports",
        action="store",
        dest="ports",
        default=default_config["ports"],
        help=messages(language, "port_seperator"),
    )
    method.add_argument(
        "-T",
        "--timeout",
        action="store",
        dest="timeout_sec",
        default=default_config["timeout_sec"],
        type=float,
        help=messages(language, "read_passwords"),
    )
    method.add_argument(
        "-w",
        "--time-sleep",
        action="store",
        dest="time_sleep",
        default=default_config["time_sleep"],
        type=float,
        help=messages(language, "time_to_sleep"),
    )
    method.add_argument(
        "-r",
        "--range",
        action="store_true",
        default=default_config["check_ranges"],
        dest="check_ranges",
        help=messages(language, "range"),
    )
    method.add_argument(
        "-s",
        "--sub-domains",
        action="store_true",
        default=default_config["check_subdomains"],
        dest="check_subdomains",
        help=messages(language, "subdomains"),
    )
    method.add_argument(
        "-t",
        "--thread-connection",
        action="store",
        default=default_config["thread_number"],
        type=int,
        dest="thread_number",
        help=messages(language, "thread_number_connections"),
    )
    method.add_argument(
        "-M",
        "--thread-hostscan",
        action="store",
        default=default_config["thread_number_host"],
        type=int,
        dest="thread_number_host",
        help=messages(language, "thread_number_hosts"),
    )
    method.add_argument(
        "-R",
        "--socks-proxy",
        action="store",
        dest="socks_proxy",
        default=default_config["socks_proxy"],
        help=messages(language, "outgoing_proxy"),
    )
    method.add_argument(
        "--retries",
        action="store",
        dest="retries",
        type=int,
        default=default_config["retries"],
        help=messages(language, "connection_retries"),
    )
    method.add_argument(
        "--ping-before-scan",
        action="store_true",
        dest="ping_flag",
        default=default_config["ping_flag"],
        help=messages(language, "ping_before_scan"),
    )
    method.add_argument(
        "--method-args",
        action="store",
        dest="methods_args",
        default=default_config["methods_args"],
        help=messages(language, "method_inputs"),
    )
    method.add_argument(
        "--method-args-list",
        action="store_true",
        dest="method_args_list",
        default=default_config["method_args_list"],
        help=messages(language, "list_methods"),
    )
    # API Options
    api = parser.add_argument_group(
        messages(language, "API"), messages(language, "API_options"))
    api.add_argument("--start-api", action="store_true",
                     dest="start_api", default=default_config["start_api"],
                     help=messages(language, "start_API"))
    api.add_argument("--api-host", action="store",
                     dest="api_host", default=default_config["api_host"],
                     help=messages(language, "API_host"))
    api.add_argument("--api-port", action="store",
                     dest="api_port", default=default_config["api_port"],
                     help=messages(language, "API_port"))
    api.add_argument("--api-debug-mode", action="store_true",
                     dest="api_debug_mode", default=default_config["api_debug_mode"],
                     help=messages(language, "API_debug"))
    api.add_argument("--api-access-key", action="store",
                     dest="api_access_key", default=default_config["api_access_key"],
                     help=messages(language, "API_access_key"))
    api.add_argument("--api-client-white-list", action="store_true",
                     dest="api_client_white_list", default=default_config["api_client_white_list"],
                     help=messages(language, "white_list_API"))
    api.add_argument("--api-client-white-list-ips", action="store",
                     dest="api_client_white_list_ips", default=default_config["api_client_white_list_ips"],
                     help=messages(language, "define_whie_list"))
    api.add_argument("--api-access-log", action="store_true",
                     dest="api_access_log", default=default_config["api_access_log"],
                     help=messages(language, "gen_API_access_log"))
    api.add_argument("--api-access-log-filename", action="store",
                     dest="api_access_log_filename", default=default_config["api_access_log_filename"],
                     help=messages(language, "API_access_log_file"))
    api.add_argument("--api-cert", action="store", dest="api_cert", help=messages(language, "API_cert"))
    api.add_argument("--api-cert-key", action="store", dest="api_cert_key", help=messages(language, "API_cert_key"))
    # Return Options
    return [
        parser,
        parser.parse_args(),
        default_config["startup_check_for_update"],
    ]
Exemple #22
0
def __check_external_modules():
    """
    check external libraries if they are installed

    Returns:
        True if success otherwise None
    """
    external_modules = ["argparse", "netaddr", "requests", "paramiko", "texttable", "socks", "win_inet_pton",
                        "flask", "sqlalchemy"]
    for module in external_modules:
        try:
            __import__(module)
        except:
            __die_failure("pip install -r requirements.txt ---> " +
                          module + " not installed!")

    default_config = _builder(_core_config(), _core_default_config())

    if not os.path.exists(default_config["home_path"]):
        try:
            os.mkdir(default_config["home_path"])
            os.mkdir(default_config["tmp_path"])
            os.mkdir(default_config["results_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["home_path"]))
    if not os.path.exists(default_config["tmp_path"]):
        try:
            os.mkdir(default_config["tmp_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["results_path"]))
    if not os.path.exists(default_config["results_path"]):
        try:
            os.mkdir(default_config["results_path"])
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["results_path"]))
    if default_config["database_type"] == "sqlite":
        try:
            if os.path.isfile(default_config["home_path"]+"/"+default_config["database_name"]):
                pass
            else:
                from database.sqlite_create import sqlite_create_tables
                sqlite_create_tables()
        except:
            __die_failure("cannot access the directory {0}".format(
                default_config["home_path"]))
    elif default_config["database_type"] == "mysql":
        try:
            from database.mysql_create import mysql_create_tables, mysql_create_database
            mysql_create_database()
            mysql_create_tables()
        except:
            __die_failure(messages("en", "database_connection_failed"))
    elif default_config["database_type"] == "postgres":
        try:
            from database.postgres_create import postgres_create_database
            postgres_create_database()
        except Exception as e:
            __die_failure(messages("en", "database_connection_failed"))
    else:
        __die_failure(messages("en", "invalid_database"))
    return True
Exemple #23
0
def load_honeypot_engine():
    """
    load OHP Engine

    Returns:
        True
    """
    # print logo
    logo()

    # parse argv
    parser, argv_options = argv_parser()

    #########################################
    # argv rules apply
    #########################################
    # check help menu
    if argv_options.show_help_menu:
        parser.print_help()
        __die_success()
    # check for requirements before start
    check_for_requirements(argv_options.start_api_server)
    # check api server flag
    if argv_options.start_api_server:
        start_api_server()
        __die_success()
    # check selected modules
    if argv_options.selected_modules:
        selected_modules = list(set(argv_options.selected_modules.rsplit(",")))
        if "all" in selected_modules:
            selected_modules = load_all_modules()
        if "" in selected_modules:
            selected_modules.remove("")
        # if selected modules are zero
        if not len(selected_modules):
            __die_failure(messages("en", "zero_module_selected"))
        # if module not found
        for module in selected_modules:
            if module not in load_all_modules():
                __die_failure(messages("en", "module_not_found").format(module))
    # check excluded modules
    if argv_options.excluded_modules:
        excluded_modules = list(set(argv_options.excluded_modules.rsplit(",")))
        if "all" in excluded_modules:
            __die_failure("you cannot exclude all modules")
        if "" in excluded_modules:
            excluded_modules.remove("")
        # remove excluded modules
        for module in excluded_modules:
            if module not in load_all_modules():
                __die_failure(messages("en", "module_not_found").format(module))
            # ignore if module not selected, it will remove anyway
            try:
                selected_modules.remove(module)
            except Exception as _:
                del _
        # if selected modules are zero
        if not len(selected_modules):
            __die_failure(messages("en", "zero_module_selected"))
    virtual_machine_container_reset_factory_time_seconds = argv_options. \
        virtual_machine_container_reset_factory_time_seconds
    global verbose_mode
    verbose_mode = argv_options.verbose_mode
    run_as_test = argv_options.run_as_test
    #########################################
    # argv rules apply
    #########################################
    # build configuration based on selected modules
    configuration = honeypot_configuration_builder(selected_modules)

    info(messages("en", "honeypot_started"))
    info(messages("en", "loading_modules").format(", ".join(selected_modules)))
    # check for conflict in real machine ports and pick new ports
    info("checking for conflicts in ports")
    configuration = conflict_ports(configuration)
    # stop old containers (in case they are not stopped)
    stop_containers(configuration)
    # remove old containers (in case they are not updated)
    remove_old_containers(configuration)
    # remove old images (in case they are not updated)
    remove_old_images(configuration)
    # create new images based on selected modules
    create_new_images(configuration)
    # create OWASP Honeypot networks in case not exist
    create_ohp_networks()
    # start containers based on selected modules
    configuration = start_containers(configuration)
    # start network monitoring thread
    new_network_events_thread = threading.Thread(target=new_network_events, args=(configuration,),
                                                 name="new_network_events_thread")
    new_network_events_thread.start()
    info("all selected modules started: {0}".format(", ".join(selected_modules)))

    # check if it's not a test
    if not run_as_test:
        # wait forever! in case user can send ctrl + c to interrupt
        wait_until_interrupt(virtual_machine_container_reset_factory_time_seconds, configuration)
    # kill the network events thread
    terminate_thread(new_network_events_thread)
    # stop created containers
    stop_containers(configuration)
    # remove created containers
    remove_old_containers(configuration)
    # remove created images
    remove_old_images(configuration)
    # remove_tmp_directories() error: access denied!
    info("finished.")
    # reset cmd/terminal color
    finish()
    return True
Exemple #24
0
def start(target, users, passwds, ports, timeout_sec, thread_number, num,
          total, log_in_file, time_sleep, language, verbose_level, socks_proxy,
          retries, methods_args, scan_id, scan_cmd):  # Main function
    if target_type(target) != 'SINGLE_IPv4' or target_type(
            target) != 'DOMAIN' or target_type(
                target) != 'HTTP' or target_type(target) != 'SINGLE_IPv6':
        # rand useragent
        user_agent_list = useragents.useragents()
        user_agent = {'User-agent': random.choice(user_agent_list)}
        limit = 1000
        # requirements check
        new_extra_requirements = extra_requirements_dict()
        if methods_args is not None:
            for extra_requirement in extra_requirements_dict():
                if extra_requirement in methods_args:
                    new_extra_requirements[extra_requirement] = methods_args[
                        extra_requirement]
        extra_requirements = new_extra_requirements
        random_agent_flag = True
        if extra_requirements["wordpress_dos_cve_2018_6389_vuln_random_agent"][
                0] != "True":
            random_agent_flag = False
        if extra_requirements["wordpress_dos_cve_2018_6389_vuln_no_limit"][
                0] != "False":
            limit = -1
        threads = []
        total_req = limit
        filepath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        thread_tmp_filename = '{}/tmp/thread_tmp_'.format(
            load_file_path()) + ''.join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(20))
        __log_into_file(thread_tmp_filename, 'w', '1', language)
        trying = 0
        if target_type(target) == 'SINGLE_IPv4' or target_type(
                target) == 'DOMAIN':
            url = 'http://{0}/'.format(target)
        else:
            if target.count(':') > 1:
                __die_failure(messages(language, "insert_port_message"))
            http = target.rsplit('://')[0]
            host = target_to_host(target)
            path = "/".join(
                target.replace('http://', '').replace('https://',
                                                      '').rsplit('/')[1:])
            url = http + '://' + host + '/' + path
        if test(url, retries, timeout_sec, user_agent, socks_proxy,
                verbose_level, trying, total_req, total, num, language, False,
                log_in_file, scan_id, scan_cmd, thread_tmp_filename) != 0:
            warn(messages(language, "open_error").format(url))
            return
        info(messages(language, "DOS_send").format(target))
        n = 0
        t = threading.Thread(
            target=test,
            args=(url, retries, timeout_sec, user_agent, socks_proxy,
                  verbose_level, trying, total_req, total, num, language, True,
                  log_in_file, scan_id, scan_cmd, thread_tmp_filename))
        t.start()
        keyboard_interrupt_flag = False
        while (n != limit):
            n += 1
            if random_agent_flag:
                user_agent = {'User-agent': random.choice(user_agent_list)}
            t = threading.Thread(target=send_dos,
                                 args=(url, user_agent, timeout_sec,
                                       log_in_file, language, time_sleep,
                                       thread_tmp_filename, retries,
                                       socks_proxy, scan_id, scan_cmd))
            threads.append(t)
            t.start()
            trying += 1
            if verbose_level > 3:
                info(
                    messages(language, "trying_message").format(
                        trying, total_req, num, total, target_to_host(target),
                        port, 'wordpress_dos_cve_2018_6389_vuln'))
            try:
                if int(open(thread_tmp_filename).read().rsplit()[0]) == 0:
                    if limit != -1:
                        break
            except Exception:
                pass
            while 1:
                try:
                    if threading.activeCount() >= thread_number:
                        time.sleep(0.01)
                    else:
                        break
                except KeyboardInterrupt:
                    keyboard_interrupt_flag = True
                    break
            if keyboard_interrupt_flag:
                break
        # wait for threads
        kill_switch = 0
        kill_time = int(timeout_sec /
                        0.1) if int(timeout_sec / 0.1) != 0 else 1
        while 1:
            time.sleep(0.1)
            kill_switch += 1
            try:
                if threading.activeCount() == 2 or kill_switch == kill_time:
                    break
            except KeyboardInterrupt:
                break
        thread_write = int(open(thread_tmp_filename).read().rsplit()[0])
        if thread_write == 1:
            info(
                messages(language, "no_vulnerability_found").format(
                    "wordpress_dos_cve_2018_6389_vuln"))
            if verbose_level != 0:
                data = json.dumps({
                    'HOST':
                    target,
                    'USERNAME':
                    '',
                    'PASSWORD':
                    '',
                    'PORT':
                    '',
                    'TYPE':
                    'wordpress_dos_cve_2018_6389_vuln',
                    'DESCRIPTION':
                    messages(language, "no_vulnerability_found").format(
                        "wordpress_dos_cve_2018_6389_vuln"),
                    'TIME':
                    now(),
                    'CATEGORY':
                    "scan",
                    'SCAN_ID':
                    scan_id,
                    'SCAN_CMD':
                    scan_cmd
                })
                __log_into_file(log_in_file, 'a', data, language)
        os.remove(thread_tmp_filename)
    else:
        warn(
            messages(language, "input_target_error").format(
                'wordpress_dos_cve_2018_6389_vuln', target))
Exemple #25
0
def analysis(targets, check_ranges, check_subdomains, subs_temp, range_temp, log_in_file, time_sleep,
             language, verbose_level, retries, socks_proxy, enumerate_flag):
    __log_into_file(range_temp, 'a', '', language)
    __log_into_file(subs_temp, 'a', '', language)

    for target in targets:
        if target_type(target) == 'SINGLE_IPv4':
            if check_ranges:
                if not enumerate_flag: info(messages(language, 51).format(target))
                IPs = IPRange(getIPRange(target), range_temp, language)
                if type(IPs) == netaddr.ip.IPNetwork:
                    for IPm in IPs:
                        yield IPm
                elif type(IPs) == list:
                    for IPm in IPs:
                        for IP in IPm:
                            yield IP
            else:
                if not enumerate_flag: info(messages(language, 81).format(target))
                yield target
        elif target_type(target) == 'SINGLE_IPv6':
            yield target

        elif target_type(target) == 'RANGE_IPv4' or target_type(target) == 'CIDR_IPv4':
            IPs = IPRange(target, range_temp, language)
            if not enumerate_flag: info(messages(language, 52).format(target))
            if type(IPs) == netaddr.ip.IPNetwork:
                for IPm in IPs:
                    yield IPm
            elif type(IPs) == list:
                for IPm in IPs:
                    for IP in IPm:
                        yield IP

        elif target_type(target) == 'DOMAIN':
            if check_subdomains:
                if check_ranges:
                    if enumerate_flag: info(messages(language, 52).format(target))
                    sub_domains = json.loads(open(subs_temp).read()) if len(open(subs_temp).read()) > 2 else \
                        __get_subs(target, 3, '', 0, language, 0, socks_proxy, 3, 0, 0)
                    if len(open(subs_temp).read()) is 0:
                        __log_into_file(subs_temp, 'a', json.dumps(sub_domains), language)
                    if target not in sub_domains:
                        sub_domains.append(target)
                    for target in sub_domains:
                        if not enumerate_flag: info(messages(language, 81).format(target))
                        yield target
                        n = 0
                        err = 0
                        IPs = []
                        while True:
                            try:
                                IPs.append(socket.gethostbyname(target))
                                err = 0
                                n += 1
                                if n is 12:
                                    break
                            except:
                                err += 1
                                if err is 3 or n is 12:
                                    break
                        IPz = list(set(IPs))
                        for IP in IPz:
                            if not enumerate_flag: info(messages(language, 51).format(IP))
                            IPs = IPRange(getIPRange(IP), range_temp, language)
                            if type(IPs) == netaddr.ip.IPNetwork:
                                for IPm in IPs:
                                    yield IPm
                            elif type(IPs) == list:
                                for IPm in IPs:
                                    for IPn in IPm:
                                        yield IPn
                else:
                    if enumerate_flag: info(messages(language, 52).format(target))
                    sub_domains = json.loads(open(subs_temp).read()) if len(open(subs_temp).read()) > 2 else \
                        __get_subs(target, 3, '', 0, language, 0, socks_proxy, 3, 0, 0)
                    if len(open(subs_temp).read()) is 0:
                        __log_into_file(subs_temp, 'a', json.dumps(sub_domains), language)
                    if target not in sub_domains:
                        sub_domains.append(target)
                    for target in sub_domains:
                        if not enumerate_flag: info(messages(language, 81).format(target))
                        yield target
            else:
                if check_ranges:
                    if not enumerate_flag: info(messages(language, 52).format(target))
                    yield target
                    n = 0
                    err = 0
                    IPs = []
                    while True:
                        try:
                            IPs.append(socket.gethostbyname(target))
                            err = 0
                            n += 1
                            if n is 12:
                                break
                        except:
                            err += 1
                            if err is 3 or n is 12:
                                break
                    IPz = list(set(IPs))
                    for IP in IPz:
                        if not enumerate_flag: info(messages(language, 51).format(IP))
                        IPs = IPRange(getIPRange(IP), range_temp, language)
                        if type(IPs) == netaddr.ip.IPNetwork:
                            for IPm in IPs:
                                yield IPm
                        elif type(IPs) == list:
                            for IPm in IPs:
                                for IPn in IPm:
                                    yield IPn
                else:
                    if not enumerate_flag: info(messages(language, 81).format(target))
                    yield target

        elif target_type(target) == 'HTTP':
            if not enumerate_flag: info(messages(language, 52).format(target))
            yield target
            if check_ranges:
                if 'http://' == target[:7].lower():
                    target = target[7:].rsplit('/')[0]
                if 'https://' == target[:8].lower():
                    target = target[8:].rsplit('/')[0]
                yield target
                IPs = []
                while True:
                    try:
                        IPs.append(socket.gethostbyname(target))
                        err = 0
                        n += 1
                        if n is 12:
                            break
                    except:
                        err += 1
                        if err is 3 or n is 12:
                            break
                IPz = list(set(IPs))
                for IP in IPz:
                    if not enumerate_flag: info(messages(language, 51).format(IP))
                    IPs = IPRange(getIPRange(IP), range_temp, language)
                    if type(IPs) == netaddr.ip.IPNetwork:
                        for IPm in IPs:
                            yield IPm
                    elif type(IPs) == list:
                        for IPm in IPs:
                            for IPn in IPm:
                                yield IPn

        else:
            __die_failure(messages(language, 50).format(target))