How to Install OpenVPN Server on Ubuntu

Posted on

How to Install OpenVPN Server on Ubuntu

How to Install OpenVPN Server on Ubuntu

OpenVPN is a robust, open-source VPN (Virtual Private Network) software solution. It allows you to establish secure connections to a remote network across the internet, safeguarding your data and privacy. This article provides a detailed walkthrough of installing OpenVPN on an Ubuntu server (versions 18.04, 20.04, and 22.04). We will cover two primary methods, including a script-based approach and a manual configuration.

Method 1: Installing OpenVPN using a Script

This method offers a quick and relatively straightforward way to set up an OpenVPN server. It leverages a script that automates most of the configuration process.

First, you need to download the script and grant it execute permissions:

$ curl -O https://raw.githubusercontent.com/angristan/openvpn-install/master/openvpn-install.sh
$ chmod +x openvpn-install.sh

Next, execute the script:

$ ./openvpn-install.sh

Important Notes:

  • You must run the script with root privileges (using sudo if necessary).
  • Ensure the TUN (Tunneling) module is enabled on your server. This is often enabled by default but may require manual configuration depending on your hosting provider.

The first time you execute the script, it will guide you through an interactive assistant, prompting you to answer several questions to configure your How to Install OpenVPN Server on Ubuntu server. This includes setting up network parameters, selecting a protocol (UDP or TCP), and configuring DNS settings.

After the initial installation, subsequent executions of the script offer different options:

root@ubuntu:~# ./openvpn-install.sh
Welcome to OpenVPN-install!
The git repository is available at: https://github.com/angristan/openvpn-install
It looks like OpenVPN is already installed.
What do you want to do?
   1) Add a new user
   2) Revoke existing user
   3) Remove OpenVPN
   4) Exit
Select an option [1-4]:

These options allow you to manage users (add or revoke access) and completely remove the OpenVPN installation if needed. This script simplifies the management of your How to Install OpenVPN Server on Ubuntu.


Method 2: Manual Installation and Configuration

This method provides a more granular control over the OpenVPN installation process. It involves manually installing the necessary packages, generating certificates and keys, configuring the OpenVPN server, and setting up firewall rules.

Step 1: Update and Upgrade Ubuntu

Before proceeding with any software installation, it’s essential to update your Ubuntu system’s package lists and upgrade existing packages to their latest versions:

$ sudo apt update
$ sudo apt upgrade

Step 2: Install OpenVPN

Install OpenVPN and the easy-rsa package, which is used for generating certificates and keys:

$ sudo apt install openvpn easy-rsa

Step 3: Generate Certificates and Keys

OpenVPN relies on certificates and keys for secure authentication between clients and the server. The easy-rsa script simplifies the process of generating these files.

First, create a directory for the Certificate Authority (CA) and navigate into it:

$ make-cadir ~/openvpn-ca && cd ~/openvpn-ca

Edit the vars file to configure the CA variables:

$ nano ./vars

Modify the following variables to reflect your organization’s details:

set_var EASYRSA_REQ_COUNTRY    "US"
set_var EASYRSA_REQ_PROVINCE   "California"
set_var EASYRSA_REQ_CITY       "San Francisco"
set_var EASYRSA_REQ_ORG        "Copyleft Certificate Co"
set_var EASYRSA_REQ_EMAIL      "<a href="/cdn-cgi/l/email-protection" data-cfemail="0e636b4e6b766f637e626b20606b7a">[email&nbsp;protected]</a>"
set_var EASYRSA_REQ_OU         "My Organizational Unit"

Save the file and exit the editor.

Now, execute the following commands to initialize the PKI (Public Key Infrastructure), build the CA certificate, generate a server certificate request, sign the server certificate request, generate Diffie-Hellman parameters, and create a TLS authentication key:

$ ./easyrsa init-pki
$ ./easyrsa build-ca
$ ./easyrsa gen-req server nopass
$ ./easyrsa sign-req server server
$ ./easyrsa gen-dh
$ openvpn --genkey --secret pki/ta.key

The generated certificates and keys will be stored in the ~/openvpn-ca/pki directory.

Step 4: Configure OpenVPN

Copy the necessary certificates, keys, and the sample server configuration file to the OpenVPN configuration directory:

$ sudo cp pki/dh.pem pki/ca.crt pki/ta.key pki/issued/server.crt pki/private/server.key /etc/openvpn/
$ sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf /etc/openvpn/server.conf

Edit the /etc/openvpn/server.conf file to configure the OpenVPN server settings:

$ sudo nano /etc/openvpn/server.conf

Modify the following lines to point to the correct certificate and key files, and enable TLS encryption:

ca ca.crt
cert server.crt
key server.key  # This file should be kept secret
dh dh.pem
;tls-auth ta.key 0
tls-crypt ta.key
push "redirect-gateway def1 bypass-dhcp"

Save the file and exit the editor.

Enable IP forwarding to allow OpenVPN to route traffic:

$ sudo nano /etc/sysctl.conf
# Uncomment the following line:
net.ipv4.ip_forward=1

Apply the changes:

$ sudo sysctl -p

Step 5: Start and Enable OpenVPN

Start and enable the OpenVPN service to ensure it starts automatically on boot:

$ sudo systemctl start openvpn@server
$ sudo systemctl enable openvpn@server

The @server part specifies the configuration file name (server.conf) used by OpenVPN.

Step 6: Configure Firewall

Allow OpenVPN traffic through the firewall. If you’re using ufw, use the following command:

$ sudo ufw allow OpenVPN # ignore if you don't use firewall

Add iptables routing to enable NAT (Network Address Translation) for OpenVPN clients:

First, identify your main network interface (e.g., venet0, eth0). You can use the ifconfig command:

$ ifconfig
.
.
.
venet0: flags=211<UP,BROADCAST,POINTOPOINT,RUNNING,NOARP>  mtu 1500
        inet 127.0.0.1  netmask 255.255.255.255  broadcast 0.0.0.0  destination 127.0.0.1
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 0  (UNSPEC)
        RX packets 4825  bytes 467045 (467.0 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 3331  bytes 322185 (322.1 KB)
        TX errors 0  dropped 1167 overruns 0  carrier 0  collisions 0
venet0:0: flags=211<UP,BROADCAST,POINTOPOINT,RUNNING,NOARP>  mtu 1500
        inet 7.249.98.8  netmask 255.255.255.0  broadcast 7.249.98.255  destination 7.249.98.8
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 0  (UNSPEC)
.
.

Replace venet0 with your actual network interface name in the following command:

$ sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o venet0 -j MASQUERADE

This command configures NAT for OpenVPN clients connected to the 10.8.0.0/24 network.

Step 7: Connect to OpenVPN Server

To connect to the How to Install OpenVPN Server on Ubuntu server from a client, you need to generate client certificates and a client configuration file.

Generate a client certificate and key:

$ ./easyrsa gen-req client1 nopass
$ ./easyrsa sign-req client client1
$ sudo cp pki/private/client1.key /etc/openvpn/client/
$ sudo cp pki/issued/client1.crt /etc/openvpn/client/
$ sudo cp pki/{ca.crt,ta.key} /etc/openvpn/client/

Create a base client configuration file:

$ sudo cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /root/openvpn-ca/

Edit the client configuration file:

$ sudo nano /root/openvpn-ca/client.conf

Modify the following variables:

remote 192.168.1.5 1194 # 192.168.1.5 is the server public IP
user nobody
group nogroup
;ca ca.crt
;cert client.crt
;key client.key
;tls-auth ta.key 1
key-direction 1

Replace 192.168.1.5 with your server’s public IP address.

Create a script to generate the final client configuration file, embedding the certificates and keys:

$ nano config_gen.sh

Add the following content to the script:

#!/bin/bash
# First argument: Client identifier
KEY_DIR=/etc/openvpn/client
OUTPUT_DIR=/root # change it to output directory
BASE_CONFIG=/root/openvpn-ca/client.conf # Change it to client.conf in your system
cat ${BASE_CONFIG} 
    <(echo -e '<ca>') 
    ${KEY_DIR}/ca.crt 
    <(echo -e '</ca>n<cert>') 
    ${KEY_DIR}/${1}.crt 
    <(echo -e '</cert>n<key>') 
    ${KEY_DIR}/${1}.key 
    <(echo -e '</key>n<tls-crypt>') 
    ${KEY_DIR}/ta.key 
    <(echo -e '</tls-crypt>') 
    > ${OUTPUT_DIR}/${1}.ovpn

Save the script and make it executable:

$ sudo chmod 700 /root/openvpn-ca/config_gen.sh
$ sudo ./config_gen.sh client1

This will create a file named client1.ovpn in the /root/ directory. Copy this file to your client device and use it with an OpenVPN client application to connect to your VPN server.

Alternative Solutions for Setting Up a VPN on Ubuntu

While the above methods are commonly used, alternative solutions exist, each with its own advantages and disadvantages. Here are two alternatives to installing How to Install OpenVPN Server on Ubuntu:

1. Using WireGuard:

WireGuard is a modern VPN protocol that is known for its speed, security, and ease of configuration compared to OpenVPN. It uses state-of-the-art cryptography and is designed to be simpler and more efficient.

Explanation:

WireGuard is often faster than OpenVPN because of its smaller codebase and more efficient cryptography. Setting it up typically involves installing the WireGuard package, generating public and private keys for the server and each client, configuring the WireGuard interface, and setting up IP forwarding and firewall rules.

Code Example (Simplified):

Install WireGuard:

sudo apt update
sudo apt install wireguard

Generate keys (on both server and client):

wg genkey | tee privatekey | wg pubkey > publickey

Server Configuration (/etc/wireguard/wg0.conf):

[Interface]
PrivateKey = <server_private_key>
Address = 10.6.0.1/24
ListenPort = 51820
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip link set dev %i up
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip link set dev %i down

[Peer]
PublicKey = <client_public_key>
AllowedIPs = 10.6.0.2/32

Client Configuration (/etc/wireguard/wg0.conf):

[Interface]
PrivateKey = <client_private_key>
Address = 10.6.0.2/24
DNS = 8.8.8.8

[Peer]
PublicKey = <server_public_key>
Endpoint = <server_public_ip>:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

This is a simplified example, and further configuration might be necessary based on the specific network setup.

2. Using a Docker Container:

Docker allows you to run OpenVPN (or other VPN solutions) inside a container, which simplifies deployment and management. This approach encapsulates all the dependencies and configuration within the container, making it easier to deploy and maintain.

Explanation:

With Docker, you can use pre-built OpenVPN images from Docker Hub. These images often come with scripts and configurations that make the setup process easier. You only need to configure a few environment variables, such as the server’s public IP and client certificates, and then run the container. Docker handles the rest, including managing dependencies and networking.

Code Example:

Pull an OpenVPN Docker Image:

docker pull kylemanna/openvpn

Run the Docker container:

docker run -v /your/data/dir:/etc/openvpn --name openvpn -d -p 1194:1194/udp --cap-add=NET_ADMIN kylemanna/openvpn ovpn_genconfig -u udp://YOUR_SERVER_IP
docker run -v /your/data/dir:/etc/openvpn --name openvpn-data kylemanna/openvpn ovpn_initpki
docker run --volumes-from openvpn-data --cap-add=NET_ADMIN -d -p 1194:1194/udp kylemanna/openvpn ovpn_run

These commands pull the OpenVPN image, initialize the PKI, and then run the OpenVPN server within the Docker container. Client configurations can then be generated using the ovpn_getclient command within the running container.

Conclusion

This article has detailed how to install and configure How to Install OpenVPN Server on Ubuntu using both a script-based and a manual approach. We also introduced two alternative solutions: WireGuard and Docker. Selecting the right method depends on your specific requirements, technical expertise, and the level of control you need over the VPN server configuration. Remember to prioritize security best practices when configuring your VPN server to protect your data and privacy.