Как поднять свой vpn сервер ubuntu
Перейти к содержимому

Как поднять свой vpn сервер ubuntu

  • автор:

Configure a vpn server on Linux (Ubuntu 16.04) EC2 instance

First make sure that you have AWS account and also create a Linux ubuntu system using ubuntu 16.04 AMI.

Connect to the Ubuntu server using the .pem file which you got during the installation. (Keep it confidential).If you can connect to your system with out any problem then everything is fine you can continue.

Prerequisites:

You will need to configure a non-root user with sudo privileges before you start this guide.

OpenVPN server setup

Step1: install OpenVPN onto our server.

OpenVPN is available in Ubuntu’s default repositories, so we can use apt for the installation. We will also be installing the easy-rsa package, which will help us set up an internal CA (certificate authority) for use with our VPN.

$ sudo apt-get update

$ sudo apt-get install openvpn easy-rsa

Step2 :Set Up the CA Directory

OpenVPN is an TLS/SSL VPN. This means that it utilizes certificates in order to encrypt traffic between the server and clients. In order to issue trusted certificates, we will need to set up our own simple certificate authority (CA).

Step 3: Build the Certificate Authority

Now, we can use the variables we set and the easy-rsa utilities to build our certificate authority

The output looks something like this

NOTE: If you run ./clean-all, I will be doing a rm -rf on /home/sammy/openvpn-ca/keys

Make sure we’re operating in a clean environment by typing:

Next build our root CA

Just press ENTER through the prompts to confirm the selections:

We now have a CA that can be used to create the rest of the files we need.

step 4: Create the Server Certificate,Key, and Encryption Files

Next, we will generate our server certificate and key pair, as well as some additional files used during the encryption process

Generate OpenVPN server certificate and key pair by typing

Just press ENTER. Do not enter a challenge password for this setup. Towards the end, you will have to enter y to two questions to sign and commit the certificate.

We can generate a strong Diffie-Hellman keys to use during key exchange by typing

we can generate an HMAC signature to strengthen the server’s TLS integrity verification capabilities

$ openvpn — genkey — secret keys/ta.key

Step 5: Generate a Client Certificate and Key Pair.

Next, we can generate a client certificate and key pair, this can be done on the client machine and then signed by the server/CA for security purposes. But we are generating on the

server to make it simple.

We will use clientconnection as the value for our first certificate/key pair for this guide.

To produce credentials without a password, to aid in automated connections, use the build-key command like this

Step 6: Configure the OpenVPN Service

Copy the Files to the OpenVPN Directory

Next, we need to copy and unzip a sample OpenVPN configuration file into configuration directory so that we can use it as a basis for our setup

Adjust the OpenVPN Configuration

Now that our files are in place, we can modify the server configuration file

Basic Configuration

First, find the HMAC section by looking for the tls-auth directive. Remove the ";" to uncomment the tls-auth line. Below this, add the key-direction parameter set to "0"(Zero):

Next, find the section on cryptographic ciphers by looking for the commented out cipher lines. The AES-128-CBC cipher offers a good level of encryption and is well supported. Remove the ";" to uncomment the cipher AES-128-CBC line:

Below this, add an auth line to select the HMAC message digest algorithm.

Finally, find the user and group settings and remove the ";" at the beginning of to uncomment those lines

Step 7: Adjust the Server Networking Configuration

We can adjust this setting by modifying the /etc/sysctl.conf file

sudo vim /etc/sysctl.conf

Inside, look for the line that sets net.ipv4.ip_forward . Remove the "#" character from the beginning of the line to uncomment that setting

Adjust the UFW Rules to Masquerade Client Connections

Before we open the firewall configuration file to add masquerading, we need to find the public network interface of our machine. To do this, type

ip route | grep default

Your public interface should follow the word “dev”. For example, this result shows the interface named eth0 , which is highlighted below

When you have the interface associated with your default route, open the /etc/ufw/before.rules file to add the relevant configuration:

add these lines in before.rules file

save the file and close.

We need to tell UFW to allow forwarded packets by default as well. To do this, we will open the /etc/default/ufw file.

Inside, find the DEFAULT_FORWARD_POLICY directive. We will change the value from DROP to ACCEPT

Open the OpenVPN Port and Enable the Changes

Next, we’ll adjust the firewall itself to allow traffic to OpenVPN.

If you did not change the port and protocol in the /etc/openvpn/server.conf file, you will need to open up UDP traffic to port 1194. If you modified the port and/or protocol, substitute the values you selected here.

We’ll also add the SSH port in case you forgot to add it when following the prerequisite tutorial:

Now, we can disable and re-enable UFW to load the changes from all of the files we’ve modified:

Our server is now configured to correctly handle OpenVPN traffic.

Step 8: Start and Enable the OpenVPN Service

start vpn server by typing

sudo systemctl start openvpn@server

Check the server status by typing

sudo systemctl status openvpn@server

The output looks something like this

Step 9: Create Client Configuration Infrastructure

Creating the Client Config Directory Structure

Create a directory structure within your home directory to store the files:

Since our client configuration files will have the client keys embedded, we should lock down permissions on our inner directory:

Creating a Base Configuration

Next, let’s copy an example client configuration into our directory to use as our base configuration:

Open this new file in your text editor:

First, locate the remote directive. This points the client to our OpenVPN server address. This should be the public IP address of your OpenVPN server. If you changed the port that the OpenVPN server is listening on, change 1194 to the port you selected:

Next, uncomment the user and group directives by removing the ";":

Find the directives that set the ca , cert , and key . Comment out these directives since we will be adding the certs and keys within the file itself:

Mirror the cipher and auth settings that we set in the /etc/openvpn/server.conf file:

Next, add the key-direction directive somewhere in the file. This must be set to "1" to work with the server:

Finally, add a few commented out lines. We want to include these with every config, but should only enable them for Linux clients that ship with a /etc/openvpn/update-resolv-conf file. This script uses the resolvconf utility to update DNS information for Linux clients.

paste the following script in make_config.sh file

Give permission to execute

Step 10: Generate Client Configurations

Now, we can easily generate client configuration files.

If you followed along with the guide, you created a client certificate and key called clientconnection.crt and clientconnection.key respectively by running the ./build-key clientconnection command in step 6. We can generate a config for these credentials by moving into our

/client-configs directory and using the script we made:

If everything went well, we should have a clientconnection.ovpn file in our

The client can connect to vpn server using this .ovpn file (Keep it confidential)

Linux (Ubuntu/Debian) client connection:

first install openvpn by typing the command

$ sudo apt-get install openvpn

Run the OpenVPN client with the downloaded client config file:

Usually, the easiest way to install an OpenVPN client is to use the — config argument to specify the location of the downloaded client config file:

Service — OpenVPN

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 chapter will cover installing and configuring OpenVPN to create a VPN.

If you want more than just pre-shared keys OpenVPN makes it easy to set up a Public Key Infrastructure (PKI) to use SSL/TLS certificates for authentication and key exchange between the VPN server and clients. OpenVPN can be used in a routed or bridged VPN mode and can be configured to use either UDP or TCP. The port number can be configured as well, but port 1194 is the official one; this single port is used for all communication. VPN client implementations are available for almost anything including all Linux distributions, macOS, Windows and OpenWRT-based WLAN routers.

Server Installation

To install openvpn in a terminal enter:

Public Key Infrastructure Setup

The first step in building an OpenVPN configuration is to establish a PKI (public key infrastructure). The PKI consists of:

a separate certificate (also known as a public key) and private key for the server and each client.

a master Certificate Authority (CA) certificate and key, used to sign the server and client certificates.

OpenVPN supports bidirectional authentication based on certificates, meaning that the client must authenticate the server certificate and the server must authenticate the client certificate before mutual trust is established.

Both server and client will authenticate the other by first verifying that the presented certificate was signed by the master certificate authority (CA), and then by testing information in the now-authenticated certificate header, such as the certificate common name or certificate type (client or server).

Certificate Authority Setup

To setup your own Certificate Authority (CA) and generate certificates and keys for an OpenVPN server and multiple clients first copy the easy-rsa directory to /etc/openvpn . This will ensure that any changes to the scripts will not be lost when the package is updated. From a terminal, run:

Note: If desired, you can alternatively edit /etc/openvpn/easy-rsa/vars directly, adjusting it to your needs.

As root user change to the newly created directory /etc/openvpn/easy-rsa and run:

Server Keys and Certificates

Next, we will generate a key pair for the server:

Diffie Hellman parameters must be generated for the OpenVPN server. The following will place them in pki/dh.pem .

And finally a certificate for the server:

All certificates and keys have been generated in subdirectories. Common practice is to copy them to /etc/openvpn/:

Client Certificates

The VPN client will also need a certificate to authenticate itself to the server. Usually you create a different certificate for each client.

This can either be done on the server (as the keys and certificates above) and then securely distributed to the client. Or vice versa: the client can generate and submit a request that is sent and signed by the server.

To create the certificate, enter the following in a terminal while being user root:

If the first command above was done on a remote system, then copy the .req file to the CA server. There you can then import it via easyrsa import-req /incoming/myclient1.req myclient1 . Then you can go on with the second sign-eq command.

In both cases, afterwards copy the following files to the client using a secure method:

  • pki/ca.crt
  • pki/issued/myclient1.crt

As the client certificates and keys are only required on the client machine, you can remove them from the server.

Simple Server Configuration

Along with your OpenVPN installation you got these sample config files (and many more if you check):

Start with copying and unpacking server.conf.gz to /etc/openvpn/server.conf.

Edit /etc/openvpn/myserver.conf to make sure the following lines are pointing to the certificates and keys you created in the section above.

Complete this set with a ta key in etc/openvpn for tls-auth like:

Edit /etc/sysctl.conf and uncomment the following line to enable IP forwarding.

Then reload sysctl.

That is the minimum you have to configure to get a working OpenVPN server. You can use all the default settings in the sample server.conf file. Now start the server.

Be aware that the “systemctl start openvpn” is not starting your openvpn you just defined.
Openvpn uses templatized systemd jobs, openvpn@CONFIGFILENAME. So if for example your configuration file is myserver.conf your service is called openvpn@myserver. You can run all kinds of service and systemctl commands like start/stop/enable/disable/preset against a templatized service like openvpn@server.

You will find logging and error messages in the journal. For example, if you started a templatized service openvpn@server you can filter for this particular message source with:

The same templatized approach works for all of systemctl:

You can enable/disable various openvpn services on one system, but you could also let Ubuntu do it for you. There is config for AUTOSTART in /etc/default/openvpn . Allowed values are “all”, “none” or space separated list of names of the VPNs. If empty, “all” is assumed. The VPN name refers to the VPN configutation file name. i.e. home would be /etc/openvpn/home.conf If you’re running systemd, changing this variable will require running systemctl daemon-reload followed by a restart of the openvpn service (if you removed entries you may have to stop those manually).

After “systemctl daemon-reload” a restart of the “generic” openvpn will restart all dependent services that the generator in /lib/systemd/system-generators/openvpn-generator created for your conf files when you called daemon-reload.

Now check if OpenVPN created a tun0 interface:

Simple Client Configuration

There are various different OpenVPN client implementations with and without GUIs. You can read more about clients in a later section on VPN Clients. For now we use commandline/service based OpenVPN client for Ubuntu which is part of the very same package as the server. So you have to install the openvpn package again on the client machine:

This time copy the client.conf sample config file to /etc/openvpn/:

Copy the following client keys and certificate files you created in the section above to e.g. /etc/openvpn/ and edit /etc/openvpn/client.conf to make sure the following lines are pointing to those files. If you have the files in /etc/openvpn/ you can omit the path.

And you have to specify the OpenVPN server name or address. Make sure the keyword client is in the config. That’s what enables client mode.

Now start the OpenVPN client with the same templatized mechanism:

You can check status as you did on the server:

On the server log an incoming connection looks like the following.
You can see client name and source address as well as success/failure messages.

And you can check on the client if it created a tun0 interface:

Check if you can ping the OpenVPN server:

Note

The OpenVPN server always uses the first usable IP address in the client network and only that IP is pingable. E.g. if you configured a /24 for the client network mask, the .1 address will be used. The P-t-P address you see in the ip addr output above is usually not answering ping requests.

Check out your routes:

First trouble shooting

If the above didn’t work for you, check this:

  • Check your journal -xe
  • Check that you have specified the keyfile names correctly in client and server conf files
  • Can the client connect to the server machine? Maybe a firewall is blocking access? Check journal on server.
  • Client and server must use same protocol and port, e.g. UDP port 1194, see port and proto config option
  • Client and server must use same config regarding compression, see comp-lzo config option
  • Client and server must use same config regarding bridged vs routed mode, see server vs server-bridge config option

Advanced configuration

Advanced routed VPN configuration on server

The above is a very simple working VPN. The client can access services on the VPN server machine through an encrypted tunnel. If you want to reach more servers or anything in other networks, push some routes to the clients. E.g. if your company’s network can be summarized to the network 192.168.0.0/16, you could push this route to the clients. But you will also have to change the routing for the way back — your servers need to know a route to the VPN client-network.

The example config files that we have been using in this guide are full of all these advanced options in the form of a comment and a disabled configuration line as an example.

Note

Please read the OpenVPN hardening security guide for further security advice.

Advanced bridged VPN configuration on server

OpenVPN can be setup for either a routed or a bridged VPN mode. Sometimes this is also referred to as OSI layer-2 versus layer-3 VPN. In a bridged VPN all layer-2 frames — e.g. all ethernet frames — are sent to the VPN partners and in a routed VPN only layer-3 packets are sent to VPN partners. In bridged mode all traffic including traffic which was traditionally LAN-local like local network broadcasts, DHCP requests, ARP requests etc. are sent to VPN partners whereas in routed mode this would be filtered.

Prepare interface config for bridging on server

First, use netplan to configure a bridge device using the desired ethernet device.

Static IP addressing is highly suggested. DHCP addressing can also work, but you will still have to encode a static address in the OpenVPN configuration file.

The next step on the server is to configure the ethernet device for promiscuous mode on boot. To do this, ensure the networkd-dispatcher package is installed and create the following configuration script.

Then add the following contents.

Prepare server config for bridging

Edit /etc/openvpn/server.conf to use tap rather than tun and set the server to use the server-bridge directive:

After configuring the server, restart openvpn by entering:

Prepare client config for bridging

The only difference on the client side for bridged mode to what was outlined above is that you need to edit /etc/openvpn/client.conf and set tap mode:

Finally, restart openvpn:

You should now be able to connect to the full remote LAN through the VPN.

Alexell.Ru

Запускаем собственный PPTP сервер на Ubuntu

В этой статье я расскажу как поднять собственный PPTP сервер на Ubuntu. Почему именно PPTP? У каждого свои цели и задачи, кому-то нужен PPTP, кому-то L2TP/IPSec, кому-то IKEv2, а может и OpenVPN. Я постараюсь написать статьи по установке и настройке хотя бы двух протоколов VPN на Ubuntu и начну с PPTP. Все описанные действия производились на Ubuntu 14.04.5 LTS. Напоминаю, что дешевые VPS во Франции для запуска своего VPN вы можете посмотреть здесь.

Для установки понадобятся права root пользователя или sudo.

Настройка OpenVPN в Ubuntu 20.04

Частная виртуальная сеть или Virtual Private Network (VPN) — это сеть между компьютерами или серверами в сети, в которой шифруются все передаваемые данные и к которой могут подключится только клиенты, имеющие специальные ключи. Фактически, это та же локальная сеть, только между компьютерами, которые могут находится на разных частях земного шара. Несмотря на то, что все данные передаются через сеть Интернет никто не может получить к ним доступ, потому что они зашифрованы.

В последнее время различные сервисы VPN набирают популярность. Они позволяют обходить блокировки сайтов в вашей стране, а также позволяют сотрудникам использовать корпоративные сервисы из дома, как будто они находятся в офисе. Существует много проприетарых VPN сервисов, но их использовать не обязательно, поскольку есть свободный и бесплатный OpenVPN. В этой статье мы рассмотрим как выполняется установка OpenVPN в Ubuntu 20.04.

Установка OpenVPN в Ubuntu

1. Установка пакетов

На обоих машинах должен быть установлен OpenVPN, это довольно популярная программа, поэтому вы можете установить ее из официальных репозиториев. Также нам понадобится Easy-RSA для работы с секретными ключами. Для установки программ в Ubuntu используйте такую команду:

sudo apt install openvpn easy-rsa

Оба пакеты должны быть установлены как на сервере, так и на клиенте. Они понадобятся для настройки программы. Первый этап статьи установка и настройка openvpn завершен.

2. Настройка центра сертификации

Первое что нужно сделать, это создать правильную инфраструктуру для генерации открытых ключей на сервере. Сервером мы считаем ту машину, к которой будут подключаться пользователи. Обратите внимание, что все секретные ключи должны находится в надежном месте. В OpenVPN открытый ключ называется сертификатом и имеет расширение .crt, а закрытый ключ так и называется ключом, его расширение — .key. Обслуживать всё это мы будем с помощью набора скриптов Easy-RSA.

Для того чтобы после обновления системы все ваши сертификаты и настройки не были стёрты, надо скопировать набор скриптов из каталога /usr/share/easy-rsa куда-нибудь, например, в /etc/openvpn/:

sudo mkdir /etc/openvpn/easy-rsa

Затем скопируем в эту папку все необходимые скрипты easy-rsa:

sudo cp -R /usr/share/easy-rsa /etc/openvpn/

Далее нам нужно создать центр сертификации в этой папке. Для этого сначала перейдите в неё:

Эта команда создаст папку pki и и необходимые файлы для генерации сертификатов. Алгоритм шифрования можно настраивать, но с параметрами по умолчанию тоже всё будет работать:

sudo ./easyrsa init-pki

Следующая команда создаёт ключ центра сертификации, для него понадобится придумать пароль:

sudo ./easyrsa build-ca

Далее надо создать ключи Диффи-Хафмана, которые используются при обмене ключами между клиентом и сервером. Для этого выполните:

sudo ./easyrsa gen-dh

Команда создаст файл /etc/openvpn/easy-rsa/pki/dh.pem. Если вы хотите использовать TLS авторизацию, то вам ещё понадобится ключ Hash-based Message Authentication Code (HMAC). Он используется для предотвращения DoS атаки при использовании протокола UDP. Для его создания выполните:

sudo openvpn —genkey —secret /etc/easy-rsa/pki/ta.key

Для отзыва уже подписанных сертификатов нам понадобится сертификат отзыва. Для его создания выполните команду:

sudo ./easyrsa gen-crl

Будет создан файл ./pki/crl.pem.

3. Создание сертификатов сервера

Для создания сертификатов, которые будут использоваться сервером надо выполнить команду:

sudo ./easyrsa build-server-full server nopass

Здесь server — это имя нашего сервера, а опция nopass отключает использование пароля. Теперь все полученные ключи надо скопировать в папку /etc/openvpn:

cp ./pki/ca.crt /etc/openvpn/ca.crt cp ./pki/dh.pem /etc/openvpn/dh.pem cp ./pki/crl.pem /etc/openvpn/crl.pem cp ./pki/ta.key /etc/openvpn/ta.key cp ./pki/issued/server.crt /etc/openvpn/server.crt cp ./pki/private/server.key /etc/openvpn/server.key

Все эти сертификаты надо будет использовать позже, при создании конфигурационного файла сервера.

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 и proto — порт и протокол, по которым будет работать программа;

port 1194 proto udp

Все созданные ключи нужно прописать в конфигурационном файле. Наши ключи хранятся по адресу /etc/openvpn, в самой папке с конфигурационным файлом, поэтому можно не прописывать к ним полный путь:

ca ca.crt cert server.crt key server.key dh dh.pem tls-auth ta.key 0

Настраиваем диапазон адресов для виртуальной сети, наш сервер будет доступен по первому из них — 10.8.0.1:

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. Для этого откройте файл для этого выполните такую команду:

sysctl -w net.ipv4.ip_forward=1

6. Настройка брандмауэра

Теперь надо разрешить прохождение пакетов в брандмауэре. Давайте будем использовать iptables. Но сначала надо посмотреть сетевой интерфейс, который используется для доступа к внешней сети. Это можно сделать с помощью команды:

В данном случае — это ens3. Поэтому правила iptables будут выглядеть вот так:

sudo iptables -I FORWARD -i tun0 -o ens3 -j ACCEPT sudo iptables -I FORWARD -i ens3 -o tun0 -j ACCEPT sudo iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE

Настройка OpenVPN Ubuntu на сервере завершена, теперь осталось подготовить всё необходимое для подключения клиентов.

7. Создание сертификатов для клиента

Чтобы не скидывать ключи на сервер, а потом обратно, лучше создавать ключи на сервере. Для этого в той же директории /etc/openvpn/easy-rsa/ выполните такую команду:

sudo ./easyrsa build-client-full losst nopass

Вместо 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/

Теперь давайте создадим конфигурационный файл клиента, его тоже можно скопировать из директории с примерами:

sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ./losst.conf

Перед тем, как редактировать конфигурационный файл надо узнать публичный IP вашего сервера. Для этого можно воспользоваться командой:

Теперь можно открыть скопированный конфигурационный файл:

sudo vi ./losst.conf

Здесь обязательно надо заменить в этой строке 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 используется такой синтаксис:

<cert> ——BEGIN CERTIFICATE—— текст_сертификата ——END CERTIFICATE—— </cert>

Текст ключа надо взять из файла 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 для работы с аутентификацией по ключу. Организация частных виртуальных сетей может быть очень полезной не только в организациях, но и скажем для обмена данными между двумя вашими компьютерами или для повышения безопасности в сети.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *