Портал > База знаний > VPN > Настройка VPN с помощью OpenVPN
Это достаточно простой VPN-демон, не требующий специальных модулей ядра, в отличие от IPsec. Обмен данными происходит с помощью зашифрованных UDP-пакетов. Для доступа к трафику VPN в Linux используются специальные устройства tun и tap. Значительным достоинством OpenVPN является его сравнительно несложная конфигурация. OpenVPN работает в Linux, Windows и в различных UNIX-производных системах (Solaris, *BSD, Mac OS X).
Так как в основе идеи VPN лежит шифрование трафика, для его работы нам потребуются сертификаты.
Устанавливаем необходимые пакеты:
[root@centos]# yum install openvpn easy-rsa -y
После чего переходим в директорию /usr/share/easy-rsa/3 и создаем файл vars который будет содержать переменные:
[root@centos]# cd /usr/share/easy-rsa/3
[root@centos]# vi vars
* в качестве исходного файла можно взять пример из документации /usr/share/doc/easy-rsa-3.0.7/vars.example
Добавим в файл vars следующие строки:
export EASYRSA_REQ_COUNTRY="BY"
export EASYRSA_REQ_PROVINCE="Minsk"
export EASYRSA_REQ_CITY="Minsk"
export EASYRSA_REQ_ORG="technical support service"
export EASYRSA_REQ_EMAIL="info@support.by"
export EASYRSA_REQ_OU="support.by"
* где EASYRSA_REQ_ORG название вашей организации, EASYRSA_REQ_OU - рабочее подраздление (отдел), EASYRSA_REQ_NAME - DNS-адрес по которму буде выполнять подлкючение по VPN.
Прочитаем файл с переменными при помощи встроенной команды source из файла vars:
[root@centos 3]# . ./vars
Перед созданием сертификатов инициализируем PKI:
[root@centos 3]# ./easyrsa init-pki
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /usr/share/easy-rsa/3/pki
Об успешном выполнении инициализации свидетельствует следующая строка:
init-pki complete; you may now create a CA or requests.
А в текущей директории должна появиться директория pki.
[root@centos 3]# ls
easyrsa openssl-easyrsa.cnf pki vars x509-types
Генерируем корневой сертифкат - задаем пароль и подтверждаем его ввод, вводим имя сервера, например vpn.support.by
[root@centos 3]# ./easyrsa build-ca
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
Enter New CA Key Passphrase:
Re-Enter New CA Key Passphrase:
Generating RSA private key, 2048 bit long modulus
...........................................+++
.......................................................................................................+++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:vpn.support.by
CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/usr/share/easy-rsa/3/pki/ca.crt
После чего нам потребуется создать ключ Диффи-Хеллмана:
[root@centos 3]# ./easyrsa gen-dh
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
..............................................................................+............+...........................................................................................+....................................................................................................................................
+*++*
DH parameters of size 2048 created at /usr/share/easy-rsa/3/pki/dh.pem
Для создания сертификата сервера создаем файл запроса:
[root@centos 3]# ./easyrsa gen-req vpn-server nopass
* при использовании параметра nopass не запрашивается пароль при создании сертификата, в противном случае при каждом перазапуске OpenVPN будет спрашивать пароль.
При запросе ввода Common Name вводим имя VPN-сервера, например vpn.support.by:
[root@centos 3]# ./easyrsa gen-req vpn-server nopass
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
Generating a 2048 bit RSA private key
..................+++
....+++
writing new private key to '/usr/share/easy-rsa/3/pki/easy-rsa-2578.LfZwnL/tmp.l9zRQn'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [vpn-server]:vpn.support.by
Keypair and certificate request completed. Your files are:
req: /usr/share/easy-rsa/3/pki/reqs/vpn-server.req
key: /usr/share/easy-rsa/3/pki/private/vpn-server.key
Создаем и подписываем сертификат:
[root@centos 3]# ./easyrsa sign-req server vpn-server
После ввода команды подтверждаем правильность данных, введя yes и вводим пароль который указывали при создании корневого сертификата.
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.
Request subject, to be signed as a server certificate for 825 days:
subject=
commonName = vpn.support.by
Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes
Using configuration from /usr/share/easy-rsa/3/pki/easy-rsa-2605.z0AUZH/tmp.BvaU6V
Enter pass phrase for /usr/share/easy-rsa/3/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName :ASN.1 12:'vpn.support.by'
Certificate is to be certified until Nov 23 08:14:04 2022 GMT (825 days)
Write out database with 1 new entries
Data Base Updated
Certificate created at: /usr/share/easy-rsa/3/pki/issued/vpn-server.crt
Создаем ta ключ:
[root@centos 3]# openvpn --genkey --secret pki/ta.key
Сертификаты сервера готовы и находятся в директории pki:
[root@centos 3]# ls pki/
ca.crt dh.pem index.txt.attr index.txt.old openssl-easyrsa.cnf renewed revoked serial ta.key
certs_by_serial index.txt index.txt.attr.old issued private reqs safessl-easyrsa.cnf serial.old
Создаем директорию в /etc/openvpn, в которой будут храниться созданные сертификаты:
[root@centos 3]# mkdir /etc/openvpn/keys
Копируем в него содержимое директории pki:
[root@centos 3]# cp -r pki/* /etc/openvpn/keys/
Для настройки OpenVPN-сервера создаем конфигурационный файл со следующим содержимым:
[root@centos 3]# vi /etc/openvpn/server.conf
local 185.66.71.62
port 1194
proto udp
dev tun
ca keys/ca.crt
cert keys/issued/vpn-server.crt
key keys/private/vpn-server.key
dh keys/dh.pem
tls-auth keys/ta.key 0
server 172.16.10.0 255.255.255.0
ifconfig-pool-persist ipp.txt
keepalive 10 120
max-clients 32
client-to-client
persist-key
persist-tun
status /var/log/openvpn/openvpn-status.log
log-append /var/log/openvpn/openvpn.log
verb 0
mute 20
daemon
mode server
tls-server
comp-lzo
Где изменения нужно внести в параметр local - указать IP-адрес Вашего сервера VPN.
Создаем директорию для логов сервера:
[root@centos 3]# mkdir /var/log/openvpn
Добавляем OpenVPN в автозагрузку и запускаем его:
[root@centos 3]# systemctl enable openvpn@server
Created symlink from /etc/systemd/system/multi-user.target.wants/openvpn@server.service to /usr/lib/systemd/system/openvpn@.service.
[root@centos 3]# systemctl start openvpn@server
Для настройки OpenVPN клиента необходимо на сервере сгенерировать сертификаты, а на клиентском компьютере установить программу OpenVPN и настроить ее.
По прежнему все работы производим в директории /usr/share/easy-rsa/3. Создаем запрос на получение сертификата:
[root@centos 3]# ./easyrsa gen-req vpn_user_1 nopass
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
Generating a 2048 bit RSA private key
.....................................+++
.+++
writing new private key to '/usr/share/easy-rsa/3/pki/easy-rsa-2792.uTEMa8/tmp.yJpvkX'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Common Name (eg: your user, host, or server name) [vpn_user_1]:
Keypair and certificate request completed. Your files are:
req: /usr/share/easy-rsa/3/pki/reqs/vpn_user_1.req
key: /usr/share/easy-rsa/3/pki/private/vpn_user_1.key
* где аргумент vpn_user_1 имя нашего пользователя.
Создаем сертификат:
[root@centos 3]# ./easyrsa sign-req client vpn_user_1
Note: using Easy-RSA configuration from: /usr/share/easy-rsa/3.0.7/vars
Using SSL: openssl OpenSSL 1.0.2k-fips 26 Jan 2017
You are about to sign the following certificate.
Please check over the details shown below for accuracy. Note that this request
has not been cryptographically verified. Please be sure it came from a trusted
source or that you have verified the request checksum with the sender.
Request subject, to be signed as a client certificate for 825 days:
subject=
commonName = vpn_user_1
Type the word 'yes' to continue, or any other input to abort.
Confirm request details: yes
Using configuration from /usr/share/easy-rsa/3/pki/easy-rsa-2834.z3dvkO/tmp.s2ZbMS
Enter pass phrase for /usr/share/easy-rsa/3/pki/private/ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
commonName :ASN.1 12:'vpn_user_1'
Certificate is to be certified until Nov 23 08:36:32 2022 GMT (825 days)
Write out database with 1 new entries
Data Base Updated
Certificate created at: /usr/share/easy-rsa/3/pki/issued/vpn_user_1.crt
Как и при получении сертификата сервера, подтверждаем правильность данных и вводим пароль корневого сертификата. В данном примере мы создали сертификат для пользователя vpn_user_1.
После чего создадим директорию в которую скопируем сертификаты и ключи и в последствии передадим нашему пользователю:
[root@centos 3]# cp pki/issued/vpn_user_1.crt pki/private/vpn_user_1.key pki/dh.pem pki/ca.crt pki/ta.key vpn_user_1/
config.ovpn
В директории vpn_user_1 также создадим конфигурационный файл config.ovpn, который будет содержать все необходимые параметры для подключения:
[root@centos 3]# vi config.ovpn
client
resolv-retry infinite
nobind
remote 185.66.71.62 1194
proto udp
dev tun
comp-lzo
ca ca.crt
cert vpn_user_1.crt
key vpn_user_1.key
dh dh.pem
tls-client
tls-auth ta.key 1
float
keepalive 10 120
persist-key
persist-tun
verb 0
* где необходимо в параметре remote изменить IP-адрес на адрес VPN-сервера.
Теперь файлы из директории vpn_user_1 могут быть переданы пользователю для настройки подключения к VPN.
Так как наш сервер будет выступать в качестве маршрутизатора, включаем форвардинг пакетов в конфигурационном файле /etc/sysctl.conf. Для этого добавляем строку:
[root@centos]# vi /etc/sysctl.conf
net.ipv4.ip_forward = 1
Для вступления изменений в силу используем команду:
[root@centos]#sysctl -p
На CentOS 7 в качестве фаерволла используется по умолчанию firewalld, но можно его заменить iptables. Для этого установим пакет iptables:
[root@centos]# yum install iptables-services
Остановим firewalld и уберем его из автозапуска:
[root@centos]# systemctl stop firewalld
[root@centos]# systemctl disable firewalld
Добавим в автозапуск iptables и запустим его:
[root@centos]# systemctl enable iptables
[root@centos]# systemctl start iptables
Если ssh у Вас находится на нестандартном порту, то добавьте следующее правило заменим номер порта на свой:
[root@centos]# iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 52222 -j ACCEPT
Создаем правила iptables OpenVPN-сервера.
Разрешаем входящие подключения на порт 1194 OpenVPN-сервера по протоколу udp
[root@centos]# iptables -I INPUT -i ens192 -m state --state NEW -p udp --dport 1194 -j ACCEPT
Для того, чтобы OpenVPN-клиенты смогли общаться между собой дополнительно настраиваем iptables – цепочку FORWARD в таблице filter (если политика по умолчанию для цепочки FORWARD установлена в DROP):
[root@centos]# iptables -I FORWARD -i tun+ -j ACCEPT
[root@centos]# iptables -I FORWARD -i tun+ -o ens192 -m state --state RELATED,ESTABLISHED -j ACCEPT
[root@centos]# iptables -I FORWARD -i ens192 -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT
Настраиваем NAT для доступа к сети Интернет:
[root@centos]# iptables -t nat -A POSTROUTING -s 172.16.10.0/24 -o ens192 -j MASQUERADE
Разрешаем исходящий трафик на tun-интерфейсе:
[root@centos]# iptables -A OUTPUT -o tun+ -j ACCEPT
Не забываем сохранить правила iptables:
[root@centos 3]# service iptables save
На этом настройка VPN-сервера закончена, для добавления новых пользователей необходимо выполнить шаги по аналогии с получением сертификатов для пользователя vpn_user_1.
Добавить в избранное Распечатать статью
Powered by WHMCompleteSolution