Faire un serveur openvpn très sécurisé

On commence par synchroniser les dépôts :

apt update

On installe le paquet openvpn :

apt install openvpn

Nous allons configurer le serveur openvpn dans un dossier temporaire afin que la publication dans /etc/openvpn soit la plus propre possible.

mkdir /tmp/openvpn

Nous nous rendons maintenant dans ce dossier :

cd /tmp/openvpn

À noter que EsayRSA sera utilisé dans ce tutoriel pour la génération des clés ainsi que des certificats. Pour ce faire, nous allons télécharger la dernière version de ce dernier disponible sur leur github : https://github.com/OpenVPN/easy-rsa/releases/ En date de ce tutoriel ce sera la version 3.0.7. On récupère donc la dernière archive :

wget https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.7/EasyRSA-3.0.7.tgz

Une fois l’archive récupérée, il suffira de la décompresser de la manière suivante :

tar -xvf EasyRSA-3.0.7.tgz

Nous nous délaçons maintenant dans notre nouveau répertoire :

cd EasyRSA-3.0.7

Nous allons maintenant éditer le fichier vars permettant de configurer la génération des clés et des certificats. Nous allons nous baser sur le fichier d’exemple, on en fait donc une copie :

cp vars.example vars

On peut peut maintenant passer à la configuration de ce fichier, nous l’éditons donc :

nano vars

Dans ce fichier, les arguments suivants doivent être dé-commentés et configuré de la manière suivante :

# Activation des courbes elliptiques
set_var EASYRSA_ALGO ec

# On définit la courbe à utiliser, recommendé : secp521r1 ou secp384r1
set_var EASYRSA_CURVE secp384r1

# On définit la durée de validité du certificat racine
set_var EASYRSA_CA_EXPIRE 3650
 
# On définit la durée de validité des certificats
set_var EASYRSA_CERT_EXPIRE 3650
 
# On définit le temps avant la vérification des certificats
set_var EASYRSA_CRL_DAYS 3650
 
# On définit l'algorithme de hachage
set_var EASYRSA_DIGEST "sha512"

On passe maintenant à la génération du répertoire pki là où vont se situer nos futures clés ainsi que nos futurs certificats :

./easyrsa init-pki

On génère le certificat racine, une passphrase sera demandée, on en choisit une avec de forts caractères, il faudra impérativement s’en souvenir et de la garder de manière confidentielle :

./easyrsa build-ca

On génère la clé serveur :

./easyrsa gen-req server nopass

On signe le certificat serveur grâce à notre fichier server.ca qui constitue l’autorité de certification et que nous avons crée précédemment :

./easyrsa sign-req server server nopass

Enfin nous générons le certificat ainsi que la clé de notre premier client :

./easyrsa build-client-full client

Nous allons passer à l’arborescence de notre serveur openvpn :

mkdir /tmp/openvpn/ccd/
mkdir /tmp/openvpn/server/
mkdir -p /tmp/openvpn/server/certificates
mkdir -p /tmp/openvpn/client/certificates
cp /tmp/openvpn/EasyRSA-3.0.7/pki/ca.crt /tmp/openvpn/server/certificates/
cp /tmp/openvpn/EasyRSA-3.0.7/pki/issued/server.crt /tmp/openvpn/server/certificates/
cp /tmp/openvpn/EasyRSA-3.0.7/pki/private/server.key /tmp/openvpn/server/certificates/
cp /tmp/openvpn/EasyRSA-3.0.7/pki/ca.crt /tmp/openvpn/client/certificates/
cp /tmp/openvpn/EasyRSA-3.0.7/pki/issued/client.crt /tmp/openvpn/client/certificates/
cp /tmp/openvpn/EasyRSA-3.0.7/pki/private/client.key /tmp/openvpn/client/certificates/

On génère la clé HMAC :

openvpn --genkey --secret /tmp/openvpn/client/certificates/ta.key

On génère le CRL (Certification Revocation List) :

./easyrsa gen-crl
cp /tmp/openvpn/EasyRSA-3.0.7/pki/crl.pem /tmp/openvpn/server/certificates/

On configure notre serveur openvpn avec le fichier server.conf, on l’édite :

nano /tmp/openvpn/server.conf

on y place ceci :

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

port 16843

# TCP or UDP server?
proto tcp
;proto udp

# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one.  On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
# ca keys/ca.crt
# cert keys/server.crt
# key keys/server.key  # This file should be kept secret

ca /etc/openvpn/server/certificates/ca.crt
cert /etc/openvpn/server/certificates/server.crt
key /etc/openvpn/server/certificates/server.key  # This file should be kept secret
#crl-verify /etc/openvpn/crl.pem
# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
# dh keys/dh.pem
dh none 
crl-verify /etc/openvpn/server/certificates/crl.pem
# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
topology subnet

# 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.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file.  If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0.  Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 192.168.1.248 255.255.255.0 192.168.1.249 192.168.1.253

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses.  You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
#push "route 192.168.99.0 255.255.255.0"


# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
#   iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN.  This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
#client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
#   ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients.  There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
#     group, and firewall the TUN/TAP interface
#     for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
#     modify the firewall in response to access
#     from different clients.  See man
#     page for more info on learn-address script.
;learn-address ./script

# 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"
#push "redirect-ipv6-gateway"
# 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 "redirect-gateway def1"
push "route-ipv6 2000::/3"
push "dhcp-option DNS 80.67.169.12"
push "dhcp-option DNS 80.67.169.40"

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names.  This is recommended
# only for testing purposes.  For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-crypt /etc/openvpn/client/certificates/ta.key 0 # This file is secret
tls-server

tls-version-min 1.2
tls-cipher TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256:TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384

#tls-version-min 1.3 # if openvpn >= 2.4.5
#tls-cipher TLS_CHACHA20_POLY1305_SHA256:TLS-AES-256-GCM-SHA384 # if openvpn >= 2.4.5 with TLSv1.3 
 
# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
auth SHA512
cipher AES-256-GCM
;cipher AES-256-CTR
;cipher BF-CBC        # Blowfish (default)
;cipher AES-128-CBC   # AES
;cipher DES-EDE3-CBC  # Triple-DES

# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# 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

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status 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 Files\OpenVPN\log" 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         /var/log/openvpn.log
log-append  /var/log/openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages.  At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20

On édite le fichier /etc/sysctl.d/99-sysctl.conf afin d’activer le suivi ipv4 et de désactiver le suivi ipv6

nano /etc/sysctl.d/99-sysctl.conf

On ajoute ceci en fin de fichier, attention à l’interface réseau, dans notre cas c’est eth0 :

net.ipv4.ip_forward = 1
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
net.ipv6.conf.eth0.disable_ipv6 = 1

On applique les changements avec la commande suivante :

sysctl -p

On copie maintenant toute notre configuration dans le vrai dossier openvpn :

cp /tmp/openvpn/server.conf /etc/openvpn/
cp -r /tmp/openvpn/server /etc/openvpn/
cp -r /tmp/openvpn/client /etc/openvpn/
cp -r /tmp/openvpn/ccd /etc/openvpn/
cp -r /tmp/openvpn/EasyRSA-3.0.7 /root/

On édite la configuration du service en gestion d’openvpn :

nano /etc/default/openvpn

Et on remplace AUTOSTART=”all” par AUTOSTART=”server”

On applique les changement de la manière suivante :

systemctl daemon-reload 

On peut maintenant démarrer le service openvpn :

systemctl start openvpn

Et on l’active de manière permanente :

systemctl enable openvpn

Pour une bonne gestion de pare-feu nous recommandons l’utilisation de netfilter-persistent.

apt install iptables iptables-persistent netfilter-persistent

On configure notre par-feux de la manière suivante pour notre serveur openvpn, on commence par l’ipv4 /etc/iptables/rules.v4 , on l’édite :

nano /etc/iptables/rules.v4

Ce fichier doit ressembler à ceci, attention à bien choisir la bonne interface réseau de votre serveur, dans notre cas c’est eth0:

*nat
:PREROUTING ACCEPT [20:740]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [3:218]
:POSTROUTING ACCEPT [3:218]
-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
COMMIT

*filter
:INPUT DROP [99:6428]
:OUTPUT ACCEPT [442:65826]
:FORWARD ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp --icmp-type 8 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# For SSH
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT

# For openvpn server
-A INPUT -i eth0 -p tcp -m tcp --dport 16843 -j ACCEPT
# or if your openvpn is in udp: 
#-A INPUT -i eth0 -p udp -m udp --dport 16843 -j ACCEPT

COMMIT

Maintenant on passe à la configuration ipv6 dont le fichier se situe ici /etc/iptables/rules.v6 , on l’édite :

nano /etc/iptables/rules.v6

Ce fichier doit ressembler à ceci :

*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
COMMIT

On redémarre le par-feux :

netfilter-persistent restart

Maintenant on peut faire un pack de tout les fichiers de connexion de notre premier client que nous avons fait au tout début :

cd /root
mkdir -p openvpn/client1
cp /root/EasyRSA-3.0.7/pki/ca.crt /root/openvpn/client1/
cp /root/EasyRSA-3.0.7/pki/issued/client.crt /root/openvpn/client1/
cp /root/EasyRSA-3.0.7/pki/private/client.key /root/openvpn/client1/
cp /etc/openvpn/client/certificates/ta.key /root/openvpn/client1/

On fait à notre client un fichier de configuration ovpn, attention à bien remplacer 0.0.0.0 par la vrai ipv4 public du serveur :

nano /root/openvpn/client1/client.ovpn

On y met ceci :

# Oui c'est un client et pas le serveur
client

# Oui on est sur un VPN Routé
dev tun

# Pour Windows xp seulement et il faut qu'il s'appelle MyTap sinon tu changes
;dev-node MyTap 

# en mode TCP
proto tcp

# On se connecte ici à openvpn
remote 0.0.0.0 16843

# Pas besoin de load balancing, ya qu'un seul serveur
;remote-random

# Réessaye à l'infini de se connecter, utile si problème réseau fréquent du client
resolv-retry infinite

# Pas besoin de bind sur port spécifique local
nobind

# A activer seulement si Linux
;user nobody
;group nobody

# Pour préserver le lien de connexion en cas d'inactivité
persist-key
persist-tun

#On passe pas par un proxy HTTP
;http-proxy-retry 
;http-proxy [proxy server] [proxy port #]

# Cela peut être utile de lui faire fermer sa gueule en cas d'instabilité de connexion
;mute-replay-warnings

# Les certificats clients avec leur chemin exact
ca ca.crt
cert client.crt
key client.key

# La clé TLS
#tls-auth ta.key 1
tls-crypt ta.key

tls-version-min 1.2
tls-cipher TLS-ECDHE-ECDSA-WITH-CHACHA20-POLY1305-SHA256:TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384

#tls-version-min 1.3 # if openvpn >= 2.4.5
#tls-cipher TLS_CHACHA20_POLY1305_SHA256:TLS-AES-256-GCM-SHA384 # if openvpn >= 2.4.5 with TLSv1.3 

# Auth en miaou 512
auth SHA512

# Le Cypher
cipher AES-256-GCM

# Compression OK
comp-lzo

# Verbosité
verb 3

# Inutile
;mute 20

On peut également fixer une ipv4 privée de manière fixe à notre client, pour ce faire on fait un fichier portant le non d’utilisateur du client dans le dossier ccd :

nano /etc/openvpn/ccd/client

Et on spécifie l’ip de la manière suivante :

ifconfig-push 10.8.0.10 255.255.255.0

Si on veut ajouter un deuxième client, on réutilise la technique suivante :

./easyrsa build-client-full client2

Le tutoriel est maintenant finit, n’hésitez pas dans les commentaires à faire part de vos erreurs si vous en avez, nous tacherons d’y apporter de l’aide.

Leave a Reply