VPN – Virtual Private Network and OpenVPN

This article will describe a configuration of Virtual Private Network connection by using an OpenVPN application on Linux. Firstly, you will be exposed to some basic theory behind Virtual Private Networks. Then, the article will guide you with step-by-step instructions on how to setup a OpenVPN virtual private network by using Symmetric Key Encryption and Public Key Encryption. This article is meant for everybody who possesses a basic knowledge of Linux administration and networking.

In this tutorial you will learn:

  • What is a VPN and how does it work?
  • How to install OpenVPN on major Linux distros
  • How to setup VPN tunnel with Symmetric Key Encryption
  • How to setup VPN tunnel with Public Key Encryption
Creating a Virtual Private Network with OpenVPN

Creating a Virtual Private Network with OpenVPN
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software OpenVPN
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Why VPN?



If you work in the IT industry, it is very common that you do not use only a single computer sitting on your work desk, but you also utilize other systems connected to the same local area network. As long as you are sitting in your office chair this approach should not be a problem. However, this situation can become complicated once you are in hurry, and therefore, you need to take some of your work home.

You are able to take your company laptop with you, but to fully utilize company resources, you would also need to be connected to the company’s local area network. The solution to this problem depends on what resources are needed to complete your job. If you need some shared files available on the company’s network, you may just simply copy these file to your laptop’s hard drive or to a USB stick. In case you need to work on the system installed on your company’s PC, you can also use some virtualization tools such as VirtualBox or VMware.

Soon enough you will realize that this approach is not as convenient as you would like it to be, and that you spent more time by copying files and synchronizing virtual systems than concentrating on your work. The ideal solution in this case should allow employees to access company’s local resources from an external network.

This can be done by forwarding ports of the local services via firewall. Exposing local ports to the Internet is not entirely the safest approach. The more ports that are exposed from your local network to an external network such as the Internet, the more vulnerable your local system will become. The ideal approach in this situation could be the use of just a single port for all services, coupled with encryption and user authentication. This can be achieved, for example, by using a Virtual Private Network (VPN).

How Does a VPN Work?

VPN networks are often operated as client-server applications. A good example could be an implementation of MS Windows PPTP or OpenVPN on the Linux platform. The VPN server is directly running on a firewall, where it creates virtual network interface and additional virtual network subnet. The VPN server is waiting for connections on the external network interface of the firewall, where it performs authentication of a VPN client application.

After successful VPN client authentication, a VPN client is given an IP address from a virtual subnet. Consequently, an encrypted tunnel is created between the VPN client and the VPN server, which is used for safe transfer of packets between two distant networks via the Internet. Services, which a VPN client can connect to, can furthermore be defined by firewall rules.

This way, the firewall ensures that the VPN client can connect only to services it is allowed to connect to. If the previous couple sentences seemed a little difficult to understand, do not despair! Everything will become clearer once we see how an encrypted tunnel works in an example.

VPN Encrypted Tunnel Fundamentals

VPN tunnels are generally considered something mysterious, and anybody who mentions them, is “cool” :-). However, do not worry about struggling to understand them. In fact, the principle of Virtual Private Networks is very simple. Data in IP networks is exchanged in packets. Information about destination and a source of the packet can be found in the packet’s header. The actual user data are carried as a payload.

Let’s imagine that an SSH client wants to talk to the SSH server over the Virtual Private Network. Packets leaving a host’s network interface located on the local network are sent with a destination port number 22. When this packet reaches a VPN tunnel, it is encapsulated into the VPN packet where the original packet is now treated as a payload. If the VPN server listens on port 443, the VPN packet will carry a destination port 443.

The payload is encapsulated inside of a VPN packet

The payload is encapsulated inside of a VPN packet

When looking at the previous figure, it is apparent that this kind of network data transfer over the VPN is a waste of transfer rate because the original packet has a smaller payload space just because it needs to fit into the VPN tunnel packet. In a VPN analogical sense, this can be considered as a drawback.

The Theory Behind VPNs

Let’s imagine a small company network consisting of just a single subnet in which all clients are connected to the Internet via the company’s gateway, which can also be used as a firewall. How the connection is done is not important. The only thing important to know for this example is that the external gateway network interface uses an external IP address. This scenario is visualized in the following figure:

Multiple internal hosts use one external interface

Multiple internal hosts use one external interface

In case an employee wants to connect to some company’s services from the outside world, his/her attempt would be rejected by the firewall. Not just because this attempt is coming from a completely different subnet, but also because the ports to the particular services are not open. Once the VPN server starts functioning on the gateway, it automatically creates a virtual network interface with subnet 192.168.2.0/24, which would then start accepting a connection from the external network.

Once the employee passes the VPN server’s authentication, a VPN server will assign an IP address from a 192.168.2.0/24 subnet. Hosts on the 192.168.1.0/24 subnet would then be able to see systems on the 192.168.2.0/24 network as if they are located on a separate local subnet, but in fact the communication is done by an encrypted VPN tunnel over the Internet.



VPN Fundamentals

The following image will try to explain fundamental principles of VPN server-client communication. The gif animation will change every 14 seconds. The aim of this animation is to explain the logic behind a VPN communication in the simplest form as possible. Please note, that there are many other factors behind the scenes which have been omitted for the sake of simplicity.

The VPN process is broken down into 14 steps

The VPN process is broken down into 14 steps

Here are the 14 steps that take place in the animated graphic:

  1. VPN Client establishes a connection with a VPN Server via external network interface.
  2. VPN Server assigns an IP address to a VPN client from a local virtual subnet 192.168.2.0/24.
  3. VPN Client prepares a packet for a host 192.168.1.3 located within a private subnet 192.168.1.0/24.
  4. VPN Client encrypts and hides an original packet inside the outer public packet.
  5. The packet is dispatched by the VPN client via public network to the VPN Server.
  6. A network packet acquired from the public network is decrypted and decapsulated by the VPN server. This way, the VPN server obtains a packet for the private network.
  7. VPN Server handles a newly acquired packet as it was sent locally on a 192.168.1.0/24 subnet.
  8. Packet is delivered to the host with destination IP address 192.168.1.3.
  9. Host with IP address 192.168.1.3 creates a network packet with destination IP 192.168.2.2.
  10. VPN Server receives a reply packet.
  11. According to the VPN Server’s routing table, this packet links up with the Virtual Private Network.
  12. VPN server encrypts and hides an original packet inside the outer public packet.
  13. The packet is dispatched by the VPN server via public network to the VPN client.
  14. The network packet acquired from the public network is decrypted and decapsulated by the VPN Client. This way, the VPN client obtains a packet from the private network.

Static Key vs. Certificates

One of the best characteristics of a VPN solution is an encryption which leads to the client-server confidentiality communication enhancement. Once the connection between VPN Server and VPN Client is encrypted, an interceptor cannot read the message.

Encryption is done on both sides of the VPN transmissio, thus creating a so called VPN tunnel via public network such as the Internet. Encryption can be divided into two main groups: symmetric key encryption and public key encryption. See the sections below to what both of these are.

Symmetric Key Encryption

This type of communication requires one symmetric key which will be used on both sides to encrypt a message, which is a way of preventing an interceptor to read a message. To do this, the symmetric key needs to be produced and exchanged between both sides. This means that both sides will use the same encryption key to encrypt as well as to decrypt sent and received messages.

Public Key Encryption



When it comes to the public key encryption, each side has a public key and private key. There are four keys in total. The sender encrypts a message with a receiver’s public key and receiver decrypts a message with its own private key. Since only the receiver has access to its own private key, only he can decrypt a message. OpenVPN supports both ways of above mentioned encryptions.

Symmetric encryption in terms of OpenVPN is regarded as a static key mode and public key encryption as a certificate mode. Before we put both types of encryptions to the test by showing a real configuration and testing examples, let’s have a look at the following list which contains deliberately unsorted strengths and weaknesses for each solution:

Symmetric Key Encryption:

  • Symmetric encryption
  • Simple configuration
  • No Certificate Authority ( CA ) is required
  • Server can serve only single client at the same time
  • key must be stored in text file on both systems, which increases a risk that it will fall into the wrong hands
  • Difficult key exchange

Public Key Encryption:

  • Asymmetric encryption
  • More complicated configuration
  • Certificate Authority ( CA ) is required
  • Server can serve many clients simultaneously

Examples of VPN Connection

Now that we have grasped a necessary theory about Virtual Private Networks, we can move on and explore all mandatory steps for creating a VPN connection with Symmetric Key Encryption and Public Key Encryption. As a starting point in both cases there will be two computers with a fresh Linux installation. How the connection between those two PCs is created is not important.

The connection can be done via cross-over cable, two bridged virtual machines, or over the Internet. What is important, is that both PCs can ping each other and VPN Server will have 1194/UDP port open for connection from a VPN Client. In the further text we will refer to these systems as a VPN-Server ( IP Address: 10.1.1.3 ) and a VPN-Client ( IP Address: 10.1.1.4 ).

Virtual Private Network implementation example

Virtual Private Network implementation example

A VPN tunnel will be created as point-to-point 192.168.0.1192.168.0.2. However, for VPN tunnel created with use of Public Key Encryption ( OpenVPN certification mode ) the client’s IP address will differ and will be assigned from 192.168.0.0/16 subnet IP address pool. In our case, the client will obtain an IP address 192.168.0.6.

Installation of OpenVPN

The OpenVPN application consists only of one binary file which name is equal to the application name itself, thus openvpn. This binary file is used to start an OpenVPN server as well as OpenVPN client and therefore it is important to install the same OpenVPN packages on both sides. To be more precise, a difference between an OpenVPN Server and OpenVPN Client is just in how the configuration is carried out on both sides.

It is recommended to install OpenVPN packages from the official repository of your Linux Distribution you intend to use for this purpose. If, from some reason the packages for OpenVPN are not included in the official repository of your linux distribution feel free to install from source code. See the instructions below to use your system’s package manager to install the OpenVPN package on both the VPN Server and VPN Client systems.

How to Install OpenVPN From Official Repository

To install OpenVPN on Ubuntu, Debian, and Linux Mint:

$ sudo apt install openvpn

To install OpenVPN on CentOS, Fedora, AlmaLinux, and Red Hat:

$ sudo dnf install openvpn

To install OpenVPN on Arch Linux and Manjaro:

$ sudo pacman -S openvpn

How to Install OpenVPN From Source Code



Installation of OpenVPN from source code involves steps like downloading the source code from the OpenVPN home page and compiling it with the following sequence of commands:

$ wget http://openvpn.net/release/openvpn-2.0.9.tar.gz
$ tar xfz openvpn-2.0.9.tar.gz
$ cd openvpn-2.0.9
$ ./configure --prefix=/usr/local
$ make
# make install 

What happens here, is that the openvpn binary file will be created by the source code compilation and installed in the /usr/local/sbin directory.

Enabling a Virtual Network Interface

OpenVPN works with Virtual Network Interfaces TUN/TAP. TUN and TAP are virtual network kernel drivers and TUN ( TUNnel ) must be enabled in the kernel or at least as a module in order for a virtual private network to be able to function. TAP kernel driver can be found in the network interfaces section under the name “Universal TUN/TAP device driver support”.

To confirm that a TUN module is supported by your system, check a config file created during the kernel compilation. For the vast majority of modern Linux installations these days, the TUN driver is supported by default in the form of a kernel module. This can by confirmed by the following Linux command:

$ grep CONFIG_TUN= /boot/config-*
/boot/config-5.8.0-55-generic:CONFIG_TUN=y
/boot/config-5.8.0-59-generic:CONFIG_TUN=y

The eth0 interface directly represents a hardware device, which can be, for example a PCI network card. On the other hand, the TUN/TAP devices represents a virtual network interface. Packets traveling via TUN/TAP interface are sent to the application before they reach eth0 network interface. This allows an application such as OpenVPN to encrypt or decrypt packets before they reach a physical network.

VPN Connection and Symmetric Key Encryption

Setting up VPN Server

Almost all configuration settings can be passed to the OpenVPN application via command line. Another option is to create a configuration file which will be read during the OpenVPN initialization.

Creating a configuration file is a clean way to maintain a Virtual Private Network connection settings, since the number of outgoing connections can grow where the only limits is just a robustness of your system. However, for sake of simplicity and transparency in the following example we will use command line parameters to configure an OpenVPN server.

linux_VPN_Server:~# ip addr show dev eth0
 eth0      Link encap:Ethernet  HWaddr 00:0C:29:70:5A:F7  
           inet addr:10.1.1.3  Bcast:10.255.255.255  Mask:255.0.0.0
           inet6 addr: fe80::20c:29ff:fe70:5af7/64 Scope:Link
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:110 errors:0 dropped:0 overruns:0 frame:0
           TX packets:85 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000 
           RX bytes:11724 (11.4 KiB)  TX bytes:13204 (12.8 KiB)
           Interrupt:169 Base address:0x2000  

Generate Static Symmetric Key

Before we can start an OpenVPN tunnel, a symmetric key needs to be generated and exchanged between the server and client. To generate a symmetric key, run the following linux command:

linux_VPN_Server:~# openvpn --genkey --secret staticVPN.key
# cat staticVPN.key 
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
00e5dea65588eec9800f72607c6fb050
62a58ad4a44039d22635bdd817886c8b
69dbe38384eed05dcdca54c604e46d74
daec8f0e074f2a142db0efafe25520cb
a71a0c0314800be297275205bc6d18e3
852419caac500dc4135c2ce375c5020a
dd4ed783c1f47518e74c6b10124173ca
8ef3b52cfc297daf21683bb4f735856f
825c7ee868385dfcf4c3363d261e0e13
dfb60d3e3abc6a2075b8d243d3976eee
1afdff0e865d5973e2f6b6418f603aca
1923053d44ac0021ff74efbf00e60e3f
b928d4cc32f9d3d65566f8c1aaa5eb45
e1ebc134a1b060b6dde30ca5b9a54900
a1a5e0746ba7778285f163317433fb19
c0d5669677d9e921051c1fa6d3c75d47
-----END OpenVPN Static key V1-----

Start OpenVPN Server

At this stage, a static symmetric key can be used to start an OpenVPN server with will create one side of a Virtual Private Network tunnel ready for connections:

linux_VPN_Server:~# openvpn --dev tun --ifconfig 192.168.0.1 192.168.0.2 --secret staticVPN.key 
Wed Jan 28 03:48:09 2009 OpenVPN 2.0.9 i486-pc-linux-gnu [SSL] [LZO] [EPOLL] built on Sep 20 2007
Wed Jan 28 03:48:09 2009 IMPORTANT: OpenVPN's default port number is now 1194,  based on an official 
                         port number assignment by IANA.
                         OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Wed Jan 28 03:48:09 2009 TUN/TAP device tun0 opened
Wed Jan 28 03:48:09 2009 ifconfig tun0 192.168.0.1 pointopoint 192.168.0.2 mtu 1500
Wed Jan 28 03:48:09 2009 UDPv4 link local (bound): [undef]:1194
Wed Jan 28 03:48:09 2009 UDPv4 link remote: [undef]

Parameter --dev tun instructs an OpenVPN application to use a virtual network interface TUN. The following parameter --ifconfig 192.168.0.1 192.168.0.2 specifies IP addresses for both sides of virtual tunnel. OpenVPN consequently sets a virtual network interface tun0 to an IP address 192.168.0.1 and will enable a slot for a connection form an OpenVPN client on an IP address 192.168.0.2.

The last parameter --secret staticVPN.key specifies a file with Static Symmetric Key created in the previous step. Let’s confirm the correctness of the previous statements with the ip command:



linux_VPN_Server:~# ip addr show dev tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:192.168.0.1  P-t-P:192.168.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

Setting up VPN Client

The procedure for setting up an OpenVPN client is very similar the the one which was used to set up an OpenVPN server. At this point we assume an established connecton via 10.0.0.0 network, client has installed and ready to use an OpenVPN application as well as a Symmetric key generated previously was copied over to the client by means of USB key or SCP. If this is the case nothing can stop us to start an OpenVPN client:

linux_VPN_Client:~# ip addr show dev eth0 
 eth0      Link encap:Ethernet  HWaddr 00:0C:29:00:C1:42 
            inet addr:10.1.1.4  Bcast:10.255.255.255  Mask:255.0.0.0
           inet6 addr: fe80::20c:29ff:fe00:c142/64 Scope:Link
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:456 errors:0 dropped:0 overruns:0 frame:0
           TX packets:293 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000 
           RX bytes:434285 (424.1 KiB)  TX bytes:28413 (27.7 KiB)
           Interrupt:169 Base address:0x2000

Start Client

The following command and paramaters can be used to start an OpenVPN client with static symmetric key:

linux_VPN_Client:~# openvpn --remote 10.1.1.3 --dev tun --ifconfig 192.168.0.2 192.168.0.1 \ 
--secret staticVPN.key 
Wed Jan 28 03:51:02 2009 OpenVPN 2.0.9 i486-pc-linux-gnu [SSL] [LZO] [EPOLL] built on Sep 20 2007
Wed Jan 28 03:51:02 2009 IMPORTANT: OpenVPN's default port number is now 1194, based on an official port  
number assignment by IANA.
                         OpenVPN 2.0-beta16 and earlier used 5000 as the default port.
Wed Jan 28 03:51:02 2009 TUN/TAP device tun0 opened
Wed Jan 28 03:51:02 2009 ifconfig tun0 192.168.0.2 pointopoint 192.168.0.1 mtu 1500
Wed Jan 28 03:51:02 2009 UDPv4 link local (bound): [undef]:1194
Wed Jan 28 03:51:02 2009 UDPv4 link remote: 10.1.1.3:1194

Parameter --remote 10.1.1.3 specifies the real IP address of the OpenVPN server which is waiting for a connection and therefore an OpenVPN client will connect to socket 10.1.1.3:1194/UDP. The rest of the parameters have exactly the same meaning as it was in the case of OpenVPN server.

The only difference is the order of IP addresses which are passed to the --ifconfig parameter. This way an OpenVPN application sets a local tun0 virtual network interface to 192.168.0.2 and will expect the OpenVPN Server to be set on 192.168.0.1. Agian confirm the corectenss of these settings with ip command:

linux_VPN_Client:~# ip addr show dev tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:192.168.0.2  P-t-P:192.168.0.1  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b) 

Testing A VPN Connection

OpenVPN server and client now use a tun0 virtual network interface to maintain an encrypted virtual tunnel connection. OpenVPN server’s tun0 interface is set to 192.168.0.1 and OpenVPN client’s tun0 interface is set to 192.168.0.2.

If everything went smoothly and there is no firewall set between both endpoints which may interfere with the VPN tunnel, it should be easy to confirm a VPN connection with ping command.

linux_VPN_Server:~# ping -c 5 192.168.0.2
PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=3.24 ms
64 bytes from 192.168.0.2: icmp_seq=2 ttl=64 time=4.30 ms
64 bytes from 192.168.0.2: icmp_seq=3 ttl=64 time=1.76 ms
64 bytes from 192.168.0.2: icmp_seq=4 ttl=64 time=1.83 ms
64 bytes from 192.168.0.2: icmp_seq=5 ttl=64 time=2.52 ms

--- 192.168.0.2 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4012ms
rtt min/avg/max/mdev = 1.766/2.733/4.305/0.952 ms

If at the same time we would start a tcpdump program on the OpenVPN client’s virtual tun0 network interface we see the ICMP packets transmitted by ping program, including the reply packets.

linux_VPN_Client:~# tcpdump -i tun0
03:54:11.648040 IP 192.168.0.1 > 192.168.0.2: ICMP echo request, id 32520, seq 1, length 64 

However, on the OpenVPN client’s real eth0 network interface, the tcpdump program will produce the following ouptut:



linux_VPN_Client:~# tcpdump -i eth0
03:54:11.803616 IP 10.1.1.3.openvpn > 10.1.1.3.openvpn: UDP, length 124

This output from the tcpdump program can be used as proof of what we have learn previously, that packets from a virtual tun0 network interface are encapsulated into public network packets and are sent to the recipient encrypted via single 1194/UDP port.

Using OpenVPN Configuration Files

The previous VPN tunnel example used a number of arguments and parameters passed on the command line to create a VPN connection. Although almost every OpenVPN configuration directive can be passed to the openvpn command from the command line, this can sometimes become very tiresome work.

Therefore, we should complete this section on how to create a VPN connection using a Static Symmetric Key and OpenVPN configuration files. Here is a solution which involves a configuration file to achieve the same goal as shown previously.

OpenVPN Server config file – Create a vpn-server.conf file with the following content:

# OpenVPN configuration file for VPN SERVER
dev tun
ifconfig 192.168.0.1 192.168.0.2
secret /root/staticVPN.key
comp-lzo
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
user openvpn
group openvpn
daemon 

OpenVPN Client config file – Create a vpn-client.conf file with the following content:

# OpenVPN configuration file for VPN CLIENT
dev tun
remote 10.1.1.3
ifconfig 192.168.0.2 192.168.0.1
secret /root/staticVPN.key
comp-lzo
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
user openvpn
group openvpn
daemon 

Explanation of OpenVPN configuration directives:

  • dev – use a TUN virtual network device
  • remote – specifies a IP address or name of a VPN Server
  • ifconfig – specifies local and remote endpoint
  • secret – a path to the pre-shared static key file
  • comp-lzo – enable a fast LZO data compression
  • keepalive – keep connection alive by sending a regular ping packets, in our case the ping packet is sent every 10 seconds where reply packet must come within 60 seconds otherwise assume that the other endpoint is down.
  • ping-timer-rem – should be used only on VPN server side where daemon started without explicit remote IP address, this way timeout starts only after VPN client connection.
  • persist-tun – do not re-create a virtual network interface TUN after automatic restart
  • persist-key – no need to read pre-shared static key file again after automatic restart
  • user – run openvpn tunnel a user openvpn
  • group – run openvpn tunnel a group openvpn
  • daemon – once the initialization functions are completed run in the background as a daemon

It is time now to put those two OpenVPN configuration files into action. As stated in both config files we need to create an openvpn user and group first. OpenVPN can run as root. However, running a vpn tunnel as a non-privileged user “openvpn” is a smart move, and it will greatly enhance the security of your hosts. To create an openvpn group an addgroup command can be used:

NOTE: openvpn user and group need to be created on both sides of the VPN tunnel (VPN Server and VPN Clients )

# addgroup openvpn 

Now, that “openvpn” group is ready we can create a “openvpn” user.



# useradd --shell=/bin/false -g openvpn openvpn

At this point we are ready to engage both configuration files in OpenVPN tunnel creation:

Start OpenVPN Server:

linux_VPN_Server:~# openvpn --config /root/vpn-server.conf
linux_VPN_Server:~# ps aux | grep openvpn
     openvpn   2310  0.2  0.6   4060   988 ?        Ss   01:00   0:00 openvpn --config vpn-server.conf
root      2313  0.0  0.1   1512   224 pts/1    R+   01:00   0:00 grep openvpn

Start OpenVPN Client:

linux_VPN_Client:~# openvpn --config /root/vpn-client.conf
linux_VPN_Client:~# ps aux | grep openvpn            
openvpn   2317  0.8  0.7   4060  1188 ?        Ss   01:16   0:00 openvpn --config vpn-client.conf
root      2319  0.0  0.4   2852   704 pts/0    S+   01:16   0:00 grep openvpn

Test VPN Connection:

linux_VPN_Client:~# ping 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=8.50 ms
64 bytes from 192.168.0.1: icmp_seq=2 ttl=64 time=4.32 ms

--- 192.168.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1005ms
rtt min/avg/max/mdev = 4.327/6.416/8.506/2.091 ms 

VPN Connection with Public Key Encryption

If you have followed this article from the beginning up to this point, you may already know some basics on how Virtual Private Network works as well as you have established a VPN connection using Symmetric Key Encryption. Prior to the establishment of a VPN connection using Symmetric Key Encryption both VPN endpoints need to exchange a symmetric key first. Symmetric key needs to be exchanged securely using some private medium.

In case a company has a large number of employees and each employee needs to exchange symmetric key with anyone who wishes to establish VPN connection with, this task can become very tedious, not to mention that a key can be disclosed to the public somewhere on the way and the whole process would need to start again. This is where it comes to the Public key infrastructure (PKI).

Public Key Infrastructure

To avoid a public key exchange chaos when using a mesh like model, we could delegate one employee as a Certification Authority ( CA ) who will be responsible for keeping a record of all public keys. The aim of CA will be to collect all private keys from all employees and sign them with CA’s private key – to issue a certificate. If anyone would like to confirm a document’s signature created by any other employee, s|he would first use a CA’s public key to confirm a sender’s public key ( certificate ).

Once the sender’s public key is confirmed, this key can be further used to confirm a signature of the actual document. Since every peer sends it’s own CA signed certificate, only what needs to be done, is just to redistribute CA’s public key to every employee.

Setting up PKI

To reduce complexity, let’s briefly describe steps which need to be done in order to create a VPN connection using OpenVPN and Symmetric Key Encryption: First we would need to establish Certification Authority. For this we will be using our VPN-Server with IP 10.1.1.3. Note that you can establish CA on any other system. The fact that we intend to have CA and vpn-server on the same system as our VPN-Server, is just matter of convenience.

This step will produce a CA’s self-signed public key ( certificate ) as well as matching private key. In the next step, we will generate a server’s and client’s Certificate Signing Request (CSR) and the outcome would be CSR also private key for both peers ( server & client ). Note that both operations will be done separately on the server and client side. This way we do not have to transfer a client’s private key over unsecured connection.

Next, we would need to transfer client’s CSR to the server where we would sign both server’s and clients requests using CA’s private key. This will produce two signed certificates one for a server and one for a client. In the next step, we would transfer client’s signed certificate to the client along with CA’s public key. Before we start, make sure that you have an openssl package installed on both systems ( vpn-client and vpn-server ):

# apt install openssl
OR
# dnf install openssl
OR
# pacman -S openssl

Also make sure that username “openvpn” and “openvpn” group does exist on both endpoints ( vpn-client and vpn-server ) of your future VPN connection.

# addgroup openvpn
# useradd --shell=/bin/false -g openvpn openvpn 

Establishment of Certification Authority

The following Linux command will generate a CA self-signed certificate and private key. Which is all that we need, in order to be able to sign CSRs.



linux_VPN_Server:~#
openssl req -new -x509 -extensions v3_ca -keyout ca-private-key.pem -out ca-certificate.pem -days 365

You will need to supply some details and more importantly pass-phrase which you would use to sign CSR’s. The output will look something like this:

linux_VPN_Server:~# openssl req -new -x509 -extensions v3_ca -keyout ca-private-key.pem \ 
-out ca-certificate.pem -days 365
Generating a 1024 bit RSA private key
...............++++++
...++++++
writing new private key to 'ca-private-key.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:SK
State or Province Name (full name) [Some-State]:Slovakia
Locality Name (eg, city) []:Bratislava
Organization Name (eg, company) [Internet Widgits Pty Ltd]:linuxconfig.org
Organizational Unit Name (eg, section) []: Certificate Authority ( CA )
Common Name (eg, YOUR name) []:Certificate Authority ( CA )
Email Address []:

If everything went well, now you have established your own CA ready to sign CSR. You can find two new files in a directory from where you have issued openssl command:

linux_VPN_Server:~# ls
ca-certificate.pem  ca-private-key.pem

Generate a Certificate Signing Request

Our CA is ready, so at this point we need to create a Certificate Signing Request for our vpn-server and vpn-client. You will be asked to enter some details in regard to your company. It is important that “Common Name” reflects your IP address or a fully qualified domain name (or FQDN) of the system the certificate is intended for.

linux_VPN_Server:~# openssl req -new -nodes -out vpn-server-CSR.pem
Generating a 1024 bit RSA private key
..........................++++++
............................................++++++
writing new private key to 'privkey.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:SK
State or Province Name (full name) [Some-State]:Slovakia
Locality Name (eg, city) []:Bratislava
Organization Name (eg, company) [Internet Widgits Pty Ltd]:linuxconfig.org
Organizational Unit Name (eg, section) []:VPN-SERVER
Common Name (eg, YOUR name) []:10.1.1.3
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:


After creating a Certificate Signing Request you should have acquired two new files. One is vpn-server-CSR.pem, the vpn-server Certificate Signing Request, and the other is privkey.pem, the vpn-server private key.

linux_VPN_Server:~# ls
ca-certificate.pem  ca-private-key.pem  privkey.pem  vpn-server-CSR.pem
linux_VPN_Client:~# openssl req -new -nodes -out vpn-client-CSR.pem
Generating a 1024 bit RSA private key
............++++++
.....++++++
writing new private key to 'privkey.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:SK
State or Province Name (full name) [Some-State]:Slovakia
Locality Name (eg, city) []:Bratislava
Organization Name (eg, company) [Internet Widgits Pty Ltd]:linuxconfig.org
Organizational Unit Name (eg, section) []:VPN-CLIENT
Common Name (eg, YOUR name) []:10.1.1.4
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

After creating a Certificate Signing Request you shoud have accquired two new files. One is vpn-client-CSR.pem, which is the vpn-client Certificate Signing Request, and the other is privkey.pem, the vpn-client private key.

linux_VPN_Client:~# ls
privkey.pem  vpn-client-CSR.pem

Since our signing Certificate Authority resides on our vpn-server we copy clients signing a request to be signed there:

linux_VPN_Client:~# scp vpn-client-CSR.pem root@10.1.1.3:~/
root@10.1.1.3's password:
vpn-client-CSR.pem                100%  672     0.7KB/s   00:00

Signing Certificate Signing Requests

Both Certificates Signing Requests are waiting to be signed.

  • vpn-server-CSR.pem
  • vpn-client-CSR.pem


For that we could create an openssl config file similar to below and use it in conjunction with the openssl command. Use your favorite text editor and create a file called CA-openssl.config with content shown below:

linux_VPN_Server:~# cat CA-openssl.config
[ ca ]
default_ca = ca_default
[ ca_default ]
dir = .
new_certs_dir = .
private_key = ca-private-key.pem
certificate = ca-certificate.pem
database = index.txt
default_md = md5
serial = serial
default_days = 365
x509_extensions = usr_cert
 

policy = generic_policy
[ generic_policy ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
 
[ usr_cert ]
authorityKeyIdentifier = keyid
basicConstraints = CA:FALSE
keyUsage = digitalSignature
extendedKeyUsage = serverAuth

Certificate Authority needs to keep track of all signed certificates ( index.txt ) and assigned a serial numbers to each of them ( serial ). Therefore, we need to create these two files:

# touch index.txt; echo 01 > serial;  

All is ready to sign CSR. Let’s first sign vpn-server’s CSR:

linux_VPN_Server:~# openssl ca -config CA-openssl.config -infiles \
 vpn-server-CSR.pem 
Using configuration from CA-openssl.config    
Enter pass phrase for ca-private-key.pem:     
Check that the request matches the signature 
Signature ok  
The Subject's Distinguished Name is as follows    
countryName           :PRINTABLE:'SK'            
stateOrProvinceName   :PRINTABLE:'Slovakia'          
localityName          :PRINTABLE:'Bratislava'             
organizationName      :PRINTABLE:'linuxconfig.org'   
organizationalUnitName:PRINTABLE:'VPN-SERVER'      
commonName            :PRINTABLE:'10.1.1.3'  
Certificate is to be certified until Feb 25 21:34:25 2010 GMT (365 days)    
Sign the certificate? [y/n]:y    
                                              

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries 

Server certificated is ready, we need to amend CA-openssl.config to sign VPN-Client’s public key. Change line:

extendedKeyUsage = serverAuth
TO:
extendedKeyUsage = clientAuth 

The following Linux command will also do the trick:

# sed 's/serverAuth/clientAuth/' CA-openssl.config > temp; mv temp CA-openssl.config

Now, we are ready to sign vpn-client’s CSR:



linux_VPN_Server:~# openssl ca -config CA-openssl.config -infiles \
vpn-client-CSR.pem
Using configuration from CA-openssl.config     
Enter pass phrase for ca-private-key.pem: 
Check that the request matches the signature   
Signature ok                               
The Subject's Distinguished Name is as follows 
countryName           :PRINTABLE:'SK'       
stateOrProvinceName   :PRINTABLE:'Slovakia'     
localityName          :PRINTABLE:'Bratislava'     
organizationName      :PRINTABLE:'linuxconfig.org' 
organizationalUnitName:PRINTABLE:'VPN-CLIENT'      
commonName            :PRINTABLE:'10.1.1.4'            
Certificate is to be certified until Feb 25 21:37:53 2010 GMT (365 days)    
Sign the certificate? [y/n]:y   
                                              

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries 

Signed certificates are ready to use:

  • 01.pem – vpn-server certificate
  • 02.pem – vpn-client certificate
linux_VPN_Server:~# ls
01.pem  ca-certificate.pem  ca-private-key.pem
index.txt.attr      index.txt.old  serial
vpn-client-CSR.pem 02.pem  CA-openssl.config
index.txt           index.txt.attr.old  privkey.pem
serial.old  vpn-server-CSR.pem

You can see both certificates with the following Linux commands:

# openssl x509 -in 01.pem -noout -text
# openssl x509 -in 02.pem -noout -text

At this stage we need to copy vpn-vlient’s certificate to the vpn-client system (10.1.1.4) and change the name to something like vpn-client-certificate.pem. Along with the vpn-client certificate we also need to copy a CA’s certificate:

linux_VPN_Server:~# scp 02.pem root@10.1.1.4:~/vpn-client-certificate.pem
root@10.1.1.4's password:
02.pem                  100% 3173     3.1KB/s   00:00
linux_VPN_Server:~# scp ca-certificate.pem root@10.1.1.4:~/
root@10.1.1.4's password:
ca-certificate.pem      100% 1367     1.3KB/s   00:00

Change the name of vpn-server’s certificate to something like vpn-server-certificate.pem.

linux_VPN_Server:~# mv 01.pem vpn-server-certificate.pem

List of files in vpn-server working directory:

linux_VPN_Server:~# ls
02.pem              ca-private-key.pem  index.txt.attr.old   privkey.pem  vpn-client-CSR.pem
ca-certificate.pem  index.txt           index.txt.old        serial       vpn-server-certificate.pem
CA-openssl.config   index.txt.attr      openvpn-server.conf  serial.old   vpn-server-CSR.pem

Diffie-Hellman Key Agreement Protocol

Diffie-Hellman Key Agreement protocol allows two users to exchange a secret key over an insecure medium without any prior secrets. We need Diffie-Hellman Key Agreement file only on the server side of our vpn. It can be created by the following Linux command:

linux_VPN_Server:~# openssl dhparam -out dh.pem 1024 

Creating Configuration Files



OpenVPN configuration files will look similar to those we have created in the previous sections where we have created a virtual private network using Symmetric Key Encryption. Create files named openvpn-server.conf and openvpn-client.conf with the following content:

OpenVPN Server config file – Create a openvpn-server.conf file with the following content:

# OpenVPN server configuration file example
local 10.1.1.3
dev tun
server 192.168.0.0 255.255.0.0
ca ca-certificate.pem
cert vpn-server-certificate.pem
key privkey.pem
dh dh.pem
push "redirect-gateway"
comp-lzo
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
user openvpn
group openvpn
daemon 

OpenVPN Client config file – Create a openvpn-client.conf file with the following content:

# OpenVPN client configuration file example
client
dev tun
remote 10.1.1.3
tls-remote 10.1.1.3
ca ca-certificate.pem
cert vpn-client-certificate.pem
key privkey.pem
comp-lzo
keepalive 10 60
ping-timer-rem
persist-tun
persist-key
user openvpn
group openvpn
daemon

Explanation of OpenVPN configuration directives:

  • dev – use a TUN virtual network device
  • remote – specifies a IP address or name of a VPN Server
  • ifconfig – specifies local and remote endpoint
  • secret – a path to the pre-shared static key file
  • comp-lzo – enable a fast LZO data compression
  • keepalive – keep connection alive by sending a regular ping packets, in our case the ping packet is sent every 10 seconds where reply packet must come within 60 seconds otherwise assume that the other endpoint is down.
  • ping-timer-rem – should be used only on VPN server side where daemon started without explicit remote IP address, this way timeout starts only after VPN client connection.
  • persist-tun – do not re-create a virtual network interface TUN after automatic restart
  • persist-key – no need to read pre-shared static key file again after automatic restart
  • user – run openvpn tunnel a user openvpn
  • group – run openvpn tunnel a group openvpn
  • daemon – once the initialization functions are completed run in the background as a daemon

Start OpenVPN Server

linux_VPN_Server:~# openvpn --config openvpn-server.conf
linux_VPN_Server:~# ip addr show dev tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:192.168.0.1  P-t-P:192.168.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

Start OpenVPN Client

linux_VPN_Client:~# openvpn --config openvpn-client.conf
linux_VPN_Client:~# ip addr show dev tun0
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:192.168.0.6  P-t-P:192.168.0.5  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

Test VPN Connection

linux_VPN_Client:~# ping 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=0.805 ms
64 bytes from 192.168.0.1: icmp_seq=2 ttl=64 time=1.51 ms

--- 192.168.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.805/1.159/1.513/0.354 ms


Closing Thoughts

In this guide, we saw how to install OpenVPN on major Linux distros and use it to setup a VPN between a server and one or more client systems. OpenVPN gives us numerous options with regards to configuration of the VPN tunnel, such as Symmetric Key Encryption and Public Key Encryption. We covered both methods in this guide, and also weighed their pros and cons, so you can make an informed decision about which type of VPN tunnel suits your environment best.



Comments and Discussions
Linux Forum