Ejemplo n.º 1
0
def _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):
    # Starting the API
    write_to_api_console(messages(language, 156).format(api_access_key))
    p = multiprocessing.Process(
        target=__process_it,
        args=(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))
    p.start()
    # Sometimes it's take much time to terminate flask with CTRL+C
    # So It's better to use KeyboardInterrupt to terminate!
    while 1:
        try:
            exitflag = True
            if len(multiprocessing.active_children()) is not 0:
                exitflag = False
            time.sleep(0.3)
            if exitflag:
                break
        except KeyboardInterrupt:
            for process in multiprocessing.active_children():
                process.terminate()
            break

    __die_success()
Ejemplo n.º 2
0
def _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):
    """
    entry point to run the API through the flask

    Args:
        api_host: host/IP to bind address
        api_port: bind port
        api_debug_mode: debug mode
        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
    """
    # Starting the API
    write_to_api_console(messages(language, "API_key").format(api_access_key))
    p = multiprocessing.Process(target=__process_it,
                                args=(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))
    p.start()
    # Sometimes it's take much time to terminate flask with CTRL+C
    # So It's better to use KeyboardInterrupt to terminate!
    while 1:
        try:
            exitflag = True
            if len(multiprocessing.active_children()) != 0:
                exitflag = False
            time.sleep(0.3)
            if exitflag:
                break
        except KeyboardInterrupt:
            for process in multiprocessing.active_children():
                process.terminate()
            break

    __die_success()
Ejemplo n.º 3
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):
    # 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
    ]
Ejemplo n.º 4
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):
    # 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]
Ejemplo n.º 5
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]
Ejemplo n.º 6
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