def new_scan(): """ new scan through the API Returns: a JSON message with scan details if success otherwise a JSON error """ _start_scan_config = {} __api_key_check(app, flask_request, __language()) targetValue = __get_value(flask_request, "targets") if (target_type(targetValue) == "UNKNOWN"): return jsonify({"error": "Please input correct target"}), 400 for key in _core_default_config(): if __get_value(flask_request, key) is not None: _start_scan_config[key] = escape(__get_value(flask_request, key)) _start_scan_config["backup_ports"] = __get_value(flask_request, "ports") _start_scan_config = __rules( __remove_non_api_keys( _builder(_start_scan_config, _builder(_core_config(), _core_default_config()))), _core_default_config(), __language()) _p = multiprocessing.Process(target=__scan, args=[_start_scan_config]) _p.start() # Sometimes method_args is too big! _start_scan_config["methods_args"] = {"as_user_set": "set_successfully"} return jsonify(_start_scan_config), 200
def __log_into_file(filename, mode, data, language, final=False): if version() is 2: if _builder(_paths(), default_paths())["tmp_path"] in filename: if not final: flock = lockfile.FileLock(filename) flock.acquire() with open(filename, mode) as save: save.write(data + '\n') if not final: flock.release() else: if final: with open(filename, mode) as save: save.write(data + '\n') else: submit_logs_to_db(language, data) else: if _builder(_paths(), default_paths())["tmp_path"] in filename: if not final: flock = lockfile.FileLock(filename) flock.acquire() with open(filename, mode, encoding='utf-8') as save: save.write(data + '\n') if not final: flock.release() else: if final: with open(filename, mode, encoding='utf-8') as save: save.write(data + '\n') else: submit_logs_to_db(language, data)
def __log_into_file(filename, mode, data, language, final=False): """ write a content into a file (support unicode) and submit logs in database. if final=False its writing log in the database. Args: filename: the filename mode: writing mode (a, ab, w, wb, etc.) data: content language: language final: True if it's final report otherwise False (default False) Returns: True if success otherwise None """ if version() is 2: if _builder(_paths(), default_paths())["tmp_path"] in filename: if not final: flock = lockfile.FileLock(filename) flock.acquire() with open(filename, mode) as save: save.write(data + '\n') if not final: flock.release() else: if final: with open(filename, mode) as save: save.write(data + '\n') else: submit_logs_to_db(language, data) else: if _builder(_paths(), default_paths())["tmp_path"] in filename: if not final: flock = lockfile.FileLock(filename) flock.acquire() with open(filename, mode, encoding='utf-8') as save: save.write(data + '\n') if not final: flock.release() else: if final: with open(filename, mode, encoding='utf-8') as save: save.write(data + '\n') else: submit_logs_to_db(language, data) return True
def new_scan(): _start_scan_config = {} language = app.config["OWASP_NETTACKER_CONFIG"]["language"] __api_key_check(app, flask_request, language) for key in _core_default_config(): if __get_value(flask_request, key) is not None: _start_scan_config[key] = __get_value(flask_request, key) _start_scan_config = __rules(__remove_non_api_keys(_builder(_start_scan_config, _builder(_core_config(), _core_default_config()))), _core_default_config(), language) scan_id = "".join(random.choice("0123456789abcdef") for x in range(32)) scan_cmd = messages(language, 158) _start_scan_config["scan_id"] = scan_id p = multiprocessing.Process(target=__scan, args=[_start_scan_config, scan_id, scan_cmd]) p.start() return jsonify(_start_scan_config)
def __profiles(): profiles = _builder(_profiles(), default_profiles()) res = "" for profile in profiles: res += """<label><input id="{0}" type="checkbox" class="checkbox"><a class="label label-primary">{0}</a></label> """.format(profile) return res
def index(): """ index page for WebUI Returns: rendered HTML page """ filename = _builder(_core_config(), _core_default_config())["log_in_file"] if version() == 2: return render_template("index.html", scan_method=__scan_methods(), profile=__profiles(), graphs=__graphs(), languages=__languages(), filename=filename, method_args_list=load_all_method_args( __language(), API=True).decode('utf-8')) return render_template("index.html", scan_method=__scan_methods(), profile=__profiles(), graphs=__graphs(), languages=__languages(), filename=filename, method_args_list=load_all_method_args(__language(), API=True))
def load_file_path(): """ load home path Returns: value of home path """ return _builder(_core_config(), _core_default_config())["home_path"]
def new_scan(): _start_scan_config = {} __api_key_check(app, flask_request, __language()) for key in _core_default_config(): if __get_value(flask_request, key) is not None: _start_scan_config[key] = __get_value(flask_request, key) _start_scan_config["backup_ports"] = __get_value(flask_request, "ports") _start_scan_config = __rules( __remove_non_api_keys( _builder(_start_scan_config, _builder(_core_config(), _core_default_config()))), _core_default_config(), __language()) p = multiprocessing.Process(target=__scan, args=[_start_scan_config]) p.start() # Sometimes method_args is too big! _start_scan_config["methods_args"] = {"as_user_set": "set_successfully"} return jsonify(_start_scan_config), 200
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 Exception: __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 Exception: __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 Exception: __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 Exception: __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 Exception: __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 Exception: __die_failure(messages("en", "database_connection_failed")) else: __die_failure(messages("en", "invalid_database")) return True
def index(): filename = _builder(_core_config(), _core_default_config())["log_in_file"] return render_template("index.html", scan_method=__scan_methods(), profile=__profiles(), graphs=__graphs(), languages=__languages(), filename=filename, method_args_list=load_all_method_args(__language(), API=True))
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", "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
def __profiles(): """ all available profiles for API Returns: HTML content or available profiles """ profiles = _builder(_profiles(), default_profiles()) res = "" for profile in profiles: res += """<label><input id="{0}" type="checkbox" class="checkbox"><a class="label label-primary">{0}</a></label> """.format( profile) return res
def create_connection(language): try: # retries for i in range(0, 100): try: return sqlite3.connect( os.path.join( os.path.dirname(os.path.dirname(__file__)), _builder(_core_config(), _core_default_config())["api_db_name"])) except: pass time.sleep(0.01) except: warn(messages(language, 168)) return False
def __profiles(): """ all available profiles for API Returns: HTML content or available profiles """ profiles = _builder(_profiles(), default_profiles()) res = "" for profile in profiles: label = "success" if (profile == "scan") else "warning" if ( profile == "brute") else "danger" if ( profile == "vulnerability") else "default" res += """<label><input id="{0}" type="checkbox" class="checkbox checkbox-{0}"><a class="label label-{1}">{0}</a></label> """.format( profile, label) return res
def __wizard(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, language): # default config module_name = scan_method[:] ex_module_name = scan_method[:] ex_module_name.remove('all') default_config = _builder(get_config(), all_config_keys()) targets = __input(messages(language, 118).format(messages(language, 120), default_config["targets"]), default_config["targets"]) thread_number = __input(messages(language, 118).format(messages(language, 121), default_config["thread_number"]), default_config["thread_number"]) thread_number_host = __input(messages(language, 118) .format(messages(language, 122), default_config["thread_number_host"]), default_config["thread_number_host"]) log_in_file = __input(messages(language, 118).format(messages(language, 123), default_config["log_in_file"]), default_config["log_in_file"]) scan_method = __input(messages(language, 119) .format(messages(language, 124), ', '.join(module_name), default_config["scan_method"]), default_config["scan_method"]) exclude_method = __input(messages(language, 119) .format(messages(language, 125), ', '.join(ex_module_name), default_config["exclude_method"]), default_config["exclude_method"]) users = __input(messages(language, 118).format(messages(language, 126), default_config["users"]), default_config["users"]) passwds = __input(messages(language, 118).format(messages(language, 127), default_config["passwds"]), default_config["passwds"]) timeout_sec = __input(messages(language, 118).format(messages(language, 128), default_config["timeout_sec"]), default_config["timeout_sec"]) ports = __input(messages(language, 118).format(messages(language, 129), default_config["ports"]), default_config["ports"]) verbose_level = __input(messages(language, 118).format(messages(language, 130), default_config["verbose_level"]), default_config["verbose_level"]) socks_proxy = __input(messages(language, 118).format(messages(language, 131), default_config["socks_proxy"]), default_config["socks_proxy"]) retries = __input(messages(language, 118).format(messages(language, 132), default_config["retries"]), default_config["retries"]) graph_flag = __input(messages(language, 119) .format(messages(language, 133), ', '.join(graph_flag), default_config["graph_flag"]), default_config["graph_flag"]) return [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]
def create_connection(language): """ a function to create sqlite3 connections to db, it retries 100 times if connection returned an error Args: language: language Returns: sqlite3 connection if success otherwise False """ try: # retries for i in range(0, 100): try: return sqlite3.connect( os.path.join( os.path.dirname(os.path.dirname(__file__)), _builder(_core_config(), _core_default_config())["api_db_name"])) except: time.sleep(0.01) except: warn(messages(language, "database_connect_fail")) return False
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from core.config_builder import _builder from core.config_builder import _api_default_config from config import _api_config app = Flask(__name__) @app.route('/') def index(): return "Hello, World!" if __name__ == '__main__': config = _builder(_api_config(), _api_default_config()) app.run(host=config["host"], port=config["port"], debug=config["debug_mode"])
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, 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 from core.color import finish default_config = _builder(get_config()) 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: error("Please select one of these languages {0}".format( language_list)) finish() sys.exit(1) # 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)) # 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("Method", 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="proxies", 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)) # 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]
def __rules(config, defaults, language): # Check Ranges config["check_ranges"] = True if config[ "check_ranges"] is not False else False # Check Subdomains config["check_subdomains"] = True if config[ "check_subdomains"] is not False else False # Check Graph config["graph_flag"] = config["graph_flag"] if config[ "graph_flag"] in load_all_graphs() else None # Check Language config["language"] = config["language"] if config["language"] in [ lang for lang in messages(-1, 0) ] else "en" # Check Targets if config["targets"] is not None: config["targets"] = list(set(config["targets"].rsplit(","))) else: abort(400, messages(language, 26)) # Check Log File try: f = open(config["log_in_file"], "a") f.close() except: abort(400, messages(language, 40).format(config["log_in_file"])) # Check Method ARGS methods_args = config["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: 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 config["methods_args"] = methods_args # Check Passwords config["passwds"] = config["passwds"].rsplit( ',') if config["passwds"] is not None else None # Check Ping Before Scan config["ping_flag"] = True if config["ping_flag"] is not False else False # Check Ports ports = config["ports"] 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: abort(400, messages(language, 157)) if len(tmp_ports) is 0: ports = None else: ports = tmp_ports[:] config["ports"] = ports # Check Profiles if config["profile"] is not None: _all_profiles = _builder(_profiles(), default_profiles()) if config["scan_method"] is None: config["scan_method"] = "" else: config["scan_method"] += "," if "all" in config["profile"].rsplit(","): config["profile"] = ",".join(_all_profiles) tmp_sm = config["scan_method"] for pr in config["profile"].rsplit(","): try: for sm in _all_profiles[pr]: if sm not in tmp_sm.rsplit(","): tmp_sm += sm + "," except: abort(400, messages(language, 137).format(pr)) if tmp_sm[-1] == ",": tmp_sm = tmp_sm[0:-1] config["scan_method"] = ",".join(list(set(tmp_sm.rsplit(",")))) # Check retries try: config["retries"] = int(config["retries"]) except: config["retries"] = defaults["retries"] # Check Scanning Method if config["scan_method"] is not None and "all" in config[ "scan_method"].rsplit(","): config["scan_method"] = load_all_modules() config["scan_method"].remove("all") elif len(config["scan_method"].rsplit( ",")) is 1 and "*_" not in config["scan_method"]: if config["scan_method"] in load_all_modules(): config["scan_method"] = config["scan_method"].rsplit() else: abort(400, messages(language, 30).format(config["scan_method"])) else: if config["scan_method"] is not None: if config["scan_method"] not in load_all_modules(): if "*_" in config["scan_method"] or "," in config[ "scan_method"]: config["scan_method"] = config["scan_method"].rsplit(",") scan_method_tmp = config["scan_method"][:] for sm in scan_method_tmp: scan_method_error = True if sm.startswith("*_"): config["scan_method"].remove(sm) found_flag = False for mn in load_all_modules(): if mn.endswith("_" + sm.rsplit("*_")[1]): config["scan_method"].append(mn) scan_method_error = False found_flag = True if found_flag is False: abort(400, messages(language, 117).format(sm)) elif sm == "all": config["scan_method"] = load_all_modules() scan_method_error = False config["scan_method"].remove("all") break elif sm in load_all_modules(): scan_method_error = False elif sm not in load_all_modules(): abort(400, messages(language, 30).format(sm)) else: scan_method_error = True if scan_method_error: abort(400, messages(language, 30).format(config["scan_method"])) else: abort(400, messages(language, 41)) config["scan_method"] = list(set(config["scan_method"])) # Check Socks Proxy socks_proxy = config["socks_proxy"] 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: abort(400, messages(language, 63)) if socks_flag is 4: socks_proxy = "socks4://" + socks_proxy if socks_flag is 5: socks_proxy = "socks5://" + socks_proxy config["socks_proxy"] = socks_proxy # Check thread numbers try: config["thread_number"] = int(config["thread_number"]) except: config["thread_number"] = defaults["thread_number"] # Check thread number for hosts try: config["thread_number_host"] = int(config["thread_number_host"]) except: config["thread_number_host"] = defaults["thread_number_host"] # Check time sleep try: config["time_sleep"] = float(config["time_sleep"]) except: config["time_sleep"] = defaults["time_sleep"] # Check timeout sec try: config["timeout_sec"] = int(config["timeout_sec"]) except: config["thread_number_host"] = defaults["thread_number_host"] # Check users config["users"] = config["users"].rsplit( ',') if config["users"] is not None else None return config
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]
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"], ]
def __wizard(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, language): """ start the framework in wizard mode Args: targets: targets (default value) thread_number: thread number (default value) thread_number_host: thread number for hosts (default value) log_in_file: output filename (default value) scan_method: module names (default value) exclude_method: excluded module names (default value) users: usernames (default value) passwds: passwords (default value) timeout_sec: timeout seconds (default value) ports: port numbers (default value) verbose_level: verbose level number (default value) socks_proxy: socks proxy (default value) retries: retries number (default value) graph_flag: graph name (default value) language: language Returns: an array with user inputs """ # default config module_name = scan_method[:] ex_module_name = scan_method[:] ex_module_name.remove('all') default_config = _builder(_core_config(), _core_default_config()) targets = __input( messages(language, "enter_default").format(messages(language, "all_targets"), default_config["targets"]), default_config["targets"]) thread_number = __input( messages(language, "enter_default").format( messages(language, "all_thread_numbers"), default_config["thread_number"]), default_config["thread_number"]) try: thread_number = int(thread_number) except: thread_number = default_config["thread_number"] thread_number_host = __input( messages(language, "enter_default").format( messages(language, "thread_number_hosts"), default_config["thread_number_host"]), default_config["thread_number_host"]) try: thread_number_host = int(thread_number_host) except: thread_number_host = default_config["thread_number_host"] log_in_file = __input( messages(language, "enter_default").format(messages(language, "out_file"), default_config["log_in_file"]), default_config["log_in_file"]) scan_method = __input( messages(language, "enter_choices_default").format( messages(language, "all_scan_methods"), ', '.join(module_name), default_config["scan_method"]), default_config["scan_method"]) exclude_method = __input( messages(language, "enter_choices_default").format( messages(language, "all_scan_methods_exclude"), ', '.join(ex_module_name), default_config["exclude_method"]), default_config["exclude_method"]) users = __input( messages(language, "enter_default").format(messages(language, "all_usernames"), default_config["users"]), default_config["users"]) passwds = __input( messages(language, "enter_default").format(messages(language, "all_passwords"), default_config["passwds"]), default_config["passwds"]) timeout_sec = __input( messages(language, "enter_default").format(messages(language, "timeout_seconds"), default_config["timeout_sec"]), default_config["timeout_sec"]) try: timeout_sec = int(timeout_sec) except: timeout_sec = default_config["timeout_sec"] ports = __input( messages(language, "enter_default").format(messages(language, "all_ports"), default_config["ports"]), default_config["ports"]) verbose_level = __input( messages(language, "enter_default").format( messages(language, "all_verbose_level"), default_config["verbose_level"]), default_config["verbose_level"]) socks_proxy = __input( messages(language, "enter_default").format(messages(language, "all_socks_proxy"), default_config["socks_proxy"]), default_config["socks_proxy"]) retries = __input( messages(language, "enter_default").format(messages(language, "retries_number"), default_config["retries"]), default_config["retries"]) try: retries = int(retries) except: retries = default_config["retries"] graph_flag = __input( messages(language, "enter_choices_default").format(messages(language, "graph"), ', '.join(graph_flag), default_config["graph_flag"]), default_config["graph_flag"]) return [ 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 ]
def discovery(target, ports=None, timeout=3, thread_number=1000, send_data=None, time_sleep=0, socks_proxy=None): """ Discover the service run on the port, it can detect real service names when users change default port number Args: target: target to scan ports: ports in array, or if None it will test 1000 common ports timeout: timeout seconds thread_number: thread numbers send_data: data to send by socket, if None it will send b"ABC\x00\r\n" * 10 by default time_sleep: time to sleep between requests socks_proxy: socks proxy Returns: discovered services and ports in JSON dict """ threads = [] if not send_data: send_data = b"ABC\x00\r\n" * 10 if not ports: from lib.scan.port.engine import extra_requirements_dict as port_scanner_default_ports ports = port_scanner_default_ports()["port_scan_ports"] for port in ports: t = threading.Thread(target=discover_by_port, args=(target, int(port), int(timeout), send_data, socks_proxy)) threads.append(t) t.start() time.sleep(time_sleep) while 1: try: if threading.activeCount() <= thread_number: break time.sleep(0.01) except KeyboardInterrupt: break kill_switch = 0 while 1: time.sleep(0.01) kill_switch += 1 try: if threading.activeCount() is 1 or int(kill_switch) is int( timeout * 5 * 10): break except KeyboardInterrupt: break if _builder(_core_config(), _core_default_config())["send_diagnostics"]: diagnostics_data = {} diagnostics_data["services"] = json.dumps(result_dict) diagnostics_data["timeout"] = timeout diagnostics_data["thread_number"] = thread_number diagnostics_data["send_data"] = binascii.b2a_base64(send_data) diagnostics_data["target"] = target send_service_scan_diagnostics(diagnostics_data) return result_dict
def load_file_path(): return _builder(_core_config(), _core_default_config())["home_path"]
def __rules(config, defaults, language): """ Load ARGS from API requests and apply the rules Args: config: all user config defaults: default config language: language Returns: config with applied rules """ # Check Ranges config["check_ranges"] = True if config[ "check_ranges"] is not False else False # Check Subdomains config["check_subdomains"] = True if config[ "check_subdomains"] is not False else False # Check Graph config["graph_flag"] = config["graph_flag"] if config[ "graph_flag"] in load_all_graphs() else None # Check Language config["language"] = config["language"] if config["language"] in list( messages(-1, 0)) else "en" # Check Targets if config["targets"] is not None: config["targets"] = list(set(config["targets"].rsplit(","))) else: abort(400, messages(language, "error_target")) # Check Log File try: f = open(config["log_in_file"], "a") f.close() except: abort( 400, messages(language, "file_write_error").format(config["log_in_file"])) # Check Method ARGS methods_args = config["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: new_methods_args[imethod_args.rsplit("=") [0]] = imethod_args.rsplit("=")[1].rsplit(",") else: new_methods_args[imethod_args] = ["True"] methods_args = new_methods_args config["methods_args"] = methods_args # Check Passwords config["passwds"] = config["passwds"].rsplit( ',') if config["passwds"] is not None else None # Check Ping Before Scan config["ping_flag"] = True if config["ping_flag"] is not False else False # Check Ports ports = config["ports"] 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: abort(400, messages(language, "ports_int")) if len(tmp_ports) == 0: ports = None else: ports = tmp_ports[:] config["ports"] = ports # Check Profiles if config["profile"] is not None: _all_profiles = _builder(_profiles(), default_profiles()) synonyms = _synonym_profile().keys() for synonym in synonyms: del (_all_profiles[synonym]) if config["scan_method"] is None: config["scan_method"] = "" else: config["scan_method"] += "," if "all" in config["profile"].rsplit(","): config["profile"] = ",".join(_all_profiles) tmp_sm = config["scan_method"] for pr in config["profile"].rsplit(","): try: for sm in _all_profiles[pr]: if sm not in tmp_sm.rsplit(","): tmp_sm += sm + "," except: abort(400, messages(language, "profile_404").format(pr)) if tmp_sm[-1] == ",": tmp_sm = tmp_sm[0:-1] config["scan_method"] = ",".join(list(set(tmp_sm.rsplit(",")))) # Check retries try: config["retries"] = int(config["retries"]) except: config["retries"] = defaults["retries"] # Check Scanning Method if config["scan_method"] is not None and "all" in config[ "scan_method"].rsplit(","): config["scan_method"] = load_all_modules() config["scan_method"].remove("all") elif config["scan_method"] is not None and len( config["scan_method"].rsplit( ",")) == 1 and "*_" not in config["scan_method"]: if config["scan_method"] in load_all_modules(): config["scan_method"] = config["scan_method"].rsplit() else: abort( 400, messages(language, "scan_module_not_found").format( config["scan_method"])) else: if config["scan_method"] is not None: if config["scan_method"] not in load_all_modules(): if "*_" in config["scan_method"] or "," in config[ "scan_method"]: config["scan_method"] = config["scan_method"].rsplit(",") scan_method_tmp = config["scan_method"][:] for sm in scan_method_tmp: scan_method_error = True if sm.startswith("*_"): config["scan_method"].remove(sm) found_flag = False for mn in load_all_modules(): if mn.endswith("_" + sm.rsplit("*_")[1]): config["scan_method"].append(mn) scan_method_error = False found_flag = True if found_flag is False: abort( 400, messages(language, "module_pattern_404").format(sm)) elif sm == "all": config["scan_method"] = load_all_modules() scan_method_error = False config["scan_method"].remove("all") break elif sm in load_all_modules(): scan_method_error = False elif sm not in load_all_modules(): abort( 400, messages(language, "scan_module_not_found").format(sm)) else: scan_method_error = True if scan_method_error: abort( 400, messages(language, "scan_module_not_found").format( config["scan_method"])) else: abort(400, messages(language, "scan_method_select")) config["scan_method"] = list(set(config["scan_method"])) # Check Socks Proxy socks_proxy = config["socks_proxy"] 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: e = True if e: abort(400, messages(language, "valid_socks_address")) if socks_flag == 4: socks_proxy = "socks4://" + socks_proxy if socks_flag == 5: socks_proxy = "socks5://" + socks_proxy config["socks_proxy"] = socks_proxy # Check thread numbers try: config["thread_number"] = int(config["thread_number"]) except: config["thread_number"] = defaults["thread_number"] # Check thread number for hosts try: config["thread_number_host"] = int(config["thread_number_host"]) except: config["thread_number_host"] = defaults["thread_number_host"] # Check time sleep try: config["time_sleep"] = float(config["time_sleep"]) except: config["time_sleep"] = defaults["time_sleep"] # Check timeout sec try: config["timeout_sec"] = int(config["timeout_sec"]) except: config["thread_number_host"] = defaults["thread_number_host"] # Check users config["users"] = config["users"].rsplit( ',') if config["users"] is not None else None return config