OpenVPN

How can we help?

OpenVPN

Навигация
$sudo apt install openvpn easy-rsa

Чтение списков пакетов… Готово
Построение дерева зависимостей… Готово
Чтение информации о состоянии… Готово
Уже установлен пакет easy-rsa самой новой версии (3.0.8-1).
Предлагаемые пакеты:
  resolvconf openvpn-systemd-resolved
Следующие НОВЫЕ пакеты будут установлены:
  libpkcs11-helper1 openvpn
Обновлено 0 пакетов, установлено 2 новых пакетов, для удаления отмечено 0 пакетов, и 0 пакетов не обновлено.
Необходимо скачать 658 kB архивов.
После данной операции объём занятого дискового пространства возрастёт на 1 844 kB.
Пол:1 http://mirror-1.truenetwork.ru/kali kali-last-snapshot/main amd64 libpkcs11-helper1 amd64 1.28-1 [50,9 kB]
Пол:2 http://mirror-1.truenetwork.ru/kali kali-last-snapshot/main amd64 openvpn amd64 2.5.6-1 [607 kB]
Получено 658 kB за 3с (233 kB/s)
Предварительная настройка пакетов …
Выбор ранее не выбранного пакета libpkcs11-helper1:amd64.
(Чтение базы данных … на данный момент установлено 569233 файла и каталога.)
Подготовка к распаковке …/libpkcs11-helper1_1.28-1_amd64.deb …
Распаковывается libpkcs11-helper1:amd64 (1.28-1) …
Выбор ранее не выбранного пакета openvpn.
Подготовка к распаковке …/openvpn_2.5.6-1_amd64.deb …
Распаковывается openvpn (2.5.6-1) …
Настраивается пакет libpkcs11-helper1:amd64 (1.28-1) …
Настраивается пакет openvpn (2.5.6-1) …
update-rc.d: We have no instructions for the openvpn init script.
update-rc.d: It looks like a network service, we disable it.
openvpn.service is a disabled or a static unit not running, not starting it.
Обрабатываются триггеры для man-db (2.10.2-1) …
Обрабатываются триггеры для kali-menu (2022.2.0) …
Обрабатываются триггеры для libc-bin (2.33-6) …

В OpenVPN открытый ключ называется сертификатом и имеет расширение .crt, а закрытый ключ так и называется ключом, его расширение — .key. Для того чтобы после обновления системы все ваши сертификаты и настройки не были стёрты, надо скопировать набор скриптов:

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

Создаем центр сертификации:

$cd /etc/openvpn/easy-rsa/
$sudo ./easyrsa init-pki
init-pki complete; you may now create a CA or requests.
Your newly created PKI dir is: /etc/openvpn/easy-rsa/pki

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

$sudo ./easyrsa build-ca

Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.1.1n  15 Mar 2022

Enter New CA Key Passphrase:
Re-Enter New CA Key Passphrase:
read EC key
writing EC 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.
-----
Common Name (eg: your user, host, or server name) [Easy-RSA CA]:zamiloffVpnServ

CA creation complete and you may now import and sign cert requests.
Your new CA certificate file for publishing is at:
/etc/openvpn/easy-rsa/pki/ca.crt

Создаем ключи Диффи-Хафмана (создается файл ./pki/dh.pem):

$sudo ./easyrsa gen-dh
Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.1.1n  15 Mar 2022
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 /etc/openvpn/easy-rsa/pki/dh.pem

Создаем ключ Hash-based Message Authentication Code (HMAC), он используется для предотвращения DoS атаки при использовании протокола UDP (содается файл ./pki/ta.key)

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

Для отзыва подписанных сертификатов может понадобиться сертификат отзыва (создается файл ./pki/crl.pem):

$sudo ./easyrsa gen-crl
Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.1.1n  15 Mar 2022
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-69299.dWsof3/tmp.Zvhz64
Enter pass phrase for /etc/openvpn/easy-rsa/pki/private/ca.key:

An updated CRL has been created.
CRL file: /etc/openvpn/easy-rsa/pki/crl.pem

Содержимое каталога ./pki можно посмотреть так:

$sudo ls -l /etc/openvpn/easy-rsa/pki
итого 76
-rw------- 1 root root  765 июн  6 12:13 ca.crt
drwx------ 2 root root 4096 июн  6 13:40 certs_by_serial
-rw------- 1 root root  438 июн  6 13:37 crl.pem
-rw------- 1 root root  424 июн  6 12:13 dh.pem
drwx------ 2 root root 4096 июн  6 12:12 ecparams
-rw------- 1 root root   69 июн  6 13:40 index.txt
-rw------- 1 root root   20 июн  6 13:40 index.txt.attr
-rw------- 1 root root    0 июн  6 12:12 index.txt.attr.old
-rw------- 1 root root    0 июн  6 12:12 index.txt.old
drwx------ 2 root root 4096 июн  6 13:40 issued
-rw------- 1 root root 4616 июн  6 12:12 openssl-easyrsa.cnf
drwx------ 2 root root 4096 июн  6 13:40 private
drwx------ 5 root root 4096 июн  6 12:12 renewed
drwx------ 2 root root 4096 июн  6 13:40 reqs
drwx------ 5 root root 4096 июн  6 12:12 revoked
-rw------- 1 root root 4640 июн  6 12:12 safessl-easyrsa.cnf
-rw------- 1 root root   33 июн  6 13:40 serial
-rw------- 1 root root   33 июн  6 13:40 serial.old
-rw------- 1 root root  636 июн  6 12:28 ta.key

Создаем сертификаты, которые будут использоваться сервером, server — это имя нашего сервера, а опция nopass отключает использование пароля:

$sudo ./easyrsa build-server-full server nopass

Копируем ключи в папку /etc/openvpn:

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

Создаем конфигурационный файл, копируя пример:

$cat /usr/share/doc/openvpn/examples/sample-config-files/server.conf | sudo tee /etc/openvpn/server.conf

Далее правим конфиг:

$sudo nano /etc/openvpn/server.conf
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

Настройка завершена, запускаем сервер:

$sudo openvpn /etc/openvpn/server.conf
2022-06-06 13:51:59 WARNING: --topology net30 support for server configs with IPv4 pools will be removed in a future release. Please migrate to --topology subnet as soon as possible.
2022-06-06 13:51:59 DEPRECATED OPTION: --cipher set to 'AES-256-CBC' but missing in --data-ciphers (AES-256-GCM:AES-128-GCM). Future OpenVPN version will ignore --cipher for cipher negotiations. Add 'AES-256-CBC' to --data-ciphers or change --cipher 'AES-256-CBC' to --data-ciphers-fallback 'AES-256-CBC' to silence this warning.
2022-06-06 13:51:59 OpenVPN 2.5.6 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Mar 20 2022
2022-06-06 13:51:59 library versions: OpenSSL 1.1.1n  15 Mar 2022, LZO 2.10
2022-06-06 13:51:59 net_route_v4_best_gw query: dst 0.0.0.0
2022-06-06 13:51:59 net_route_v4_best_gw result: via 10.4.22.1 dev eth0
2022-06-06 13:51:59 Diffie-Hellman initialized with 2048 bit key
2022-06-06 13:51:59 Outgoing Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
2022-06-06 13:51:59 Incoming Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
2022-06-06 13:51:59 net_route_v4_best_gw query: dst 0.0.0.0
2022-06-06 13:51:59 net_route_v4_best_gw result: via 10.4.22.1 dev eth0
2022-06-06 13:51:59 ROUTE_GATEWAY 10.4.22.1/255.255.255.0 IFACE=eth0 HWADDR=8c:8c:aa:5f:f1:99
2022-06-06 13:51:59 TUN/TAP device tun0 opened
2022-06-06 13:51:59 net_iface_mtu_set: mtu 1500 for tun0
2022-06-06 13:51:59 net_iface_up: set tun0 up
2022-06-06 13:51:59 net_addr_ptp_v4_add: 10.8.0.1 peer 10.8.0.2 dev tun0
2022-06-06 13:51:59 net_route_v4_add: 10.8.0.0/24 via 10.8.0.2 dev [NULL] table 0 metric -1
2022-06-06 13:51:59 Could not determine IPv4/IPv6 protocol. Using AF_INET
2022-06-06 13:51:59 Socket Buffers: R=[212992->212992] S=[212992->212992]
2022-06-06 13:51:59 UDPv4 link local (bound): [AF_INET][undef]:1194
2022-06-06 13:51:59 UDPv4 link remote: [AF_UNSPEC]
2022-06-06 13:51:59 MULTI: multi_init called, r=256 v=256
2022-06-06 13:51:59 IFCONFIG POOL IPv4: base=10.8.0.4 size=62
2022-06-06 13:51:59 IFCONFIG POOL LIST
2022-06-06 13:51:59 Initialization Sequence Completed
^C2022-06-06 13:52:29 event_wait : Interrupted system call (code=4)
2022-06-06 13:52:31 net_route_v4_del: 10.8.0.0/24 via 10.8.0.2 dev [NULL] table 0 metric -1
2022-06-06 13:52:31 Closing TUN/TAP interface
2022-06-06 13:52:31 net_addr_ptp_v4_del: 10.8.0.1 dev tun0
^X2022-06-06 13:52:31 SIGINT[hard,] received, process exiting

Сообщение Initialization Sequence Completed говорит что всё хорошо, после чего останавливаем и запускаем сервер с помощью systemd:

$sudo systemctl stop openvpn@server.service
$sudo systemctl start openvpn@server

Для того чтобы OpenVPN сервер мог предоставить клиентам доступ к внешней сети сервера надо включить ip_forwarding:

$sysctl -w net.ipv4.ip_forward=1

Разрешаем прохождение пакетов в брандмауэре:

$ip -br a
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             10.4.22.27/24 fe80::8e8c:aaff:fe5f:f199/64
wlan0            DOWN
tun0             UNKNOWN        10.8.0.1 peer 10.8.0.2/32 fe80::57d2:e6f1:2611:b2d7/64

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

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

$sudo ./easyrsa build-client-full client1 nopass
Note: using Easy-RSA configuration from: /etc/openvpn/easy-rsa/vars
Using SSL: openssl OpenSSL 1.1.1n  15 Mar 2022
Generating an EC private key
writing new private key to '/etc/openvpn/easy-rsa/pki/easy-rsa-80161.LTUCBP/tmp.mPn7w4'
-----
Using configuration from /etc/openvpn/easy-rsa/pki/easy-rsa-80161.LTUCBP/tmp.evUN7o
Enter pass phrase for /etc/openvpn/easy-rsa/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:'client2'
Certificate is to be certified until Sep  8 11:05:00 2024 GMT (825 days)

Write out database with 1 new entries
Data Base Updated

Создадим папку для клиентских файлов и копируем их туда:

$sudo mkdir /etc/openvpn/clients/client1
$sudo cp /etc/openvpn/easy-rsa/pki/ca.crt /etc/openvpn/clients/client1
$sudo cp /etc/openvpn/easy-rsa/pki/ta.key /etc/openvpn/clients/client1
$sudo cp /etc/openvpn/easy-rsa/pki/issued/client1.crt /etc/openvpn/clients/client1
$sudo cp /etc/openvpn/easy-rsa/pki/private/client1.key /etc/openvpn/clients/client1

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

$cd /etc/openvpn/clients/client1
$sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ./client1.conf
$sudo nano client1.conf
client
dev tun
proto udp
remote 10.4.22.27 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

Далее переходим на клиента, генерируем SSH ключ:

$ssh-keygen

Generating public/private rsa key pair.
Enter file in which to save the key (/home/zamiloff/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/zamiloff/.ssh/id_rsa.
Your public key has been saved in /home/zamiloff/.ssh/id_rsa.pub.

$cat .ssh/id_rsa.pub

Копируем ключ и вставляем на серверной стороне, для этого логинимся под рутом:

$sudo -i
#cd
#pwd
/root
#mkdir  .ssh
#cat > .ssh/authorized_keys        //сюда вставляем ключ

#chmod 600 .ssh/authorized_keys
#exit

Возвращаемся на клиента и копируем файлы в текущую директорию с сервера и затем в /etc/openvpn/:

$ scp -r root@10.4.22.27:/etc/openvpn/clients/client1 ./
ca.crt
client1.key
client1.conf
client1.crt
ta.key
$ sudo cp -r client1 /etc/openvpn/
$ sudo ls /etc/openvpn/
ca.crt  client1.conf  client1.crt  client1.key  ta.key

Запускаем клиента:

$ sudo openvpn client1.conf
Mon Jun  6 19:42:02 2022 OpenVPN 2.4.4 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Mar 22 2022
Mon Jun  6 19:42:02 2022 library versions: OpenSSL 1.1.1  11 Sep 2018, LZO 2.08
Mon Jun  6 19:42:02 2022 Outgoing Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Mon Jun  6 19:42:02 2022 Incoming Control Channel Authentication: Using 160 bit message hash 'SHA1' for HMAC authentication
Mon Jun  6 19:42:02 2022 TCP/UDP: Preserving recently used remote address: [AF_INET]10.4.22.27:1194
Mon Jun  6 19:42:02 2022 Socket Buffers: R=[212992->212992] S=[212992->212992]
Mon Jun  6 19:42:02 2022 UDP link local: (not bound)
Mon Jun  6 19:42:02 2022 UDP link remote: [AF_INET]10.4.22.27:1194
Mon Jun  6 19:42:02 2022 TLS: Initial packet from [AF_INET]10.4.22.27:1194, sid=0e8cd2b9 bd8adda6
Mon Jun  6 19:42:02 2022 VERIFY OK: depth=1, CN=zamiloffVpnServ
Mon Jun  6 19:42:02 2022 VERIFY KU OK
Mon Jun  6 19:42:02 2022 Validating certificate extended key usage
Mon Jun  6 19:42:02 2022 ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
Mon Jun  6 19:42:02 2022 VERIFY EKU OK
Mon Jun  6 19:42:02 2022 VERIFY OK: depth=0, CN=server
Mon Jun  6 19:42:02 2022 Control Channel: TLSv1.3, cipher TLSv1.3 TLS_AES_256_GCM_SHA384, 384 bit EC, curve: secp384r1
Mon Jun  6 19:42:02 2022 [server] Peer Connection Initiated with [AF_INET]10.4.22.27:1194
Mon Jun  6 19:42:04 2022 SENT CONTROL [server]: 'PUSH_REQUEST' (status=1)
Mon Jun  6 19:42:04 2022 PUSH: Received control message: 'PUSH_REPLY,route 10.8.0.1,topology net30,ping 10,ping-restart 120,ifconfig 10.8.0.6 10.8.0.5,peer-id 0,cipher AES-256-GCM'
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: timers and/or timeouts modified
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: --ifconfig/up options modified
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: route options modified
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: peer-id set
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: adjusting link_mtu to 1624
Mon Jun  6 19:42:04 2022 OPTIONS IMPORT: data channel crypto options modified
Mon Jun  6 19:42:04 2022 Data Channel: using negotiated cipher 'AES-256-GCM'
Mon Jun  6 19:42:04 2022 Outgoing Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
Mon Jun  6 19:42:04 2022 Incoming Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
Mon Jun  6 19:42:04 2022 ROUTE_GATEWAY 10.7.39.193/255.255.255.192 IFACE=ens160 HWADDR=00:50:56:aa:c1:de
Mon Jun  6 19:42:04 2022 TUN/TAP device tun0 opened
Mon Jun  6 19:42:04 2022 TUN/TAP TX queue length set to 100
Mon Jun  6 19:42:04 2022 do_ifconfig, tt->did_ifconfig_ipv6_setup=0
Mon Jun  6 19:42:04 2022 /sbin/ip link set dev tun0 up mtu 1500
Mon Jun  6 19:42:04 2022 /sbin/ip addr add dev tun0 local 10.8.0.6 peer 10.8.0.5
Mon Jun  6 19:42:04 2022 /sbin/ip route add 10.8.0.1/32 via 10.8.0.5
Mon Jun  6 19:42:04 2022 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Mon Jun  6 19:42:04 2022 Initialization Sequence Completed

Проверяем коннект:

$ ping 10.8.0.1
PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
64 bytes from 10.8.0.1: icmp_seq=1 ttl=64 time=1.13 ms
64 bytes from 10.8.0.1: icmp_seq=2 ttl=64 time=1.17 ms
64 bytes from 10.8.0.1: icmp_seq=3 ttl=64 time=0.985 ms
^C