Using OpenVPN client with Ubuntu 16.04 server

The post will show you how to setup a headless linux server using Ubuntu 16.04 LTS and only allowing outgoing connections using a secure VPN connection with OpenVPN. If the VPN connection fails, no traffic is leaked. I will be using NordVPN as an example VPN provider since it is what I use myself, but any VPN provider with OpenVPN profiles should work. Check out my affiliate link to NordVPN here.

VPN setup

First we install the OpenVPN client and required dependencies as described at NordVPN guide:

sudo apt install openvpn unzip ca-certificates

Next we download and unzip the OpenVPN configuration files:

cd /etc/openvpn
sudo wget
sudo unzip zip
sudo rm zip

Now we can connect to a server. To see a list of all servers available, do a ls -al from /etc/openvpn. Choose one of these files, e.g.

sudo openvpn

And enter your login credentials. You can test that you are in Austria from another shell using:


And when disconnecting the OpenVPN from the first shell (just use CTRL + C) and rerunning the above command you should get your origin country.


Next we make sure we can only use the VPN internet connection. If you are doing this over SSH remember to do a sudo ufw allow 22 to prevent being locked out.

sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow out 1194/udp
sudo ufw allow out on tun0
sudo ufw enable

The above will prevent all incoming and outgoing connections except for tun0 which is the VPN and port 1194 so we can connect to the VPN. Notice that I do not allow VPN connections on port 443 since I might accidentally connect to websites without VPN.

We also make sure to use NordVPN’s DNS servers as described here.

sudo cat > nano /etc/resolvconf/resolv.conf.d/base << EOF

We now test the connection without being on the VPN which prevents dataconnections and DNS lookups.

ping -c 1
ping: unknown host
curl: (6) Could not resolve host:

And with the VPN we are able to

ping -c 1
PING ( 56(84) bytes of data.
64 bytes from ( icmp_seq=1 ttl=57 time=34.3 ms

--- ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 34.301/34.301/34.301/0.000 ms

Autostart VPN

First we save our credentials in a file. The information is stored as cleartext so be sure to secure it. Replace Username and Password with your own information.

sudo sh -c 'cat > /etc/openvpn/NordVPN_credentials << EOF

Next we modify the OpenVPN files to use the credentials from the file.

sudo sed -i -- 's/auth-user-pass.*/auth-user-pass \/etc\/openvpn\/NordVPN_credentials/g' /etc/openvpn/*

And finally we create a cronjob to autostart the VPN client on boot, replace with whatever configuration file you want to use.

(crontab -u root -l; echo "@reboot sleep 10 && /usr/sbin/openvpn /etc/openvpn/" ) | crontab -u root -

Restart the server and you should automatically use the VPN connection.

Leave a Reply

Be the First to Comment!