6.14 Installation and configuration of the OpenVPN server

Banner 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:
  1. System update:
  1. sudo apt update && sudo apt upgrade -y
  1. Installing OpenVPN and easy-rsa utility:
  1. sudo apt install openvpn easy-rsa -y
  1. PKI setup:
  1. mkdir -p /etc/openvpn/server/certs
  2. cd /etc/openvpn/server
  3. cp -r /usr/share/easy-rsa .
  4. cd easy-rsa
Installation on CentOS/AlmaLinux/RockyLinux:
  1. System update:
  1. sudo yum update -y
  1. Adding EPEL repository:
  1. sudo yum install epel-release -y
  1. Installing OpenVPN:
  1. sudo yum install openvpn easy-rsa -y
  1. Preparing directories:
  1. mkdir -p /etc/openvpn/server/certs
  2. cd /etc/openvpn/server
  3. cp -r /usr/share/easy-rsa .
  4. 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:

  1. Action confirmation. If a confirmation prompt appears, enter yes and press Enter. Confirmation yes
  2. 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. Password confirmation
  3. 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 press Enter.
  1. ./easyrsa init-pki
  1. ./easyrsa build-ca nopass
  1. ./easyrsa gen-req server nopass
  1. ./easyrsa sign-req server server
  1. ./easyrsa gen-dh
  1. 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:

  1. cat > /etc/openvpn/server/server.conf << EOF
  2. port 1194
  3. proto udp
  4. dev tun
  5. ca easy-rsa/pki/ca.crt
  6. cert easy-rsa/pki/issued/server.crt
  7. key easy-rsa/pki/private/server.key
  8. dh easy-rsa/pki/dh.pem
  9. tls-auth easy-rsa/ta.key 0
  10. server 10.8.0.0 255.255.255.0
  11. push "redirect-gateway def1 bypass-dhcp"
  12. push "dhcp-option DNS 8.8.8.8"
  13. push "dhcp-option DNS 8.8.4.4"
  14. keepalive 10 120
  15. cipher AES-256-GCM
  16. auth SHA256
  17. user nobody
  18. group nogroup
  19. persist-key
  20. persist-tun
  21. status openvpn-status.log
  22. verb 3
  23. 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):

  1. echo 'net.ipv4.ip_forward=1' > /etc/sysctl.d/99-openvpn.conf
  2. 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
  1. 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
  1. Saving Iptables rules.

For Debian/Ubuntu:

  1. sudo apt install iptables-persistent -y
  2. netfilter-persistent save
  3. netfilter-persistent reload

For CentOS/AlmaLinux/RockyLinux:

  1. service iptables save
  2. /etc/init.d/iptables restart
UFW on Ubuntu/Debian:
  1. UFW Configuration:
  1. ufw default deny incoming
  2. ufw default allow outgoing
  3. ufw allow ssh
  4. ufw allow 1194/udp
  5. ufw allow from 10.8.0.0/24
  1. Forwarding configuration:
  1. echo 'net.ipv4.ip_forward=1' >> /etc/ufw/sysctl.conf
  2. echo '*nat' >> /etc/ufw/before.rules
  3. echo ':POSTROUTING ACCEPT [0:0]' >> /etc/ufw/before.rules
  4. echo '-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE' >> /etc/ufw/before.rules
  5. echo 'COMMIT' >> /etc/ufw/before.rules
  6. ufw enable
Firewalld on CentOS/AlmaLinux/RockyLinux:
  1. Basic settings:
  1. firewall-cmd --permanent --add-service=openvpn
  2. firewall-cmd --permanent --add-port=1194/udp
  3. firewall-cmd --permanent --add-masquerade
  1. Forwarding configuration:
  1. firewall-cmd --permanent --direct --passthrough ipv4 -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
  1. Applying changes:
  1. firewall-cmd --reload

Client Certificate Generation

  1. Generating certificates for the client:
  1. cd /etc/openvpn/server/easy-rsa
  2. ./easyrsa gen-req client1 nopass
  3. ./easyrsa sign-req client client1
  1. Creating client configuration:
  1. mkdir -p /etc/openvpn/client
  2. cat > /etc/openvpn/client/client.ovpn << EOF
  3. client
  4. dev tun
  5. proto udp
  6. remote YOUR_SERVER_IP 1194
  7. resolv-retry infinite
  8. nobind
  9. persist-key
  10. persist-tun
  11. remote-cert-tls server
  12. cipher AES-256-GCM
  13. auth SHA256
  14. key-direction 1
  15. verb 3
  16. EOF
  1. Adding certificates to configuration:
  1. echo "<ca>" >> /etc/openvpn/client/client.ovpn
  2. cat pki/ca.crt >> /etc/openvpn/client/client.ovpn
  3. echo "</ca>" >> /etc/openvpn/client/client.ovpn
  4. echo "<cert>" >> /etc/openvpn/client/client.ovpn
  5. cat pki/issued/client1.crt >> /etc/openvpn/client/client.ovpn
  6. echo "</cert>" >> /etc/openvpn/client/client.ovpn
  7. echo "<key>" >> /etc/openvpn/client/client.ovpn
  8. cat pki/private/client1.key >> /etc/openvpn/client/client.ovpn
  9. echo "</key>" >> /etc/openvpn/client/client.ovpn
  10. echo "<tls-auth>" >> /etc/openvpn/client/client.ovpn
  11. cat ta.key >> /etc/openvpn/client/client.ovpn
  12. echo "</tls-auth>" >> /etc/openvpn/client/client.ovpn

Starting the Server

For Debian/Ubuntu:

  1. systemctl enable openvpn-server@server
  2. systemctl start openvpn-server@server

For CentOS/AlmaLinux/RockyLinux:

  1. systemctl enable openvpn@server
  2. systemctl start openvpn@server

Information: how to check service status:

Check on Debian/Ubuntu:
  1. systemctl status openvpn-server@server
Check on CentOS/AlmaLinux/RockyLinux:
  1. 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.

  1. Client installation:

    • Download the OpenVPN client.
    • Run the installer and follow the standard installation steps.
  2. Setup:

    • Move configuration files to C:\Users\Your_User\OpenVPN\config\ or C:\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).

Folder with files

Information: for convenience, You can create a separate folder for each configuration.

  1. Connection:
    • Launch the OpenVPN GUI client.
    • Right-click on the icon in the system tray. Settings
    • Select Connect. Connection

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:
For Ubuntu/Debian:
  1. sudo apt install openvpn -y
For CentOS/AlmaLinux/RockyLinux:
  1. sudo yum install openvpn -y
  1. Terminal configuration:
  1. sudo cp *.ovpn /etc/openvpn/client/
  2. sudo cp *.crt /etc/openvpn/client/
  3. sudo cp *.key /etc/openvpn/client/
  1. Starting connection:
  1. sudo openvpn --config /etc/openvpn/client/client.ovpn
Graphical Interface Installation:
  1. Install Network Manager OpenVPN plugin:
For Ubuntu/Debian:
  1. sudo apt install network-manager-openvpn-gnome
For CentOS:
  1. sudo yum install NetworkManager-openvpn-gnome
  1. Open network settings.
  2. Add VPN connection.
  3. 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.

  1. Installation:

    • Download OpenVPN Connect
    • Run the installer and follow standard installation steps.
  2. Setup:

    • Open OpenVPN Connect.
    • Click + to add a profile.
    • Import the .ovpn file by dragging or through the Browse 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-устройств, включая смартфоны и планшеты различных производителей. Интерфейс программы оптимизирован для удобного использования на мобильных устройствах.

  1. Установка:

    • Загрузите OpenVPN Connect из Google Play Market.
  2. Настройка:

    • Перенесите .ovpn файл на устройство.
    • Откройте OpenVPN Connect.
    • Нажмите + и выберите способ импорта: URL или Upload File.

Плюс

  • Мы используем Upload File, нажимаем Browse для выбора файла конфигурации

Загрузка

  • Найдите и выберите ранее загруженный .ovpn файл.
  • Введите название подключения (Profile Name) и учетные данные (Username и Password).

Ввод данных

iOS

OpenVPN Connect для iOS разработан с учетом особенностей экосистемы Apple и обеспечивает бесперебойную работу на iPhone и iPad. Приложение полностью соответствует требованиям безопасности App Store и интегрируется с системными настройками iOS для максимального удобства использования.

  1. Установка:

    • Загрузите OpenVPN Connect из App Store.
  2. Настройка:

    • Импортируйте профиль одним из способов:
      • Через файл .ovpn (iCloud, Dropbox).
      • Через URL подключения.
      • Через прямой импорт от провайдера.
      • Введите название подключения и учетные данные.

Важно:

  • Убедитесь в наличии всех необходимых файлов сертификатов.
  • Используйте только официальные источники для загрузки клиентов.
  • Регулярно обновляйте программное обеспечение.
  • Храните конфигурационные файлы в надежном месте.

Информируем: для получения дополнительной информации обращайтесь к официальной документации OpenVPN и документации Вашего устройства.