6.14 Installation and configuration of the OpenVPN server
OpenVPN is reliable open-source software for creating secure VPN tunnels. It allows secure data transmission through public networks by encrypting all traffic.
Using a VPN server provides the ability to securely connect to corporate networks remotely, bypass geographical restrictions, and protect personal data when working through public Wi-Fi networks.
Today, OpenVPN is considered one of the most secure VPN solutions due to its use of reliable encryption algorithms and open source code that is continuously reviewed by the community.
Important: before starting installation, make sure You have the following privileges:
- You have root access to the server.
- Your server has a static IP address.
- Required ports are open on the server (UDP 1194 by default).
- The system is updated to the latest version.
Installation Procedure
The OpenVPN installation process depends on the operating system. Before starting installation, it’s important to ensure that the system meets all necessary requirements and has sufficient resources for stable VPN server operation.
OpenVPN installation includes not only copying files but also configuring system security, creating certificates, and setting up network parameters. It’s important to perform all steps sequentially and carefully, as errors at this stage can lead to security or server functionality issues.
Installation on Debian/Ubuntu:
- System update:
- sudo apt update && sudo apt upgrade -y
- Installing OpenVPN and easy-rsa utility:
- sudo apt install openvpn easy-rsa -y
- PKI setup:
- mkdir -p /etc/openvpn/server/certs
- cd /etc/openvpn/server
- cp -r /usr/share/easy-rsa .
- cd easy-rsa
Installation on CentOS/AlmaLinux/RockyLinux:
- System update:
- sudo yum update -y
- Adding EPEL repository:
- sudo yum install epel-release -y
- Installing OpenVPN:
- sudo yum install openvpn easy-rsa -y
- Preparing directories:
- mkdir -p /etc/openvpn/server/certs
- cd /etc/openvpn/server
- cp -r /usr/share/easy-rsa .
- cd easy-rsa
PKI and Certificate Preparation
Public Key Infrastructure (PKI) is a critically important component of OpenVPN security. It provides creation and management of digital certificates used for authentication and connection encryption. Easy-RSA is a PKI management utility that allows easy creation of certificates for servers and clients.
During PKI setup, the following are created:
- Root certificate (CA) for signing other certificates
- Server certificate and private key
- Diffie-Hellman parameters for secure key exchange
- Additional TLS key for DOS attack protection
Execute the following commands in sequence. During execution, one of the following actions may occur:
- Action confirmation. If a confirmation prompt appears, enter
yes
and press Enter. - Password entry. Some commands may require a password. Remember that during password entry, characters are not displayed in the console. Simply enter the password and press
Enter
. - Username or
commonName
request. In some cases, the system may request a username or commonName value. This can be the server or client name. Enter the desired value (for example, server for the server or client1 for the client) and pressEnter
.
- ./easyrsa init-pki
- ./easyrsa build-ca nopass
- ./easyrsa gen-req server nopass
- ./easyrsa sign-req server server
- ./easyrsa gen-dh
- openvpn --genkey secret ta.key
Server Configuration
This stage includes creating the main OpenVPN configuration file, which defines server operation parameters, including protocol, port, encryption and authentication methods, as well as network settings for clients.
Creating basic configuration:
- cat > /etc/openvpn/server/server.conf << EOF
- port 1194
- proto udp
- dev tun
- ca easy-rsa/pki/ca.crt
- cert easy-rsa/pki/issued/server.crt
- key easy-rsa/pki/private/server.key
- dh easy-rsa/pki/dh.pem
- tls-auth easy-rsa/ta.key 0
- server 10.8.0.0 255.255.255.0
- push "redirect-gateway def1 bypass-dhcp"
- push "dhcp-option DNS 8.8.8.8"
- push "dhcp-option DNS 8.8.4.4"
- keepalive 10 120
- cipher AES-256-GCM
- auth SHA256
- user nobody
- group nogroup
- persist-key
- persist-tun
- status openvpn-status.log
- verb 3
- EOF
Next, we prepare the operating system for working with the VPN server, including IP forwarding configuration, which allows packet transmission between different network interfaces, which is necessary for VPN functionality.
Enabling IP forwarding (for all OS):
- echo 'net.ipv4.ip_forward=1' > /etc/sysctl.d/99-openvpn.conf
- sysctl --system
Firewall Configuration
Firewall configuration includes creating rules for filtering incoming and outgoing traffic, setting up NAT (Network Address Translation) to provide client access to external resources, and configuring traffic routing between different network interfaces.
In this section, we’ll look at configuring different types of firewalls, including traditional iptables, UFW (Uncomplicated Firewall) for Ubuntu/Debian, and firewalld for CentOS. Each of these tools has its own features and advantages, so the choice of a specific solution depends on Your needs and administration experience.
Iptables Configuration:
Important: replace eth0
with Your actual network interface.
# Clearing existing rules
iptables -F
iptables -X
iptables -t nat -F
# Setting basic policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allowing local traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allowing established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allowing SSH (port 22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allowing OpenVPN (port 1194 UDP)
iptables -A INPUT -p udp --dport 1194 -j ACCEPT
- NAT and forwarding configuration:
# Determining external interface
INTERFACE=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)')
# NAT configuration
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o $INTERFACE -j MASQUERADE
# Forwarding configuration
iptables -A FORWARD -i tun0 -j ACCEPT
iptables -A FORWARD -i $INTERFACE -o tun0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i tun0 -o $INTERFACE -j ACCEPT
- Saving Iptables rules.
For Debian/Ubuntu:
- sudo apt install iptables-persistent -y
- netfilter-persistent save
- netfilter-persistent reload
For CentOS/AlmaLinux/RockyLinux:
- service iptables save
- /etc/init.d/iptables restart
UFW on Ubuntu/Debian:
- UFW Configuration:
- ufw default deny incoming
- ufw default allow outgoing
- ufw allow ssh
- ufw allow 1194/udp
- ufw allow from 10.8.0.0/24
- Forwarding configuration:
- echo 'net.ipv4.ip_forward=1' >> /etc/ufw/sysctl.conf
- echo '*nat' >> /etc/ufw/before.rules
- echo ':POSTROUTING ACCEPT [0:0]' >> /etc/ufw/before.rules
- echo '-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE' >> /etc/ufw/before.rules
- echo 'COMMIT' >> /etc/ufw/before.rules
-
- ufw enable
Firewalld on CentOS/AlmaLinux/RockyLinux:
- Basic settings:
- firewall-cmd --permanent --add-service=openvpn
- firewall-cmd --permanent --add-port=1194/udp
- firewall-cmd --permanent --add-masquerade
- Forwarding configuration:
- firewall-cmd --permanent --direct --passthrough ipv4 -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
- Applying changes:
- firewall-cmd --reload
Client Certificate Generation
- Generating certificates for the client:
- cd /etc/openvpn/server/easy-rsa
- ./easyrsa gen-req client1 nopass
- ./easyrsa sign-req client client1
- Creating client configuration:
- mkdir -p /etc/openvpn/client
- cat > /etc/openvpn/client/client.ovpn << EOF
- client
- dev tun
- proto udp
- remote YOUR_SERVER_IP 1194
- resolv-retry infinite
- nobind
- persist-key
- persist-tun
- remote-cert-tls server
- cipher AES-256-GCM
- auth SHA256
- key-direction 1
- verb 3
- EOF
- Adding certificates to configuration:
- echo "<ca>" >> /etc/openvpn/client/client.ovpn
- cat pki/ca.crt >> /etc/openvpn/client/client.ovpn
- echo "</ca>" >> /etc/openvpn/client/client.ovpn
-
- echo "<cert>" >> /etc/openvpn/client/client.ovpn
- cat pki/issued/client1.crt >> /etc/openvpn/client/client.ovpn
- echo "</cert>" >> /etc/openvpn/client/client.ovpn
-
- echo "<key>" >> /etc/openvpn/client/client.ovpn
- cat pki/private/client1.key >> /etc/openvpn/client/client.ovpn
- echo "</key>" >> /etc/openvpn/client/client.ovpn
-
- echo "<tls-auth>" >> /etc/openvpn/client/client.ovpn
- cat ta.key >> /etc/openvpn/client/client.ovpn
- echo "</tls-auth>" >> /etc/openvpn/client/client.ovpn
Starting the Server
For Debian/Ubuntu:
- systemctl enable openvpn-server@server
- systemctl start openvpn-server@server
For CentOS/AlmaLinux/RockyLinux:
- systemctl enable openvpn@server
- systemctl start openvpn@server
Information: how to check service status:
- systemctl status openvpn-server@server
- systemctl status openvpn@server
Computer Connection
Setting up OpenVPN on a personal computer provides secure remote access to corporate resources and protected connection when working through public networks. The setup process differs depending on the operating system, but the general principles remain the same.
Windows
Connecting on Windows computers can be done using the official OpenVPN GUI client. This client offers a convenient graphical interface for managing VPN connections and supports all modern Windows versions. The setup process includes installing the program and importing configuration files.
-
Client installation:
- Download the OpenVPN client.
- Run the installer and follow the standard installation steps.
-
Setup:
- Move configuration files to
C:\Users\Your_User\OpenVPN\config\
orC:\Program Files\OpenVPN\config\
. - Required files (may need 1 to 4 files, depending on server settings):
- Configuration (
*.ovpn
). - Client certificate (
*.crt
). - Private key (
*.key
). - CA certificate (
ca.crt
).
- Configuration (
- Move configuration files to
Information: for convenience, You can create a separate folder for each configuration.
- Connection:
- Launch the OpenVPN GUI client.
- Right-click on the icon in the system tray.
- Select
Connect
.
Linux
Linux provides flexible options for configuring OpenVPN through both command line and graphical interface. Thanks to built-in OpenVPN support in most distributions, the setup process usually doesn’t cause difficulties for users familiar with Linux systems.
Terminal Installation:
- sudo apt install openvpn -y
- sudo yum install openvpn -y
- Terminal configuration:
- sudo cp *.ovpn /etc/openvpn/client/
- sudo cp *.crt /etc/openvpn/client/
- sudo cp *.key /etc/openvpn/client/
- Starting connection:
- sudo openvpn --config /etc/openvpn/client/client.ovpn
Graphical Interface Installation:
- Install Network Manager OpenVPN plugin:
- sudo apt install network-manager-openvpn-gnome
- sudo yum install NetworkManager-openvpn-gnome
- Open network settings.
- Add VPN connection.
- Import
.ovpn
file.
MacOS
For MacOS users, You can use a special version of OpenVPN Connect that fully integrates with the system and provides a simple and reliable way to manage VPN connections. The application supports all modern MacOS versions and offers an intuitive interface.
-
Installation:
- Download OpenVPN Connect
- Run the installer and follow standard installation steps.
-
Setup:
- Open OpenVPN Connect.
- Click
+
to add a profile. - Import the
.ovpn
file by dragging or through theBrowse
menu. - Enter necessary credentials.
- Save the profile.
Here’s the text translated into Russian while maintaining the specified formatting:
Подключение на мобильных устройствах
Мобильные устройства стали важной частью нашей жизни, поэтому безопасный доступ к сети через VPN на смартфонах и планшетах может понадобиться для защиты данных. OpenVPN предлагает официальные клиенты для всех популярных мобильных платформ.
Важно: большинство бесплатных мобильных клиентов OpenVPN не поддерживают протокол tap
, который используется по умолчанию. Чтобы избежать проблем, настройте сервер OpenVPN для работы с протоколом tun
.
Android
OpenVPN Connect для Android обеспечивает надежный и безопасный способ подключения к VPN-серверам. Приложение доступно через Google Play Market и поддерживает широкий спектр Android-устройств, включая смартфоны и планшеты различных производителей. Интерфейс программы оптимизирован для удобного использования на мобильных устройствах.
-
Установка:
- Загрузите OpenVPN Connect из Google Play Market.
-
Настройка:
- Перенесите
.ovpn
файл на устройство. - Откройте OpenVPN Connect.
- Нажмите
+
и выберите способ импорта:URL
илиUpload File
.
- Перенесите
- Мы используем
Upload File
, нажимаемBrowse
для выбора файла конфигурации
- Найдите и выберите ранее загруженный
.ovpn
файл. - Введите название подключения (
Profile Name
) и учетные данные (Username
иPassword
).
iOS
OpenVPN Connect для iOS разработан с учетом особенностей экосистемы Apple и обеспечивает бесперебойную работу на iPhone и iPad. Приложение полностью соответствует требованиям безопасности App Store и интегрируется с системными настройками iOS для максимального удобства использования.
-
Установка:
- Загрузите OpenVPN Connect из App Store.
-
Настройка:
- Импортируйте профиль одним из способов:
- Через файл
.ovpn
(iCloud, Dropbox). - Через URL подключения.
- Через прямой импорт от провайдера.
- Введите название подключения и учетные данные.
- Через файл
- Импортируйте профиль одним из способов:
Важно:
- Убедитесь в наличии всех необходимых файлов сертификатов.
- Используйте только официальные источники для загрузки клиентов.
- Регулярно обновляйте программное обеспечение.
- Храните конфигурационные файлы в надежном месте.
Информируем: для получения дополнительной информации обращайтесь к официальной документации OpenVPN и документации Вашего устройства.