openvpn - yar145/mytestrepo1 GitHub Wiki

OpenVPN Access Server system requirements

OpenVPN Access Server system requirements

On Red Hat Enterprise Linux 8, we advise you to remove the firewalld daemon

Almost all modern CPUs support AES-NI to speed up AES processing. Access Server automatically uses AES-NI for the default AES-256 encryption. A non-AES-NI CPU severely lowers the speed of the encryption/decryption process. As a very rough estimate, you should quadruple your estimates for CPU sizing if AES-NI is not supported on your intended deployment platform. As a rule of thumb, you should assume that on a modern CPU with an AES-NI chipset you need approximately** 12MHz for each megabit **per second (Mbps) transferred in one direction. Access Server can use all available CPU cores on a system, so for example a modern 4-core system at 3GHz would count as 12,000MHz, which equates to approximately 1,000Mbps maximum throughput.

For more than 10 users, calculate your maximum expected bandwidth in Mbps and choose an instance type accordingly: T-series is usually fine if less than 200Mbps total, and C-series is better if you need more.

going beyond the** C-series 2xlarge **type seems **pointless **because you would hit the bandwidth limit before you hit the CPU limit.

OpenVPN authentication against FreeIPA, SSSD

OpenVPN authentication against FreeIPA, SSSD

Configure OpenVPN LDAP Based Authentication

How to Create OpenLDAP Member Groups Therefore, to enable group membership authentication, set the value of the RequireGroup option to true and edit the group section such that you configuration may look like;

<LDAP> URL ldap://ldapmaster.kifarunix-demo.com BindDN cn=readonly,ou=system,dc=ldapmaster,dc=kifarunix-demo,dc=com Password P@ssW0rd Timeout 15 TLSEnable no FollowReferrals no </LDAP> <Authorization> BaseDN "ou=people,dc=ldapmaster,dc=kifarunix-demo,dc=com" SearchFilter "(uid=%u)" RequireGroup true <Group> BaseDN "ou=groups,dc=ldapmaster,dc=kifarunix-demo,dc=com" SearchFilter "memberOf=cn=vpnonly,ou=groups,dc=ldapmaster,dc=kifarunix-demo,dc=com" MemberAttribute uniqueMember </Group> </Authorization>

FreeIPA CA -- user certificates for OpenVPN server

Настройка сервиса OpenVPN + LDAP аутентификация


[root@ovpn2 server]# yum install openvpn-auth-ldap

-rwxr-xr-x. 1 root root 157880 окт 15 2021 /usr/lib64/openvpn/plugins/openvpn-auth-ldap.so

-rwxr-xr-x. 1 root root 16352 мар 25 22:53 /usr/lib64/openvpn/plugins/openvpn-plugin-auth-pam.so

-rwxr-xr-x. 1 root root 15848 мар 25 22:53 /usr/lib64/openvpn/plugins/openvpn-plugin-down-root.so

[root@ovpn2 server]# cp /etc/openvpn/auth/ldap.conf /etc/openvpn/auth/ldap.conf.old

[root@ovpn2 server]# cat /etc/pam.d/openvpn

#%PAM-1.0 auth sufficient pam_permit.so

account include system-auth


Instlallation OPENVPN

from here

How to Install OpenVPN Server and Client with Easy-RSA 3 on CentOS 8

How To Set Up and Configure an OpenVPN Server on CentOS 8

Detailed configuration server + client + config generation How To Set Up and Configure an OpenVPN Server on Ubuntu 22.04

OpenVPN

OpenVPN - Getting started How-To

Ubuntu/OpenVPN Server ( PAM and more )

Install and Configure OpenVPN Server on RHEL 8 / CentOS 8

2x HOW TO

2.3.1.9 Disabling Source/Dest Checking (Recommended) If your VPN setup consists of a site-to-site setup between your cloud instances and your machines on-premises, you will need to disable source destination check protection on Amazon, otherwise routing will not function properly. To do this, right click on the VPN instance, select Change Source/Dest. Check and make sure the status is Disabled. This setting must also be used if for for example want traffic from your VPC to go directly to the IP addresses of your VPN clients in the VPN client subnet or this security feature will block the traffic. 2.3.1.10 Setup static routes By default, the OpenVPN Access Server gives VPN clients access to your VPC by using the NAT method (Network Address Translation). Using this method, traffic originating from the VPN clients will appear to be coming from the local IP address of the Access Server. For that reason, routing is not necessary and is much easier to implement. However, one drawback of using such method is that traffic from the VPC itself cannot directly access a VPN client as the NAT engine prevents such direct contact. In order to allow a VPN client to be directly addressable via the VPC, you will need to configure the Access Server to use the routing method instead of NAT. Once that is done, the source IP address of packets coming from the VPN 27 clients is kept intact, and direct access from the VPC network to the VPN client subnet is then possible. However, because the VPC does not automatically recognize the VPN subnet within the VPN instance, it does not know how to send the return traffic back to the instance. To correct this problem, you will need to add a static route in the Amazon routing table for your VPC so that the return traffic flows properly. To learn how to do this see this document on Amazon AWS VPC routing: https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html

Mobile device

Mobile device only

Configure OpenVPN to block clients by OS?

P0f sophisticated, purely passive traffic fingerprinting mechanisms

nfnl_osf - load and unload os fingerprint database

Особенности конфигурирования openvpn

# auth-user-pass-verify

script-security 2

auth-user-pass-verify /etc/openvpn/server/envprinter via-env

# does not work with uncommented

_#user nobody_

_#group nobody_

cat **envprinter **

#!/bin/bash

echo "common name is: ${common_name}"

echo "username is: ${username}"

set

exit 0

log from server

common name is: yaruser

username is:

_='username is: '

common_name=yaruser

config=server.conf

daemon=0 daemon_log_redirect=1 daemon_pid=3533 daemon_start_time=1652358974 dev=tun0 dev_type=tun ifconfig_local=172.28.0.1 ifconfig_remote=172.28.0.2 link_mtu=1621 local_port_1=1194 proto_1=udp redirect_gateway=0 remote_port_1=1194 route_gateway_1=172.28.0.2 route_net_gateway=172.31.0.1 route_netmask_1=255.255.255.0 route_network_1=172.28.0.0 route_vpn_gateway=172.28.0.2 script_context=init script_type=user-pass-verify tls_digest_0=37:17:48:ce:f3:fe:64:ee:fa:4d:f8:e4:01:45:a3:e0:8b:bf:49:42 tls_digest_1=43:53:a6:37:c9:9a:02:0c:30:de:4c:80:37:b0:78:7b:e7:1a:90:51 tls_digest_sha256_0=aa:16:2b:40:9a:f7:ab:3a:6e:69:7c:18:46:a3:19:84:67:25:98:58:eb:c9:20:5d:97:24:32:2f:93:bb:f8:17 tls_digest_sha256_1=8e:95:43:b2:84:ac:36:13:ec:d1:ec:aa:68:e4:18:3e:9f:6a:99:ca:81:07:fc:ed:e2:e7:b3:6f:0f:ae:22:1c tls_id_0='O=TUTON.CF, CN=yaruser' tls_id_1='O=TUTON.CF, CN=Certificate Authority' tls_serial_0=19 tls_serial_1=1 tls_serial_hex_0=13 tls_serial_hex_1=01 tun_mtu=1500 untrusted_ip=91.203.114.1 untrusted_port=43832 username= verb=4

Интересные параметры:

--push-peer-info на стороне клиента peer info: IV_HWADDR=10:51:07:60:43:f2
peer info: IV_PLAT=linux --duplicate-cn Allow multiple clients with the same common name to concurrently connect. In the absence of this option, OpenVPN will disconnect a client instance upon connection of a new client having the same common name. --auth --tls-verify cmd Run command cmd to verify the X509 name of a pending TLS connection that has otherwise passed all other tests of certification (except for revocation via --crl-verify directive; the revocation test occurs after --x509-username-field [ext:]fieldname Field in the X.509 certificate subject to be used as the username (default=CN). Typically, this option is specified with fieldname as either of the following:

          --x509-username-field emailAddress
          --x509-username-field ext:subjectAltName
        the --tls-verify test).-user-pass-verify cmd method

--x509-track attribute Save peer X509 attribute value in environment for use by plugins and management interface. Prepend a '+' to attribute to save values from full cert chain. Values will be encoded as X509__=. Multiple --x509-track options can be defined to track multiple attributes. --remote-cert-tls client|server --remote-cert-eku oid Require that peer certificate was signed with an explicit extended key usage. --crl-verify crl ['dir'] Check peer certificate against the file crl in PEM format

Management Interface

Management Interface

Openvpn client

Enable IP forwarding

sysctl -w net.ipv4.ip_forward=1

sysctl -p

check: systemctl status sysctl , iptables -L -v -n

problem with ermission to start --up script

less /etc/selinux/config

setenforce Permissive

up script: iptables -t nat -A POSTROUTING -o $1 -j MASQUERADE

down script: iptables -t nat -D POSTROUTING -o $1 -j MASQUERADE

to check: iptables -L -t nat -nv

iptables

OpenVPN: Настройка на собственном сервере. Часть 3 — iptables

How to configure iptables for openvpn

cat ** /etc/sysconfig/iptables**

:INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0]

-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p icmp -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

#-yar accept openvpn clients -I INPUT -i eth0 -m state --state NEW -p udp --dport 1194 -j ACCEPT

-A INPUT -j REJECT --reject-with icmp-host-prohibited

#-yar forwarding from tun to eth0 -I FORWARD -i tun+ -j ACCEPT
-I FORWARD -i tun+ -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-I FORWARD -i eth0 -o tun+ -m state --state RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -j REJECT --reject-with icmp-host-prohibited #allow output to tun -A OUTPUT -o tun+ -j ACCEPT COMMIT

# openvpn-client@service

root@ovpn2 client: cat up-actions

#!/bin/sh /bin/sudo /sbin/iptables -t nat -A POSTROUTING -o $1 -j MASQUERADE

#publish some server

/bin/sudo /sbin/iptables -A PREROUTING -t nat -p tcp -m tcp -i $1 --dport 8443 -j DNAT --to-destination 172.30.0.10:443 /bin/sudo /sbin/iptables -I FORWARD -i $1 -m state -p tcp -d 172.30.0.10 --dport 443 --state NEW,ESTABLISHED,RELATED -j ACCEPT

/bin/sudo /sbin/ip route add 10.100.0.0/16 via $5

enabling daemons

systemctl enable openvpn-client@ systemctl enable openvpn-server@

systemctl start openvpn-server@service systemctl start openvpn-client@service

update-systemd-resolved

update-systemd-resolved

$ resolvectl status

2FA

How to configure OpenVPN multiple authentication method?

openvpn-multi-authentication-plugin

Troubleshutting

Client does not reconnect after server is restarted

[https://forums.openvpn.net/viewtopic.php?t=22873](Client does not reconnect after server is restarted)

EG: If the connection times out for some unknown problem then the client will exit with a fatal error if you use --user/group nobody/nogroup but not --persist-tun/key.

I would recommend that you do not use --user/group nobody/nogroup & --persist-tun/key on the client until you are more familiar with how they interact with the other parts of openvpn ..

PUSH_REQUEST_INTERVAL

Small delay on authentication. #14

works like this:

Client -> Sends auth details. Server -> Server initiates the deferred auth mechanism (creates auth_control_file) and moves on. Client -> Sends PUSH_REQUEST to check status on the auth. Server checks the auth_control_file and if its updated by the background process sends the auth status to client (success or failed). Otherwise doesn't reply anything and moves on (just like the step 2). If client gets the auth status = all good. Otherwise client waits for PUSH_REQUEST_INTERVAL (by default 5 seconds in src/openvpn/common.h) and sends another PUSH_REQUEST (back to step 3). So as you can see the delay on re-checking the auth status is determined by the client OpenVPN and not the server which does it only when the client asks for it. If the background process updates the auth_control_file by the time client sends the first PUSH_REQUEST, the authentication is almost instantaneous.

OpenVPN Server + Monitoring on Ubuntu 20.04

Упражнения с OpenVPN ... Если мы хотим использовать собственные скрипты "auth-user-pass-verify" и/или "client-connect", то нужно предусмотреть RAMFS-раздел для обмена файлами между процессом OpenVPN и этими скриптами. Например, лично я в "/etc/fstab" прописываю:

tmpfs /mnt/ovpn tmpfs nodev,nosuid,size=12M,uid=998,gid=998,mode=700 0 0 Много места там не нужно: файлики совсем крохотные и удаляются автоматически сразу как только отработает скрипт. Так что 12 мегабайт — это прям по-царски, за глаза хватило бы и одного.

Последний раз я всерьёз настраивал OpenVPN примерно в 2018-м году. С тех пор зарелизилась в качестве стабильной версия уже 2.5.4. В составе которой появилось множество вкусных фич, включая (но не ограничиваясь):

поддержку ED25519-подписей в X509-сертификатах;

механизм TLS-crypt-v2, который в числе прочего иногда помогает обходить некоторые DPI;

management-интерфейс через UNIX-сокет, а не через TCP;

TLS 1.3;

драйвер WinTUN для шиндошс (windows).

Теперь понадобилось снова взять эту шашку в руки. При этом в качестве "отягчающего" вводного появилось требование дополнительно проверять аккаунты пользователей об виндовую Active Directory дабы выяснить не уволился ли пациент, на имя которого был выписан X509-сертификат. А ещё меня с прошлых инсталляций забодала необходимость лапами назначать внутренние IP-адреса пользователям. Особенно когда поднимаешь на сервере параллельно два инстанса: UDPшный и TCPшный. Так что я решил этот процесс несколько автоматизировать.

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

... В стандартном Debian-овском EasyRSA файлик "vars" надо класть в "/usr/share/easy-rsa/". Тогда не надо проводить никаких дополнительных манипуляций для того, чтобы его потом "подцепить" из скриптов.

... Если хочется ED25519-подписи, то в этом самом "vars" надо выставлять "EASYRSA_ALGO=ed" и "EASYRSA_CURVE="ed25519". Только еще помнить при этом, что OpenVPN ниже чем 2.5 в эти алгоритмы не умеет.

... Ключи для TLS-crypt-v2 проще всего генерировать при помощи самого бинарника OpenVPN: "openvpn --genkey tls-crypt-v2-server" и "openvpn --tls-crypt-v2 server.key --genkey tls-crypt-v2-client" для серверного и клиентского соответственно. Оно выплюнет их на стандартный вывод. Серверный один на всех, клиентский у каждого может быть (и лучше если) свой.

... Лично я в качестве common name сертификата использую строку типа "002-v.pupkin", где сначала идет трехзначное число от 002 до 254, которое по совместительству является последним октетом внутреннего IP-адреса. А после дефиса sAMAccountName (логин) этого же пользователя в Active Directory (AD). Таким образом, в этом common name одновременно кодируется и IP-адрес, и AD-идентификатор пользователя.

... Если мы пишем в конфиг директиву "mlock", то одновременно с этим нужно либо отказаться от сброса привилегий и пускать демон от рута. Либо заранее в systemd предусмотреть "LimitMEMLOCK=128M" (например). Иначе процесс OpenVPN вывалится в Out-of-Memory при попытке подключения первого же клиента. И это не баг.

... Если мы хотим использовать собственные скрипты "auth-user-pass-verify" и/или "client-connect", то нужно предусмотреть RAMFS-раздел для обмена файлами между процессом OpenVPN и этими скриптами. Например, лично я в "/etc/fstab" прописываю:

tmpfs /mnt/ovpn tmpfs nodev,nosuid,size=12M,uid=998,gid=998,mode=700 0 0 Много места там не нужно: файлики совсем крохотные и удаляются автоматически сразу как только отработает скрипт. Так что 12 мегабайт — это прям по-царски, за глаза хватило бы и одного.

Мой конфиг сервера выглядит примерно следующим образом.

dev tun local 11.11.121.212 topology subnet proto udp4 server 192.168.1.0 255.255.255.0 keepalive 15 45 dh none cipher AES-256-GCM tls-version-min 1.3 tls-ciphersuites TLS_AES_256_GCM_SHA384 remote-cert-tls client

client-config-dir /etc/openvpn/ccd client-connect /etc/openvpn/scripts/on-connect auth-user-pass-verify /etc/openvpn/scripts/on-auth via-file auth-user-pass-optional tmp-dir /mnt/ovpn script-security 2

persist-tun persist-key sndbuf 0 rcvbuf 0 fast-io mlock

log-append /var/log/openvpn/udp-2022.log verb 2 user openvpn group openvpn management /run/openvpn-server/udp-server.sock unix

push "topology subnet" push "dhcp-option DNS 192.168.2.3" push "dhcp-option DNS 192.168.3.4"

-----BEGIN CERTIFICATE----- Тута корневой сертификат -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- Тута сертификат сервера -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- Тута закрытый ключ сервера -----END PRIVATE KEY----- -----BEGIN OpenVPN tls-crypt-v2 server key----- Тута TLS-crypt ключ сервера -----END OpenVPN tls-crypt-v2 server key-----

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

Формально, я бы мог проводить проверку пользователя в скрипте "on-connect" и не вводить дополнительную сущность для авторизации. Но это было бы не совсем правильно с идеологической точки зрения, хотя работать будет и так, и сяк. Поскольку я аутентифицирую пользователя в скрипте прямо по common name, то мне не нужно требовать от клиента дополнительного логина-пароля. Поэтому "auth-user-pass-optional".

Далее. В качестве скрипта аутентификации я использую банальный bash. Вот так:

#!/bin/bash

LDAP_AGENT="бла-бла-бла" LDAP_PASS="бла-бла-бла" LDAP_SRV="192.168.2.2" BASE="OU=Супер,OU=подразделение,OU=foo,DC=bar" NAME=${common_name:4} LDAP_SEARCHFILTER="(&(objectClass=organizationalPerson)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(objectClass=user)(memberOf=CN=VPN,OU=VPN,OU=foo,DC=bar)(sAMAccountName=${NAME}))" CAN_BYPASS_LDAP="v.pupkin v.batareikin"

$CAN_BYPASS_LDAP =~ (^)$NAME($|:space:) ]] && exit 0

/usr/bin/ldapsearch -LLL -h "${LDAP_SRV}" -x -D "${LDAP_AGENT}" -w "${LDAP_PASS}" -E pr=1000/noprompt -b "${BASE}" "${LDAP_SEARCHFILTER}" dn | /usr/bin/grep -q ^dn:

Скрипт лезет на LDAP-сервер имени M$ AD и проверяет есть ли там пользователь с таким логином (если отбросить первые четыре символа), входит ли он в группу "VPN" и не заблокирован ли. Если таковой находится, то grep по dn выдает код возврата ноль и OpenVPN понимает, что аутентификация успешно пройдена. Сисадминам по имени Вася Пупкин и Витя Батарейкин позволяется обходить проверку в LDAP на случай, если контроллер домена вдруг упадет (а чинить-то иначе как без доступа в сеть?).

В качестве скрипта "on-connect" я тоже использую bash. Он по сути занимается только тем, что раздает IP-адреса, больше ничем.

#!/bin/bash

umask 077

LAST_OCTET=${common_name:0:3} $LAST_OCTET =~ ^[0-9]+$ || exit 1 echo "$ifconfig_local" | /usr/bin/awk -v oct="$LAST_OCTET" -F'.' '{print "ifconfig-push "$1"."$2"."$3"."oct+0" 255.255.255.0"}' > $1

exit 0

Тут наоборот, берем первые три символа из common name, проверяем число ли это (на всякий случай) и суём OpenVPN-у в ответ в качестве "ifconfig-push". При этом неважно, в который из инстансов зацепился пользователь, т.к. подсеть будет взята из переменной окружения "$ifconfig_local".

Еще стоит отметить, что OpenVPN построен по однопоточной архитектуре. Поэтому если скрипты будут слишком сильно тупить, то это отразится на работе всех остальных пользователей в виде неприемлемого jitter-а. Но пока клиентов не шибко много (компания не масштабов Яндекса), то "и так сойдёт". В противном же случае понадобится менять bash на python или golang, а аккаунты таскать не напрямую из LDAP-а, а из локального периодически синхронизируемого с LDAP-ом кеша в оперативной памяти.

⚠️ **GitHub.com Fallback** ⚠️