- Установка и настройка сервера OpenVPN на Debian
- Создание сертификатов
- Включаем NAT на OpenVPN сервере
- Настройка клиента OpenVPN
- OpenVPN
- Prerequisites
- Configuration
- Raw (unsecured) VPN connection for test
- Server part
- Client part
- Static-Key VPN connection
- Static-Key VPN server configuration
- Static-Key VPN client configuration
- TLS-enabled VPN connection
- Init easy-rsa
- Generate CA CERTIFICATE/KEY
- Generate DIFFIE-HELLMAN PARAMETERS
- Generate Static Key for TLS authentication
- Generate CERTIFICATE/KEYs of the client(s)
- Install Client CERTIFICATE/KEYs
- VPN connection from command line
- VPN Server configuration file
- VPN Client configuration file
- VPN connection started as a Systemd service
- At the root of /etc/openvpn/
- in subfolders server and client
- VPN connection started via interfaces file
- Android / iOS devices certificate generation
- on the Server
- on the Client
- Forward traffic to provide access to the Internet
- on the Server
- Manage the Public Key Infrastructure
- Application to a VPN passing through a http proxy
- Enable and use the Management Interface
Установка и настройка сервера OpenVPN на Debian
Инструкция по установке и настройке OpenVPN-сервера на базе Linux -дистрибутива Debian 8 Jessie.
Для работы OpenVPN необходима поддержка TUN/TAP интерфейса на сервере. Если вы устанавливаете OpenVPN на физической машине, либо используете виртуализацию KVM, в с этим не должно возникнуть проблем.
В случае использования OpenVZ, необходимо активировать поддержку TUN/TAP в настройках контейнера.
Проверяем поддержку в системе tun/tap-интерфейсов:
Клиенты будут использовать на сервере аутентификацию по ключу. Для этого создадим директорию в которую будут скопированы сгенерированные ключи:
И скопируем в нее утилиты и конфиги для работы с ключами:
переходим в созданную директорию:
В файле vars можно настроить параметры ключей и сертификатов. Данный пункт не обязательный и при желании его можно пропустить.
Меняем (по желанию) следующие строки:
Остальное оставляем по умолчанию.
После правки vars инициализируем переменные и очищаем каталог keys/serverот старых сертификатов и ключей:
Создание сертификатов
Создаем корневой сертификат:
В квадратных скобках будут указаны значения по умолчанию, которые вы записали в файле vars. Если вы не планируете их менять, то просто нажимайте Enter.
Генерируем сертификаты сервера и клиента:
Для каждого клиента должны быть сгенерированы отдельные ключи.
Генерируем ключ Диффи — Хеллмана:
Cоздаем ключ для tls-аутификации:
Все сгенерированные сертификаты и ключи находятся в директории /etc/openvpn/easy-rsa/keys/
Копируем сертификаты и ключи сервера в директорию OpenVPN:
На клиентскую машину OpenVPN необходимо скопировать следующие ключи и сертификаты:
client1.crt
client1.key
ca.crt
ta.key
Для понимания назначения и расположения соответствующих файлов, я сделал небольшую таблицу:
Имя файла | Где необходим | Назначение | Секретный |
ca.crt | сервер + все клиенты | Корневой CA-сертификат | НЕТ |
ca.key | машина для подписи ключей | Корневой CA-ключ | ДА |
dh | только сервер | Параметры Diffie Hellman’а | НЕТ |
server.crt | только сервер | Сертификат сервера | НЕТ |
server.key | только сервер | Ключ сервера | ДА |
client1.crt | только клиент1 | Сертификат клиента1 | НЕТ |
client1.key | только клиент1 | Ключ клиента1 | ДА |
client2.crt | только клиент2 | Сертификат клиента2 | НЕТ |
client2.key | только клиент2 | Ключ клиента2 | ДА |
На этом установка сервера OpenVPN завершена, осталось настроить конфигурацию сервера.
Пример конфигурационного файла OpenVPN расположен в директории /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz, копируем и распаковываем его в /etc/openvpn:
# cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
# gzip -d /etc/openvpn/server.conf.gz
В зависимости от потребностей, изменяем настройки сервера OpenVPN:
Вот моя конфигурация:
Если вам нужно чтобы , чтобы после подключения у клиента весь траффик шел через сервер OpenVPN, то раскомментируйте строку 20:
Таким образом шлюзом по умолчанию для клиентов у вас станет OpenVPN — сервер.
Для повышения безопасности на linux-системах можно понизить права VPN-сервера, раскомментировав в конфиге сервера следующие строки:
Создаем директорию для клиентских настроек и перезагружаем сервер:
После завершения настройки OpenVPN, перезагружаем сервер:
В случае успешного запуска OpenVPN в системе должен появиться новый tun0 интерфейс:
Наличие данного интерфейса означает, что OpenVPN Запущен и работает. Если по каким-либо причинам он не появился, то смотрим лог-файл на наличие ошибок:
После подключения клиента к серверу OpenVPN, если он (клиент) находится в локальной сети, нужно дополнительно настроить маршрутизацию для доступа к ресурсам внутри сети. Для этого создаем файл в каталоге ccd с тем же именем ключа клиента:
Добавим в файл следующие параметры:
Первая строка добавляет маршрут в локальную сеть клиента. Проще говоря — говорит клиенту OpenVPN «ходить» в сеть 192.168.2.0 через сервер OpenVPN. Если ваша локалка связана еще с какой-либо подсетью, то её также нужно указать.
Вторая строка задает DNS-сервер, который будет использоваться после подключения (Если в вашей локальной сети DNS-сервер отсутствует, то можно указать ns от Google — 8.8.8.8, либо не указывать вообще.
Включаем NAT на OpenVPN сервере
Чтобы использовать OpenVPN для выхода в интернет, на сервере необходимо задать правило для маршрутизации трафика из сети OpenVPN в локальную сеть или сеть интернет-провайдера и обратно.
Чтобы включить поддержку IP forwarding, нужно в файле /etc/sysctl.conf раскомментировать строчку:
Применяем изменения (загружаем переменные ядра):
Не забываем прописать правила iptables. Нам нужно разрешить клиентам из подсети 10.10.10.0/24 доступ в интернет, разрешить принимать пакеты из интернета и пропустить трафик клиентов через NAT.
В первой строке мы разрешаем форвардинг пакетов на интерфейсе tun0.
Второй строкой разрешаем форвардинг с tun0 на eth0.
Третей — разрешаем формардинг с eth0 на tun0.
Замените eth0 на имя своего внешнего интерфейса. Следует отметить, что MASQUERADE создает нагрузку на процессор. Поэтому, предпочтительнее использовать SNAT:
iptables -t nat -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j SNAT —to-source ВНЕШНИЙ_IP
(в моем случае внешним IP был локальный адрес OpenVPN-сервера)
Разница между SNAT и MASQUERADE:
Маскарадинг постоянно запрашивает IP адрес у интерфейса, тем самым создавая нагрузку на процессор, в то время как SNAT «знает» IP (в нашем случае мы его указываем явно, т.к он статический).
Сохраняем правила и добавляем их в автозагрузку:
Настройка клиента OpenVPN
Если OpenVPN не установлен, то установим его::
Копируем на компьютер клиента следующие ключи и сертификаты:
Затем переносим их в директорию OpenVPN — /etc/openvpn/
Копируем и распаковываем пример конфигурационного файла в содержимое директории OpenVPN:
и редактируем его:
Добавим в содержимое файла следующие параметры:
Для Windows-машин нужно положить файл client.ovpn в папку:
C:\Program Files\OpenVPN\config\
Опции протокола, шифрования и сжатия у клиента и сервера должны быть одинаковые.
На этом настройка OpenVPN в Debian закончена, проверяем его работоспособность:
Подключаемся с клиентской машины к OpenVPN-серверу , и пингуем с неё OpenVPN-сервер:
Если пинг проходит, то все хорошо, если же нет, то смотрим логи и проверяем настройки маршрутизации.
P.S. Если у вас на сервере динамический IP, то можете воспользоваться скриптом замены IP в конфиге OpenVPN, и последующей его отправкой на email.
Если возникнут какие-либо вопросы — пишите в комментариях.
Источник
- OpenVPN
OpenVPN is an SSL/TLS VPN solution. It is able to traverse NAT connections and firewalls. This page explains briefly how to configure a VPN with OpenVPN, from both server-side and client-side for different setups: from a simple raw connexion for testing purpose up to a TLS enabled connexion.
Install the openvpn package on both client and server.
To enable OpenVPN in the Gnome NetworkManager applet for the taskbar notification area, the additional package network-manager-openvpn-gnome has to be installed on the client:
Prerequisites
On the server’s firewall, open up UDP 1194 (default port).
Bear in mind that 90% of all connection problems encountered by new OpenVPN users are firewall-related.
Configuration
OpenVPN can authenticate users via user/pass, pre-shared key, certificates, etc.
Raw (unsecured) VPN connection for test
Server part
From a server shell, run
if your client has a static IP#; otherwise, run
You should see console output resembling
While openvpn is running, check your network configuration with ip a. Output should include
Note that, if you kill openvpn (e.g., with Control-c in its console), you will not see the above network interface.
Client part
You may also ping the server to test it can be reached: ping 10.9.8.1.
Static-Key VPN connection
Static-Key VPN server configuration
In the server’s /etc/openvpn directory, run the following command to generate a static key:
Copy this static key to the clients /etc/openvpn directory using a secure channel like scp or sftp.
On the server, create a new /etc/openvpn/tun0.conf file and add the following:
Where 10.9.8.x is your VPN subnetwork, 10.9.8.1 will be IP of the server, 10.9.8.2 is IP of client.
Static-Key VPN client configuration
On the client, copy /etc/openvpn/static.key from server and create a new /etc/openvpn/tun0.conf file and add the following:
Start OpenVPN by hand on both sides with the following command (verbose output at 6):
To verify that the VPN is running, you should be able to ping 10.9.8.2 from the server and 10.9.8.1 from the client.
TLS-enabled VPN connection
Starting with Jessie, easy-rsa is a separate package that should be pulled along with openvpn installation.
Init easy-rsa
To initialize the environment, just use the following command:
All the commands that are run from the easy-rsa dir. Refer to ./easyrsa help for a detailed description of the available commands.
Remember:
- only .key files should be kept confidential.
- .crt and .csr files can be sent over insecure channels such as plaintext email.
- do not need to copy a .key file between computers.
- each computer will have its own certificate/key pair.
Generate CA CERTIFICATE/KEY
Generate CERTIFICATE/KEY of the CERTIFICATE AUTHORITY (CA):
It will generate ca.crt and ca.key in /etc/openvpn/easy-rsa/
Generate CERTIFICATE/KEY of the server:
It will generate server.crt and server.key in /etc/openvpn/easy-rsa/pki/
Generate DIFFIE-HELLMAN PARAMETERS
Generate BUILD DIFFIE-HELLMAN PARAMETERS (necessary for the server end of a SSL/TLS connection):
Generate Static Key for TLS authentication
If you already generated a static key, you may rename it to ta.key and move it to the /etc/openvpn/server folder. Else execute the following:
Generate CERTIFICATE/KEYs of the client(s)
Generate key for each client: Use one of the following two commands.
- You’ll be asked for «Enter PEM pass phrase», this is the passphrase you’ll need to login at the client.
Generate key with password (this protect the key and request the password every time that you connect to the server), for each client:
Install Client CERTIFICATE/KEYs
Copy the ca.crt, clientname.crt, clientname.key from Server to Client ‘s /etc/openvpn/easy-rsa/pki/
Check OpenVPN RSA Key for details.
VPN connection from command line
VPN Server configuration file
If the previous connection is successful, create the server configuration file /etc/openvpn/server.conf as follows:
Create log status file:
Note that the /etc/init.d/openvpn script launched by ‘service openvpn restart’ will start an openvpn server for every .conf file in /etc/openvpn/, so if you still have the tun0.conf file from above, rename it to something else than *.conf. This is because systemd wants only one openvpn server by default.
VPN Client configuration file
In client, create /etc/openvpn/client.conf as follows:
(note: you may use graphical vpn tool network-manager UI by providing the key and certificates)
VPN connection started as a Systemd service
At the root of /etc/openvpn/
By default, all configured VPNs in /etc/openvpn/ are started during system boot. Edit /etc/default/openvpn to start specific VPNs or to disable this behavior. You need to run systemctl daemon-reload once to enable new VPNs
in subfolders server and client
On Debian the systemd service expects the server and client configuration files to be, respectively, in /etc/openvpn/server and /etc/openvpn/client. Once you created the config file in the correct folder, you need to enable it. For example, suppose you created the configuration in /etc/openvpn/server/myserver.conf:
VPN connection started via interfaces file
openvpn ifupdown hooks are also available for starting/stopping tunnels using /etc/network/interfaces, e.g.:
See /usr/share/doc/openvpn/README.Debian.gz for more information.
Android / iOS devices certificate generation
OpenVPN Debian Server can be configured to use with Android / iOS devices.
on the Server
In Debian Server, create required certificates — we consider you installed via apt openvpn and created the easy-rsa folder as described above:
Modify below lines in /etc/openvpn/server.conf:
8.8.8.8 is Google DNS server. You may change to your preferred DNS server.
Test that the configuration works:
If it does, Ctrl-C out of this and restart OpenVPN server to use the new configuration:
Create client profile file /etc/openvpn/client.ovpn and attach certificates to it:
Modify below lines in client profile file /etc/openvpn/client.ovpn:
where ?YourServerIp and ?YourServerPort should be changed to your server. Three lines (#ca, #cert, #key) are commented as the required certificates were integrated into the ovpn file instead of being individual files.
e-mail or upload the client configuration file /etc/openvpn/$YOUR_CLIENT_NAME.ovpn to google drive in order to download to iPhone.
You’ll also want to run the server parts of the «Forward traffic via VPN» steps below.
on the Client
For iOS devices, install OpenVPN Connect client. Then transfer the client configuration file /etc/openvpn/$YOUR_CLIENT_NAME.ovpn to the device by e-mail or by Google Drive. Open the configuration file in Mail apps or Google Drive apps.
For Android devices, install OpenVPN Connect client. Then copy the client configuration file /etc/openvpn/$YOUR_CLIENT_NAME.ovpn to the storage of the device. Open the configuration file in OpenVPN apps.
Your phone OpenVPN client should take care of the client parts automatically.
Forward traffic to provide access to the Internet
on the Server
In Server enable runtime IP forwarding:
Edit /etc/sysctl.conf uncomment the following line to make it permanent:
Execute the following command in server for testing (Old way):
Execute the following command in server for testing (Starting with Bullseye):
You may also use the rc.firewall-iptables script from TLDP Masquerade as an alternative.
If everything is working fine, save the rules: Debian wiki iptables and nftables pages for details.
Manage the Public Key Infrastructure
?easy-rsa helps to manage the key of your PKI:
Generation of client & server certificates
More info here: /usr/share/doc/easy-rsa/doc
For security purpose, it is advised to set up the PKI in a different server that the openvpn server.
Application to a VPN passing through a http proxy
This part describe how to configure a VPN to pass through a http proxy, which allow only trafic on port 443 (and 80). This use the http-proxy option of OpenVPN.
- First of all, check that the port 443 isn’t already used by another service on your server.
Configure OpenVPN on server side by adding port 443 and proto tcp-server to the configuration file. This option works only with TCP as the tunnel carrier protocol
Configure OpenVPN on the client side by adding port 443, proto tcp-client and http-proxy 1.1.1.1 8080 to the configuration file.
Where 1.1.1.1 and 8080 are IP and port of your proxy.
- Now you should launch OpenVPN on the server and next on the client.
Enable and use the Management Interface
Enable the option in server conf file by adding:
Connect to this interface:
This is useful for authentication (http-proxy) or killing an open session. More info
Источник