Setup an IKEv2 server with strongSwan

Setup an IKEv2 server with strongSwan

more private for your public network

IKEv2, or Internet Key Exchange v2, is a protocol that allows for direct IPSec tunnelling between two points. In IKEv2 implementations, IPSec provides encryption for the network traffic. What’s more, 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.

This tutorial is adapted from this post with little customisations. Also, contexts were based on a Ubuntu 20.04 server (also works on 18.04, I just upgraded from that).

Installing strongSwan

First, we’ll install strongSwan. We’ll also install the public key infrastructure (PKI) 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 following commands:

sudo apt update
sudo apt install strongswan strongswan-pki libcharon-extra-plugins libcharon-extauth-plugins

The additional libcharon-extauth-plugins package is used to ensure the various clients (especially Windows 10) can authenticate to the strongSwan server using username and passphrase.

Now that everything’s installed, let’s move on to creating our certificates.

Creating a certificate authority

An IKEv2 server requires a certificate to identify itself to clients. To help us create the certificates required, the strongswan-pki package comes with a utility (pki) 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.

Execute the following command to generate a RSA key with a cryptographic strength of 4096 bits:

pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem

Alternative key type are ecdsa, ed25519 and ed448.

Never store the private key of the Certificate Authority (CA) on a host with constant direct access to the Internet since a theft of this master signing key will completely compromise your PKI.1

Following that we can move on to creating our root certificate authority, using the key that we just generated to sign the root certificate:

pki --self --ca --lifetime 3652 --in ~/pki/private/ca-key.pem \
    --dn "C=CN, O=Frank inDev., CN=strongSwan Root CA" \
    --type rsa \
    --outform pem > ~/pki/cacerts/ca-cert.pem

The --lifetime 3652 flag is used to ensure that the certificate authority’s root certificate will be valid for 10 years.

You can change the Distinguished Name (DN)2 value to something else if you would like. The Common Name (CN field) here is just the indicator, so it doesn’t have to match anything in your infrastructure, just name it of your choice.

You can list the information with the pki --print command.

pki --print --in ~/pki/cacerts/ca-cert.pem 

If you prefer the CA private key and X.509 certificate to be in binary DER format then just omit the --outform pem option.

Now that we’ve got our root certificate authority up and running, we can create a certificate that the StrongSwan server will use.

Generating a certificate for the strongSwan server

We’ll now create a end entity certificate and key for the strongSwan server. This certificate will allow the client to verify the server’s authenticity using the CA certificate that we just generated.

First, create a private key for the strongSwan server with the following command:

pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem

Now, create and sign the strongSwan 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 server’s DNS name or IP address:

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

Through the use of the (multiple) --san parameter any number of desired subjectAlternativeNames can be added. These can be of the form:

--san     # fully qualified host name
--san   # RFC822 user email address
--san            # IPv4 address
--san fec0::1                # IPv6 address

Although strongSwan doesn’t support wildcard certs, you can assign multiple domains through --san:

--dn "" --san "" --san ""

Note: If you are using an IP address instead of a DNS name, you will need to specify multiple --san entries. The line in the previous command block where you specify the distinguished name (--dn ...) will need to be modified with the extra entry like the following excerpted line:

--dn "CN=IP_address --san @IP_address --san IP_address \"

The reason for this extra --san @IP_address entry is that some clients will check whether the TLS certificate has both an DNS entry and an IP address entry for a server when they verify its identity.

The --flag serverAuth option is used to indicate that the certificate will be used explicitly for server authentication, before the encryption tunnel is established. The --flag ikeIntermediate option is used to support old macOS clients.

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/

After this, you can safely delete the ~/pki/ folder.

In this step, we’re created a certificate pair that will be used to secure communications between the client and the strongSwan server. We’ve also signed the certificates with the CA key, so the client will be able to verify the authenticity of the strongSwan server using the CA certificate. With all of these certificates ready, we’ll move on to configuring the strongSwan server.

Configuring strongSwan

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

A complete configuration is presented at the end of this section, but it’s better to understand the meaning of each part.

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"

Then, we’ll create a configuration section for our server. We’ll also tell strongSwan to create IKEv2 tunnels and to automatically load this configuration section when it starts up. Append the following lines to the ipsec.conf file:

. . .
conn ikev2-strongswan

We’ll also configure dead-peer detection to clear any “dangling” connections in case the client unexpectedly disconnects. Add these lines:

. . .
conn ikev2-strongswan
    . . .

Then, we’ll configure the server (left) side IPSec parameters. Add these to the file:

. . .
conn ikev2-strongswan
    . . .

Each of the parameters ensures that the server is configured to accept connections from clients and to identify itself correctly.

  • left=@any: The %any value ensures that the server will use the network interface where it receives incoming connections for subsequent communication with clients. For example, if you are connecting a client over a private network, the server will use the private IP address where it receives traffic for the rest of the connection.

  • leftid=@server_domain_or_IP: This option controls the name that the server presents to clients. When combined the the next option leftcert, the leftid option ensures that the server’s configured name and the distinguished name that is contained in the public certificate match. If you’d like to support multiple domains, you can use leftid=@*

  • leftcert=server-cert.pem: This option is the path to the public certificate for the server that you configured in previous step. Without it, the server will not be able to authenticate itself with clients, or finish negotiating the IKEv2 set up.

  • leftsendcert=always: The always value ensures that any client that connects to the server will always receive a copy of the server’s public certificate as part of the initial connection set up.

  • leftsubnet= This tells clients about the subnets that are reachable behind the server. In this case, is used to represent the entire set of IPv4 addresses, meaning that the server will tell clients to send all their traffic over the IKEv2 tunnel by default.

Note: When configuring the server ID (leftid), only include the @ character if your strongSwan server will be identified by a domain name:

If the server will be identified by its IP address, just put the IP address without the @ character, for example:


Next, we can configure the client (right) side IPSec parameters, like the private IP address ranges and DNS servers to use:

conn ikev2-strongswan
    . . .
  • right=%any: The %any option for the right side of the connection instructs the server to accept incoming connections from any remote client.

  • rightid=%any: This option ensures that the server will not reject connections from clients that provide an identity before the encrypted tunnel is established.

  • rightauth=eap-mschapv2: This option configures the authentication method that clients will use to authenticate to the server. eap-mschapv2 is used here for broad compatibility to support clients like Windows, macOS, and Android devices.

  • rightsourceip= This option instructs the server to assign private IP addresses to clients from the specified pool of IPs.

  • rightdns=, These IP addresses are Google’s public DNS resolvers. They can be changed to use other public resolvers. Here is a list of known DNS providers to choose from.

  • rightsendcert=never: This option instructs the server that clients do not need to send a certificate to authenticate themselves.

Now we’ll tell strongSwan to ask the client for user credentials when they connect:

conn ikev2-strongswan
    . . .

Finally, add the following lines to support Linux, Windows, macOS, iOS, and Android clients. These lines specify the various key exchange, hashing, authentication, and encryption algorithms (commonly referred to as Cipher Suites) that strongSwan will allow different clients to use:

conn ikev2-strongswan
    . . .

Each supported cipher suite is delineated from the others by a comma. For example, chacha20poly1305-sha512-curve25519-prfsha512 is one suite, and aes256gcm16-sha384-prfsha384-ecp384 is another. The cipher suites that are listed above are selected to ensure the widest range of compatibility across multiple platforms.

The complete configuration file should look like this:

config setup
    charondebug="ike 1, knl 1, cfg 0"

conn ikev2-strongswan

Save and close the file once you’ve verified that you’ve configured each line correctly.

Configuring strongSwan authentication

Our IKEv2 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:

  • We need to tell strongSwan where to find the private key for our server certificate, so the server will be able to authenticate to clients.
  • We also need to set up a list of users that will be allowed to connect to the strongSwan server.

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 server parameters, we’ll restart the strongSwan service so that our configuration is applied:

sudo systemctl restart strongswan-starter

Older versions of strongSwan should refer to the system service name of strongswan, to restart the strongSwan use sudo systemctl restart strongswan.

Now that the strongSwan 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.

Ads by Google

Configuring the Firewall & Kernel IP forwarding

With the strongSwan configuration complete, we need to configure the firewall to forward and allow network traffic through.

First, allow UDP traffic to the standard IPSec ports, 500 & 4500. I configured this in the server provider’s firewall web interface. And you should config it via iptables or UFW, choose one that fits your needs.

Using iptables:

We will edit the iptables with 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.

ip route | grep default

Your public interface should follow the word “dev”, ens3 for example.

When you have your public network interface, add the following configuration block:

sudo iptables -t nat -A POSTROUTING -o ens3 -m policy --pol ipsec --dir out -j ACCEPT
sudo iptables -t nat -A POSTROUTING -o ens3 -j MASQUERADE

sudo iptables -t mangle -A FORWARD --match policy --pol ipsec --dir in -o ens3 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360

Change each instance of ens3 in the above configuration to match the interface name you found with ip route. The -t nat lines create rules so that the firewall can correctly route and manipulate traffic between the clients and the internet. The -t mangle line adjusts the maximum packet segment size to prevent potential issues with certain clients.

Next, we’ll change some network kernel parameters to allow routing from one interface to another. Open kernel parameters configuration file:

sudo nano /etc/sysctl.conf

We’ll need to configure a few things here:

  • First, we’ll enable IPv4 packet forwarding so that traffic can move between the strongSwan server and public facing network interfaces.

  • We’ll disable Path MTU discovery to prevent packet fragmentation problems.

  • We also won’t accept ICMP redirects nor send ICMP redirects to prevent man-in-the-middle attacks.

Add or uncomment these lines in sysctl.conf file:

. . .

# 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

If you need IPv6 support, also uncomment:

  • net.ipv6.conf.all.forwarding=1
  • net.ipv6.conf.all.accept_redirects = 0

Save the file to persist the settings:

sudo sysctl -p

Using UFW:

First add a rule to allow UDP traffic to port 500 & 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.

When you have your public network interface (i.e. ens3), open the /etc/ufw/before.rules file in your text editor. The rules in this file are added to the firewall before the rest of the usual input and output rules. They are used to configure NAT so that the server can correctly route connections to and from clients and the Internet.

sudo nano /etc/ufw/before.rules

Near the top of the file (before the *filter line), add the following configuration block. Change each instance of ens3 in the above configuration to match the interface name you found with ip route.

-A POSTROUTING -s -o ens3 -m policy --pol ipsec --dir out -j ACCEPT

-A FORWARD --match policy --pol ipsec --dir in -s -o ens3 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360

:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
. . .

Next, after the *filter and chain definition lines, add one more block of configuration:

. . .
: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 -j ACCEPT
-A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d -j ACCEPT

When you’re finished, save and close the file once you’ve verified that you’ve added each line correctly.

Before restarting the firewall, we’ll change some network kernel parameters to allow routing from one interface to another. The file that controls these settings is called /etc/ufw/sysctl.conf. We’ll need to configure a few things in the file including.

sudo nano /etc/ufw/sysctl.conf
. . .

. . .

. . .

Save and close the file when you’re finished. Now we can enable all of our changes by disabling and re-enabling the firewall, since UFW applies these settings any time that it restrats:

sudo ufw disable
sudo ufw enable

Connection on macOS, iOS, Android, and Windows

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 strongSwan server. 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:


. . .


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.

Connecting from macOS

Follow these steps to import the certificate:

  • Double-click the certificate file. Keychain Access will pop up with a dialog that says “Keychain Access is trying to modify the system keychain. Enter your password to allow this.”

  • Enter your password, then click on Modify Keychain

  • Double-click the newly imported certificate (display name as configured CN name, i.e., strongSwan root CA as previous example). This brings up a small properties window where you can specify the trust levels. Set IP Security (IPSec) to Always Trust and you’ll be prompted for your password again. This setting saves automatically after entering the password.

Now that the certificate is important and trusted, configure the network connection with these steps:

  • Go to System Preferences and choose Network.

  • Click on the small “plus” button on the lower-left of the list of networks.

  • In the popup that appears, Set Interface to VPN, set the VPN Type to IKEv2, and give the connection a name.

  • In the Server Address and Remote ID field, enter the server’s domain name or IP address. Leave the Local ID blank.

  • Click on Authentication Settings, select Username, and enter your username and password you configured. Then click OK.

Finally, click on Connect to connect to the IKEv2 tunnel. You should now be connected to the strongSwan server.

Connecting from iOS

To configure the strongSwan connection on an iOS device, follow these steps:

  • Send yourself an email with the root certificate attached.

  • Open the email on your iOS device and tap on the attached certificate file, then tap Install and enter your passcode. Once it installs, tap Done.

  • Go to Settings, General, VPN and tap Add VPN Configuration. This will bring up the VPN connection configuration screen.

  • Tap on Type and select IKEv2.

  • In the Description field, enter a short name for the VPN connection. This could be anything you like.

  • In the Server and Remote ID field, enter the server’s domain name or IP address. The Local ID field can be left blank.

  • Enter your username and password in the Authentication section, then tap Done.

  • Select the VPN connection that you just created, tap the switch on the top of the page, and you’ll be connected.

Connecting from Android

Follow these steps to import the certificate:

  • Send yourself an email with the CA certificate attached. Save the CA certificate to your downloads folder.

  • Download the strongSwan VPN client from the Play Store, or download it from strongSwan’s official website:

  • Open the strongSwan app. Tap the “more” icon (…) in the upper-right corner and select CA certificates.

  • Tap the “more” icon (…) in the upper-right corner again. Select Import certificate.

  • Browse to the CA certificate file in your downloads folder and select it to import it into the app.

Now that the certificate is imported into the strongSwan app, you can configure the VPN connection with these steps:

  • In the app, tap ADD VPN PROFILE at the top.

  • Fill out the Server with your strongSwan server’s domain name or public IP address.

  • Make sure IKEv2 EAP (Username/Password) is selected as the VPN Type.

  • Fill out the Username and Password with the credentials you defined on the server.

  • Deselect Select automatically in the CA certificate section and click Select CA certificate.

  • Tap the IMPORTED tab at the top of the screen and choose the CA you imported.

  • If you’d like, fill out Profile name (optional) with a more descriptive name.

Connecting from Windows

First, import the root certificate by following these steps:

  1. Press WINDOWS+R to bring up the Run dialog, and enter mmc.exe to launch the Windows Management Console.

  2. From the File menu, navigate to Add or Remove Snap-in, select Certificates from the list of available snap-ins, and click Add.

  3. We want the strongSwan IKEv2 to work with any user, so select Computer Account and click Next.

  4. We’re configuring things on the local computer, so select Local Computer, then click Finish.

  5. Under the Console Root node, expand the Certificates (Local Computer) entry, expand Trusted Root Certification Authorities, and then select the Certificates entry.

Install certificate on Windows

  1. From the Action menu, select All Tasks and click Import to display the Certificate Import Wizard. Click Next to move past the introduction.

  2. On the File to Import screen, press the Browse button, ensure that you change the file type from “X.509 Certificate (.cer;.crt)” to “All Files (.)”, and select the certificate file that you’ve saved. Then click Next.

  3. Ensure that the Certificate Store is set to Trusted Root Certification Authorities, and click Next.

  4. Click Finish to import the certificate.

Then configure the network connection with these steps:

  • Launch Control Panel, then navigate to the Network and Sharing Center.

  • Click on Set up a new connection or network, then select Connect to a workplace.

  • Select Use my Internet connection (VPN).

  • Enter the strongSwan server details. Enter the server’s domain name or IP address in the Internet address field, then fill in Destination name with something that describes your strongSwan connection. Then click Done.

Your new strongSwan 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.

Configuring Windows using PowerShell

To import the root CA certificate using PowerShell, first open a PowerShell prompt with administrator privileges. To do so, right click the Start menu icon and select Windows PowerShell (Admin). You can also open a command prompt as administrator and type powershell.

Next we’ll import the certificate using the Import-Certificate PowerShell cmdlet. In the following command, the first -CertStoreLocation argument will ensure that the certificate is imported into the computer’s Trusted Root Certificate Authorities store so that all programs and users will be able to verify the strongSwan server’s certificate. The -FilePath argument should point to the location where you copied the certificate. In the following example the path is C:\Users\franklin\Documents\ca-cert.pem. Ensure that you edit the command to math the location that you used.

Import-Certificate `
    -CertStoreLocation cert:\LocalMachine\Root\ `
    -FilePath C:\users\sammy\Documents\ca-cert.pem

The command will output something like the following:


   PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\Root

Thumbprint                                Subject
----------                                -------
DB00813B4087E9367861E8463A60CEA0ADC5F002  CN=strongSwan root CA

Now to configure the VPN using PowerShell, run the following command. Substitute your server’s DNS name or IP address on the -ServerAddress line. The various flags will ensure that Windows is correctly configured with the appropriate security parameters that match the options that you set in /etc/ipsec.conf.

Add-VpnConnection -Name "VPN Connection" `
    -ServerAddress "server_domain_or_IP" `
    -TunnelType "IKEv2" `
    -AuthenticationMethod "EAP" `
    -EncryptionLevel "Maximum" `
    -RememberCredential `

If the command is successful there will not be any output. To confirm the VPN is configured correctly, use the Get-VPNConnection cmdlet:

Get-VpnConnection -Name "VPN Connection"

You will receive output like the following:


Name                  : VPN Connection
ServerAddress         : your_server_ip
AllUserConnection     : False
Guid                  : {B055A1AB-175C-4028-B4A8-D34309A2B20E}
TunnelType            : Ikev2
AuthenticationMethod  : {Eap}
EncryptionLevel       : Maximum
L2tpIPsecAuth         :
UseWinlogonCredential : False
EapConfigXmlStream    : #document
ConnectionStatus      : Disconnected
RememberCredential    : True
SplitTunneling        : False
DnsSuffix             :
IdleDisconnectSeconds : 0

By default Windows choose older and slower algorithms. Run the Set-VpnConnectionIPsecConfiguration cmdlet up upgrade the encryption parameters that Windows will use for the IKEv2 key exchange, and to encrypt packets:

Set-VpnConnectionIPsecConfiguration -Name "VPN Connection" `
    -AuthenticationTransformConstants GCMAES256 `
    -CipherTransformConstants GCMAES256 `
    -DHGroup ECP384 `
    -IntegrityCheckMethod SHA384 `
    -PfsGroup ECP384 `
    -EncryptionMethod GCMAES256

Note: If you would like to delete the VPN connection and reconfigure it with different options, you can run the Remove-VpnConnection cmdlet.

Remove-VpnConnection -Name "VPN Connection" -Force

The -Force flag will skip prompting you to confirm the removal. You must be disconnected from the VPN if you attempt to remove it using this command.

Now, you can connect to the strongSwan server in the list of networks.

Special notes for IPv6 routes on Windows 10

Windows always requires something special - you have to set IPv6 routes manually:

First, connect to the server, it’s connected but IPv6 is not working yet. Then search for cmd or powershell - and run it as an administrator. List all network devices and set the default route for that interface:

netsh interface ipv6 show interfaces

netsh interface ipv6 add route ::/0 interface="<name of the strongswan connection>"


In this post, you’ve built a strongSwan server that uses the IKEv2 protocol. Now you can be assured that your online activities will remain secure wherever you go!

This is a much easier implementation than OpenConnect(ocserv) that a single click brought me to a secure network environment.

Ads by Google


Frank Lin, PhD

Hey, there! This is Frank Lin (@flinhong), one of the 1.41 billion . This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.


Hands on IBM Cloud Functions with CLI



Hands on IBM Cloud Functions with CLI

IBM Cloud CLI allows complete management of the Cloud Functions system. You can use the Cloud Functions CLI plugin-in to manage your code snippets in actions, create triggers, and rules to enable your actions to respond to events, and bundle actions into packages.