Configuring IPsec IKEv2 in OpenWrt 15.05

The interoperability of IPsec implementations on various platforms has been becoming better and better over the last few years. For example, Windows 7 and newer releases fully support the IKEv2 (RFC 4306) and MOBIKE (RFC 4555) standards, and iOS started to support configuration of IKEv2 in the GUI since version 9.0.

In this tutorial, we’ll install strongSwan 5.3.3 in openwrt 15.05, configure it to provide IKEv2 service with public key authentication of the server and username/password based authentication of the clients using EAP-MSCHAP v2, and finally setup the VPN clients in Windows, Android and iOS so they can connect to it. Much of the complexity of IKEv2 configuration lies in the creation of SSL certificates.

Installation

First of all, install necessary strongSwan packages in openwrt 15.05:

root@OpenWrt:~# opkg update
root@OpenWrt:~# opkg install strongswan-minimal strongswan-mod-eap-mschapv2 strongswan-mod-eap-identity strongswan-mod-constraints strongswan-mod-md5 strongswan-mod-pem strongswan-mod-pkcs1 strongswan-mod-revocation

Creating CA and server certificates

I recommend using XCA to create and maintain your root CA for your IKEv2 service. iOS silently refuses to trust CA certificates with MD5 signatures. So make sure to create CA certificates with SHA1, or better SHA256, signatures. Export your CA certificate in DER format. In the configuration example below, our CA cert is exported as file ZhangsRootCA2.cer. You are advised to upload the CA certificate to a secured web server or mail it to your own E-mail accounts.

Different IPsec implementations have different requirements on the server certificate. See the strongSwan wiki article for details. These requirements can be satisfied in XCA by making the following changes to a new certificate based on its HTTPS_server template:

1. Add “IP security end entity” to “X509v3 Extended Key Usage” attribute.
2. Add all domain names and IP addresses of the IPsec server to the “X509v3 Subject Alternative Name” in the type of DNS and IP. IP addresses can be added to the SAN attribute as both DNS and IP to achieve best compatibility.

Here are the important details of an example IPsec server certificate created using XCA:

commonName: openwrt
X509v3 Extended Key Usage: TLS Web Server Authentication, IP security end entity
X509v3 Subject Alternative Name: DNS:openwrt, DNS:openwrt.lan, DNS:ipsec.example.com, DNS:192.168.1.1, DNS:10.8.0.1, IP Address:192.168.1.1, IP Address:10.8.0.1 
Netscape Cert Type: SSL Server

Export the server cert and the server key as openwrt.cer and openwrt.der respectively. The server key should only be stored in openwrt.

Configuration

Certificates

1. Save the CA certificate in folder /etc/ipsec.d/cacerts/.

2. Save the server key as /etc/ipsec.d/private/openwrt.der. Change the file permission of the key file to 0600:

# chmod 0600 /etc/ipsec.d/private/*

3. Save the server certificate as /etc/ipsec.d/certs/openwrt.cer.

/etc/ipsec.conf

# ipsec.conf - strongSwan IPsec configuration file

# basic configuration

config setup
        # strictcrlpolicy=yes
        # uniqueids = no
        uniqueids=never

conn roadwarrior-ikev2
        keyexchange=ikev2
        dpdaction=clear
        dpddelay=300s
        rekey=no
        left=%any
        leftid=openwrt
        leftcert=openwrt.cer
        leftauth=pubkey
        leftsendcert=always
        leftsubnet=0.0.0.0/0
        leftfirewall=yes
        right=%any
        rightauth=eap-mschapv2
        rightsourceip=<CIDR>
        rightdns=<DNS>
        eap_identity=%any
        auto=add

Note: rightsourceip can specify an IP address pool in the form of CIDR notation. rightdns specifies the IP address of the DNS server that the IPsec clients should use.

/etc/ipsec.secrets

# /etc/ipsec.secrets - strongSwan IPsec secrets file
: RSA openwrt.der
<username> : EAP "<PASSWORD>"

Firewall rules

If you want to connect from the WAN side, add the following configuration to /etc/config/firewall:

# allow incoming IPsec connections
config rule
 option src wan
 option proto esp
 option target ACCEPT

config rule
 option src wan
 option proto udp
 option dest_port 500
 option target ACCEPT

config rule
 option src wan
 option proto udp
 option dest_port 4500
 option target ACCEPT

config rule
 option src wan
 option proto ah
 option target ACCEPT

and then restart the firewall:

root@OpenWrt:~# /etc/init.d/firewall restart

Circumventing the PMTUD Problem

It’s a common practice in IPsec implementations to set the MTU of the IPsec tunnel interface to 1400 or lower. You won’t experience Path MTU Discovery problems if the MTU of your WAN interface is standard, which is 1500 in the case of Ethernet, or 1492 in the case of PPPoE. However, if the MTU of your WAN interface is significantly lower than 1500, you need to set the MTU of the installed routes for IPsec clients to a value lower than 1400, which can be achieved using the strongswan kernel-netlink module.

The MTU of my PPPoE WAN interface is 1442. To prevent IPsec clients from running into PMTUD problems, I have to change the mtu option in /etc/strongswan.d/charon/kernel-netlink.conf to around 1350:

# MTU to set on installed routes, 0 to disable.
mtu = 1352

Testing

Now stop the IPsec IKE daemon and restart it in foreground, so that we can immediately see its log messages on the ssh console:

root@OpenWrt:~# ipsec stop
root@OpenWrt:~# ipsec start --nofork

After testing is done, interrupt the “ipsec start –nofork” command by pressing Ctrl-C and start ipsec again by typing the following command:

root@OpenWrt:~# ipsec start

We can check the detailed information about established and configured connections by typing the ipsec status and statusall commands.

root@OpenWrt:~# ipsec status
root@OpenWrt:~# ipsec statusall

Client Configuration

Android 5+

1. Install the official strongSwan app.

2. Import the CA certificate ZhangsRootCA2.der. When opening the certificate, you’ll be prompted whether to open with the android “Certificate Installer” or the strongSwan “Import certificate” utility. If you’re using the CA certificate for IPsec only, you may import it to the strongSwan app, instead of the system certificate store of your Android device.

3. Open the strongSwan app, and tap “ADD VPN Profile”.

4. Edit the profile as follows. Uncheck the “Select automatically” option under “CA certificate:” and manually select the CA certificate we just imported. Tap “Save”.

Android_strongSwan_IKEv2

iOS 9+

1. Import the CA certificate. As of iOS 9.2.1, a reboot is apparently necessary for the certificate import to take effect.

2. Open Settings / VPN, tap “Add VPN Configuration…“. Enter all the necessary information as follows, and then tap Done.

Description: profile name
Server: server address
Remote ID: commonName(CN) of server certificate
Username: username
Password: password

iOS9-VPN-IKEv2

Windows 10

1. Import the CA certificate, ZhangsRootCA2.cer, to the Trusted Root Certification Authorities / Certificates folder of the system certificate store:

Double-click the certificate file, click Open and then Install Certificate…. You must choose Local Computer as Store Location. On the Certificate Store popup, choose the option Place all certificates in the following store. Click Browse… and choose the Trusted Root Certification Authorities / Certificates folder. Click Next and then Finish to complete the certificate import.

2. Click the Windwos Start menu / Settings / Network and Internet / VPN / Add VPN Connection. Enter information as in the following screenshot. Click Save.

ipsec-ikev2-win10

3. By default, Windows 10 IPsec client adds a route to the remote network based on its IPv4 address class. If you want to set the default gateway on the remote network, you need to change the adapter settings of the VPN connection:

On the “Network and Internet / VPN” settings page, click “Change Adapter Settings“. Right-click the VPN connection you just created and then click “Properties / Networking tab / Internet Protocol Version 4 (TCP/IPv4) / Properties / Advanced(V)…“. On the “Advanced TCP/IP Properties” dialog, check “Use default gateway on the remote network”. Click the OK buttons to close the configuration dialogs you just opened.

Note: Although Windows 10 can successfully get the remote DNS server addresses when establishing IPsec connections, it keeps querying the local (LAN) DNS servers for resolving domain names. This can cause connectivity issues for GSLB (Global Server Load Balancing) domain names and those domain names under DNS-poisoning attacks. In such cases, you’re strongly advised to use a http proxy or a socks5 proxy server on the remote network.

41 comments

  • pazerbuy

    在Use default gateway on the remote network下面,把interface metric手动设为15,应该可以解决DNS问题。Win10真是一团渣。

  • froer

    用XCA制作的证书导出格式只有.cer和.crt,没有.der的选项,怎么办??

  • froer

    感谢!现在证书的问题搞定了,但是还有一个问题,我想同一个账号多个终端同时使用,/etc/config/firewall中rightsourceip=的格式改怎样写呢?我现在写成rightsourceip=192.168.100.20-30是不行的。

    • wenzhuo

      CIDR形式,如 192.168.100.192/27

      • froer

        uniqueids = yes | no | never | replace | keep

        whether a particular participant ID should be kept unique, with any new IKE_SA using an ID
        deemed to replace all old ones using that ID. Participant IDs normally are unique, so a new
        IKE_SA using the same ID is almost invariably intended to replace an old one.
        The difference between no and never is that the daemon will replace old IKE_SAs when receiving an
        INITIAL_CONTACT notify if the option is no but will ignore these notifies if never is configured.
        The daemon also accepts the value replace which is identical to yes and the value keep to reject
        new IKE_SA setups and keep the duplicate established earlier.

        以上几种参数都试过了,但是为什么就是同一id在不同终端上重复拨号分配不到不同的IP呢?只能最后一个拨号的上网。

  • 李勇

    你好,可以请“Creating CA and server certificates”,的操作命令列出来吗?

  • Rogan

    I can connect and ping the right hand virtual ip, but I do not see traffic coming back from my IOS10 phone.
    your config was very helpful, though I use letsencrypt public free certificates.

  • froer

    大哥,windows7连不上,客户端证书到地怎么做啊?我服务器证书:C=CN O=DIR505_VPN CN=DIR505_Root_CA,客户端:C=CN O=DIR505_VPN CN=CLIENT@DIR505,不行呢!!此外修改注册表HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\RasMan\Parameters\
    也不行,请赐教!

  • Robert

    export the server key as public or private der?

    • wenzhuo

      Xca exports key as .der and certificate as .cer

      • Robert

        Thanks for the reply, there are options called “Der Public(.der)” and “Der Private(.der)” available. Both are in .der.
        and XCA version is 1.3.2.
        Tried both .der formats. No success. Something else must be wrong. But to make the key is right first.

        • wenzhuo

          I was using xca ver. 1.1.0 when writing the article. It provides two options only for exporting keys: PEM and DER. As for the latest version, you should obviously choose DER private, according to its latest documentation: http://xca.sourceforge.net/xca-7.html#ss7.2

          • Robert

            Many thanks. Finally get iOS connected. Your tutorial is complete.
            Turns out the racoon service on my stock openwrt is alive and un-configed. It intercepts each incoming VPN connection request before strongswan.

  • hunhun

    大神,到底能不能让我提问啊?我可是怀着崇拜的心情来的啊

  • HunHun

    好的.首先感谢您的分享.

    其次请教您一个问题,我按照您的方法配置完成,唯一的不同就是我的证书不是自签发的,而是购买的证书,原因是:
    我在国外的VPS上部署了IKEv2/IPSec并且购买了comodorsa的证书,运行一切OK,所以证书肯定是没问题的.考虑到国内的VPS贵且家里现成的宽带可以利用,所以才打算在OpenWRT上安装IKEv2/IPSec服务器.

    另外就是mtu没改

    证书拷贝如下:
    ca.cert.pem拷入/etc/ipsec.d/cacerts/
    server.cert.pem和client.cert.pem拷入/etc/ipsec.d/certs/
    server.pem和client.pem拷入/etc/ipsec.d/private/

    /etc/ipsec.conf内容如下:
    config setup
    uniqueids=never

    conn iOS_cert
    keyexchange=ikev1
    fragmentation=yes
    left=%defaultroute
    leftauth=pubkey
    leftsubnet=0.0.0.0/0
    leftcert=server.cert.pem
    right=%any
    rightauth=pubkey
    rightauth2=xauth
    rightsourceip=10.31.2.0/24
    rightcert=client.cert.pem
    auto=add

    conn android_xauth_psk
    keyexchange=ikev1
    left=%defaultroute
    leftauth=psk
    leftsubnet=0.0.0.0/0
    right=%any
    rightauth=psk
    rightauth2=xauth
    rightsourceip=10.31.2.0/24
    auto=add

    conn networkmanager-strongswan
    keyexchange=ikev2
    left=%defaultroute
    leftauth=pubkey
    leftsubnet=0.0.0.0/0
    leftcert=server.cert.pem
    right=%any
    rightauth=pubkey
    rightsourceip=10.31.2.0/24
    rightcert=client.cert.pem
    auto=add

    conn ios_ikev2
    keyexchange=ikev2
    ike=aes256-sha256-modp2048,3des-sha1-modp2048,aes256-sha1-modp2048!
    esp=aes256-sha256,3des-sha1,aes256-sha1!
    rekey=no
    left=%defaultroute
    leftid=My Domain
    leftsendcert=always
    leftsubnet=0.0.0.0/0
    leftcert=server.cert.pem
    right=%any
    rightauth=eap-mschapv2
    rightsourceip=10.31.2.0/24
    rightsendcert=never
    eap_identity=%any
    dpdaction=clear
    fragmentation=yes
    auto=add

    conn windows7
    keyexchange=ikev2
    ike=aes256-sha1-modp2048!
    rekey=no
    left=%defaultroute
    leftauth=pubkey
    leftsubnet=0.0.0.0/0
    leftcert=server.cert.pem
    right=%any
    rightauth=eap-mschapv2
    rightsourceip=10.31.2.0/24
    rightsendcert=never
    eap_identity=%any
    auto=add

    /etc/ipsec.secrets内容如下:
    : RSA server.pem
    : PSK “mysecurepsk”
    : XAUTH “mysecurepsk”

    Test %any : EAP “Test”

    测试前先用虚拟机里的Win7(NAT方式上网)连了我的国外VPS,连接成功,说明客户端配置OK.然后修改hosts文件,将192.168.200.1对应我的那个域名,以便强制客户端连接OpenWRT的IKEv2/IPSec服务器,结果连不上,Win7提示13801错误: IKE authentication credentials are unacceptable

    检查OpenWRT上的输出,显示:
    10[NET] received packet: from 192.168.200.2[1000] to 192.168.200.1[500] (528 bytes)
    10[ENC] parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) ]
    10[IKE] 192.168.200.2 is initiating an IKE_SA
    10[IKE] remote host is behind NAT
    10[IKE] sending cert request for “C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO RSA Domain Validation Secure Server CA”
    10[ENC] generating IKE_SA_INIT response 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) CERTREQ N(MULT_AUTH) ]
    10[NET] sending packet: from 192.168.200.1[500] to 192.168.200.2[1000] (333 bytes)
    07[NET] received packet: from 192.168.200.2[4298] to 192.168.200.1[4500] (484 bytes)
    07[ENC] parsed IKE_AUTH request 1 [ IDi CERTREQ N(MOBIKE_SUP) CPRQ(ADDR DNS NBNS SRV ADDR6 DNS6 SRV6) SA TSi TSr ]
    07[IKE] received 8 cert requests for an unknown ca
    07[CFG] looking for peer configs matching 192.168.200.1[%any]…192.168.200.2[192.168.222.7]
    07[CFG] selected peer config ‘ios_ikev2’
    07[IKE] initiating EAP_IDENTITY method (id 0x00)
    07[IKE] peer supports MOBIKE
    07[LIB] hash algorithm HASH_SHA256 not supported
    07[IKE] authentication of ‘My Domain’ (myself) with RSA signature successful
    07[IKE] sending end entity cert “OU=Domain Control Validated, OU=PositiveSSL, CN=My Domain”
    07[ENC] generating IKE_AUTH response 1 [ IDr CERT AUTH EAP/REQ/ID ]
    07[NET] sending packet: from 192.168.200.1[4500] to 192.168.200.2[4298] (1732 bytes)
    (过了十几秒后)
    14[JOB] deleting half open IKE_SA after timeout

    另外,发现我在输入ipsec restart时,提示
    Stopping strongSwan IPsec…
    no files found matching ‘/etc/strongswan.d/*.conf’
    Starting strongSwan 5.3.2 IPsec [starter]…

    我将ipsec.conf复制到/etc/strongswan.d/,再运行ipsec restart,提示
    Stopping strongSwan IPsec…
    /etc/strongswan.d/ipsec.conf:1: syntax error, unexpected NAME, expecting NEWLINE or ‘{‘ or ‘=’ [setup]
    invalid config file ‘/etc/strongswan.conf’
    Starting strongSwan 5.3.2 IPsec [starter]…

    麻烦帮忙看一下问题原因,谢谢!

    • wenzhuo

      日志显示win7连接时选中的连接配置是ios_ikev2,建议你把ike、esp加密套件注释掉试试,或者按照https://wiki.strongswan.org/projects/strongswan/wiki/Win7EapMultipleConfig设置。另,/etc/ipsec.conf不能移到strongswan.d目录下。

      • Hun Hun

        加密套件注释掉了,那岂不是不安全了?
        我之前试过把ios_ikev2的删掉,还是不行,只是日志忘了弄下来了

        • wenzhuo

          不会不安全,strongswan会接受win7提出的加密套件。你的日志里有条信息:“07[LIB] hash algorithm HASH_SHA256 not supported”,应该是你设定了加密套件造成的。

          • Hun Hun

            那对于ios来说,没有了HASH_SHA256,也是个隐患了吧

          • Hun hun

            注释掉了,还是报错,算了,不管了,反正已经装好了,最好的安装方式其实就两句话:
            opkg install strongswan-full openssl-util

            另外,关于端口映射的问题,因为服务器在内网,我映射了UDP 500和4500,但是服务器上的日志完全没反应,也连不上,有什么办法吗?

          • wenzhuo

            你的路由器存储空间可能比较大,别人4M/8M闪存就得省着点用,能不装就不装了。

            如果你的网关操作系统内核是Linux,可以用以下命令设置端口转发:

            iptables -t nat -I PREROUTING -d <external ip> -p udp --dport 500 -j DNAT --to <ipsec ip>
            iptables -t nat -I PREROUTING -d <external ip> -p udp --dport 4500 -j DNAT --to <ipsec ip>
            iptables -t nat -I PREROUTING -d <external ip> -p esp -j DNAT --to <ipsec ip>
            iptables -I FORWARD -d <ipsec ip> -p udp --dport 500 -j ACCEPT
            iptables -I FORWARD -d <ipsec ip> -p udp --dport 4500 -j ACCEPT
            iptables -I FORWARD -d <ipsec ip> -p esp -j ACCEPT
            
  • hunhun

    之前测试有误,其实只要映射500和4500端口就可以连上了,很神奇,居然不需要映射eap,不过必须是linux路由器才可以,普通路由器映射了500和4500也不行.
    但有个问题,Win7连上后,无法上网,这是为何?

  • hunhun

    我有两级路由,第一级是装了SS的TT(WAN: PPPoE拨号动态IP, LAN: 192.168.2.1),DMZ到二级路由(WAN: 静态192.168.2.2, LAN: 10.10.10.1),二级路由也是TT,应该可以映射esp,之所以需要两级,是因为SS和OpenVPN冲突,所以只能分开.

    现在IKEv2/IPSec服务器(WAN: 静态10.10.10.93, LAN: 192.168.200.1)是挂在二级路由器的下面,UDP端口映射没问题,二级路由器也可以映射esp报文,那一级路由器上是否也要做映射?光DMZ够不够?

    这样的网络环境下,IKEv2/IPSec服务器的mtu还需要改吗?

    另外,无法上网的原因会是啥?毕竟在服务器端,可以ping通客户端的IP.

    谢谢!

    • wenzhuo

      如果通过NAT,ESP报文就会被封装在UDP/4500报文里,无ESP映射不要紧。但是你的Win7和openwrt都在局域网,IPSec连接未穿透NAT,有很大可能是因为ESP协议类型的报文没被允许通过,造成win7可以连接,但无法上网。

      MTU需不需要改主要看你的宽带PPPoE的MTU。如果有些网站可以上有些不行,或者同一个网页上部分内容无法打开,那就很有可能碰到了PMTU-D问题。

      这些和本文相关。你的网络结构比较复杂,其他具体联网问题,须靠你自己解决。

      • hunhun

        Win7在局域网肯定没问题的,因为这就像在路由器下面一样,没听说哪个手机/电脑在一个或多个路由器下就不能连接VPN服务器了,对吧.
        我的openwrt虽然也在内网,但500和4500端口都做了映射(或者叫转发)了啊.也不行吗?

        • wenzhuo

          IPSec连接如果穿透NAT,会把ESP报文封装在UDP/4500报文里,所以不需要防火墙规则允许ESP报文通过。如果两端都在LAN上或者路径中无NAT,则需要保证防火墙规则允许ESP协议报文通过。你按照本文Firewall Rules一节操作了吗?这是你碰到的Win7能建立连接,却无法上网最可能的原因。如果不是这个问题,我建议你用tcpdump/wireshark抓包进一步分析。

          • hunhun

            封装在4500里,那就相当于隧道模式了吧?

            我的firewall是完全按照你文中写的来的
            config rule
            option src wan
            option proto esp
            option target ACCEPT

            config rule
            option src wan
            option proto udp
            option dest_port 500
            option target ACCEPT

            config rule
            option src wan
            option proto udp
            option dest_port 4500
            option target ACCEPT

            config rule
            option src wan
            option proto ah
            option target ACCEPT

            即使从LAN口连接服务器,也不能上网,我觉得这跟防火墙关系应该也不大了…

            顺便说一下,普通路由器映射500,4500根本不行,TT只映射这两个端口立马连上

  • wanderer

    能否将路由器当作客户端,额外需要什么配置?

发表评论

电子邮件地址不会被公开。 必填项已用*标注