How to access your Ubiquiti home-network via OpenVPN and certificate authentication

In this tutorial we will setup OpenVPN SSL authentication on your Ubiquiti USG which will then allow you to access your home-network remotely and securely via TLS certificate authentication which then can be used on any client platform to remotely connect to your home-network. In my setup I use the Ubiquiti CloudKey to manage the network.

Setting up OpenVPN certificate authentication

1. Connect to your Ubiquiti USG via SSH and install Easy RSA which simplifies key generation and management:

$ ssh -l admin <YOUR-USG-IP>

$ sudo bash
$ cd /tmp
$ curl -O http://ftp.us.debian.org/debian/pool/main/e/easy-rsa/easy-rsa_2.2.2-1~bpo70+1_all.deb
$ sudo dpkg -i easy-rsa_2.2.2-1~bpo70+1_all.deb

2. Next we do the initial setup and setup the CA certificate (adjust the certificate information accordingly):

$ cd /usr/share/easy-rsa/
$ ./clean-all
$ source ./vars

$ ./build-ca
Generating a 2048 bit RSA private key
..........................................................................................+++
.........................................................................+++
writing new private key to 'ca.key'
-----
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) [US]:ZA
State or Province Name (full name) [CA]:Gauteng
Locality Name (eg, city) [SanFrancisco]:Johannesburg
Organization Name (eg, company) [Fort-Funston]:naschenweng.info
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:unifi
Common Name (eg, your name or your server's hostname) [Fort-Funston CA]:unifi.naschenweng.info
Name [EasyRSA]:vpn-unifi
Email Address [[email protected]]:[email protected]

3) We then need to generate the server key and certificate:

$ ./build-key-server server
Generating a 2048 bit RSA private key
...............................+++
..........................+++
writing new private key to 'server.key'
-----
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) [US]:ZA
State or Province Name (full name) [CA]:Gauteng
Locality Name (eg, city) [SanFrancisco]:Johannesburg
Organization Name (eg, company) [Fort-Funston]:naschenweng.info
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:unifi
Common Name (eg, your name or your server's hostname) [server]:unifi.naschenweng.info
Name [EasyRSA]:vpn-unifi
Email Address [[email protected]]:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:<YOURPASSWORD>
An optional company name []:
Using configuration from /usr/share/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'ZA'
stateOrProvinceName   :PRINTABLE:'Gauteng'
localityName          :PRINTABLE:'Johannesburg'
organizationName      :PRINTABLE:'naschenweng.info'
organizationalUnitName:PRINTABLE:'unifi'
commonName            :PRINTABLE:'unifi.naschenweng.info'
name                  :PRINTABLE:'vpn-unifi'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Mar 15 13:25:55 2027 GMT (3650 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
Data Base Updated

4. The next step is generating the DH parameters – this will take a VERY long time (in my case about 8-10 minutes)

$ ./build-dh
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
.......................

5. For each VPN user you need to create a key-set:

$ ./build-key vpn-gerd
Generating a 2048 bit RSA private key
.......................................................................................................................+++
............................................................................+++
writing new private key to 'vpn-gerd.key'
-----
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) [US]:ZA
State or Province Name (full name) [CA]:Gauteng
Locality Name (eg, city) [SanFrancisco]:Johannesburg
Organization Name (eg, company) [Fort-Funston]:Gerd VPN
Organizational Unit Name (eg, section) [MyOrganizationalUnit]:VPN
Common Name (eg, your name or your server's hostname) [vpn-gerd]:
Name [EasyRSA]:Gerd VPN
Email Address [[email protected]]:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /usr/share/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'ZA'
stateOrProvinceName   :PRINTABLE:'Gauteng'
localityName          :PRINTABLE:'Johannesburg'
organizationName      :PRINTABLE:'Gerd VPN'
organizationalUnitName:PRINTABLE:'VPN'
commonName            :PRINTABLE:'vpn-gerd'
name                  :PRINTABLE:'Gerd VPN'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Mar 15 14:42:34 2027 GMT (3650 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
Data Base Updated

6. To persist the keys over reboots, we create a persistent directory on the USG and copy all the key files (remember to recopy all files if you add or remove users):

 

$ mkdir /config/auth/keys/
$ cp keys/* /config/auth/keys/

7. Create the .ovpn client configuration file – you can import the file into any OpenVPN client (i.e. send the .ovpn file to your iOS device and then open it via the OpenVPN client):

client
float
dev tun
remote <YOUR-USG-WAN-IP-ADDRESS> 1194 udp
resolv-retry infinite
nobind
persist-key
persist-tun
cipher AES-256-CBC
comp-lzo
verb 5
<ca>
-----BEGIN CERTIFICATE----- 
Replace this section with the /config/auth/keys/ca.crt
-----END CERTIFICATE----- 
</ca>
<cert> 
-----BEGIN CERTIFICATE------
Replace this section with the public certificate - i.e. /config/auth/keys/vpn-gerd.crt
----END CERTIFICATE-----
</cert>
<key>
-----BEGIN PRIVATE KEY-----
Replace this section with the private key - i.e. /config/auth/keys/vpn-gerd.key
-----END PRIVATE KEY-----
</key>

In the above .ovpn configuration file replace the “—–BEGIN CERTIFICATE—– / —–END CERTIFICATE—–” sections with the content of the respective files.

8. Connect to the CloudKey (or UniFi controller) and update the config.gateway.json file:

{
  "firewall": {
    "options": {
      "mss-clamp": {
        "interface-type": [ "all" ], 
        "mss": "1440" 
      }
    },
    "name": {
      "WAN_LOCAL": {"rule": {"20": {"action": "accept","description": "Allow OpenVPN clients in","destination": {"port": "1194"},"log": "disable","protocol": "udp"}}}
    }
  },
  "interfaces": {
    "ethernet": {
      "eth0": {
        "mtu": "1480"
      }
    },
    "openvpn": {
      "vtun0": {
        "encryption": "aes256",
        "mode": "server",
        "openvpn-option": [
           "--keepalive 8 30",
           "--comp-lzo",
           "--duplicate-cn",
           "--user nobody --group nogroup",
           "--verb 1",
           "--proto udp",
           "--port 1194",
           "--push redirect-gateway def1",
           "--push dhcp-option DNS 192.168.1.97"
        ],
        "server": {"subnet": "172.16.0.0/24"},
        "tls": {
          "ca-cert-file": "/config/auth/keys/ca.crt",
          "cert-file": "/config/auth/keys/server.crt",
          "dh-file": "/config/auth/keys/dh2048.pem",
          "key-file": "/config/auth/keys/server.key"
        }
      }
    }
  },
  "service": {
    "dns": {
      "forwarding": {
        "cache-size": "10000"
      }
    },
    "snmp": {
      "community": {
        "muffinsnmp": {
          "authorization": "ro",
          "client": [ "192.168.1.97" ]
        }
      }
    },
    "upnp2": {
      "listen-on": [ "eth1" ],
      "nat-pmp": "enable",
      "secure-mode": "enable",
      "wan": "eth0"
    },
    "nat": {
       "rule": {"5010": {"description": "Masquerade for WAN","outbound-interface": "eth0","type": "masquerade"} }
    }
  }
}

In the above configuration adjust the VPN subnet / DNS. You also might want to remove the DNS, SNMP, UPNP2 and MSS-clamping sections if they are not relevant to you (for me those were necessary due to my upstream fibre-provider). If your USG connects via PPPOE to a layer2 device, change the nat-rule #5010’s interface from “eth0” to “pppoe0”.

Once you have updated the USG and the device completed provisioning, your VPN server will start (you can see this in /var/log/messages on your USG):

Mar 17 16:53:19 Gatekeeper openvpn[24203]: OpenVPN 2.3.2 mips-unknown-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Dec  5 2014
Mar 17 16:53:19 Gatekeeper openvpn[24203]: WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail
Mar 17 16:53:19 Gatekeeper openvpn[24203]: WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail
Mar 17 16:53:19 Gatekeeper openvpn[24203]: WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want
Mar 17 16:53:19 Gatekeeper openvpn[24203]: TUN/TAP device vtun0 opened
Mar 17 16:53:19 Gatekeeper zebra[679]: interface vtun0 index 8 <POINTOPOINT,NOARP,MULTICAST> added.
Mar 17 16:53:19 Gatekeeper openvpn[24203]: do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
Mar 17 16:53:19 Gatekeeper openvpn[24203]: /sbin/ip link set dev vtun0 up mtu 1500
Mar 17 16:53:19 Gatekeeper zebra[679]: interface vtun0 index 8 changed <UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>.
Mar 17 16:53:19 Gatekeeper openvpn[24203]: /sbin/ip addr add dev vtun0 172.16.0.1/24 broadcast 172.16.0.255

Connecting to your Ubiquiti OpenVPN server via OS X

If you are a Mac user, you want to use SetApp as it comes with a huge bundle of apps for a very small monthly fee. I use Shimo via SetApp which allows you to import the .ovpn file you created in section #7 above:

 

Connecting to your Ubiquiti OpenVPN server via iOS

If you need to connect to your home-network via your iOS devices, you need to download the OpenVPN Client from the iTunes store. Once installed, you can just email your .ovpn file to your iOS device and opening the attachment will automatically import it into the iOS OpenVPN client:

 


🍺 Pay it forward: If any of my content helped you in any way, then follow me on Twitter or send me some coins:
(CRO)    cro1w2kvwrzp23aq54n3amwav4yy4a9ahq2kz2wtmj (Memo: 644996249) or 0xb83c3Fe378F5224fAdD7a0f8a7dD33a6C96C422C (Cronos)
(USDC)   0xb83c3Fe378F5224fAdD7a0f8a7dD33a6C96C422C
(BTC)    3628nqihXvw2RXsKtTR36dN6WvYzaHyr52
(ETH)    0xb83c3Fe378F5224fAdD7a0f8a7dD33a6C96C422C
(BAT)    0xb83c3Fe378F5224fAdD7a0f8a7dD33a6C96C422C
(LTC)    MQxRAfhVU84KDVUqnZ5eV9MGyyaBEcQeDf
(Ripple) rKV8HEL3vLc6q9waTiJcewdRdSFyx67QFb (Tag: 1172047832)
(XLM)    GB67TJFJO3GUA432EJ4JTODHFYSBTM44P4XQCDOFTXJNNPV2UKUJYVBF (Memo ID: 1406379394)

🚀 Use my referral link https://crypto.com/app/ref6ayzqvp to sign up for Crypto.com and we both get $25 USD 😸
Free Crypto.com Visa Card! 100% rebate on Spotify, Netflix. Up to 8% cashback on all your shopping.
🧨 During signup use my referral code ref6ayzqvp to claim your reward 🧨
Go to Curve.com to add your Crypto.com card to ApplePay (get 1% cashback)