Tag Archives: strongswan

Android VPN

strongswanandroid

This setup below is what suited my requirements.  I'm sure there'll be another way of implementing this, but this works for me :)

For this I'm using the following:

# emerge --info
Portage 2.3.0 (python 3.4.3-final-0, default/linux/amd64/13.0/no-multilib, gcc-4.9.3, glibc-2.22-r4, 4.8.7-gentoo x86_64)
=================================================================
System uname: Linux-4.8.7-gentoo-x86_64-Intel-R-_Core-TM-_i7-6700K_CPU_@_4.00GHz-with-gentoo-2.2
KiB Mem: 32896588 total, 15127076 free
KiB Swap: 3640916 total, 3640916 free
Timestamp of repository gentoo: Sun, 13 Nov 2016 04:15:01 +0000

And this version of strongswan:

# emerge -p strongswan

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild R ~] net-misc/strongswan-5.5.0

Strongswan Config

Once installed, we need to setup the configs.  The main config is located at /etc/ipsec.conf:

This is my file with the obvious changes ;)

# ipsec.conf - strongSwan IPsec configuration file

config setup
 uniqueids=never
 #charondebug="cfg 2, dmn 2, ike 2, net 2"

conn %default
 dpdaction=restart
 dpddelay=300s
 reauth=yes
 aggressive=no
 fragmentation=yes
 type=tunnel
 forceencaps=yes
 modeconfig=pull
 auto=add
 closeaction=clear
 compress=no
 left=my.vpn.com
 leftid="C=GB, O=strongSwan, CN=my.vpn.com"
 leftsubnet=0.0.0.0/0
 leftcert=vpnHostCert.pem
 leftsendcert=always
 leftfirewall=yes

conn IPSec-Android-Strongswan
 keyexchange=ikev2
 rightauth=pubkey
 rightauth2=eap-md5
 right=%any
 rightid="C=GB, O=strongSwan, CN=my@email.com"
 rightsourceip=10.10.10.199/31
 rightsendcert=ifasked

# Unable to get the native VPN working with this setup
#conn IPSec-Android-Native
# keyexchange=ikev1
# rightauth=pubkey
# rightauth2=xauth
# right=%any
# rightsourceip=10.10.10.199/26
# rightsendcert=ifasked

I'll explain each segment in order.  The official doc can be found here.

conn %default This is the default stanza.  This instructs strongswan to use anything here in addition to other connections if defined.
dpdaction=restart Controls the use of the Dead Peer Detection.
dpddelay=300s How often to check if the client is still connected.
reauth=yes When re-exchanging keys whether to re-athenticate.
aggressive=no Whether to use IKEv1 Aggressive or Main Mode (the default).
fragmentation=yes If set to yes (the default since 5.5.1) and the peer supports it, larger IKE messages will be sent in fragments.
type=tunnel The type of the connection.
forceencaps=yes Force UDP encapsulation for ESP packets even if no NAT situation is detected.
modeconfig=pull Defines which mode is used to assign a virtual IP.
auto=add What operation, if any, should be done automatically at IPsec startup.
closeaction=clear Defines the action to take if the remote peer unexpectedly closes.
compress=no Whether IPComp compression of content is proposed on the connection.
left=my.vpn.com The IP address of the participant's public-network interface.
leftid="C=GB, O=strongSwan, CN=my.vpn.com" How the left|right participant should be identified for authentication.
leftsubnet=0.0.0.0/0 Private subnet behind the left participant.
leftcert=vpnHostCert.pem The path to the left|right participant's X.509 certificate.
leftsendcert=always Ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return
leftfirewall=yes Whether the left participant is doing forwarding-firewalling (including masquerading)
using iptables for traffic from leftsubnet.
conn IPSec-Android-Strongswan A connection stanza
keyexchange=ikev2 Method of key exchange.
rightauth=pubkey Authentication method to use locally (left) or require from the remote (right) side.
rightauth2=eap-md5 Same as rightauth, but defines an additional authentication exchange.
right=%any If %any is used for the remote endpoint it literally means any IP address.
rightid="C=GB, O=strongSwan, CN=my@email.com" How the right participant should be identified for authentication.
rightsourceip=10.10.10.199/26 The internal source IP to use in a tunnel for the remote peer.
rightsendcert=ifasked ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return.
conn IPSec-Android-Native A connection stanza
keyexchange=ikev1 Method of key exchange.
rightauth=pubkey Authentication method to use locally (left) or require from the remote (right) side.
rightauth2=xauth Same as rightauth, but defines an additional authentication exchange.
right=%any If %any is used for the remote endpoint it literally means any IP address.
rightsourceip=10.10.10.200 The internal source IP to use in a tunnel for the remote peer.
rightsendcert=ifasked ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return.

Next we setup a secret.

# cat /etc/ipsec.secrets 
: RSA vpnHostKey.pem
<user> : XAUTH "top_secret_password"
<user> : EAP "top_secret_password"

I'll explain each line.  Full documentation can be found here.

: RSA vpnHostKey.pem Sets the cert to be used for authentication.
<user> : XAUTH "top_secret_password" Sets the password for XAUTH method of authentication.
<user> : EAP "top_secret_password" Sets the password for EAP method of authentication.

That's it for the strongswan config itself. Now we need to create the certificates.

As of version 5.8.0, ipsec.conf and ipsec.secrets are no longer required or work.  These now need to be converted into a json format in swanctl.conf.

connections {
        IPSec-Android-Strongswan {
          unique=no
          version=2
          dpd_delay=300s
          rekey_time=0
          reauth_time=0
          aggressive=no
          fragmentation=yes
          encap=yes
          pull=yes
          version=2
          pools=vpn_example
          mobike=yes
          send_cert=always
                local {
                  certs=vpnHostCert.pem
                  id = @vpn.example.com
                }
                remote {
                  auth=pubkey
                }
                remote2 {
                  auth=eap-md5
                }
                children {
                        IPSec-Android-Strongswan {
                          mode=tunnel
                          dpd_action=clear
                          start_action=none
                          close_action=none
                          ipcomp=yes
                          local_ts=0.0.0.0/0
                        }
                }
        }
}
pools {
  vpn_example {
    addrs=10.10.10.10/30
  }
}
secrets {
  private-vpn_example {
    file=vpnHostKey.pem
  }
  eap-user1 {
    id=username1
    secret="password1"
  }
  eap-user2 {
    id=username2
    secret="password2"
  }
}
authorities {
  IPSec-Android-Strongswan {
    cacert=strongswanCert.pem
  }
}

Certificates

NOTE:  From 5.8.0, the certificate paths have changed from /etc/ipsec.d/... to /etc/swanctl/...

x509/ = User Certs

private/ = Private key(s)

x509ca/ = Root cert(s)

Let's start by creating the root certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 4096 --outform pem > private/strongswanKey.pem
$ chmod 600 private/strongswanKey.pem
$ ipsec pki --self --ca --lifetime 3650 --in private/strongswanKey.pem --type rsa --dn "C=GB, O=strongSwan, CN=strongSwan Root CA" --outform pem > cacerts/strongswanCert.pem

You can change the Distinguished Name (DN) to more relevant values for country (C), organization (O), and common name (CN), but you don’t have to.

To list the properties of your newly generated certificate, type in the following command:

$ ipsec pki --print --in cacerts/strongswanCert.pem

Create your VPN host certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 2048 --outform pem > private/vpnHostKey.pem
$ chmod 600 private/vpnHostKey.pem
$ ipsec pki --pub --in private/vpnHostKey.pem --type rsa | ipsec pki --issue --lifetime 730 --cacert cacerts/strongswanCert.pem --cakey private/strongswanKey.pem --dn "C=GB, O=strongSwan, CN=my.vpn.com" --san my.vpn.com --flag serverAuth --flag ikeIntermediate --outform pem > certs/vpnHostCert.pem

To look at the properties of your new certificate, execute the command:

ipsec pki --print --in certs/vpnHostCert.pem

Create a client certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 2048 --outform pem > private/UserKey.pem
$ chmod 600 private/UserKey.pem
$ ipsec pki --pub --in private/UserKey.pem --type rsa | ipsec pki --issue --lifetime 730 --cacert cacerts/strongswanCert.pem --cakey private/strongswanKey.pem --dn "C=GB, O=strongSwan, CN=user@vpn.com" --san user@vpn.com --outform pem > certs/UserCert.pem

Export client certificate as a PKCS#12 file:

cd /etc/ipsec.d/
$ openssl pkcs12 -export -inkey private/UserKey.pem \
 -in certs/UserCert.pem -name "User's VPN Certificate" \
 -certfile cacerts/strongswanCert.pem \
 -caname "strongSwan Root CA" \
 -out User.p12

Revoke a certificate (if needed):

$ cd /etc/ipsec.d/
$ ipsec pki --signcrl --reason key-compromise \
 --cacert cacerts/strongswanCert.pem \
 --cakey private/strongswanKey.pem \
 --cert certs/UserCert.pem \
 --outform pem > crls/crl.pem

To add another revoked certificate to the same list, we need to copy the existing list into a temporary file:

$ cd /etc/ipsec.d/
$ cp crls/crl.pem crl.pem.tmp
$ ipsec pki --signcrl --reason key-compromise \
	--cacert cacerts/strongswanCert.pem \
	--cakey private/strongswanKey.pem \
	--cert certs/AnotherStolenCert.pem \
	--lastcrl crl.pem.tmp \
	--outform pem > crls/crl.pem
$ rm crl.pem.tmp

CERTIFICATES – RECAP:

So far you’ve created the following files:

/etc/ipsec.d/private/strongswanKey.pem  # CA private key
/etc/ipsec.d/cacerts/strongswanCert.pem # CA certificate
/etc/ipsec.d/private/vpnHostKey.pem     # VPN host private key
/etc/ipsec.d/certs/vpnHostCert.pem      # VPN host certificate
/etc/ipsec.d/private/UserKey.pem   # Client "User" private key
/etc/ipsec.d/certs/UserCert.pem    # Client "User" certificate
/etc/ipsec.d/User.p12              # Client "User" PKCS#12 file

Firewall Rules

I'm sure you'll have some sort of router ;)  So you'll need to open up and forward the ports to your VPN server.

You'll only need UDP ports 500 & 4500.

Port 500 is the IPSEC port and 4500 is the port used for NATing.

That's the entry point sorted.  Now for iptables.

I have these defined to manage the VPN traffic:

iptables -t nat -A POSTROUTING -s <VIP> -o <INTERFACE> -m policy --dir out --pol ipsec -j ACCEPT
iptables -t nat -A POSTROUTING -s <VIP> -o <INTERFACE> -j MASQUERADE
iptables -t nat -A POSTROUTING -o <INTERFACE> ! -p esp -j SNAT --to-source <VPN_IP>
iptables -A INPUT -p esp -j ACCEPT
iptables -A INPUT -p ah -j ACCEPT

<VIP> is the IP/CIDR which is assigned to the client.
<INTERFACE> is the network interface name eg eth0.
<VPN_IP> is the IP the VPN server listens on.
The bottom two just accept the required protocols.

You may also need to open up access to ranges used by your mobile service provider.  eg

iptables -A INPUT -s <mobile_cidr>/22 -p udp -m multiport --dports 500,4500 -j ACCEPT

You may also need to allow the VIP address assigned to the client to connect to internal services.  This could be something as global as:

iptables -A INPUT -s 10.10.10.200 -j ACCEPT

or could be tied down to specific ports.

DNS

If the virtual IP that is assigned is on the same network as the server, you can just add the following to your ipsec.conf:

rightdns = <dns_server_ip>

If you assign a virtual IP that is on a different network, then you will need to make some additional changes.  You won't see any errors regarding DNS in any logs, it just won't work!
For example, in the client log, you'd see:

Aug 28 06:59:18 08[IKE] installing DNS server 111.111.111.119
Aug 28 06:59:18 08[IKE] installing new virtual IP 112.112.112.120

but if you try and resolve any internal hostnames, it just won't work.

You need to make the following change to either strongswan.conf or charon.conf (recommended) within the strongswan.d directory.

charon {
    plugins {
        attr {
        dns = 111.111.111.119
       split-include = 112.112.112.120, 111.111.111.0/24
             }
            }
       }

As we are splitting the DNS, we need to use the attr plugin.  You can check if this is loaded when the strongswan daemon is started.

Aug 28 07:28:23 <hostname> charon[22120]: 00[LIB] loaded plugins: charon pkcs11 aes des blowfish rc2 sha2 sha1 md4 md5 rdrand random nonce x509 revocation constraints pubkey pkcs1 pkcs7 pkcs8 pkcs12 pgp dnskey sshkey pem openssl gcrypt fips-prf gmp xcbc cmac hmac ctr ccm gcm attr kernel-netlink resolve socket-default socket-dynamic farp stroke vici updown eap-identity eap-sim eap-aka eap-aka-3gpp2 eap-simaka-pseudonym eap-simaka-reauth eap-md5 eap-gtc eap-mschapv2 eap-radius eap-tls xauth-generic xauth-eap xauth-pam dhcp unity

The other thing you will need to do (only if you run your own DNS) is to allow the VPN network to query DNS.  This is done by adding the VPN subnet or assigned virtual IP of the client to named.conf.

This is found within the options block.

allow-query { 127.0.0.1; 111.111.111.0/24; 112.112.112.120; };

Client setup (strongswan)

First of all, you'll need to get the pk12 certificate you've created onto your phone (email, cloud storage etc etc).  Once saved to a location, we need to load it into Android.

Go to settings and tap "Security".

Then tap "Install from storage".

Browse to where you saved the cert.  You will be asked for the passphrase set in the cert.

Once installed, go back to "Security" and tap "User credentials"

You should see your certificate entry.  There are no details to be had here.  The only option if you tap the cert is to remove it.

That's it for the certificate installation; now onto the client setup.

If you haven't installed Strongswan, what are you waiting for? ;)

Open the app and tap "ADD VPN PROFILE"

Complete the details and ensure you have selected the installed certificate (User certificate).

Click SAVE and you're done.

Now to test it!  Disconnect from your wifi and tap the entry you should now have in the strongswan app.  If all went well, you should be connected.