Esempio n. 1
0
def save_credentials():
    root.obtain_root_access()

    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.run("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 as 'sudo openpyn' to store credentials")
        subprocess.run("sudo rm /usr/share/openpyn/credentials".split())
        sys.exit()
    return
Esempio n. 2
0
def connect(server: str, port: str, silent: bool, test: bool, skip_dns_patch: bool,
            openvpn_options: str, server_provider="nordvpn") -> bool:
    detected_os = sys.platform
    if server_provider == "nordvpn":
        if port == "tcp":
            folder = "ovpn_tcp/"
        else:
            folder = "ovpn_udp/"

        vpn_config_file = __basefilepath__ + "files/" + folder + server +\
            ".nordvpn.com." + port + ".ovpn"
        # logger.debug("CONFIG FILE %s", vpn_config_file)
        if os.path.isfile(vpn_config_file) is False:
            logger.notice("VPN configuration file %s doesn't exist, \
don't worry running 'openpyn --update' for you :)", vpn_config_file)
            time.sleep(6)
            update_config_files()
    elif server_provider == "ipvanish":
        vpn_config_file = __basefilepath__ + "files/" + "ipvanish/" + server
        # logger.debug("ipvanish")

    if test:
        logger.success("Simulation end reached, \
openpyn would have connected to server: " + server + " on port: " + port + " with 'silent' mode: " + str(silent).lower())
        return 0

    kill_vpn_processes()   # kill existing OpenVPN processes
    kill_management_client()
    logger.success("CONNECTING TO SERVER " + server + " ON PORT " + port)

    root_access = root.verify_root_access("Sudo credentials required to run 'openvpn'")
    if root_access is False:
        root.obtain_root_access()

    if not silent:
        # notifications Don't work with 'sudo'
        if detected_os == "linux" and root.running_with_sudo():
            logger.warning("Desktop notifications don't work when using 'sudo', run without it, \
when asked, provide the sudo credentials")
            subprocess.Popen("openpyn-management".split())
        else:
            subprocess.Popen("openpyn-management --do-notify".split())
    use_systemd_resolved = False
    use_resolvconf = False
    if detected_os == "linux":
        if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
            skip_dns_patch = True
        elif os.path.exists("/etc/openwrt_release"):
            skip_dns_patch = True
        else:
            use_systemd_resolved = uses_systemd_resolved()
            use_resolvconf = os.path.isfile("/sbin/resolvconf")
    else:
        use_systemd_resolved = False
        use_resolvconf = False
        skip_dns_patch = True
    if not openvpn_options:
        openvpn_options = ""
    if (use_systemd_resolved or use_resolvconf) and skip_dns_patch is False:  # Debian Based OS + do DNS patching
        try:
            route_up_script = __basefilepath__ + "scripts/docker-shim.sh"
            if use_systemd_resolved:
                openvpn_options += " " + "--dhcp-option DOMAIN-ROUTE ."
                up_down_script = __basefilepath__ + "scripts/update-systemd-resolved.sh"
                logger.success("Your OS '%s' has systemd-resolve running, \
using it to update DNS Resolver Entries", detected_os)
            elif use_resolvconf:
                # tunnel DNS through VPN by changing /etc/resolv.conf using
                # "update-resolv-conf.sh" to change the DNS servers to NordVPN's.

                up_down_script = __basefilepath__ + "scripts/update-resolv-conf.sh"
                logger.success("Your OS '%s' Does have '/sbin/resolvconf', \
using it to update DNS Resolver Entries", detected_os)
            else:
                raise RuntimeError("Should not happen")

            def run_openvpn(*args):
                cmdline = [
                    "sudo", "openvpn",
                    "--redirect-gateway",
                    "--auth-retry", "nointeract",
                    "--config", vpn_config_file,
                    "--auth-user-pass", __basefilepath__ + "credentials",
                    "--script-security", "2",
                    "--route-up", route_up_script,
                    "--up", up_down_script,
                    "--down", up_down_script,
                    "--down-pre",
                    *args,
                ] + openvpn_options.split()
                subprocess.run(cmdline, check=True)

            if silent:
                run_openvpn()
            else:
                run_openvpn(
                    "--management", "127.0.0.1", "7015",
                    "--management-up-down",
                )
        except subprocess.CalledProcessError as openvpn_err:
            # logger.debug(openvpn_err.output)
            if "Error opening configuration file" in str(openvpn_err.output):
                logger.error(
                    "Error opening config file %s, make sure it exists, run 'openpyn --update'", vpn_config_file)
                return 1
        except KeyboardInterrupt:
            logger.info("Shutting down safely, please wait until process exits")
            return 0
        except PermissionError:     # needed cause complains when killing sudo process
            return 0

    else:       # If not Debian Based or skip_dns_patch
        # if skip_dns_patch, do not touch etc/resolv.conf
        if skip_dns_patch is False:
            logger.warning("Your OS '%s' Does not have '/sbin/resolvconf'", detected_os)
            logger.notice(
                "Manually applying patch to tunnel DNS through the VPN tunnel by modifying '/etc/resolv.conf'")
            subprocess.call(["sudo", __basefilepath__ + "scripts/manual-dns-patch.sh"])
        else:
            logger.warning(
                "Not modifying '/etc/resolv.conf', DNS traffic likely won't go through the encrypted tunnel")
        try:   # pylint: disable=R1702
            if silent:
                if detected_os == "linux":
                    if subprocess.check_output(["/bin/uname", "-o"]).decode(sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
                        # make sure module is loaded
                        if os.popen("test ! -c /dev/net/tun && echo 0 || echo 1").read()[0:-1] == '0':
                            subprocess.call("modprobe tun", shell=True)
                            if os.popen("test ! -c /dev/net/tun && echo 0 || echo 1").read()[0:-1] == '0':
                                logger.error(
                                    "Cannot open TUN/TAP dev /dev/net/tun: No such file or directory")
                                return 1
                subprocess.run(
                    ["sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                     "nointeract", "--config", vpn_config_file, "--auth-user-pass",
                     __basefilepath__ + "credentials"]
                    + openvpn_options.split(), check=True)
            else:
                subprocess.run(
                    ["sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                     "nointeract", "--config", vpn_config_file, "--auth-user-pass",
                     __basefilepath__ + "credentials",
                     "--management", "127.0.0.1", "7015", "--management-up-down"]
                    + openvpn_options.split(), check=True)
        except subprocess.CalledProcessError as openvpn_err:
            # logger.debug(openvpn_err.output)
            if 'Error opening configuration file' in str(openvpn_err.output):
                logger.error(
                    "Error opening config file %s, make sure it exists, run 'openpyn --update'", vpn_config_file)
                return 1
        except KeyboardInterrupt:
            logger.info('Shutting down safely, please wait until process exits')
            return 0
        except PermissionError:     # needed cause complains when killing sudo process
            return 0
Esempio n. 3
0
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
Esempio n. 4
0
def connect(server,
            port,
            silent,
            test,
            skip_dns_patch,
            openvpn_options,
            server_provider="nordvpn"):
    detected_os = sys.platform
    if server_provider == "nordvpn":
        if port == "tcp":
            folder = "ovpn_tcp/"
        else:
            folder = "ovpn_udp/"

        vpn_config_file = __basefilepath__ + "files/" + folder + server +\
            ".nordvpn.com." + port + ".ovpn"
        # print("CONFIG FILE", vpn_config_file)
        if os.path.isfile(vpn_config_file) is False:
            print(
                Fore.RED + "VPN configuration file", vpn_config_file,
                "doesn't exist, don't worry running 'openpyn --update' for you :)"
                + Fore.BLUE)
            time.sleep(6)
            update_config_files()
    elif server_provider == "ipvanish":
        vpn_config_file = __basefilepath__ + "files/" + "ipvanish/" + server
        # print("ipvanish")

    if test:
        print(
            "Simulation end reached, openpyn would have connected to Server:" +
            Fore.GREEN, server, Fore.BLUE + "on port:" + Fore.GREEN, port,
            Fore.BLUE + "with 'silent' mode:" + Fore.GREEN, silent)
        print(Style.RESET_ALL)
        sys.exit(1)

    kill_vpn_processes()  # kill existing openvpn processes
    # kill_management_client()
    print(Fore.BLUE + "CONNECTING TO SERVER" + Fore.GREEN, server,
          Fore.BLUE + "ON PORT", Fore.GREEN + port + Fore.BLUE)

    root_access = root.verify_root_access(
        Fore.GREEN + "Sudo credentials required to run 'openvpn'" + Fore.BLUE)
    if root_access is False:
        root.obtain_root_access()

    if not silent:
        # notifications Don't work with 'sudo'
        if detected_os == "linux" and root.running_with_sudo():
            print(
                Fore.RED +
                "Desktop notifications don't work when using 'sudo', run without it, "
                + "when asked, provide the sudo credentials" + Fore.BLUE)
        else:
            subprocess.Popen("openpyn-management".split())

    if detected_os == "linux":
        resolvconf_exists = os.path.isfile("/sbin/resolvconf")
        # resolvconf_exists = False
    else:
        resolvconf_exists = False
        skip_dns_patch = True
    if not openvpn_options:
        openvpn_options = ""
    if resolvconf_exists is True and skip_dns_patch is False:  # Debian Based OS + do DNS patching
        # tunnel dns throught vpn by changing /etc/resolv.conf using
        # "update-resolv-conf.sh" to change the dns servers to NordVPN's.
        try:
            print(
                "Your OS'" + Fore.GREEN + detected_os + Fore.BLUE +
                "' Does have '/sbin/resolvconf'",
                "using it to update DNS Resolver Entries")
            print(Style.RESET_ALL)
            if silent:
                subprocess.run([
                    "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                    "nointeract", "--config", vpn_config_file,
                    "--auth-user-pass", __basefilepath__ + "credentials",
                    "--script-security", "2", "--up", __basefilepath__ +
                    "scripts/update-resolv-conf.sh", "--down",
                    __basefilepath__ + "scripts/update-resolv-conf.sh"
                ] + openvpn_options.split(),
                               check=True)
            else:
                # print(openvpn_options)
                subprocess.run([
                    "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                    "nointeract", "--config", vpn_config_file,
                    "--auth-user-pass", __basefilepath__ + "credentials",
                    "--script-security", "2", "--up", __basefilepath__ +
                    "scripts/update-resolv-conf.sh", "--down",
                    __basefilepath__ + "scripts/update-resolv-conf.sh",
                    "--management", "127.0.0.1", "7015", "--management-up-down"
                ] + openvpn_options.split(),
                               check=True)
        except subprocess.CalledProcessError as openvpn_err:
            # print(openvpn_err.output)
            if 'Error opening configuration file' in str(openvpn_err.output):
                print("Error opening configuration file", vpn_config_file,
                      "Make Sure it exists, run 'openpyn --update'")
                sys.exit()
        except KeyboardInterrupt:
            print('\nShutting down safely, please wait until process exits\n')
            sys.exit()
        except PermissionError:  # needed cause complains when killing sudo process
            sys.exit()

    else:  # If not Debian Based or skip_dns_patch
        # if skip_dns_patch, do not touch etc/resolv.conf
        if skip_dns_patch is False:
            print(
                "Your OS", Fore.GREEN + detected_os + Fore.BLUE,
                "Does not have" + Fore.GREEN + " '/sbin/resolvconf':\n" +
                Fore.BLUE + "Manually Applying Patch to Tunnel DNS Through" +
                "The VPN Tunnel By Modifying" + Fore.GREEN +
                "' /etc/resolv.conf'")
            print(Style.RESET_ALL)
            subprocess.call(
                ["sudo", __basefilepath__ + "scripts/manual-dns-patch.sh"])
        else:
            print(Fore.RED + "Not Modifying /etc/resolv.conf, DNS traffic",
                  "likely won't go through the encrypted tunnel")
            print(Style.RESET_ALL)
        try:  # pylint: disable=R1702
            if silent:
                if detected_os == "linux":
                    if subprocess.check_output(["/bin/uname", "-o"]).decode(
                            sys.stdout.encoding).strip() == "ASUSWRT-Merlin":
                        # make sure module is loaded
                        if os.popen(
                                "test ! -c /dev/net/tun && echo 0 || echo 1"
                        ).read()[0:-1] == '0':
                            subprocess.call("modprobe tun", shell=True)
                            if os.popen(
                                    "test ! -c /dev/net/tun && echo 0 || echo 1"
                            ).read()[0:-1] == '0':
                                print(
                                    Style.BRIGHT + Fore.RED +
                                    "Cannot open TUN/TAP dev /dev/net/tun: No such file or directory"
                                )
                                print(Style.RESET_ALL)
                                sys.exit(0)
                subprocess.run([
                    "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                    "nointeract", "--config", vpn_config_file,
                    "--auth-user-pass", __basefilepath__ + "credentials"
                ] + openvpn_options.split(),
                               check=True)
            else:
                subprocess.run([
                    "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                    "nointeract", "--config", vpn_config_file,
                    "--auth-user-pass", __basefilepath__ + "credentials",
                    "--management", "127.0.0.1", "7015", "--management-up-down"
                ] + openvpn_options.split(),
                               check=True)
        except subprocess.CalledProcessError as openvpn_err:
            # print(openvpn_err.output)
            if 'Error opening configuration file' in str(openvpn_err.output):
                print("Error opening configuration file", vpn_config_file,
                      "Make Sure it exists, run 'openpyn --update'")
                sys.exit()
        except KeyboardInterrupt:
            print('\nShutting down safely, please wait until process exits\n')
            sys.exit()
        except PermissionError:  # needed cause complains when killing sudo process
            sys.exit()
Esempio n. 5
0
def connect(server,
            port,
            daemon,
            test,
            skip_dns_patch,
            server_provider="nordvpn"):
    if server_provider == "nordvpn":
        vpn_config_file = "/usr/share/openpyn/files/" + server + ".nordvpn.com."\
                + port + ".ovpn"
        # print("CONFIG FILE", vpn_config_file)

    elif server_provider == "ipvanish":
        vpn_config_file = "/usr/share/openpyn/files/ipvanish/" + server
        # print("ipvanish")

    if test:
        print(
            "Simulation end reached, openpyn would have connected to Server:" +
            Fore.GREEN, server, Fore.BLUE + " on port:" + Fore.GREEN, port,
            Fore.BLUE + " with 'daemon' mode:" + Fore.GREEN, daemon)
        sys.exit(1)

    kill_vpn_processes()  # kill existing openvpn processes
    # kill_management_client()
    print(Fore.BLUE + "CONNECTING TO SERVER" + Fore.GREEN, server,
          Fore.BLUE + "ON PORT", Fore.GREEN + port + Fore.BLUE)

    root_access = root.verify_root_access(
        Fore.GREEN + "Sudo credentials required to run 'openvpn'" + Fore.BLUE)
    if root_access is False:
        root.obtain_root_access()

    # notifications Don't work with 'sudo'
    if root.running_with_sudo():
        print(
            Fore.RED +
            "Desktop notifications don't work when using 'sudo', run without it, "
            + "when asked, provide the sudo credentials" + Fore.BLUE)
    else:
        subprocess.Popen("openpyn-management".split())

    resolvconf_exists = os.path.isfile("/sbin/resolvconf")
    # resolvconf_exists = False
    detected_os = platform.linux_distribution()[0]

    if resolvconf_exists is True and skip_dns_patch is False:  # Debian Based OS + do DNS patching
        # tunnel dns throught vpn by changing /etc/resolv.conf using
        # "update-resolv-conf.sh" to change the dns servers to NordVPN's.
        if daemon:
            subprocess.Popen([
                "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                "nointeract", "--config", vpn_config_file, "--auth-user-pass",
                "/usr/share/openpyn/credentials", "--script-security", "2",
                "--up", "/usr/share/openpyn/update-resolv-conf.sh", "--down",
                "/usr/share/openpyn/update-resolv-conf.sh", "--daemon",
                "--management", "127.0.0.1", "7015", "--management-up-down"
            ])
            print("Started 'openvpn' in" + Fore.GREEN + "--daemon" +
                  Fore.BLUE + "mode")
        else:
            try:
                print(
                    "Your OS'" + Fore.GREEN + detected_os + Fore.BLUE +
                    "' Does have '/sbin/resolvconf'",
                    "using it to update DNS Resolver Entries")
                print(Style.RESET_ALL)
                subprocess.call(
                    "sudo openvpn --redirect-gateway --auth-retry nointeract" +
                    " --config " + vpn_config_file + " --auth-user-pass \
                    /usr/share/openpyn/credentials --script-security 2 --up \
                    /usr/share/openpyn/update-resolv-conf.sh --down \
                    /usr/share/openpyn/update-resolv-conf.sh \
                    --management 127.0.0.1 7015 --management-up-down",
                    shell=True)
            except (KeyboardInterrupt) as err:
                print(
                    '\nShutting down safely, please wait until process exits\n'
                )
                sys.exit()
            except PermissionError:  # needed cause complains when killing sudo process
                sys.exit()

    else:  # If not Debian Based or skip_dns_patch
        # if skip_dns_patch, do not touch etc/resolv.conf
        if skip_dns_patch is False:
            print(
                "Your OS", Fore.GREEN + detected_os + Fore.BLUE,
                "Does not have" + Fore.GREEN + " '/sbin/resolvconf':\n" +
                Fore.BLUE + "Manually Applying Patch to Tunnel DNS Through" +
                "The VPN Tunnel By Modifying" + Fore.GREEN +
                "' /etc/resolv.conf'")
            apply_dns_patch = subprocess.call(
                ["sudo", "/usr/share/openpyn/manual-dns-patch.sh"])
        else:
            print(Fore.RED + "Not Modifying /etc/resolv.conf, DNS traffic",
                  "likely won't go through the encrypted tunnel")
        print(Style.RESET_ALL)

        if daemon:
            subprocess.Popen([
                "sudo", "openvpn", "--redirect-gateway", "--auth-retry",
                "nointeract", "--config", vpn_config_file, "--auth-user-pass",
                "/usr/share/openpyn/credentials", "--daemon", "--management",
                "127.0.0.1", "7015", "--management-up-down"
            ])
            print("Started 'openvpn' in --daemon mode")
        else:
            try:
                subprocess.call((
                    "sudo openvpn --redirect-gateway --auth-retry nointeract "
                    + "--config " + vpn_config_file + " --auth-user-pass " +
                    "/usr/share/openpyn/credentials --management 127.0.0.1 7015 "
                    + "--management-up-down").split())
            except (KeyboardInterrupt) as err:
                print(
                    '\nShutting down safely, please wait until process exits\n'
                )
                sys.exit()
            except PermissionError:  # needed cause complains when killing sudo process
                sys.exit()
Esempio n. 6
0
def connect(server, port, daemon, test):
    if test:
        print(
            "Simulation end reached, openpyn would have connected to Server:",
            server, "on port:", port, " with 'daemon' mode:", daemon)
        sys.exit(1)

    kill_vpn_processes()  # kill existing openvpn processes
    print("CONNECTING TO SERVER", server, " ON PORT", port)

    is_root = root.verify_root_access("Root access required to run 'openvpn'")
    if daemon is True and is_root is False:
        root.obtain_root_access()

    resolvconf_exists = os.path.isfile("/sbin/resolvconf")
    # resolvconf_exists = False
    detected_os = platform.linux_distribution()[0]

    if resolvconf_exists:  # Debian Based OS
        # tunnel dns throught vpn by changing /etc/resolv.conf using
        # "update-resolv-conf.sh" to change the dns servers to NordVPN's.
        if daemon:
            subprocess.Popen([
                "sudo", "openvpn", "--redirect-gateway", "--config",
                "/usr/share/openpyn/files/" + server + ".nordvpn.com." + port +
                ".ovpn", "--auth-user-pass", "/usr/share/openpyn/credentials",
                "--script-security", "2", "--up",
                "/usr/share/openpyn/update-resolv-conf.sh", "--down",
                "/usr/share/openpyn/update-resolv-conf.sh", "--daemon"
            ])
            print("Started 'openvpn' in --daemon mode")
        else:
            try:
                print(
                    "Your OS '" + detected_os +
                    "' Does have '/sbin/resolvconf'",
                    "using it to update DNS Resolver Entries")
                subprocess.run("sudo openvpn --redirect-gateway --config" +
                               " /usr/share/openpyn/files/" + server +
                               ".nordvpn.com." + port +
                               ".ovpn --auth-user-pass \
                    /usr/share/openpyn/credentials --script-security 2 --up \
                    /usr/share/openpyn/update-resolv-conf.sh --down \
                    /usr/share/openpyn/update-resolv-conf.sh",
                               shell=True)
            except (KeyboardInterrupt) as err:
                print(
                    '\nShutting down safely, please wait until process exits\n'
                )

    else:  # If not Debian Based
        print(
            "Your OS ", detected_os,
            "Does not have '/sbin/resolvconf': Manually Applying Patch" +
            " to Tunnel DNS Through The VPN Tunnel By Modifying '/etc/resolv.conf'"
        )
        apply_dns_patch = subprocess.run(
            ["sudo", "/usr/share/openpyn/manual-dns-patch.sh"])

        if daemon:
            subprocess.Popen([
                "sudo", "openvpn", "--redirect-gateway", "--config",
                "/usr/share/openpyn/files/" + server + ".nordvpn.com." + port +
                ".ovpn", "--auth-user-pass", "/usr/share/openpyn/credentials",
                "--daemon"
            ])
            print("Started 'openvpn' in --daemon mode")
        else:
            try:
                subprocess.run("sudo openvpn --redirect-gateway --config" +
                               " /usr/share/openpyn/files/" + server +
                               ".nordvpn.com." + port +
                               ".ovpn --auth-user-pass \
                    /usr/share/openpyn/credentials",
                               shell=True)
            except (KeyboardInterrupt) as err:
                print(
                    '\nShutting down safely, please wait until process exits\n'
                )