- Configure a VPN
- Configuring an OpenVPN connection
- Configuring a WireGuard connection
- Configuring a VPN programmatically
- Управление VPN подключениями из консоли Linux
- Как создать L2TP VPN подключение в Linux?
- Создаем PPTP VPN подключение в Linux
- Настройка SSTP VPN подключения в командной строке Linux
- Подключение к OpenVPN серверу из консоли Linux
- Connect to a VPN
- More Information
Configure a VPN
VPN support requires both the use of core22 and network-manager from a 22/* channel. Currently, two types of VPN are supported:
Configuring an OpenVPN connection
Network Manager supports two methods to create an OpenVPN connection:
- import an OpenVPN credentials file
- set required parameters manually with nmcli invocations
In both cases, files used in the definition must be copied to folders where the network-manager snap has access, which is usually in SNAP_DATA or SNAP_COMMON folders.
The first method requires only that the OpenVPN configuration file is copied to one of these locations:
sudo nmcli c import type openvpn file /var/snap/network-manager/common/myopenvp.ovpn
This command needs to be run as root because it creates certificate and key files with data extracted from the configuration file. These need to be accessible by the network-manager snap, which itself runs with root id.
Using the second method requires copying around certificates and keys and creating/modifying the connection as required. For instance:
nmcli c add connection.id vpntest connection.type vpn \ vpn.service-type org.freedesktop.NetworkManager.openvpn \ ipv4.never-default true \ ipv6.never-default true \ +vpn.data ca=/var/snap/network-manager/common/creds/server_ca.crt \ +vpn.data cert=/var/snap/network-manager/common/creds/user.crt \ +vpn.data cert-pass-flags=0 \ +vpn.data cipher=AES-128-CBC \ +vpn.data comp-lzo=adaptive \ +vpn.data connection-type=tls \ +vpn.data dev=tun \ +vpn.data key=/var/snap/network-manager/common/creds/user.key \ +vpn.data ping=10 \ +vpn.data ping-restart=60 \ +vpn.data remote=: \ +vpn.data remote-cert-tls=server \ +vpn.data ta=/var/snap/network-manager/common/creds/tls_auth.key \ +vpn.data ta-dir=1 \ +vpn.data verify-x509-name=name:access.is
Configuring a WireGuard connection
The recommended way to configure a WireGuard connection is to place a configuration file in a folder readable by the network-manager snap, such as SNAP_DATA or SNAP_COMMON folders, and to import the configuration with a command similar to the following:
nmcli c import type WireGuard file /var/snap/nm-vpn-client/common/wg.conf
As with an OpenVPN connection, it is also possible to create a WireGuard connection using only nmcli with multiple parameters. Unfortunately, configuring peers in this way is not currently possible (see WireGuard in NetworkManager).
Configuring a VPN programmatically
To create a VPN connection programmatically, that is, from another snap, the user snap must define a content interface. The connection must have a slot that connects to the vpn-creds plug defined in the network-manager snap.
Once connected, any files necessary for the connection can be placed into the directory shared by the content interface. This folder is seen by the Network Manager snap /var/snap/network-manager/common/creds , which means that file path configuration also needs also use this prefix. After that, a connection can be created using Network Manager’s dbus interface where a connected network-manager plug is required.
Управление VPN подключениями из консоли Linux
В этой статье мы рассмотрим, как создать VPN подключение из консоли Linux и подключиться к удаленному VPN серверу из CLI. Отдельно рассмотрим, как создать L2TP и PPTP VPN подключения.
Как создать L2TP VPN подключение в Linux?
Вы можете использовать NetworkManager для создания VPN подключений L2TP из консоли Linux.
Для установки NetworkManager с поддержкой L2TP выполните команду:
- В CentOS/RHEL/Fedora: # yum -y install NetworkManager-l2tp
- Для установки в Ubuntu/Debian, нужно сначала добавить репозиторий:
$ sudo add-apt-repository ppa:nm-l2tp/network-manager-l2tp
$ sudo apt-get install network-manager-l2tp
Для создания нового VPN подключения L2TP используется команда:
$ nmcli connection add connection.id [VPNConnectionName] con-name [VPNConnectionName] type VPN vpn-type l2tp ifname — connection.autoconnect no ipv4.method auto vpn.data «gateway = [ipv4], ipsec-enabled = yes, ipsec-psk = 0s»$(base64
- [VPNConnectionName] — имя VPN соединения
- [ipv4] — ip адрес VPN сервера L2TP/IPSEC
- [PSK] — ключ PSK (Pre Shared Key)
- [user] — имя пользователя VPN
- [user-password] — пароль
Настройки нового VPN подключения сохраняются в файл /etc/NetworkManager/system-connections/.
Вывести все подключения в NetworkManager:
Показать информацию о созданном VPN подключении:
$ nmcli c show id [VPNConnectionName]
Для Для подключения к VPN серверу из командной строки:к VPN серверу их командной строки:
$ nmcli c up [VPNConnectionName]
При подключении к удаленному VPN серверу может появится ошибка:
Error: Connection activation failed: Could not find source connection.
- Проверьте логи journactl
- Для физического интерфейса (например, ens33 ) задан шлюз по-умолчанию
- Возможно на сервере используется интерфейс br0 , который не используется. Попробуйте удалить его
Чтобы завершить сессию VPN, выполните:
nmcli c down [VPNConnectionName]
Создаем PPTP VPN подключение в Linux
Для установки PPTP клиента VPN в Ubuntu/Debian, установите утилиту:
$ sudo apt-get install pptp-linux network-manager-pptp
Добавьте следующее содержимое:
pty "pptp YOUR_VPN_SERVER --nolaunchpppd --debug" name VPNUsername password VPNPassword remotename PPTP require-mppe-128 require-mschap-v2 refuse-eap refuse-pap refuse-chap refuse-mschap noauth debug persist maxfail 0 defaultroute replacedefaultroute usepeerdns
Сохраните файл, нажав CTLR+X, Y -> Enter.
$ chmod 600 /etc/ppp/peers/PPTP
Чтобы подключится к PPTP VPN серверу, выполните:
Настройка SSTP VPN подключения в командной строке Linux
Вы можете настроить SSTP подключение к VPN серверу в Linux. В Ubuntu можно использовать пакет sstp для nmcli.
$ sudo add-apt-repository ppa:eivnaes/network-manager-sstp
$ sudo apt update
$ sudo apt install network-manager-sstp sstp-client
Для подключения к SSTP серверу используется команда:
$ sudo sstpc —cert-warn —save-server-route —user —password usepeerdns require-mschap-v2 noauth noipdefault nobsdcomp nodeflate
Можно сохранить настройки подключения к VPN серверу в текстовый файл:
remotename sstptest linkname sstptest ipparam sstptest pty "sstpc --ipparam sstptest --nolaunchpppd sstpvpn.vmblog.ru" name user1 plugin sstp-pppd-plugin.so sstp-sock /var/run/sstpc/sstpc-sstp-test usepeerdns require-mppe require-mschap-v2 refuse-eap refuse-pap refuse-chap refuse-mschap nobsdcomp nodeflate
Имя пользователя и пароль для аутентификации на VPN сервере нужно задать в файле /etc/ppp/chap-secrets
# Secrets for authentication using CHAP # client server secret IP addresses user1 * xxxxxx *
Теперь для подключения к SSTP серверу с помощью настроенного подключения, выполните:
Чтобы отправить весь трафик через VPN подключение, нужно добавить маршрут:
$ sudo route add default (обычно это устройствл ppp0 )
Или только трафик к определенным подсетям/хостам:
$ sudo route add -net 192.168.2.0/24 dev ppp0
Подключение к OpenVPN серверу из консоли Linux
Для установки пакета OpenVPN в Linux:
- Debian, Ubuntu, Linux Mint, Kali Linux:
$ sudo apt-get update && apt-get upgrade
$ sudo apt-get install openvpn - RedHat, Fedora, CentOS, Oracle, Rocky Linux:
# yum install epel-release –y
# yum install openvpn –y
Для подключения к OpenVPN серверу вам понадобится файл конфигурации ovpn. Чтобы подключиться к VPN с помощью ovpn файла:
$ sudo openvpn —config /etc/openvpn/client.ovpn —daemon
Введите имя пользователя и пароль (если настроена AD аутентификация для OpenVPN).
Проверьте что VPN подключение установлено:
Чтобы завершить OpenVPN подключение, нажмите CTRL+C (если клиент запущен без параметра –daemon) или выполните команду:
Чтобы OpenVPN подключение автоматически устанавливалось при старте Linux, нужно создать отдельный юнит systemd:
$ sudo vi /lib/systemd/system/OpenVPNClientCorp.service
[Unit] Description=Hide.me OpenVPN Client Corp After=multi-user.target [Service] Type=idle ExecStart=/usr/sbin/openvpn --config /etc/openvpn/client.ovpn [Install] WantedBy=multi-user.target
Измените разрешения на файл:
$ sudo chmod 644 /lib/systemd/system/OpenVPNClientCorp.service
Добавьте юнит через systemctl
$ sudo systemctl daemon-reload
$ sudo systemctl enable OpenVPNClientCorp.service
Connect to a VPN
A VPN (or Virtual Private Network ) is a way of connecting to a local network over the internet. For example, say you want to connect to the local network at your workplace while you’re on a business trip. You would find an internet connection somewhere (like at a hotel) and then connect to your workplace’s VPN. It would be as if you were directly connected to the network at work, but the actual network connection would be through the hotel’s internet connection. VPN connections are usually encrypted to prevent people from accessing the local network you’re connecting to without logging in.
There are a number of different types of VPN. You may have to install some extra software depending on what type of VPN you’re connecting to. Find out the connection details from whoever is in charge of the VPN and see which VPN client you need to use. Then, go to the software installer application and search for the NetworkManager package which works with your VPN (if there is one) and install it.
If there isn’t a NetworkManager package for your type of VPN, you will probably have to download and install some client software from the company that provides the VPN software. You’ll probably have to follow some different instructions to get that working.
To set up the VPN connection:
- Open the Activities overview and start typing Network .
- Click on Network to open the panel.
- At the bottom of the list on the left, click the + button to add a new connection.
- Choose VPN in the interface list.
- Choose which kind of VPN connection you have.
- Fill in the VPN connection details, then press Add once you are finished.
- When you have finished setting up the VPN, open the system menu from the right side of the top bar, click VPN off and select Connect . You may need to enter a password for the connection before it is established. Once the connection is made, you will see a lock shaped icon in the top bar.
- Hopefully you will successfully connect to the VPN. If not, you may need to double-check the VPN settings you entered. You can do this from the Network panel that you used to create the connection. Select the VPN connection from the list, then press the button to review the settings.
- To disconnect from the VPN, click the system menu on the top bar and click Turn Off under the name of your VPN connection.
More Information
- Wired networking — Use a wired internet connection and set a static IP address.
- Wireless networking — Connect to wireless networks, including hidden networks and networks created from phone tethering.
You can choose the displayed language by adding a language suffix to the web address so it ends with e.g. .html.en or .html.de.
If the web address has no language suffix, the preferred language specified in your web browser’s settings is used. For your convenience:
[ Change to English Language | Change to Browser’s Preferred Language ]
The material in this document is available under a free license, see Legal for details.
For information on contributing see the Ubuntu Documentation Team wiki page. To report errors in this documentation, file a bug.