A virtual private network, or VPN, allows you to securely encrypt traffic as it travels through untrusted networks, such as those at the coffee shop, a conference, or an airport.
IKEv2, or Internet Key Exchange v2, is a protocol that allows for direct IPSec tunneling between the server and client. In IKEv2 VPN implementations, IPSec provides encryption for the network traffic. IKEv2 is natively supported on some platforms (OS X 10.11+, iOS 9.1+, and Windows 10) with no additional applications necessary, and it handles client hiccups quite smoothly.
In this tutorial, you’ll set up an IKEv2 VPN server using StrongSwan on an Ubuntu 18.04 server and connect to it from Windows, macOS, Ubuntu, iOS, and Android clients.
To complete this tutorial, you will need:
sudo
non-root user and a firewall.First, we’ll install StrongSwan, an open-source IPSec daemon which we’ll configure as our VPN server. We’ll also install the public key infrastructure component so that we can create a certificate authority to provide credentials for our infrastructure.
Update the local package cache and install the software by typing:
- sudo apt update
- sudo apt install strongswan strongswan-pki
Now that everything’s installed, let’s move on to creating our certificates.
An IKEv2 server requires a certificate to identify itself to clients. To help us create the certificate required, the strongswan-pki
package comes with a utility to generate a certificate authority and server certificates. To begin, let’s create a few directories to store all the assets we’ll be working on. The directory structure matches some of the directories in /etc/ipsec.d
, where we will eventually move all of the items we create. We’ll lock down the permissions so that our private files can’t be seen by other users:
- mkdir -p ~/pki/{cacerts,certs,private}
- chmod 700 ~/pki
Now that we have a directory structure to store everything, we can generate a root key. This will be a 4096-bit RSA key that will be used to sign our root certificate authority.
Execute these commands to generate the key:
- ipsec pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem
Now that we have a key, we can move on to creating our root certificate authority, using the key to sign the root certificate:
- ipsec pki --self --ca --lifetime 3650 --in ~/pki/private/ca-key.pem \
- --type rsa --dn "CN=VPN root CA" --outform pem > ~/pki/cacerts/ca-cert.pem
You can change the distinguished name (DN) values to something else to if you would like. The common name here is just the indicator, so it doesn’t have to match anything in your infrastructure.
Now that we’ve got our root certificate authority up and running, we can create a certificate that the VPN server will use.
We’ll now create a certificate and key for the VPN server. This certificate will allow the client to verify the server’s authenticity using the CA certificate we just generated.
First, create a private key for the VPN server with the following command:
- ipsec pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem
Now, create and sign the VPN server certificate with the certificate authority’s key you created in the previous step. Execute the following command, but change the Common Name (CN) and the Subject Alternate Name (SAN) field to your VPN server’s DNS name or IP address:
- ipsec pki --pub --in ~/pki/private/server-key.pem --type rsa \
- | ipsec pki --issue --lifetime 1825 \
- --cacert ~/pki/cacerts/ca-cert.pem \
- --cakey ~/pki/private/ca-key.pem \
- --dn "CN=server_domain_or_IP" --san "server_domain_or_IP" \
- --flag serverAuth --flag ikeIntermediate --outform pem \
- > ~/pki/certs/server-cert.pem
Now that we’ve generated all of the TLS/SSL files StrongSwan needs, we can move the files into place in the /etc/ipsec.d
directory by typing:
- sudo cp -r ~/pki/* /etc/ipsec.d/
In this step, we’ve created a certificate pair that would be used to secure communications between the client and the server. We’ve also signed the certificates with the CA key, so the client will be able to verify the authenticity of the VPN server using the CA certificate. Now that have all of the certificates ready, we’ll move on to configuring the software.
StrongSwan has a default configuration file with some examples, but we will have to do most of the configuration ourselves. Let’s back up the file for reference before starting from scratch:
- sudo mv /etc/ipsec.conf{,.original}
Create and open a new blank configuration file by typing:
- sudo nano /etc/ipsec.conf
First, we’ll tell StrongSwan to log daemon statuses for debugging and allow duplicate connections. Add these lines to the file:
config setup
charondebug="ike 1, knl 1, cfg 0"
uniqueids=no
Then, we’ll create a configuration section for our VPN. We’ll also tell StrongSwan to create IKEv2 VPN Tunnels and to automatically load this configuration section when it starts up. Append the following lines to the file:
. . .
conn ikev2-vpn
auto=add
compress=no
type=tunnel
keyexchange=ikev2
fragmentation=yes
forceencaps=yes
We’ll also configure dead-peer detection to clear any “dangling” connections in case the client unexpectedly disconnects. Add these lines:
. . .
conn ikev2-vpn
. . .
dpdaction=clear
dpddelay=300s
rekey=no
Then, we’ll configure the server (left) side IPSec parameters. Add this to the file:
. . .
conn ikev2-vpn
. . .
left=%any
leftid=@server_domain_or_IP
leftcert=server-cert.pem
leftsendcert=always
leftsubnet=0.0.0.0/0
Note: When configuring the server ID (leftid
), only include the @
character if your VPN server will be identified by a domain name:
leftid=@vpn.example.com
If the server will be identified by its IP address, just put the IP address in:
leftid=203.0.113.7
Next, we can configure the client (right) side IPSec parameters, like the private IP address ranges and DNS servers to use:
. . .
conn ikev2-vpn
. . .
right=%any
rightid=%any
rightauth=eap-mschapv2
rightsourceip=10.10.10.0/24
rightdns=8.8.8.8,8.8.4.4
rightsendcert=never
Finally, we’ll tell StrongSwan to ask the client for user credentials when they connect:
. . .
conn ikev2-vpn
. . .
eap_identity=%identity
The configuration file should look like this:
config setup
charondebug="ike 1, knl 1, cfg 0"
uniqueids=no
conn ikev2-vpn
auto=add
compress=no
type=tunnel
keyexchange=ikev2
fragmentation=yes
forceencaps=yes
dpdaction=clear
dpddelay=300s
rekey=no
left=%any
leftid=@server_domain_or_IP
leftcert=server-cert.pem
leftsendcert=always
leftsubnet=0.0.0.0/0
right=%any
rightid=%any
rightauth=eap-mschapv2
rightsourceip=10.10.10.0/24
rightdns=8.8.8.8,8.8.4.4
rightsendcert=never
eap_identity=%identity
Save and close the file once you’ve verified that you’ve configured things as shown.
Now that we’ve configured the VPN parameters, let’s move on to creating an account so our users can connect to the server.
Our VPN server is now configured to accept client connections, but we don’t have any credentials configured yet. We’ll need to configure a couple things in a special configuration file called ipsec.secrets
:
Let’s open the secrets file for editing:
- sudo nano /etc/ipsec.secrets
First, we’ll tell StrongSwan where to find our private key:
: RSA "server-key.pem"
Then, we’ll define the user credentials. You can make up any username or password combination that you like:
your_username : EAP "your_password"
Save and close the file. Now that we’ve finished working with the VPN parameters, we’ll restart the VPN service so that our configuration is applied:
- sudo systemctl restart strongswan
Now that the VPN server has been fully configured with both server options and user credentials, it’s time to move on to configuring the most important part: the firewall.
With the StrongSwan configuration complete, we need to configure the firewall to forward and allow VPN traffic through.
If you followed the prerequisite tutorial, you should have a very basic UFW firewall enabled. If you don’t yet have UFW configured, you can create a baseline configuration and enable it by typing:
- sudo ufw allow OpenSSH
- sudo ufw enable
Now, add a rule to allow UDP traffic to the standard IPSec ports, 500 and 4500:
- sudo ufw allow 500,4500/udp
Next, we will open up one of UFW’s configuration files to add a few low-level policies for routing and forwarding IPSec packets. Before we do, we need to find which network interface on our server is used for internet access. We can find that by querying for the interface associated with the default route:
- ip route | grep default
Your public interface should follow the word “dev”. For example, this result shows the interface named eth0
, which is highlighted below:
Outputdefault via 203.0.113.7 dev eth0 proto static
When you have your public network interface, open the /etc/ufw/before.rules
file in your text editor:
- sudo nano /etc/ufw/before.rules
Near the top of the file (before the *filter
line), add the following configuration block:
*nat
-A POSTROUTING -s 10.10.10.0/24 -o eth0 -m policy --pol ipsec --dir out -j ACCEPT
-A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
COMMIT
*mangle
-A FORWARD --match policy --pol ipsec --dir in -s 10.10.10.0/24 -o eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
COMMIT
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
. . .
Change each instance of eth0
in the above configuration to match the interface name you found with ip route
. The *nat
lines create rules so that the firewall can correctly route and manipulate traffic between the VPN clients and the internet. The *mangle
line adjusts the maximum packet segment size to prevent potential issues with certain VPN clients.
Next, after the *filter
and chain definition lines, add one more block of configuration:
. . .
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
-A ufw-before-forward --match policy --pol ipsec --dir in --proto esp -s 10.10.10.0/24 -j ACCEPT
-A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d 10.10.10.0/24 -j ACCEPT
These lines tell the firewall to forward ESP (Encapsulating Security Payload) traffic so the VPN clients will be able to connect. ESP provides additional security for our VPN packets as they’re traversing untrusted networks.
When you’re finished, save and close the file.
Before we restart the firewall, we’ll change some network kernel parameters to allow routing from one interface to another. Open UFW’s kernel parameters configuration file:
- sudo nano /etc/ufw/sysctl.conf
We’ll need to configure a few things here:
The changes you need to make to the file are highlighted in the following code:
. . .
# Enable forwarding
# Uncomment the following line
net/ipv4/ip_forward=1
. . .
# Do not accept ICMP redirects (prevent MITM attacks)
# Ensure the following line is set
net/ipv4/conf/all/accept_redirects=0
# Do not send ICMP redirects (we are not a router)
# Add the following lines
net/ipv4/conf/all/send_redirects=0
net/ipv4/ip_no_pmtu_disc=1
Save the file when you are finished. UFW will apply these changes the next time it starts.
Now, we can enable all of our changes by disabling and re-enabling the firewall:
- sudo ufw disable
- sudo ufw enable
You’ll be prompted to confirm the process. Type Y
to enable UFW again with the new settings.
Now that you have everything set up, it’s time to try it out. First, you’ll need to copy the CA certificate you created and install it on your client device(s) that will connect to the VPN. The easiest way to do this is to log into your server and output the contents of the certificate file:
- cat /etc/ipsec.d/cacerts/ca-cert.pem
You’ll see output similar to this:
Output-----BEGIN CERTIFICATE-----
MIIFQjCCAyqgAwIBAgIIFkQGvkH4ej0wDQYJKoZIhvcNAQEMBQAwPzELMAkGA1UE
. . .
EwbVLOXcNduWK2TPbk/+82GRMtjftran6hKbpKGghBVDPVFGFT6Z0OfubpkQ9RsQ
BayqOb/Q
-----END CERTIFICATE-----
Copy this output to your computer, including the -----BEGIN CERTIFICATE-----
and -----END CERTIFICATE-----
lines, and save it to a file with a recognizable name, such as ca-cert.pem
. Ensure the file you create has the .pem
extension.
Alternatively, use SFTP to transfer the file to your computer.
Once you have the ca-cert.pem
file downloaded to your computer, you can set up the connection to the VPN.
First, import the root certificate by following these steps:
Press WINDOWS+R
to bring up the Run dialog, and enter mmc.exe
to launch the Windows Management Console.
From the File menu, navigate to Add or Remove Snap-in, select Certificates from the list of available snap-ins, and click Add.
We want the VPN to work with any user, so select Computer Account and click Next.
We’re configuring things on the local computer, so select Local Computer, then click Finish.
Under the Console Root node, expand the Certificates (Local Computer) entry, expand Trusted Root Certification Authorities, and then select the Certificates entry:
From the Action menu, select All Tasks and click Import to display the Certificate Import Wizard. Click Next to move past the introduction.
On the File to Import screen, press the Browse button and select the certificate file that you’ve saved. Then click Next.
Ensure that the Certificate Store is set to Trusted Root Certification Authorities, and click Next.
Click Finish to import the certificate.
Then configure the VPN with these steps:
Your new VPN connection will be visible under the list of networks. Select the VPN and click Connect. You’ll be prompted for your username and password. Type them in, click OK, and you’ll be connected.
Follow these steps to import the certificate:
Now that the certificate is important and trusted, configure the VPN connection with these steps:
Finally, click on Connect to connect to the VPN. You should now be connected to the VPN.
To connect from an Ubuntu machine, you can set up and manage StrongSwan as a service or use a one-off command every time you wish to connect. Instructions are provided for both.
sudo apt update
sudo apt install strongswan libcharon-extra-plugins
/etc/ipsec.d/cacerts
directory: sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts
sudo systemctl disable --now strongswan
/etc/ipsec.secrets
file: your_username : EAP "your_password"
/etc/ipsec.conf
file to define your configuration.config setup
conn ikev2-rw
right=server_domain_or_IP
# This should match the `leftid` value on your server's configuration
rightid=server_domain_or_IP
rightsubnet=0.0.0.0/0
rightauth=pubkey
leftsourceip=%config
leftid=username
leftauth=eap-mschapv2
eap_identity=%identity
auto=start
To connect to the VPN, type:
- sudo systemctl start strongswan
To disconnect again, type:
- sudo systemctl stop strongswan
sudo apt update
charon-cmd
and related software sudo apt install charon-cmd libcharon-extra-plugins
cd <^>/path/to/ca-cert.pem
charon-cmd
using the server’s CA certificate, the VPN server’s IP address, and the username you configured: sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username
You should now be connected to the VPN. To disconnect, press CTRL+C
and wait for the connection to close.
To configure the VPN connection on an iOS device, follow these steps:
Follow these steps to import the certificate:
Now that the certificate is imported into the StrongSwan app, you can configure the VPN connection with these steps:
When you wish to connect to the VPN, click on profile you just created in the StrongSwan application.
If you are unable to import the certificate, ensure the file has the .pem
extension, and not .pem.txt
.
If you’re unable to connect to the VPN, check the server name or IP address you used. The server’s domain name or IP address must match what you’ve configured as the common name (CN) while creating the certificate. If they don’t match, the VPN connection won’t work. If you set up a certificate with the CN of vpn.example.com
, you must use vpn.example.com
when you enter the VPN server details. Double-check the command you used to generate the certificate, and the values you used when creating your VPN connection.
Finally, double-check the VPN configuration to ensure the leftid
value is configured with the @
symbol if you’re using a domain name:
leftid=@vpn.example.com
And if you’re using an IP address, ensure that the @
symbol is omitted.
In this tutorial, you’ve built a VPN server that uses the IKEv2 protocol. Now you can be assured that your online activities will remain secure wherever you go!
To add or remove users, just take a look at Step 5 again. Each line is for one user, so adding or removing users is as simple as editing the file.
From here, you might want to look into setting up a log file analyzer, because StrongSwan dumps its logs into syslog. The tutorial How To Install and Use Logwatch Log Analyzer and Reporter on a VPS has more information on setting that up.
You might also be interested in this guide from the EFF about online privacy.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
You guys (the authors) are ABSOLUTE LEGENDs!
After coming to China I badly needed a VPN because I needed proper English search engines to do my work. None of the commercial VPN services were working (including Nord, IPVanish and ExpressVPN). So I wanted to setup mine and came across this tutorial.
There were some issues with my Windows Setup and had to add the following two lines to ipsec.conf
This tutorial is written brilliantly and I thank you both for your contribution.
Keep up the awesome work! Cheers.
One step is missing
set DEFAULT_FORWARD_POLICY=“ACCEPT” in /etc/default/ufw
When connecting from Windows 10 using the above configuration and setup, you will be unable to connect due to the 4096-bit cert encryption scheme used. Windows only supports 1024-bit max by default. However, we can up that to 2048-bit, as long as you make sure you add this registry value:
Further, you must recreate you root CA cert and your private key cert with 2048 instead of 4096. Then sign the new private key with the root CA cert. Then you need to delete the old root CA cert your imported into Windows and replace it with the 2048-bit version.
Thankfully, a bit of Googling helped me out here, but I don’t want others to have to go through the headache that I did.
Also, if your VPN server is behind a firewall, make sure you forward the ports 500 and 4500 UDP to your server. Make sure IPSec passthrough is enabled too.
Potentially naive question. Would you have to configure multiple certificates or multiple users when connecting with two devices simultaneously? When I connect with both my Android phone and my Linux laptop, it seems like only the phone is working. When I do ipsec staus on my droplet, it says that only one Security Association is up, even though both clients think they’re connected (though one appears not to be working). Additionally, the logs and network info for both seem to indicate that they have been assigned the same virtual IP.
So essentially the question is, can I run through this tutorial once, and use same config/cert for simultaneous connections on different machines?
This fails to authenticate for MacOS and iOS both.
Thanks for your tutorials,I have connected my vpn server successfully. But I still have 2 problems.
My server is behind Nat too, and I forward 500 and 4500 to server on router.
I saw there were a couple of comments about could not ping over the ESP tunnel. I also have same problem but not sure this is the same problem other person had before. Let me explain my configuration and my problem. I have setup a server using ubuntu18/strongswan as explained in this tutoria. Also I have a client using ubuntu18/strongswan.
If I start strongswan from server and client, then output of ipsec status from the client is as shown below. root@u18: ~ # ipsec status Security Association (1 up, 0 connecting): ikev2-rw[1]: ESTABLISHED 7 minutes ago, 192.168.1.123[user123]…192.168.1.124[192.168.1.124] ikev2-rw{1}: INSTALLED, TUNNEL, reqid 1, ESP in UDP SPIs: cce4b059_i c07138fc_o ikev2-rw{1}: 192.168.11.100/32 === 0.0.0.0/0
Also, I have a line like below in ipsec.conf file in Server side. rightsourceip=192.168.11.100
My client uses one interface which has 192.168.1.123. And my server has 2 interfaces which are 192.168.1.124 and 192.168.11.124. And there is another neighbour host which has 192.168.11.219.
If I send a ping from client, I can ping to 192.168.11.124 but not to 192.168.11.219. When I captured packets using wireshark, I can see ICMP requests from server to 192.168.11.219 which is neighbor host. But I don’t see ICMP reply from server.
One thing I did is added one routing entry like below. Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.11.100 0.0.0.0 255.255.255.255 UH 0 0 0 ens32
But still I don’t see ICMP reply from server.
If you found something I did wrong, please let me know. Thanks!
First of all, thank you for the tutorial/documentation which is very well organized. I have just followed this tutorial and I could not make it work. I used ubuntu18/strongswan for server also used ubuntu18/strongswan for client.
I’m adding log from server side and client side below. [Log from server]
systemctl status strongswan
* strongswan.service - strongSwan IPsec IKEv1/IKEv2 daemon using ipsec.conf Loaded: loaded (/lib/systemd/system/strongswan.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2021-09-04 13:54:50 EDT; 1h 26min ago Main PID: 10829 (starter) Tasks: 18 (limit: 4630) CGroup: /system.slice/strongswan.service tq10829 /usr/lib/ipsec/starter --daemon charon --nofork mq10843 /usr/lib/ipsec/charon --debug-ike 1 --debug-knl 1 --debug-cfg 0
Sep 04 15:21:06 u18 charon[10843]: 07[NET] sending packet: from 192.168.1.124[500] to 192.168.1.123[500] (270 bytes) Sep 04 15:21:06 u18 charon[10843]: 08[NET] received packet: from 192.168.1.123[4500] to 192.168.1.124[4500] (336 bytes) Sep 04 15:21:06 u18 charon[10843]: 08[ENC] parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ IDr CPRQ(ADDR DNS) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) N( Sep 04 15:21:06 u18 charon[10843]: 08[IKE] received cert request for “CN=VPN root CA” Sep 04 15:21:06 u18 charon[10843]: 08[IKE] EAP-Identity request configured, but not supported Sep 04 15:21:06 u18 charon[10843]: 08[IKE] initiating EAP_MSCHAPV2 method (id 0xAE) Sep 04 15:21:06 u18 charon[10843]: 08[IKE] peer supports MOBIKE Sep 04 15:21:06 u18 charon[10843]: 08[IKE] no private key found for ‘192.168.1.124’ Sep 04 15:21:06 u18 charon[10843]: 08[ENC] generating IKE_AUTH response 1 [ N(AUTH_FAILED) ] Sep 04 15:21:06 u18 charon[10843]: 08[NET] sending packet: from 192.168.1.124[4500] to 192.168.1.123[4500] (80 bytes)
[Log from client]
systemctl status strongswan
Sep 04 15:21:06 u18 charon[9815]: 09[ENC] parsed IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ] Sep 04 15:21:06 u18 charon[9815]: 09[IKE] remote host is behind NAT Sep 04 15:21:06 u18 charon[9815]: 09[IKE] sending cert request for “CN=VPN root CA” Sep 04 15:21:06 u18 charon[9815]: 09[IKE] establishing CHILD_SA ikev2-rw{1} Sep 04 15:21:06 u18 charon[9815]: 09[IKE] establishing CHILD_SA ikev2-rw{1} Sep 04 15:21:06 u18 charon[9815]: 09[ENC] generating IKE_AUTH request 1 [ IDi N(INIT_CONTACT) CERTREQ IDr CPRQ(ADDR DNS) SA TSi TSr N(MOBIKE_SUP) N(NO_ADD_ADDR) Sep 04 15:21:06 u18 charon[9815]: 09[NET] sending packet: from 192.168.1.123[4500] to 192.168.1.124[4500] (336 bytes) Sep 04 15:21:06 u18 charon[9815]: 10[NET] received packet: from 192.168.1.124[4500] to 192.168.1.123[4500] (80 bytes) Sep 04 15:21:06 u18 charon[9815]: 10[ENC] parsed IKE_AUTH response 1 [ N(AUTH_FAILED) ] Sep 04 15:21:06 u18 charon[9815]: 10[IKE] received AUTHENTICATION_FAILED notify error
I got it to work, but the service name for strongswan is called
strongswan-starter
on ubuntu 20. Just a heads up.Good tutorial, I would add that for IOS you need to import the ca-cert.pem before attempting to connect. Otherwise will fail.