def get_active_vpns(active_servers):
    active_vpns = set([])

    try:
        output = subprocess.run([
            'nmcli', '--mode', 'tabular', '--terse', '--fields',
            'TYPE,NAME,UUID', 'connection', 'show', '--active'
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()
        lines = output.stdout.decode('utf-8').split('\n')

        for line in lines:
            if line:
                elements = line.strip().split(':')

                if elements[
                        0] == "vpn":  # Only count VPNs managed by this tool.
                    for server in active_servers.values():
                        if elements[1] == server['name'] and elements[
                                2] not in active_vpns:
                            active_vpns.add(
                                elements[2])  # Add the UUID to our set

        return active_vpns

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
def get_vpn_connections():
    try:
        output = subprocess.run([
            'nmcli', '--mode', 'tabular', '--terse', '--fields', 'TYPE,NAME',
            'connection', 'show'
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()

        lines = output.stdout.decode('utf-8').split('\n')

        vpn_connections = []
        for line in lines:
            if line:
                elements = line.strip().split(':')

                if (elements[0] == 'vpn'):
                    vpn_connections.append(elements[1])

        return vpn_connections

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False
def get_interfaces(wifi=True, ethernet=True):
    try:
        output = subprocess.run([
            'nmcli', '--mode', 'tabular', '--terse', '--fields', 'TYPE,DEVICE',
            'device', 'status'
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()

        lines = output.stdout.decode('utf-8').split('\n')

        interfaces = []
        for line in lines:
            if line:
                elements = line.strip().split(':')

                if (wifi and elements[0]
                        == 'wifi') or (ethernet and elements[0] == 'ethernet'):
                    interfaces.append(elements[1])

        return interfaces

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
Exemple #4
0
def disconnect_active_vpn(active_servers):
    disconnected_vpns = set()

    try:
        output = subprocess.run([
            'nmcli', '--mode', 'tabular', '--terse', '--fields',
            'TYPE,NAME,UUID', 'connection', 'show', '--active'
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()
        lines = output.stdout.decode('utf-8').split('\n')
        for line in lines:
            if not line:
                continue
            type_, name, uuid = line.strip().split(':')
            if not type_ == 'vpn':
                continue
            for server in active_servers.values():
                if name == server['name'] and uuid not in disconnected_vpns:
                    disconnected_vpns.add(uuid)  # Add the UUID to our set
        return bool(disconnected_vpns)

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
    def nmcli_import():
        try:
            # Create a temporary config with the connection name, so we can import the config with its prettified name
            temp_path = os.path.join(os.path.dirname(file_path),
                                     connection_name + '.ovpn')
            shutil.copy(file_path, temp_path)
        except Exception as ex:
            logger.error("Failed to copy configuration file: %s" % ex)
            return False

        try:
            output = subprocess.run([
                'nmcli', 'connection', 'import', 'type', 'openvpn', 'file',
                temp_path
            ],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            os.remove(
                temp_path)  # Remove the temporary renamed config we created
            output.check_returncode()
        except subprocess.CalledProcessError:
            error = utils.format_std_string(output.stderr)
            logger.error("Could not add options to the connection: %s" % error)
        except Exception as ex:
            logger.error(ex)

        return False
Exemple #6
0
def import_connection(file_path,
                      connection_name,
                      username=None,
                      password=None,
                      dns_list=None,
                      ipv6=False):
    try:
        # Create a temporary config with the new name, for importing (and delete afterwards)
        temp_path = os.path.join(os.path.dirname(file_path),
                                 connection_name + '.ovpn')
        shutil.copy(file_path, temp_path)

        output = subprocess.run([
            'nmcli', 'connection', 'import', 'type', 'openvpn', 'file',
            temp_path
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        os.remove(temp_path)
        output.check_returncode()

        config = ConnectionConfig(connection_name)
        if config.path:  # If the config has a path, then it was loaded correctly
            if username and password:
                config.set_credentials(username, password)

            if dns_list:
                config.set_dns_nameservers(dns_list)

            if not ipv6:
                config.disable_ipv6()

            user = utils.get_current_user()
            config.set_user(user)

            config.save()
        else:
            return False

        return True

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
Exemple #7
0
def reload_connections():
    try:
        output = subprocess.run(['nmcli', 'connection', 'reload'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()
        return True

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
def restart():
    try:
        output = subprocess.run(['systemctl', 'restart', 'NetworkManager'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()

        logger.info("NetworkManager restarted successfully!")
        return True

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
def get_version():
    try:
        output = subprocess.run(['NetworkManager', '--version'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()

        version_string = re.split(",|-", output.stdout.decode())[0].strip()

        return version_string

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False
Exemple #10
0
def get_vpn_connections():
    try:
        output = subprocess.run([
            'nmcli', '--mode', 'tabular', '--terse', '--fields', 'TYPE,NAME',
            'connection', 'show'
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output.check_returncode()

        vpn_connections = []
        for line in output.stdout.decode('utf-8').split('\n'):
            if not line:
                continue
            con_type, con = line.strip().split(':', 1)
            if con_type == 'vpn':
                vpn_connections.append(con)
        return vpn_connections
    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error(error)
        return []
Exemple #11
0
    def nmcli_modify():
        try:
            for location, values in connection_options.items():
                for value in values:
                    output = subprocess.run([
                        'nmcli', 'connection', 'modify', connection_name,
                        location, value
                    ],
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE)
                    output.check_returncode()

            return True

        except subprocess.CalledProcessError:
            error = utils.format_std_string(output.stderr)
            logger.error("Could not add options to the connection: %s" % error)
            return False

        except Exception as ex:
            logger.error(ex)
            return False
def import_connection(file_path,
                      connection_name,
                      username=None,
                      password=None,
                      dns_list=None,
                      ipv6=False):
    def nmcli_import():
        try:
            # Create a temporary config with the connection name, so we can import the config with its prettified name
            temp_path = os.path.join(os.path.dirname(file_path),
                                     connection_name + '.ovpn')
            shutil.copy(file_path, temp_path)
        except Exception as ex:
            logger.error("Failed to copy configuration file: %s" % ex)
            return False

        try:
            output = subprocess.run([
                'nmcli', 'connection', 'import', 'type', 'openvpn', 'file',
                temp_path
            ],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            os.remove(
                temp_path)  # Remove the temporary renamed config we created
            output.check_returncode()
        except subprocess.CalledProcessError:
            error = utils.format_std_string(output.stderr)
            logger.error("Could not add options to the connection: %s" % error)
        except Exception as ex:
            logger.error(ex)

        return False

    if not utils.run_as_root(nmcli_import):
        return False

    # Populate all connection options into connection_options
    connection_options = {
        '+vpn.secrets': ['password='******'+vpn.data': ['username='******'password-flags=0'],
        '+connection.permissions': ['user:'******'ipv6.method'] = ['ignore']

    if dns_list:
        dns_string = ';'.join(map(str, dns_list))
        connection_options['+ipv4.dns'] = [dns_string]
        connection_options['+ipv4.ignore-auto-dns'] = ['true']

    try:
        for location, values in connection_options.items():
            for value in values:
                output = subprocess.run([
                    'nmcli', 'connection', 'modify', connection_name, location,
                    value
                ],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                output.check_returncode()

        return True

    except subprocess.CalledProcessError:
        error = utils.format_std_string(output.stderr)
        logger.error("Could not add options to the connection: %s" % error)
        return False

    except Exception as ex:
        logger.error(ex)
        return False