コード例 #1
0
    def enable_auto_connect(self, country_code: str, category: str = 'normal', protocol: str = 'tcp'):
        enabled = False
        selected_parameters = (country_code.lower(), category.lower(), protocol.lower())

        if selected_parameters in self.active_servers:
            connection_name = self.active_servers[selected_parameters]['name']
            connection_load = self.active_servers[selected_parameters]['load']
            connection_latency = self.active_servers[selected_parameters]['latency']

            if networkmanager.set_auto_connect(connection_name):
                self.logger.info("Auto-connect enabled for '%s' (Load: %i%%, Latency: %0.2fs).", connection_name, connection_load, connection_latency)

                # Temporarily remove the kill-switch if there was one
                kill_switch = networkmanager.remove_killswitch(log=False)

                networkmanager.disconnect_active_vpn(self.active_servers)

                if kill_switch:
                    networkmanager.set_killswitch(log=False)

                if networkmanager.enable_connection(connection_name):
                    enabled = True
        else:
            self.logger.error("Auto-connect not activated: No active server found matching [%s, %s, %s].", country_code, category, protocol)

        return enabled
コード例 #2
0
    def enable_auto_connect(self,
                            country_code: str,
                            category: str = 'normal',
                            protocol: str = 'tcp'):
        enabled = False
        selected_parameters = (country_code.upper(), category, protocol)

        if selected_parameters in self.active_servers:
            connection_name = self.active_servers[selected_parameters]['name']
            connection_load = self.active_servers[selected_parameters]['load']
            connection_latency = self.active_servers[selected_parameters][
                'latency']

            if networkmanager.set_auto_connect(connection_name):
                log.info(
                    f"Auto-connect enabled for '{connection_name}' "
                    f"(Load: {connection_load}%, Latency: {connection_latency:.2f})."
                )
                networkmanager.disconnect_active_vpn(self.active_servers)
                if networkmanager.enable_connection(connection_name):
                    enabled = True
        else:
            log.error(f"Auto-connect not activated: No active server found "
                      f"matching [{country_code}, {category}, {protocol}].")

        return enabled
コード例 #3
0
    def enable_auto_connect(self,
                            country_code,
                            category='normal',
                            protocol='tcp'):
        enabled = False
        selected_parameters = (country_code.upper(), category, protocol)

        if selected_parameters in self.active_servers:
            connection_name = self.active_servers[selected_parameters]['name']

            if networkmanager.set_auto_connect(connection_name):
                networkmanager.disconnect_active_vpn(self.active_servers)
                if networkmanager.enable_connection(connection_name):
                    enabled = True
        else:
            self.logger.error(
                "Auto-connect not activated: No active server found matching [%s, %s, %s].",
                country_code, category, protocol)

        return enabled
コード例 #4
0
    def sync_servers(self, preserve_vpn, slow_mode):
        updated = False

        username = self.credentials.get_username()
        password = self.credentials.get_password()

        # Check if there are custom DNS servers specified in the settings before loading the defaults
        dns_list = self.settings.get_custom_dns_servers()

        if not self.configs_exist():
            self.logger.warning("No OpenVPN configuration files found.")
            if not self.get_configs():
                sys.exit(1)

        self.logger.info("Checking for new connections to import...")

        server_list = nordapi.get_server_list(sort_by_load=True)
        if server_list:

            valid_server_list = self.get_valid_servers(server_list)
            if valid_server_list:

                if not preserve_vpn:
                    # If there's a kill-switch in place, we need to temporarily remove it, otherwise it will kill out network when disabling an active VPN below
                    # Disconnect active Nord VPNs, so we get a more reliable benchmark
                    show_warning = False
                    if networkmanager.remove_killswitch():
                        show_warning = True
                        warning_string = "Kill-switch"
                    if networkmanager.disconnect_active_vpn(self.active_servers):
                        if show_warning:
                            warning_string = "Active VPN(s) and " + warning_string
                        else:
                            show_warning = True
                            warning_string = "Active VPN(s)"

                    if show_warning:
                        self.logger.warning("%s disabled for accurate benchmarking. Your connection is not secure until these are re-enabled.", warning_string)
                else:
                    self.logger.warning("Active VPN preserved. This may give unreliable results!")

                if slow_mode:
                    self.logger.info("Benchmarking slow mode enabled.")

                num_servers = len(valid_server_list)
                self.logger.info("Benchmarking %i servers...", num_servers)

                start = timer()
                ping_attempts = self.settings.get_ping_attempts()  # We are going to be multiprocessing within a class instance, so this needs getting outside of the multiprocessing
                valid_protocols = self.settings.get_protocols()
                valid_categories = self.settings.get_categories()
                best_servers, num_success = benchmarking.get_best_servers(valid_server_list, ping_attempts, valid_protocols, valid_categories, slow_mode)

                end = timer()

                if num_success == 0:
                    self.logger.error("Benchmarking failed to test any servers. Your network may be blocking large-scale ICMP requests. Exiting.")
                    sys.exit(1)
                else:
                    percent_success = round(num_success / num_servers * 100, 2)
                    self.logger.info("Benchmarked %i servers successfully (%0.2f%%). Took %0.2f seconds.", num_success, percent_success, end - start)

                    if percent_success < 90.0:
                        self.logger.warning("A large quantity of tests failed. Your network may be unreliable, or blocking large-scale ICMP requests. Syncing in slow mode (-s) may fix this.")

                # remove all old connections and any auto-connect, until a better sync routine is added
                if self.remove_active_connections():
                    updated = True
                if networkmanager.remove_autoconnect():
                    updated = True

                self.logger.info("Adding new connections...")

                new_connections = 0
                for key in best_servers.keys():
                    imported = True
                    name = best_servers[key]['name']

                    if not self.connection_exists(name):
                        domain = best_servers[key]['domain']
                        protocol = key[2]

                        file_path = self.get_ovpn_path(domain, protocol)
                        if file_path:
                            if networkmanager.import_connection(file_path, name, username, password, dns_list):
                                updated = True
                                new_connections += 1
                            else:
                                imported = False
                        else:
                            self.logger.warning("Could not find a configuration file for %s. Skipping.", name)

                    # If the connection already existed, or the import was successful, add the server combination to the active servers
                    if imported:
                        self.active_servers[key] = best_servers[key]
                        self.save_active_servers(self.active_servers, paths.ACTIVE_SERVERS)

                if new_connections > 0:
                    self.logger.info("%i new connections added.", new_connections)
                else:
                    self.logger.info("No new connections added.")

                return updated
            else:
                self.logger.error("No servers found matching your settings. Review your settings and try again.")
                sys.exit(1)
        else:
            self.logger.error("Could not fetch the server list from NordVPN. Check your Internet connectivity.")
            sys.exit(1)
コード例 #5
0
    def sync_servers(self):
        updated = False

        username = self.credentials.get_username()
        password = self.credentials.get_password()
        dns_list = nordapi.get_nameservers()

        self.logger.info("Checking for new connections to import...")

        if self.configs_exist():

            server_list = nordapi.get_server_list(sort_by_load=True)
            if server_list:

                valid_server_list = self.get_valid_servers(server_list)
                if valid_server_list:

                    # If there's a kill-switch in place, we need to temporarily remove it, otherwise it will kill out network when disabling an active VPN below
                    # Disconnect active Nord VPNs, so we get a more reliable benchmark
                    show_warning = False
                    if networkmanager.remove_killswitch(paths.KILLSWITCH):
                        show_warning = True
                        warning_string = "Kill-switch"
                    if networkmanager.disconnect_active_vpn(
                            self.active_servers):
                        if show_warning:
                            warning_string = "Active VPN(s) and " + warning_string
                        else:
                            show_warning = True
                            warning_string = "Active VPN(s)"

                    if show_warning:
                        self.logger.warning(
                            "%s disabled for accurate benchmarking. Your connection is not secure until these are re-enabled.",
                            warning_string)

                    self.logger.info("Benchmarking servers...")

                    start = timer()
                    ping_attempts = self.settings.get_ping_attempts(
                    )  # We are going to be multiprocessing within a class instance, so this needs getting outside of the multiprocessing
                    valid_protocols = self.settings.get_protocols()
                    best_servers = benchmarking.get_best_servers(
                        valid_server_list, ping_attempts, valid_protocols)

                    end = timer()
                    self.logger.info(
                        "Benchmarking complete. Took %0.2f seconds.",
                        end - start)

                    # Purge all old connections and any auto-connect, until a better sync routine is added
                    if self.purge_active_connections():
                        updated = True
                    if networkmanager.remove_autoconnect():
                        updated = True

                    self.logger.info("Adding new connections...")

                    new_connections = 0
                    for key in best_servers.keys():
                        imported = True
                        name = best_servers[key]['name']

                        if not self.connection_exists(name):
                            domain = best_servers[key]['domain']
                            protocol = key[2]

                            file_path = self.get_ovpn_path(domain, protocol)
                            if file_path:
                                if networkmanager.import_connection(
                                        file_path, name, username, password,
                                        dns_list):
                                    updated = True
                                    new_connections += 1
                                else:
                                    imported = False
                            else:
                                self.logger.warning(
                                    "Could not find a configuration file for %s. Skipping.",
                                    name)

                        # If the connection already existed, or the import was successful, add the server combination to the active servers
                        if imported:
                            self.active_servers[key] = best_servers[key]
                            self.save_active_servers(self.active_servers,
                                                     paths.ACTIVE_SERVERS)

                    if new_connections > 0:
                        self.logger.info("%i new connections added.",
                                         new_connections)
                    else:
                        self.logger.info("No new connections added.")

                    return updated
                else:
                    self.logger.error(
                        "No servers found matching your settings. Review your settings and try again."
                    )
                    sys.exit(1)
            else:
                self.logger.error(
                    "Could not fetch the server list from NordVPN. Check your Internet connectivity."
                )
                sys.exit(1)
        else:
            self.logger.error(
                "Can't find any OpenVPN configuration files. Please run --update before syncing."
            )
            sys.exit(1)
コード例 #6
0
    def sync_servers(self, preserve_vpn):
        # remove legacy
        for file_path in paths.LEGACY_FILES:
            try:
                os.remove(file_path)
            except FileNotFoundError:
                pass
        log.info("Checking for new connections to import...")
        server_list = nordapi.get_server_list(sort_by_load=True)
        if not server_list:
            log.error(
                "Could not fetch the server list from NordVPN. Check your Internet connectivity."
            )
            sys.exit(1)
        server_list = [s for s in server_list if self.is_valid_server(s)]
        if not server_list:
            log.error(
                "No servers found matching your settings. Review your settings and try again."
            )
            sys.exit(1)
        if preserve_vpn:
            log.warning(
                "Active VPN preserved. This may give unreliable results!")
        else:
            # If there's a kill-switch in place, we need to temporarily remove it,
            # otherwise it will kill out network when disabling an active VPN below
            # Disconnect active Nord VPNs, so we get a more reliable benchmark
            warnings = {
                'Kill-switch':
                networkmanager.remove_killswitch(),
                'Active VPN(s)':
                networkmanager.disconnect_active_vpn(self.active_servers),
            }
            if any(warnings.values()):
                log.warning(
                    f"{', '.join(warnings.keys())} disabled for accurate benchmarking. "
                    f"Your connection is not secure until these are re-enabled."
                )

        # remove all old connections and any auto-connect, until a better sync routine is added
        self.active_servers = {}
        networkmanager.remove_autoconnect()

        log.info("Adding new connections...")
        new_servers = {}
        for key, server in self.get_best_servers(server_list).items():
            if self.connection_exists(server['name']):
                new_servers[key] = server
                continue
            file_path = self.get_ovpn_path(server['domain'], key[2])
            if not file_path:
                log.warning(
                    f"Could not find a configuration file for {server['name']}. Skipping."
                )
                continue
            networkmanager.import_connection(file_path, server['name'],
                                             self.credentials.get_username(),
                                             self.credentials.get_password(),
                                             nordapi.get_nameservers())
            new_servers[key] = server
        if len(new_servers) > 0:
            self.active_servers = {**self.active_servers, **new_servers}
            log.info(f"{len(new_servers)} new connections added.")
        else:
            log.info("No new connections added.")