Subscribe on YouTube

Установка OpenVPN сервера на CentOS 6

Настройка приватного VPN сервера на базе OpenVPN в CentOS 6

Проверяем наличие устройства tun

[root@dev-server /]# file /dev/net/tun
/dev/net/tun: character special

Установка EPEL-репозитория

yum install epel-release

Устанавливаем OpenVPN

Устанавливаем пакет openvpn из репозитория EPEL.

yum -y install openvpn easy-rsa

Добавляем в автозапуск

chkconfig openvpn on
Создаем файл конфигурации
cp /usr/share/doc/openvpn-2.3.6/sample/sample-config-files/server.conf /etc/openvpn/

Конфигурация OpenVPN

nano /etc/openvpn/server.conf

Указываем на каком IP будет работать OpenVPN сервер (тут 192.168.1.100 – внешний IP сервера):

# Which local IP address should OpenVPN
# listen on? (optional)
local 192.168.1.100

Задаём OpenVPN сеть

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.0.0.0 255.255.255.0

Передаём параметр клиентам, благодаря которому весь их трафик будет направляться через OpenVPN

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
push "redirect-gateway def1 bypass-dhcp"

Теперь зададим DNS-сервера для клиентов:

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses. CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
push "dhcp-option DNS 10.0.0.1"
push "dhcp-option DNS 8.8.8.8"

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

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
user nobody
group nobody

Меняем настройки логирования:

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status /var/log/openvpn-status.log
...
# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "Program FilesOpenVPNlog" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it. Use one
# or the other (but not both).
;log openvpn.log
log-append /var/log/openvpn.log

Все готово.
Сохраняем и выходим.

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

Для начала создадим директорию для сертификатов:

mkdir -p /etc/openvpn/easy-rsa/keys

Скопируем необходимые файлы:

cp -r /usr/share/easy-rsa/2.0/* /etc/openvpn/easy-rsa/

Для удобства отредактируем параметры, чтобы не вводить их при генерации сертификатов /etc/openvpn/easy-rsa/vars:

export KEY_COUNTRY="RU"
export KEY_PROVINCE="NW"
export KEY_CITY="Moscow"
export KEY_ORG="OrgName"
export KEY_EMAIL="me@myhost.mydomain"
export KEY_OU="MyOrganizationalUnit"
# X509 Subject Field
export KEY_NAME="EasyRSA"

Генерируем сертификаты

Переходим в созданную нами директорию для сертификатов

cd /etc/openvpn/easy-rsa

Перечитаем файл vars

# source ./vars
NOTE: If you run ./clean-all, I will be doing a rm -rf on /etc/openvpn/easy-rsa/keys

Удаляем старые ключи:

./clean-all

Создаём корневой сертификат:

./build-ca

После этого шага в каталоге /etc/openvpn/easy-rsa/keys появляются новые CA (Central Authority) сертификаты:

./build-ca
Generating a 2048 bit RSA private key
..................+++
..........................................................+++
writing new private key to 'ca.key'
-----
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.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [NW]:
Locality Name (eg, city) [Moscow]:
Organization Name (eg, company) [OrgName]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:
Common Name (eg, your name or your server's hostname) [server]:vpn.example.com
Name [EasyRSA]:
-rw-r--r--. 1 root root 1,8K Апр 21 15:43 ca.crt
-rw-------. 1 root root 1,7K Апр 21 15:43 ca.key

Далее создаём корневой сертификат для самого сервера:

./build-key-server server
Generating a 2048 bit RSA private key
.+++
...............................................................+++
writing new private key to 'server.key'
-----
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.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [NW]:
Locality Name (eg, city) [Moscow]:
Organization Name (eg, company) [OrgName]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:
Common Name (eg, your name or your server's hostname) [server]:vpn.example.com
Name [EasyRSA]:
Email Address [me@myhost.mydomain]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'NW'
localityName :PRINTABLE:'Moscow'
organizationName :PRINTABLE:'OrgName'
organizationalUnitName:PRINTABLE:'MyOrganizationalUnit'
commonName :PRINTABLE:'vpn.example.com'
name :PRINTABLE:'EasyRSA'
emailAddress :IA5STRING:'me@myhost.mydomain'
Certificate is to be certified until Apr 18 12:43:37 2025 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

Генерируем ключ Диффи-Хелмана (Diffie Hellman). Алгоритм Диффи-Хелмана позволяет получить двум сторонам общий секретный ключ, использующийся для дальнейшего симметричного шифрования данных:

./build-dh
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
..............................................+......+................................................+.........................................................................................................................................................+............................................................................................................+..............................................................................................................................................+...................................................................................................+........+.............................................................................................................+............

Процесс занимает от 2 до 5 минут. Можно выпить чашечку кофе.

Приступим к созданию клиентских сертификатов – повторяем отдельно для каждого клиента:

./build-key client
Generating a 2048 bit RSA private key
.....................................+++
..+++
writing new private key to 'client.key'
-----
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.
-----
Country Name (2 letter code) [RU]:
State or Province Name (full name) [NW]:
Locality Name (eg, city) [Moscow]:
Organization Name (eg, company) [OrgName]:
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:
Common Name (eg, your name or your server's hostname) [client]:
Name [EasyRSA]:
Email Address [me@myhost.mydomain]:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName :PRINTABLE:'RU'
stateOrProvinceName :PRINTABLE:'NW'
localityName :PRINTABLE:'Moscow'
organizationName :PRINTABLE:'OrgName'
organizationalUnitName:PRINTABLE:'MyOrganizationalUnit'
commonName :PRINTABLE:'client'
name :PRINTABLE:'EasyRSA'
emailAddress :IA5STRING:'me@myhost.mydomain'
Certificate is to be certified until Apr 18 12:57:59 2025 GMT (3650 days)
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

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

  • A challenge password []:
  • An optional company name []:

Скопируем ключи

ls -l /etc/openvpn/easy-rsa/keys
итого 84
-rw-r--r--. 1 root root 5669 Апр 21 15:43 01.pem
-rw-r--r--. 1 root root 5516 Апр 21 15:58 02.pem
-rw-r--r--. 1 root root 1830 Апр 21 15:43 ca.crt
-rw-------. 1 root root 1704 Апр 21 15:43 ca.key
-rw-r--r--. 1 root root 5516 Апр 21 15:58 client.crt
-rw-r--r--. 1 root root 1184 Апр 21 15:57 client.csr
-rw-------. 1 root root 1704 Апр 21 15:57 client.key
-rw-r--r--. 1 root root 424 Апр 21 15:46 dh2048.pem
-rw-r--r--. 1 root root 307 Апр 21 15:58 index.txt
-rw-r--r--. 1 root root 21 Апр 21 15:58 index.txt.attr
-rw-r--r--. 1 root root 21 Апр 21 15:43 index.txt.attr.old
-rw-r--r--. 1 root root 161 Апр 21 15:43 index.txt.old
-rw-r--r--. 1 root root 3 Апр 21 15:58 serial
-rw-r--r--. 1 root root 3 Апр 21 15:43 serial.old
-rw-r--r--. 1 root root 5669 Апр 21 15:43 server.crt
-rw-r--r--. 1 root root 1115 Апр 21 15:43 server.csr
-rw-------. 1 root root 1704 Апр 21 15:43 server.key
cd keys/
cp dh2048.pem ca.crt server.crt server.key /etc/openvpn

Настройка роутинга и запуск OpenVPN сервера

Добавим правила iptables

iptables -I INPUT 1 -p udp --dport 1194 -j ACCEPT
iptables -I FORWARD -i eth0 -o tun0 -j ACCEPT
iptables -I FORWARD -i tun0 -o eth0 -j ACCEPT
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j SNAT --to-source 192.168.1.100

Тут предполагается что внешний интерфейс – eth0 с IP 192.168.1.100, а сеть для клиентов OpenVPN10.0.0.0/24.

Предлагаю использовать MASQUERADE вместо SNAT.

iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
# service iptables status
...
Table: nat
Chain PREROUTING (policy ACCEPT)
num target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
num target prot opt source destination
1 SNAT all -- 10.0.0.0/24 0.0.0.0/0 to:192.168.2.100
2 SNAT all -- 10.0.0.0/24 0.0.0.0/0 to:192.168.2.100
3 MASQUERADE all -- 10.0.0.0/24 0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
Table: filter
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:1194
2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
3 ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0
4 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
5 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
6 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
3 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
4 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
5 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination

Теперь добавим IP Forwarding в ядро:

nano /etc/sysctl.conf

И изменим параметр net.ipv4.ip_forward с 0 на 1

# Controls IP packet forwarding
net.ipv4.ip_forward = 1

Перезагружаем настройки sysctl

sysctl -p /etc/sysctl.conf

Запускаем OpenVPN сервер:

# service openvpn start
Starting openvpn: [ OK ]

Проверяем лог-файл

# tail -f /var/log/openvpn.log
Tue Apr 21 16:02:06 2015 OpenVPN 2.3.6 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [MH] [IPv6] built on Dec 2 2014
Tue Apr 21 16:02:06 2015 library versions: OpenSSL 1.0.1e-fips 11 Feb 2013, LZO 2.03
Tue Apr 21 16:02:06 2015 Diffie-Hellman initialized with 2048 bit key
Tue Apr 21 16:02:06 2015 Socket Buffers: R=[124928->131072] S=[124928->131072]
Tue Apr 21 16:02:06 2015 ROUTE_GATEWAY XX.XX.XX.XX
Tue Apr 21 16:02:06 2015 TUN/TAP device tun0 opened
Tue Apr 21 16:02:06 2015 TUN/TAP TX queue length set to 100
Tue Apr 21 16:02:06 2015 do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
Tue Apr 21 16:02:06 2015 /sbin/ip link set dev tun0 up mtu 1500
Tue Apr 21 16:02:06 2015 /sbin/ip addr add dev tun0 local 10.0.0.1 peer 10.0.0.2
Tue Apr 21 16:02:06 2015 /sbin/ip route add 10.0.0.0/24 via 10.0.0.2
Tue Apr 21 16:02:06 2015 GID set to nobody
Tue Apr 21 16:02:06 2015 UID set to nobody
Tue Apr 21 16:02:06 2015 UDPv4 link local (bound): [AF_INET]192.168.2.100:1194
Tue Apr 21 16:02:06 2015 UDPv4 link remote: [undef]
Tue Apr 21 16:02:06 2015 MULTI: multi_init called, r=256 v=256
Tue Apr 21 16:02:06 2015 IFCONFIG POOL: base=10.0.0.4 size=62, ipv6=0
Tue Apr 21 16:02:06 2015 IFCONFIG POOL LIST
Tue Apr 21 16:02:06 2015 Initialization Sequence Completed
# ifconfig tun0
tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:10.0.0.1 P-t-P:10.0.0.2 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
RX packets:10368 errors:0 dropped:0 overruns:0 frame:0
TX packets:17505 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:100
RX bytes:2016895 (1.9 MiB) TX bytes:18911882 (18.0 MiB)
netstat -tupln | grep openvpn
udp 0 0 192.168.2.100:1194 0.0.0.0:* 11804/openvpn

Сервер запущен. Готово.

Настройка клиента осуществляется для каждой системы по-своему.
Не забываем скопировать клиентские сертификаты.

Поделиться Комментарии