コード例 #1
0
def save_credentials():
    if root.verify_running_as_root() is False:
        print(
            "Please run as 'sudo openpyn --init' the first time. root access is",
            "needed to store credentials in /usr/share/openpyn/credentials.")
        sys.exit()
    else:
        print(
            "Storing credentials in '/usr/share/openpyn/credentials with openvpn",
            "compatible 'auth-user-pass' file format\n")

        username = input(
            "Enter your username for NordVPN, i.e [email protected]: ")
        password = input("Enter the password for NordVPN: ")
        command_1 = "sudo echo " + '"%s"' % username + " > /usr/share/openpyn/credentials"
        command_2 = "sudo echo " + '"%s"' % password + " >> /usr/share/openpyn/credentials"
        try:
            # create Empty file with 600 permissions
            subprocess.call(
                "sudo touch /usr/share/openpyn/credentials".split())
            subprocess.check_call(command_1, shell=True)
            subprocess.check_call(command_2, shell=True)
            subprocess.check_call(
                "sudo chmod 600 /usr/share/openpyn/credentials".split())

            print(
                "Awesome, the credentials have been saved in '/usr/share/openpyn/credentials'\n"
            )
        except subprocess.CalledProcessError:
            print(
                "Your OS is not letting modify /usr/share/openpyn/credentials",
                "Please run with 'sudo' to store credentials")
            subprocess.call("sudo rm /usr/share/openpyn/credentials".split())
            sys.exit()
    return
コード例 #2
0
def save_credentials():
    if root.verify_running_as_root() is False:
        print(
            "Please run as 'sudo openpyn --init' the first time. Root access is",
            "needed to store credentials in " + "'" + credentials_file_path +
            "'" + ".")
        sys.exit()
    else:
        print(
            "Storing credentials in " + "'" + credentials_file_path + "'" +
            " with openvpn", "compatible 'auth-user-pass' file format\n")

        username = input(
            "Enter your username for NordVPN, i.e [email protected]: ")
        password = input("Enter the password for NordVPN: ")
        try:
            with open(credentials_file_path, 'w') as creds:
                creds.write(username + "\n")
                creds.write(password + "\n")
            creds.close()
            # Change file permission to 600
            subprocess.check_call(
                ["sudo", "chmod", "600", credentials_file_path])

            print("Awesome, the credentials have been saved in " + "'" +
                  credentials_file_path + "'" + "\n")
        except (IOError, OSError):
            print("IOError while creating 'credentials' file.")
    return
コード例 #3
0
def save_credentials() -> None:
    if not sys.__stdin__.isatty():
        raise RuntimeError("Please run %s in interactive mode" % __name__)

    if root.verify_running_as_root() is False:
        raise RuntimeError(
            "Please run as 'sudo openpyn --init' the first time. Root access is needed to store credentials in '%s'."
            % credentials_file_path)

    logger.info(
        "Storing credentials in '%s' with openvpn compatible 'auth-user-pass' file format",
        credentials_file_path)

    username = input(
        "Enter your username for NordVPN, i.e [email protected]: ")
    password = getpass.getpass("Enter the password for NordVPN: ")
    try:
        with open(credentials_file_path, "w") as creds:
            creds.write(username + "\n")
            creds.write(password + "\n")
        # change file permission to 600
        os.chmod(credentials_file_path, 0o600)

        logger.info("Awesome, the credentials have been saved in '%s'",
                    credentials_file_path)
    except (IOError, OSError):
        raise RuntimeError(
            "IOError while creating 'credentials' file.") from None
コード例 #4
0
def save_credentials() -> None:
    if not sys.__stdin__.isatty():
        logger.critical("Please run %s in interactive mode", __name__)
        sys.exit(1)

    if root.verify_running_as_root() is False:
        logger.error(
            "Please run as 'sudo openpyn --init' the first time. \
Root access is needed to store credentials in '%s'.", credentials_file_path)
        sys.exit(1)
    else:
        logger.info(
            "Storing credentials in '%s' with openvpn \
compatible 'auth-user-pass' file format", credentials_file_path)

        username = input(
            "Enter your username for NordVPN, i.e [email protected]: ")
        password = getpass.getpass("Enter the password for NordVPN: ")
        try:
            with open(credentials_file_path, 'w') as creds:
                creds.write(username + "\n")
                creds.write(password + "\n")
            creds.close()
            # Change file permission to 600
            subprocess.check_call(
                ["sudo", "chmod", "600", credentials_file_path])

            logger.info("Awesome, the credentials have been saved in '%s'",
                        credentials_file_path)
        except (IOError, OSError):
            logger.error("IOError while creating 'credentials' file.")
    return
コード例 #5
0
def save_credentials():
    credentials_file_path = __basefilepath__ + "credentials"
    if root.verify_running_as_root() is False:
        print(
            "Please run as 'sudo openpyn --init' the first time. Root access is",
            "needed to store credentials in " + "'" + credentials_file_path +
            "'" + ".")
        sys.exit()
    else:
        print(
            "Storing credentials in " + "'" + credentials_file_path + "'" +
            " with openvpn", "compatible 'auth-user-pass' file format\n")

        username = input(
            "Enter your username for NordVPN, i.e [email protected]: ")
        password = input("Enter the password for NordVPN: ")
        command_1 = "sudo echo " + '"%s"' % username + " > " + credentials_file_path
        command_2 = "sudo echo " + '"%s"' % password + " >> " + credentials_file_path
        try:
            subprocess.call(["sudo", "mkdir", "-p", __basefilepath__])
            # create Empty file with 600 permissions
            subprocess.call(["sudo", "touch", credentials_file_path])
            subprocess.check_call(command_1, shell=True)
            subprocess.check_call(command_2, shell=True)
            subprocess.check_call(
                ["sudo", "chmod", "600", credentials_file_path])

            print("Awesome, the credentials have been saved in " + "'" +
                  credentials_file_path + "'" + "\n")
        except subprocess.CalledProcessError:
            print(
                "Your OS is not letting modify " + "'" +
                credentials_file_path + "'",
                "Please run with 'sudo' to store credentials")
            subprocess.call(["sudo", "rm", credentials_file_path])
            sys.exit()
    return
コード例 #6
0
def save_credentials():
    credentials_file_path = __basefilepath__ + "credentials"
    if root.verify_running_as_root() is False:
        print(
            "Please run as 'sudo openpyn --init' the first time. Root access is",
            "needed to store credentials in " + "'" + credentials_file_path +
            "'" + ".")
        sys.exit()
    else:
        print(
            "Storing credentials in " + "'" + credentials_file_path + "'" +
            " with openvpn", "compatible 'auth-user-pass' file format\n")

        username = input(
            "Enter your username for NordVPN, i.e [email protected]: ")
        password = input("Enter the password for NordVPN: ")
        try:
            with open(credentials_file_path, 'w') as creds:
                creds.write(username + "\n")
                creds.write(password + "\n")
            creds.close()
            subprocess.call(["sudo", "mkdir", "-p", __basefilepath__])
            # Change file permission to 600
            subprocess.check_call(
                ["sudo", "chmod", "600", credentials_file_path])

            print("Awesome, the credentials have been saved in " + "'" +
                  credentials_file_path + "'" + "\n")
        except subprocess.CalledProcessError:
            print(
                "Your OS is not letting modify " + "'" +
                credentials_file_path + "'",
                "Please run with 'sudo' to store credentials")
            subprocess.call(["sudo", "rm", credentials_file_path])
            sys.exit()
    return
コード例 #7
0
ファイル: openpyn.py プロジェクト: sjawhar/openpyn-nordvpn
def run(init: bool, server: str, country_code: str, country: str, area: str, tcp: bool, daemon: bool,
        max_load: int, top_servers: int, pings: str, kill: bool, kill_flush: bool, update: bool, list_servers: bool,
        force_fw_rules: bool, p2p: bool, dedicated: bool, double_vpn: bool, tor_over_vpn: bool, anti_ddos: bool,
        netflix: bool, test: bool, internally_allowed: List, skip_dns_patch: bool, silent: bool, nvram: str,
        openvpn_options: str, location: float) -> bool:

    if init:
        initialise(log_folder)

    fieldstyles = {
        'asctime': {'color': 'green'},
        'hostname': {'color': 'magenta'},
        'levelname': {'color': 'black', 'bold': True},
        'name': {'color': 'blue'},
        'programname': {'color': 'cyan'},
    }
    levelstyles = {
        'spam': {'color': 'green', 'faint': True},
        'debug': {'color': 'green', 'bold': True},
        'verbose': {'color': 'blue', 'bold': True},
        'info': {},
        'notice': {'color': 'magenta', 'bold': True},
        'warning': {'color': 'yellow', 'bold': True},
        'success': {'color': 'green', 'bold': True},
        'error': {'color': 'red', 'bold': True},
        'critical': {'color': 'white', 'background': 'red', 'bold': True}
    }

    logger.addHandler(logging.StreamHandler())

    # if log folder doesnt exist, exit, "--init" creates it
    if not os.path.exists(log_folder):
        logger.error(
            "Please initialise first by running 'sudo openpyn --init', then start using 'openpyn' without sudo")
        return 1

    # Add another rotating handler to log to .log files
    # fix permissions if needed
    for attempt in range(2):
        try:
            file_handler = logging.handlers.TimedRotatingFileHandler(
                log_folder + '/openpyn.log', when='W0', interval=4)
            file_handler_formatter = logging.Formatter(log_format)
            file_handler.setFormatter(file_handler_formatter)
            logger.addHandler(file_handler)
        except PermissionError:
            root.verify_root_access(
                "Root access needed to set permissions of {}/openpyn.log".format(log_folder))
            subprocess.run("sudo chmod 777 {}/openpyn.log".format(log_folder).split())
            subprocess.run("sudo chmod 777 {}/openpyn-notifications.log".format(log_folder).split())
        else:
            break

    # In this case only log messages originating from this logger will show up on the terminal.
    coloredlogs.install(level="verbose", logger=logger, fmt=log_format,
                        level_styles=levelstyles, field_styles=fieldstyles)

    stats = True
    if sys.__stdin__.isatty():
        logger.debug("Interactive")
    else:
        logger.addHandler(logging.StreamHandler(sys.stdout))
        logger.setLevel(logging.WARNING)
        logger.debug("Non-Interactive")
        stats = False

    port = "udp"
    if tcp:
        port = "tcp"

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            force_fw_rules = False
            silent = True
            skip_dns_patch = True
            if openvpn_options:
                openvpn_options += " " + "--syslog openpyn"
            else:
                openvpn_options = "--syslog openpyn"
            logger.debug(openvpn_options)
        elif os.path.exists("/etc/openwrt_release"):
            force_fw_rules = False
            silent = True
            skip_dns_patch = True
            nvram = None
        else:
            nvram = None
    elif detected_os == "win32":
        logger.error("Are you even a l33t mate? Try GNU/Linux")
        return 1

    # check if dependencies are installed
    if shutil.which("openvpn") is None or shutil.which("wget") is None or shutil.which("unzip") is None:
        # In case of Debian Sid where "openvpn" is only in root's PATH, don't error out
        try:
            root_access = root.verify_root_access(
                "Sudo credentials required to check if 'openvpn' is available in root's PATH")
            if root_access is False:
                root.obtain_root_access()
            subprocess.check_output(["sudo", "which", "wget"])
            subprocess.check_output(["sudo", "which", "unzip"])
            # subprocess.check_output(["sudo", "which", "openvpn"])
        except subprocess.CalledProcessError:
            logger.error("Please Install 'openvpn' 'wget' 'unzip' first")
            return 1

    elif daemon:
        if detected_os != "linux":
            logger.error("Daemon mode is only available in GNU/Linux distros")
            return 1

        if not root.verify_running_as_root():
            logger.error("Please run '--daemon' or '-d' mode with sudo")
            return 1
        openpyn_options = ""

        # if only positional argument used
        if country_code is None and server is None:
            country_code = country      # consider the positional arg e.g "us" same as "-c us"
        # if either "-c" or positional arg f.e "au" is present

        if country_code:
            if len(country_code) > 2:   # full country name
                # get the country_code from the full name
                country_code = api.get_country_code(full_name=country_code)
            country_code = country_code.lower()
            openpyn_options += country_code

        elif server:
            openpyn_options += " --server " + server

        if area:
            openpyn_options += " --area " + area
        if tcp:
            openpyn_options += " --tcp"
        if max_load:
            openpyn_options += " --max-load " + str(max_load)
        if top_servers:
            openpyn_options += " --top-servers " + str(top_servers)
        if pings:
            openpyn_options += " --pings " + str(pings)
        if force_fw_rules:
            openpyn_options += " --force-fw-rules"
        if p2p:
            openpyn_options += " --p2p"
        if dedicated:
            openpyn_options += " --dedicated"
        if double_vpn:
            openpyn_options += " --double"
        if tor_over_vpn:
            openpyn_options += " --tor"
        if anti_ddos:
            openpyn_options += " --anti-ddos"
        if netflix:
            openpyn_options += " --netflix"
        if test:
            openpyn_options += " --test"
        if internally_allowed:
            open_ports = ""
            for port_number in internally_allowed:
                open_ports += " " + port_number
            openpyn_options += " --allow" + open_ports
        if skip_dns_patch:
            openpyn_options += " --skip-dns-patch"
        if nvram:
            openpyn_options += " --nvram " + str(nvram)
        if openvpn_options:
            openpyn_options += " --openvpn-options '" + openvpn_options + "'"
        # logger.debug(openpyn_options)
        if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            initd.update_service(openpyn_options, run=True)
        elif os.path.exists("/etc/openwrt_release"):
            initd.update_service(openpyn_options, run=True)
        else:
            systemd.update_service(openpyn_options, run=True)
        return 0

    elif kill:
        logger.warning("Killing the running processes")
        kill_management_client()
        kill_vpn_processes()  # don't touch iptable rules
        kill_openpyn_process()

    elif kill_flush:
        firewall.clear_fw_rules()      # also clear iptable rules
        # if --allow present, allow those ports internally
        logger.info("Re-enabling ipv6")
        firewall.manage_ipv6(disable=False)
        if internally_allowed:
            network_interfaces = get_network_interfaces()
            firewall.internally_allow_ports(network_interfaces, internally_allowed)
        kill_management_client()
        kill_vpn_processes()
        kill_openpyn_process()

    elif update:
        update_config_files()

    # a hack to list all countries and their codes when no arg supplied with "-l"
    elif list_servers != 'nope':      # means "-l" supplied
        if list_servers is None:      # no arg given with "-l"
            if p2p or dedicated or double_vpn or tor_over_vpn or anti_ddos or netflix:
                # show the special servers in all countries
                display_servers(
                    list_servers="all", port=port, area=area, p2p=p2p, dedicated=dedicated,
                    double_vpn=double_vpn, tor_over_vpn=tor_over_vpn, anti_ddos=anti_ddos,
                    netflix=netflix, location=location)
            else:
                api.list_all_countries()
        # if a country code is supplied give details about that country only.
        else:
            # if full name of the country supplied get country_code
            if len(list_servers) > 2:
                list_servers = api.get_country_code(full_name=list_servers)
            display_servers(
                list_servers=list_servers, port=port, area=area, p2p=p2p, dedicated=dedicated,
                double_vpn=double_vpn, tor_over_vpn=tor_over_vpn, anti_ddos=anti_ddos,
                netflix=netflix, location=location)

    # only clear/touch FW Rules if "-f" used
    elif force_fw_rules:
        firewall.clear_fw_rules()

    # check if OpenVPN config files exist if not download them.
    check_config_files()

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country      # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        if len(country_code) > 2:   # full country name
            # get the country_code from the full name
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()

        # keep trying to connect to new servers
        for tries in range(3):  # pylint: disable=W0612
            better_servers_list = find_better_servers(
                country_code, area, max_load, top_servers, tcp, p2p,
                dedicated, double_vpn, tor_over_vpn, anti_ddos, netflix, location, stats)
            pinged_servers_list = ping_servers(better_servers_list, pings, stats)
            chosen_servers = choose_best_servers(pinged_servers_list, stats)

            # connect to chosen_servers, if one fails go to next
            for aserver in chosen_servers:
                if stats:
                    print(Style.BRIGHT + Fore.BLUE + "Out of the Best Available Servers, Chose",
                          (Fore.GREEN + aserver + Fore.BLUE) + "\n")
                # if "-f" used apply firewall rules
                if force_fw_rules:
                    network_interfaces = get_network_interfaces()
                    vpn_server_ip = get_vpn_server_ip(aserver, port)
                    firewall.apply_fw_rules(network_interfaces, vpn_server_ip, skip_dns_patch)
                    if internally_allowed:
                        firewall.internally_allow_ports(network_interfaces, internally_allowed)
                if nvram:
                    # TODO return 0 on success else 1 in asus.run()
                    asus.run(aserver, country_code, nvram, "All", "adaptive", "Strict", tcp, test)
                    logger.success("SAVED SERVER " + aserver + " ON PORT " + port + " TO NVRAM")
                return(connect(aserver, port, silent, test, skip_dns_patch, openvpn_options))
    elif server:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        server = server.lower()
        # if "-f" used apply firewall rules
        if force_fw_rules:
            network_interfaces = get_network_interfaces()
            vpn_server_ip = get_vpn_server_ip(server, port)
            firewall.apply_fw_rules(network_interfaces, vpn_server_ip, skip_dns_patch)
            if internally_allowed:
                firewall.internally_allow_ports(network_interfaces, internally_allowed)
        if nvram:
            asus.run(server, country_code, nvram, "All", "adaptive", "Strict", tcp, test)
            logger.success("SAVED SERVER " + server + " ON PORT " + port + " TO NVRAM")
            return 0
        for i in range(20):  # pylint: disable=W0612
            return(connect(server, port, silent, test, skip_dns_patch, openvpn_options))
    else:
        logger.info('To see usage options type: "openpyn -h" or "openpyn --help"')
    return 0        # if everything went ok
コード例 #8
0
def run(init, server, country_code, country, area, tcp, daemon, max_load,
        top_servers, pings, kill, kill_flush, update, list_servers,
        force_fw_rules, p2p, dedicated, double_vpn, tor_over_vpn, anti_ddos,
        netflix, test, internally_allowed, skip_dns_patch, silent, nvram,
        openvpn_options):
    port = "udp"
    if tcp:
        port = "tcp"

    detected_os = sys.platform
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            silent = True
            skip_dns_patch = True
        elif os.path.exists("/etc/openwrt_release"):
            silent = True
            skip_dns_patch = True
            nvram = None
        else:
            nvram = None
    elif detected_os == "win32":
        print(Fore.BLUE + "Are you even a l33t mate? Try GNU/Linux")
        print(Style.RESET_ALL)
        sys.exit()

    if init:
        initialise()
    elif daemon:
        if detected_os != "linux":
            print(Fore.RED +
                  "Daemon mode is only available in GNU/Linux distros")
            print(Style.RESET_ALL)
            sys.exit()

        if not root.verify_running_as_root():
            print(Fore.RED + "Please run '--daemon' or '-d' mode with sudo")
            print(Style.RESET_ALL)
            sys.exit()
        openpyn_options = ""

        # if only positional argument used
        if country_code is None and server is None:
            country_code = country  # consider the positional arg e.g "us" same as "-c us"
        # if either "-c" or positional arg f.e "au" is present

        if country_code:
            if len(country_code) > 2:  # full country name
                # get the country_code from the full name
                country_code = api.get_country_code(full_name=country_code)
            country_code = country_code.lower()
            openpyn_options += country_code

        elif server:
            openpyn_options += server

        if area:
            openpyn_options += " --area " + area
        if tcp:
            openpyn_options += " --tcp"
        if max_load:
            openpyn_options += " --max-load " + str(max_load)
        if top_servers:
            openpyn_options += " --top-servers " + str(top_servers)
        if pings:
            openpyn_options += " --pings " + str(pings)
        if force_fw_rules:
            openpyn_options += " --force-fw-rules"
        if p2p:
            openpyn_options += " --p2p"
        if dedicated:
            openpyn_options += " --dedicated"
        if double_vpn:
            openpyn_options += " --double"
        if tor_over_vpn:
            openpyn_options += " --tor"
        if anti_ddos:
            openpyn_options += " --anti-ddos"
        if netflix:
            openpyn_options += " --netflix"
        if test:
            openpyn_options += " --test"
        if internally_allowed:
            open_ports = ""
            for port_number in internally_allowed:
                open_ports += " " + port_number
            openpyn_options += " --allow" + open_ports
        if skip_dns_patch:
            openpyn_options += " --skip-dns-patch"
        if nvram:
            openpyn_options += " --nvram " + str(nvram)
        if openvpn_options:
            openpyn_options += " --openvpn-options '" + openvpn_options + "'"
        openpyn_options += " --silent"
        # print(openpyn_options)
        if subprocess.check_output(["/bin/uname", "-o"]).decode(
                sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            initd.update_service(openpyn_options, run=True)
        elif os.path.exists("/etc/openwrt_release"):
            initd.update_service(openpyn_options, run=True)
        else:
            systemd.update_service(openpyn_options, run=True)
        sys.exit()

    elif kill:
        kill_management_client()
        kill_vpn_processes()  # dont touch iptable rules
        kill_openpyn_process()
        sys.exit()
    elif kill_flush:
        firewall.clear_fw_rules()  # also clear iptable rules
        # if --allow present, allow those ports internally
        if internally_allowed:
            network_interfaces = get_network_interfaces()
            firewall.internally_allow_ports(network_interfaces,
                                            internally_allowed)
        kill_management_client()
        kill_vpn_processes()
        kill_openpyn_process()
        sys.exit()
    elif update:
        update_config_files()
        sys.exit()

    # a hack to list all countries and thier codes when no arg supplied with "-l"
    elif list_servers != 'nope':  # means "-l" supplied
        if list_servers is None:  # no arg given with "-l"
            if p2p or dedicated or double_vpn or tor_over_vpn or anti_ddos or netflix:
                # show the special servers in all countries
                display_servers(list_servers="all",
                                port=port,
                                area=area,
                                p2p=p2p,
                                dedicated=dedicated,
                                double_vpn=double_vpn,
                                tor_over_vpn=tor_over_vpn,
                                anti_ddos=anti_ddos,
                                netflix=netflix)
            else:
                api.list_all_countries()
        # if a country code is supplied give details about that country only.
        else:
            # if full name of the country supplied get country_code
            if len(list_servers) > 2:
                list_servers = api.get_country_code(full_name=list_servers)
            display_servers(list_servers=list_servers,
                            port=port,
                            area=area,
                            p2p=p2p,
                            dedicated=dedicated,
                            double_vpn=double_vpn,
                            tor_over_vpn=tor_over_vpn,
                            anti_ddos=anti_ddos,
                            netflix=netflix)

    # only clear/touch FW Rules if "-f" used
    elif force_fw_rules:
        firewall.clear_fw_rules()

    # check if openvpn config files exist if not download them.
    check_config_files()

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country  # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        if len(country_code) > 2:  # full country name
            # get the country_code from the full name
            country_code = api.get_country_code(full_name=country_code)
        country_code = country_code.lower()

        # keep trying to connect to new servers
        for tries in range(3):  # pylint: disable=W0612
            better_servers_list = find_better_servers(country_code, area,
                                                      max_load, top_servers,
                                                      tcp, p2p, dedicated,
                                                      double_vpn, tor_over_vpn,
                                                      anti_ddos, netflix)
            pinged_servers_list = ping_servers(better_servers_list, pings)
            chosen_servers = choose_best_servers(pinged_servers_list)
            # connect to chosen_servers, if one fails go to next
            for aserver in chosen_servers:
                # if "-f" used appy Firewall rules
                if force_fw_rules:
                    network_interfaces = get_network_interfaces()
                    vpn_server_ip = get_vpn_server_ip(aserver, port)
                    firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                            skip_dns_patch)
                    if internally_allowed:
                        firewall.internally_allow_ports(
                            network_interfaces, internally_allowed)
                if nvram:
                    asus.run(aserver, country_code, nvram, "All", "adaptive",
                             "Strict", tcp, test)
                    sys.exit()
                print(
                    Style.BRIGHT + Fore.BLUE +
                    "Out of the Best Available Servers, Chose",
                    (Fore.GREEN + aserver + Fore.BLUE))
                connect(aserver, port, silent, test, skip_dns_patch,
                        openvpn_options)
    elif server:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        server = server.lower()
        # if "-f" used appy Firewall rules
        if force_fw_rules:
            network_interfaces = get_network_interfaces()
            vpn_server_ip = get_vpn_server_ip(server, port)
            firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                    skip_dns_patch)
            if internally_allowed:
                firewall.internally_allow_ports(network_interfaces,
                                                internally_allowed)
        if nvram:
            asus.run(server, country_code, nvram, "All", "adaptive", "Strict",
                     tcp, test)
            sys.exit()
        for i in range(20):  # pylint: disable=W0612
            connect(server, port, silent, test, skip_dns_patch,
                    openvpn_options)
    else:
        print('To see usage options type: "openpyn -h" or "openpyn --help"')
    sys.exit()
コード例 #9
0
def run(
        # run openpyn
        init,
        server,
        country_code,
        country,
        area,
        tcp,
        daemon,
        max_load,
        top_servers,
        pings,
        kill,
        kill_flush,
        update,
        list_servers,
        force_fw_rules,
        p2p,
        dedicated,
        double_vpn,
        tor_over_vpn,
        anti_ddos,
        test,
        internally_allowed,
        skip_dns_patch,
        silent):
    port = "udp1194"
    if tcp:
        port = "tcp443"

    if sys.platform != "linux":
        if sys.platform == "win32":
            print(Fore.BLUE + "Are you even a l33t mate? Try GNU/Linux")
            print(Style.RESET_ALL)
            sys.exit()
        silent is True  # for macOS or bsd

    if init:
        initialise()
    elif daemon:
        if sys.platform != "linux":
            print(Fore.RED +
                  "Daemon mode is only available in GNU/Linux distros")
            print(Style.RESET_ALL)
            sys.exit()

        if not root.verify_running_as_root():
            print(Fore.RED + "Please run '--daemon' or '-d' mode with sudo")
            print(Style.RESET_ALL)
            sys.exit()
        openpyn_options = " "

        # if only positional argument used
        if country_code is None and server is None:
            country_code = country  # consider the positional arg e.g "us" same as "-c us"
        # if either "-c" or positional arg f.e "au" is present

        if country_code:
            if len(country_code) > 2:  # full country name
                # get the country_code from the full name
                country_code = get_country_code(full_name=country_code)
            country_code = country_code.lower()
            openpyn_options += country_code

        elif server:
            openpyn_options += server

        if area:
            openpyn_options += " --area " + area
        if max_load:
            openpyn_options += " --max-load " + str(max_load)
        if top_servers:
            openpyn_options += " --top-servers " + str(top_servers)
        if pings:
            openpyn_options += " --pings " + str(pings)
        if skip_dns_patch:
            openpyn_options += " --skip-dns-patch "
        if force_fw_rules:
            openpyn_options += " --force-fw-rules "
        if p2p:
            openpyn_options += " --p2p "
        if dedicated:
            openpyn_options += " --dedicated "
        if double_vpn:
            openpyn_options += " --double "
        if tor_over_vpn:
            openpyn_options += " --tor "
        if anti_ddos:
            openpyn_options += " --anti-ddos "
        if test:
            openpyn_options += " --test "
        if internally_allowed:
            open_ports = ""
            for port_number in internally_allowed:
                open_ports += port_number + " "
            openpyn_options += " --allow " + open_ports
        openpyn_options += " --silent"
        # print(openpyn_options)
        systemd.update_service(openpyn_options, run=True)
        sys.exit()

    elif kill:
        kill_vpn_processes()  # dont touch iptable rules
        # let management-client normally shut, if still alive kill it with fire
        kill_management_client()
        sys.exit()
    elif kill_flush:
        kill_vpn_processes()
        kill_management_client()
        firewall.clear_fw_rules()  # also clear iptable rules
        # if --allow present, allow those ports internally
        if internally_allowed:
            network_interfaces = get_network_interfaces()
            firewall.internally_allow_ports(network_interfaces,
                                            internally_allowed)
        sys.exit()
    elif update:
        update_config_files()
        sys.exit()

    # a hack to list all countries and thier codes when no arg supplied with "-l"
    elif list_servers != 'nope':  # means "-l" supplied
        if list_servers is None:  # no arg given with "-l"
            if p2p or dedicated or double_vpn or tor_over_vpn or anti_ddos:
                # show the special servers in all countries
                display_servers(list_servers="all",
                                area=area,
                                p2p=p2p,
                                dedicated=dedicated,
                                double_vpn=double_vpn,
                                tor_over_vpn=tor_over_vpn,
                                anti_ddos=anti_ddos)
            else:
                list_all_countries()
        # if a country code is supplied give details about that country only.
        else:
            # if full name of the country supplied get country_code
            if len(list_servers) > 2:
                list_servers = get_country_code(full_name=list_servers)
            display_servers(list_servers=list_servers,
                            area=area,
                            p2p=p2p,
                            dedicated=dedicated,
                            double_vpn=double_vpn,
                            tor_over_vpn=tor_over_vpn,
                            anti_ddos=anti_ddos)

    # only clear/touch FW Rules if "-f" used
    elif force_fw_rules:
        firewall.clear_fw_rules()

    # check if openvpn config files exist if not download them.
    check_config_files()

    # if only positional argument used
    if country_code is None and server is None:
        country_code = country  # consider the positional arg e.g "us" same as "-c us"
    # if either "-c" or positional arg f.e "au" is present
    if country_code:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        if len(country_code) > 2:  # full country name
            # get the country_code from the full name
            country_code = get_country_code(full_name=country_code)
        country_code = country_code.lower()
        better_servers_list = find_better_servers(country_code, area, max_load,
                                                  top_servers, tcp, p2p,
                                                  dedicated, double_vpn,
                                                  tor_over_vpn, anti_ddos)
        pinged_servers_list = ping_servers(better_servers_list, pings)
        chosen_servers = choose_best_servers(pinged_servers_list)

        for tries in range(5):  # keep trying to connect
            # connect to chosen_servers, if one fails go to next
            for aserver in chosen_servers:
                # if "-f" used appy Firewall rules
                if force_fw_rules:
                    network_interfaces = get_network_interfaces()
                    vpn_server_ip = get_vpn_server_ip(aserver, port)
                    firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                            skip_dns_patch)
                    if internally_allowed:
                        firewall.internally_allow_ports(
                            network_interfaces, internally_allowed)
                print(Fore.BLUE + "Out of the Best Available Servers, Chose",
                      (Fore.GREEN + aserver + Fore.BLUE))
                connection = connect(aserver, port, silent, test,
                                     skip_dns_patch)
    elif server:
        # ask for and store credentials if not present, skip if "--test"
        if not test:
            if credentials.check_credentials() is False:
                credentials.save_credentials()

        server = server.lower()
        # if "-f" used appy Firewall rules
        if force_fw_rules:
            network_interfaces = get_network_interfaces()
            vpn_server_ip = get_vpn_server_ip(server, port)
            firewall.apply_fw_rules(network_interfaces, vpn_server_ip,
                                    skip_dns_patch)
            if internally_allowed:
                firewall.internally_allow_ports(network_interfaces,
                                                internally_allowed)
        for i in range(5):
            connection = connect(server, port, silent, test, skip_dns_patch)
    else:
        print('To see usage options type: "openpyn -h" or "openpyn --help"')
    sys.exit()