How to install openvpn ubuntu
How to install openvpn ubuntu
OpenVPN
Содержание
Просьба к редакторам тоже там отписываться
OpenVPN
OpenVPN — свободная реализация технологии Виртуальной Частной Сети (VPN) с открытым исходным кодом для создания зашифрованных каналов типа точка-точка или сервер-клиенты между компьютерами. Она позволяет устанавливать соединения между компьютерами, находящимися за NAT-firewall, без необходимости изменения их настроек.
Варианты применения данной статьи
Исходные данные
Локальная сеть 1
Локальная сеть 2
Настройка OpenVPN
Установка
И на сервере и на клиенте ставим один и тот же пакет.
Создание сервера
Создание ключей и сертификатов
Защита соединения в OpenVPN в данном случае строится на использовании сертификатов и ключей для сервера и для клиентов.
Переходим в созданную директорию, где и займёмся генерацией ключей и сертификатов
Редактируем файл переменных
Здесь можно заполнить например так:
копируем конфиг openssl
Очищаем от старых сертификатов и ключей папку keys и создаем серийный и индексные файлы для новых ключей
Создаем сертификат. По умолчанию поля будут заполняться данными, введенными ранее в vars, поэтому можно ничего не менять.
Создаем ключ сервера
В конце соглашаемся с запросом на подпись и добавление сертификата в базу.
Создаем ключ Диффи-Хеллмана
Cоздаем ключ для tls-аутификации
Создание файла конфигурации сервера
Создадим директорию для клиентских конфигов
Можно запускать наш сервер OpenVPN
Смотрим список интерфейсов
Если среди прочих видим
значит VPN-сервер завелся. Если нет, то смотрим лог
Настройка маршрутизации на стороне сервера
Создаем файл в каталоге ccd с тем же именем, что и ключ для клиента, т.е. /etc/openvpn/ccd/client
Включаем ipv4_forwarding
В /etc/sysctl.conf расскомментируем #net.ipv4.ip_forward=1 после чего
Создание клиента
Создание ключей и сертификатов
Переходим в созданную директорию, где и замёмся генерацией ключей и сертификатов
Создаем ключ клиента
Если хотим защитить ключ паролем, то генерируем его другой командой
В этом случае при запуске соединения нужно будет каждый раз вводить пароль на ключ.
Создание файла конфигурации клиента
/etc/openvpn/client.conf
ИЛИ единый файл конфигурации клиента client.ovpn с сертификатами и ключами для импорта
Можно запускать наш клиент OpenVPN
Настройка маршрутизации на стороне клиента
Машина с openvpn уже готова работать с сервером в чём можно убедится
Но для того, чтобы пользоваться туннелем в другой офис могли другие устройства в локальной сети нужно указать им, чтобы доступ в подсеть 192.168.1.0/24 осуществляется через 192.168.0.100. Или, что часто проще и быстрее прописать это правило маршрутизации на роутере, который является шлюзом для устройств в сети.
Включаем ipv4_forwarding
Также как в случае с сервером.
Настройка выхода в интернет с IP сервера
Настройки сервера
Если же вы хотите организовать доступ из VPN сети в интернет с IP адреса сервера, то вам нужно настроить на сервере NAT. Сделать это можно следующей командой (на сервере):
Здесь мы указали, что сеть 10.8.0.0/24 будет выходить наружу через интерфейс eth0.
Для того что бы настройки iptables сохранились после перезагрузки нужно их дополнительно сохранить:
Настройки клиента
К конфиге клиента client.conf нужно добавить строчку
Отзыв сертификата
Если все прошло штатно вы должны увидеть следующий вывод, сообщающий о том, что сертификат отозван:
Скрипт revoke-full создаст CRL-файл (certificate revocation list, список отозванных сертификатов) с именем crl.pem в подкаталоге keys. Файл должен быть скопирован в каталог, в котором сервер OpenVPN может получить к нему доступ. Ранее в конфиге мы прописали, что этот файл должен находится в /etc/openvpn, туда и копируем.
Отключение автозапуска OpenVPN
Тест производительности OpenVPN
Максимальный прирост при отключении сжатия, шифрования и аутентификации составил около 35%. Не думаю, что это стоит того, чтобы отключать механизмы защиты, но ситуации бывают разные.
Может кому-то как мне будет интересно влияние опций на производительность и не придется тратить время на проведение замеров, хотя я бы с удовольствием ознакомился с результами других людей. Изначально тестил для себя, поэтому точных замеров не проводил, потом решил поделиться результатами.
Источники
© 2018 Ubuntu-ru — Русскоязычное сообщество Ubuntu Linux.
© 2012 Canonical Ltd. Ubuntu и Canonical являются зарегистрированными торговыми знаками Canonical Ltd.
How to Install and Configure OpenVPN Server on Ubuntu 18.04, 16.04
VPN or Virtual Private Network is a group of computers connected to the private network over the public network (Internet). These days security is the primary concern for everyone and it’s more required while working over the public network.
Like you have a group of computers in a remote location. Now you need to access those computers as a LAN network in your system. Also, you need all data should be encrypted during transfer between computers. The solution is a VPN. You can use a VPN network to connect two remote location systems with each other as they are on the same LAN. This tutorial will help you to install and configure the OpenVPN server on Ubuntu, Debian, and Linux Mint systems.
Step 1 – Prerequisites
Login to your Ubuntu system using SSH. Now update system’s apt cache and update your system packages to latest versions.
Step 2 – Install OpenVPN Server
Now, Install the OpenVPN package by typing below command. Also, install easy-rsa packages for managing SSL certificates required for data encryption between server and client.
Copy the sample configuration file for OpenVPN to /etc/openvpn/server.conf file. This will be used as an OpenVPN server configuration file.
Step 3 – Configure OpenVPN Server
Edit the OpenVPN server configuration file in your favorite text editor.
Remove the “;” to uncomment lines or add new lines for the following entries in the configuration file.
The above settings will allow VPN connection between systems. But they will not direct the client’s internet traffic through VPN. Also, uncomment the dhcp-option values.
Step 4 – Update Network Configuration
Do some network settings to allow users to access the server on the same network of OpenVPN servers. First, Allow IP forwarding on the server by executing the below commands to set net.ipv4.ip_forward value to 1 in /etc/sysctl.conf file.
Masquerade the internet traffic coming from the VPN network (10.8.0.0/24) to systems local network interface (eth0). Where 10.8.0.0 is my VPN network and eth0 is the network interface of my system.
Step 5 – Setup Certificate Authority
OpenVPN provides secure VPN service using TLS/SSL encryption of traffic between server and client. For this, you need to issue trusted certificates for servers and clients to work. To issue certificates you need to configure Certificate Authority on your system.
Let’s create a directory for certificate authority using make-cadir command. This command also initializes the directory with the required files.
Edit vars file in your favorite text editor.
and update the below values as required. These values will be used as default values to issues the certificates for servers and clients. You can also overwrite these values during certificate creation.
Load the values in system environment.
Sample output of above command:
Now your system is ready as Certificate Authority to issue the certificates.
Step 6 – Generate Server Certificate Files
Sample output of above command:
Now generate a strong Diffie-Hellman key to use for the key exchange using the command. This command may take some time to complete.
After that generate an HMAC signature to make more secure TLS integrity verification capabilities of the server.
After creating all files, copy them to /etc/openvpn directory.
Step 7 – Start OpenVPN Service
OpenVPN server is ready now. Let’s start the service using the systemctl command. Also, Check the status of service.
On the successful start of service, you will see results like below.
Step 8 – Generate Client Configuration
You OpenVPN server is ready to use. Now generate the client configuration files including the private key, certificates. I have made this process easier for you to generate any number of configurations files using a simple script. Follow the below steps to generate configuration files. Make sure to use correct directory structure.
Create a shell script file as below.
copy the below content. Update the OPENVPN_SERVER variable with the correct OpenVPN server ip address and save it.
Ubuntu Documentation
Overview
OpenVPN is a Virtual Private Networking (VPN) solution provided in the Ubuntu Repositories. It is flexible, reliable and secure. It belongs to the family of SSL/TLS VPN stacks (different from IPSec VPNs).
This page refers to the community version of the OpenVPN server. Setup examples are also provided on the OpenVPN community website. There is also a commercial Web GUI which might be easier to set up and maintain, especially for non-experts, and which allows clients to download VPN configurations themselves using the web browser.
What is a bridged VPN?
Setting up a Bridged VPN using OpenVPN
Note that good networking knowledge and enough time is required to follow this manual setup guide. These instructions are for setting up a Bridged VPN on Ubuntu 8.04 using x509 certs and some general administration tasks.
This example installation was performed using Ubuntu Jeos 8.04 in a KVM virtual machine (but could just have easily been performed on a standalone Ubuntu Server). In my configuration eth0 is connected to the Internet and eth1 is connected to the LAN network that will be bridged. Comments in configuration files are preceeded by two pound signs (##).
Installing the Server
Setting up the Bridge
When a Linux server is behind a NAT firewall, the /etc/network/interfaces file commonly looks like
Edit this and add a bridge interface:
The bridging declarations come from the libvirt documentation. (I really only understand the bridge_ports directive and the bridge_stp directive. Please add more instructions here.)
Generating Certificates
The Certificate Authority is now setup and the needed keys are in /etc/openvpn/
Configuring the Server
By default all servers specified in *.conf files in the /etc/openvpn/ directory are started on boot. Therefore, all we have to do is creating a new file named server.conf in the /etc/openvpn/ directory.
First, we’re going to create a couple of new scripts to be used by the openvpn server.
This script should contain the following
Now, we’ll create a «down» script.
It should contain the following.
Now, make both scripts executable.
And now on to configuring openvpn itself.
The server initialization script will complain about WARN: could not open database for 4096 bits. Skipped and you can work around it by running this command:
Pre-systemd setup
Don’t forget to either reboot or run the command below. This will restart openvpn and load the new config.
systemd setup
For systemd, the /lib/systemd/system/openvpn@.service file is defined so that multiple OpenVPN servers can be active concurrently. This is accomplished by the %i in the service definition file, which will be used as the name of the configuration file. Since we created a server.conf file, use the following commands to enable OpenVPN:
Firewall notes
In case you run a firewall like ufw, please consider enabling ip forwarding, otherwise the clients will only be able to connect to the server, but not to other LAN servers.
Getting Clients Connected
This section concerns creating client certificate and key files and setting up a client configuration file. The files can then be used with OpenVPN on a client platform. The described configuration will work with OpenVPN installations of OpenVPN GUI for Windows and Tunnelblick for Mac OS X clients. For a detailed discussion of each, refer to their respective home pages. It should also be compatible with Linux OpenVPN clients.
Generating Client Certificate and Key
Generating certificates and keys for a client is very similar to the process used for generating server certificates. It is assumed that you have already set up the /etc/openvpn/easy-rsa/ directory and updated the /etc/openvpn/easy-rsa/vars file as described above. You should have already setup your Certificate Authority and created a server certificate and keys.
Configuring the Client
The client configuration has been adapted from the OpenVPN 2.0 sample configuration file. For Windows, the file should be named client.ovpn and for other operating systems, the file should be named client.conf. The file can be created using vi or other editor that can create plain text files.
The configuration file assumes that there is only one TUN/TAP device configured on the client.
Place the client.ovpn (or client.conf) configuration file along with the certificate and key files in the openvpn configuration directory on the client. With the above setup, the following files should be in the configuration directory.
(For the OpenVPN GUI for Windows, the default location for the files is C:\Program Files\OpenVPN\config.)
(For Tunnelblick for Mac OS X, the default location for the files is
Resolv.conf (optional)
If you deployed a full vpn tunnel, in which all or most routes traverse the tunnel, then you might need to install helper scripts to update /etc/resolv.conf with your tunneled dns servers. This will allow you to access private name resolution while the tunnel is connected and restore your non-tunneled dns servers when disconnected. If you do not have an internal authoritative zone then you might not benefit from this optional script.
Then insert these up down statements into your clients configuration file in /etc/openvpn/
Suspend (Optional)
If your vpn tunnel is not re-establishing after resuming from a sleep or suspended state, you may need to create the following script to restart the openvpn service. This is useful for always-on full tunneled connections.
Firestarter configuration for OpenVPN
Firestarter requires some configuration on both client and server machines to allow services like SAMBA over a VPN tunnel. In addition the creation of rules within the GUI, it was also necessary to edit the /etc/firestarter/user-pre file. I used the instructions found here:
Also, though the tutorial didn’t discuss it, I found it necessary to save the original user-pre file as a copy, then rename the original and rename the copy to user-pre due to permissions issues.
Upstream Packages
Ubuntu LTS 22.04 has OpenVPN 2.5.5, if you are on a previous Ubuntu release and need an OpenVPN 2.5 feature set (i.e. v2crypt), openvpn.net upstream has packages available. Using these may break your Ubuntu support warranty.
LTS 20.04 example:
Other Resources
Consult the official OpenVPN Howto.
OpenVPN (последним исправлял пользователь nicabbi 2022-05-26 04:11:09)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
How to Install OpenVPN in Ubuntu 20.04
OpenVPN is an open-source, fast, popular program for creating a VPN (Virtual Private Network). It uses both the TCP and UDP transmission protocols, and VPN tunnels are secured with OpenVPN protocol with SSL/TLS authentication, certificates, credentials, and optionally MAC address lock as well as multi-factor authentication.
It can be used on a wide variety of devices and systems. Like most VPN protocols out there, it has a client-server architecture. The OpenVPN access server runs on a Linux system, and the clients can be installed on other Linux systems, Windows, macOS, as well as mobile operating systems such as Android, Windows mobile, and iOS.
The OpenVPN access server accepts incoming VPN connections and OpenVPN Connect clients or any open-source clients compatible with OpenVPN can initiate a connection to the server.
In this article, you will learn how to set up an OpenVPN access server on Ubuntu 20.04 and connect VPN clients from other Linux systems.
Prerequisites:
Step 1: Setting Up OpenVPN Server on Ubuntu
1. Installing and configuring an OpenVPN server manually is not a simple task from my experience. That’s the reason, we will be using a script that lets you set up your own secure OpenVPN server in a matter of seconds.
Before downloading and running the script, note that the script will auto-detect your server’s private IP address. But you need to take note of your server public IP address especially if it is running behind NAT.
Check Ubuntu Server IP Address
2. Now download the installer script using the curl command-line tool, then make it executable using the chmod command as follows.
3. Next, run the executable installer script as shown.
When executed for the first time, the script will ask you some questions, read them carefully, and provide answers according to your preferences, to set up your OpenVPN server.
Run OpenVPN Installer Script
4. Once the VPN installation process is complete, a client configuration file will be written under the current working directory. This is the file you will use to configure your OpenVPN client as described in the next section.
OpenVPN Installation Summary
5. Next, confirm that the OpenVPN service is up and running by checking its status using the following systemctl command.
6. Also, confirm that the OpenVPN daemon is listening on the port you instructed the script to use, using the ss command as shown.
Check OpenVPN Listening Port
7. If you check your network interfaces, a new interface has been created for a VPN tunnel, you can confirm this by using IP command.
Check VPN Tunnel Interface
Step 2: Setup OpenVPN Clients in Ubuntu
8. Now its time to set up your OpenVPN client and connect it to the VPN server. First, install the OpenVPN package in the client machine as follows.
9. On a desktop system, you also need to install the network-manager-openvpn package to make VPN settings from the graphical interface.
10. After installing the above packages, start the OpenVPN service, for now, enable it to automatically start at system boot and check its status to confirm that it’s up and running.
11. Now you need to import the OpenVPN client settings from the OpenVPN server. Open a terminal window and use the SCP command to grab the file as shown.
Import OpenVPN Client Settings
12. Open system Settings, then go to Networks. Under VPN, click the add button to get the necessary options.
Add New VPN Setting
Import VPN Settings
Select OpenVPN File to Import
14. On other Linux desktop systems, click on the network icon on the system panel, go to Network Connections. Then click the plus button to add a new connection. From the drop, select “Import a saved VPN configuration…” as highlighted in the following screenshot.
Create the connection and import the file.
Import VPN Client Settings
15. After importing the file, the VPN settings should be added as shown in the following screenshot. Then click Add.
VPN Settings Added
16. Your VPN client settings should be added successfully. You can connect to the OpenVPN server by turning on the VPN as highlighted in the following screenshot.
Connect to VPN
17. Now the VPN connection should be established successfully as shown in the following screenshot.
VPN Connection Successful
18. If you check your network interface connections using the IP add command, there should now exist a VPN tunnel interface as highlighted in the following screenshot.
Check VPN Tunnel Interface
Connecting Another Linux Server as a VPN Client
19. To connect another Linux server as a VPN client, ensure that you have installed the OpenVPN package, started, and enabled the OpenVPN service as described above.
Download Openvpn Client File
20. Next, start the VPN client service, enable it, and check its status with the following commands.
Start OpenVPN Client Service
21. Then confirm that a VPN tunnel interface has been created using the IP add command as shown.
Confirm VPN Tunnel Interface
22. To set up other OpenVPN clients on operating systems, use the following clients:
23. If you want to add a new VN user or revoke an existing user or remove the OpenVPN server from your system, simply run the installer script again. Then select what you wish to do from the list of options and follow the prompts.
Remove OpenVPN in Ubuntu
That brings us to the end of this guide. To share any thoughts with us or ask questions, use the feedback form below. For more information, go to the openvpn-install script Github repository.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Настройка OpenVPN в Ubuntu 20.04
В последнее время различные сервисы VPN набирают популярность. Они позволяют обходить блокировки сайтов в вашей стране, а также позволяют сотрудникам использовать корпоративные сервисы из дома, как будто они находятся в офисе. Существует много проприетарых VPN сервисов, но их использовать не обязательно, поскольку есть свободный и бесплатный OpenVPN. В этой статье мы рассмотрим как выполняется установка OpenVPN в Ubuntu 20.04.
Установка OpenVPN в Ubuntu
1. Установка пакетов
На обоих машинах должен быть установлен OpenVPN, это довольно популярная программа, поэтому вы можете установить ее из официальных репозиториев. Также нам понадобится Easy-RSA для работы с секретными ключами. Для установки программ в Ubuntu используйте такую команду:
sudo apt install openvpn easy-rsa
Оба пакеты должны быть установлены как на сервере, так и на клиенте. Они понадобятся для настройки программы. Первый этап статьи установка и настройка openvpn завершен.
2. Настройка центра сертификации
Для того чтобы после обновления системы все ваши сертификаты и настройки не были стёрты, надо скопировать набор скриптов из каталога /usr/share/easy-rsa куда-нибудь, например, в /etc/openvpn/:
sudo mkdir /etc/openvpn/easy-rsa
Затем скопируем в эту папку все необходимые скрипты easy-rsa:
Далее нам нужно создать центр сертификации в этой папке. Для этого сначала перейдите в неё:
Эта команда создаст папку pki и и необходимые файлы для генерации сертификатов. Алгоритм шифрования можно настраивать, но с параметрами по умолчанию тоже всё будет работать:
Следующая команда создаёт ключ центра сертификации, для него понадобится придумать пароль:
Далее надо создать ключи Диффи-Хафмана, которые используются при обмене ключами между клиентом и сервером. Для этого выполните:
Команда создаст файл /etc/openvpn/easy-rsa/pki/dh.pem. Если вы хотите использовать TLS авторизацию, то вам ещё понадобится ключ Hash-based Message Authentication Code (HMAC). Он используется для предотвращения DoS атаки при использовании протокола UDP. Для его создания выполните:
Для отзыва уже подписанных сертификатов нам понадобится сертификат отзыва. Для его создания выполните команду:
Будет создан файл ./pki/crl.pem.
3. Создание сертификатов сервера
Для создания сертификатов, которые будут использоваться сервером надо выполнить команду:
Все эти сертификаты надо будет использовать позже, при создании конфигурационного файла сервера.
4. Конфигурационный файл сервера
По умолчанию, конфигурационных файлов OpenVPN нет. Их нужно создать самостоятельно в зависимости от того, что планируется настраивать, сервер или клиент. Нужный файл конфигурации OpenVPN можно найти по адресу /usr/share/doc/openvpn/examples/sample-config-files/. Давайте создадим конфигурационный файл для сервера:
zcat /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz | sudo tee /etc/openvpn/server.conf
port 1194
proto udp
Все созданные ключи нужно прописать в конфигурационном файле. Наши ключи хранятся по адресу /etc/openvpn, в самой папке с конфигурационным файлом, поэтому можно не прописывать к ним полный путь:
ca ca.crt
cert server.crt
key server.key
dh dh.pem
tls-auth ta.key 0
server 10.8.0.0 255.255.255.0
Следующая директива позволяет раздавать одним и тем же клиентам одни и те же IP адреса:
После завершения настройки сохраните изменения в файле, вы можете либо вставить всю эту конфигурацию себе или отредактировать файл с примером. Если убрать все комментарии получится такой конфигурационный файл:
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist /var/log/openvpn/ipp.txt
push «redirect-gateway def1 bypass-dhcp»
push «dhcp-option DNS 8.8.8.8»
push «dhcp-option DNS 8.8.8.8»
keepalive 10 120
tls-auth ta.key 0
cipher AES-256-CBC
persist-key
persist-tun
status /var/log/openvpn/openvpn-status.log
verb 3
explicit-exit-notify 1
Настройка сервера OpenVPN завершена. Дальше необходимо запустить OpenVPN сервер. Это можно сделать прямо из командной строки, просто укажите адрес конфигурационного файла:
sudo openvpn /etc/openvpn/server.conf
Если вы увидели сообщение Initialization Sequence Completed значит всё хорошо и можно двигаться дальше. Если возникли ошибки, исправьте их, скорее всего вы сделали что-то не то в конфигурационном файле. После этого остановите запущенный сервер и запустите его снова уже с помощью systemd:
sudo systemctl start openvpn@server
5. Настройка форвардинга пакетов
Для того чтобы OpenVPN сервер мог предоставить клиентам доступ к внешней сети сервера надо включить параметр ip_forwarding. Для этого откройте файл для этого выполните такую команду:
6. Настройка брандмауэра
Теперь надо разрешить прохождение пакетов в брандмауэре. Давайте будем использовать iptables. Но сначала надо посмотреть сетевой интерфейс, который используется для доступа к внешней сети. Это можно сделать с помощью команды:
Настройка OpenVPN Ubuntu на сервере завершена, теперь осталось подготовить всё необходимое для подключения клиентов.
7. Создание сертификатов для клиента
Чтобы не скидывать ключи на сервер, а потом обратно, лучше создавать ключи на сервере. Для этого в той же директории /etc/openvpn/easy-rsa/ выполните такую команду:
Вместо losst используйте нужное вам имя пользователя, а опция nopass аналогично генерации ключей для сервера отключает использование пароля.
8. Конфигурационный файл клиента
Давайте создадим папку /etc/openvpn/clients, куда будем складывать все ключи и конфигурационные файлы клиентов:
sudo mkdir /etc/openvpn/clients
sudo mkdir /etc/openvpn/clients/losst
Затем перейдите в папку клиента:
Затем туда надо скопировать ca.crt, ta.key и ключи клиента losst.crt и losst.key:
cp /etc/openvpn/easy-rsa/pki/ca.crt /etc/openvpn/clients/losst/
cp /etc/openvpn/easy-rsa/pki/ta.key /etc/openvpn/clients/losst/
cp /etc/openvpn/easy-rsa/pki/issued/losst.crt /etc/openvpn/clients/losst/
cp /etc/openvpn/easy-rsa/pki/private/losst.key /etc/openvpn/clients/losst/
Теперь давайте создадим конфигурационный файл клиента, его тоже можно скопировать из директории с примерами:
Перед тем, как редактировать конфигурационный файл надо узнать публичный IP вашего сервера. Для этого можно воспользоваться командой:
Теперь можно открыть скопированный конфигурационный файл:
Здесь обязательно надо заменить в этой строке my-server-1 на IP адрес сервера, который вы узнали ранее. Например:
remote 185.117.155.209 1194
Всё остальное можно оставить по умолчанию, сертификаты должны лежать в той же папке, в которой будет находится конфигурационный файл. В результате, если убрать все комментарии получится вот так:
client
dev tun
proto udp
remote 185.117.155.209 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert losst.crt
key losst.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-CBC
verb 3
Обратите внимание, что конфигурационные файлы должны максимально совпадать, отсутствие определенных опций в одном из файлов может привести к ошибкам. Это не значит, что файлы будут идентичны, но основные параметры openvpn должны быть одинаковыми. Например, если вы включили опцию comp-lzo для сервера, то она должна быть включена и для клиента.
Далее осталось всё это упаковать в архив и отправить клиенту. Но можно поступить по другому. Ключи для опций ca, cert, key и tls-auth можно упаковать в сам файл конфигурации. Например, для опции cert используется такой синтаксис:
——BEGIN CERTIFICATE——
текст_сертификата
——END CERTIFICATE——
Текст ключа надо взять из файла losst.crt между BEGIN CERTIFICATE и END CERTIFICATE. Например:
Для ca.crt всё будет выглядеть аналогично:
Для приватного ключа losst.key надо использовать немного другой синтаксис:
И для tls-auth тоже:
После этого директивы, указывающие на файлы можно удалить, и передать клиенту только один этот файл.
9. Проверка подключения
Вы можете скачать конфигурационный файл клиента с сервера, например, с помощью scp:
scp root@ip_сервера:/etc/openvpn/clients/losst/losst.conf /etc/openvpn/
Вам осталось запустить OpenVPN на этой машине используя этот конфигурационный файл:
Готово, теперь все работает, если вы выполните ifconfig, то увидите что был добавлен интерфейс tun0. Также вы можете попробовать выполнить ping адреса 10.8.0.1, именно этот адрес мы настроили для нашего сервера OpenVPN, пакеты ping будут нормально отправляться.
Если пакеты не идут, или еще что-то не работает, обратите внимание на вывод обоих программ, возможно, возникли какие-либо ошибки или предупреждения, также убедитесь, что брандмауэр сервера разрешает доступ извне по udp для порта 1194. Еще можно запустить сервер или клиент, настроив в конфигурационном файле уровень подробности на максимум verb 9. Очень часто это помогает понять почему что-то не работает. Но вы еще не можете направлять трафик через туннель.
Выводы
В этой статье мы рассмотрели как выполняется установка и настройка OpenVPN в Ubuntu 20.04, а также как настроить openvpn для работы с аутентификацией по ключу. Организация частных виртуальных сетей может быть очень полезной не только в организациях, но и скажем для обмена данными между двумя вашими компьютерами или для повышения безопасности в сети.