Saturday, 6 January 2018

IPsec VPN for macOS High Sierra and Android Nougat

After switching to OpenWRT from DD-WRT which doesn't support IPsec, this is post describes the settings I use.

Since Android (at least up to Nougat) does not support IKEv2, we will use a certificate-based IKEv1 setup (IPsec Xauth RSA in Android speak).

strongSwan configuration

The configuration is taken from strongSwan's usable examples.

# /etc/ipsec.conf - strongSwan IPsec configuration file

config setup
        #charondebug="asn 2, cfg 2, chd 2, dmn 2, enc 1, esp 2, ike 2, imc 2, imv 2, job 2, knl 2, lib 2, mgr 2, net 2, pts 2, tls 2, tnc 2"

conn %default
        fragmentation=yes
        dpdaction=clear
        dpddelay=30s
        dpdtimeout=90s

        reauth=no
        rekey=no

        leftauth=pubkey
        leftcert=serverCert.pem
        leftid=@vpn.example.com
        leftsubnet=0.0.0.0/0
        leftfirewall=yes

        rightauth=pubkey
        rightsourceip=10.0.2.0/24
        rightdns=10.0.1.1

        # Android Nougat native client.
        # IKE:AES_CBC_256/HMAC_SHA2_384_192/PRF_HMAC_SHA2_384/MODP_1024
        # macOS High Sierra Cisco IPsec.
        # IKE:AES_CBC_256/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_2048
        ike=aes256-sha384-sha256-prfsha384-prfsha256-modp2048-modp1024!

        # For some reason, data cannot be transferred using Android's second suggestion.
        # ESP:AES_CBC_256/HMAC_SHA1_96/NO_EXT_SEQ
        # ESP:AES_CBC_256/HMAC_SHA2_256_128/NO_EXT_SEQ
        esp=aes256-sha1!

conn pubkey
        auto=add

conn xauth-pubkey
        # Android's native client requires XAuth in addition to certificates.
        rightauth2=xauth
        auto=add

conn xauth-hybrid
        leftsendcert=always
        rightauth=xauth
        auto=add

conn ipsecuritas
        # IPSecuritas apparently needs a specific IP or the CHILD_SA cannot be found.
        rightsubnet=10.0.3.1/32
        auto=add

In order to prevent routing headaches, it's advisable to assign addresses to IPsec clients (rightsourceip) from a different subnet than the LAN (10.0.1.0/24 in this example).

I did not set up IKEv2 connections (for use on macOS, for example) because that would require installing additional modules for EAP, such as eap-md5 or eap-tls.

# /etc/ipsec.secrets - strongSwan IPsec secrets file

: RSA moonKey.pem
client : XAUTH "password"

I have chosen the legacy ipsec configuration in favour of swanctl because the latter is a much bigger packet to install.

Firewall configuration

Confusingly, OpenWRT /etc/config/firewall already has a couple of rules for IPsec (Allow-IPSec-ESP and Allow-ISAKMP), but another important one is missing. Moreover, as of this writing these rules handle IPsec forwarding to the LAN. In order for the router to be able to receive IPsec traffic, the option dest lan must be dropped. Here's the result:

config rule
        option name             Allow-IPSec-ESP
        option src              wan
        #option dest             lan
        option proto            esp
        option target           ACCEPT

config rule
        option name             Allow-ISAKMP
        option src              wan
        #option dest             lan
        option proto            udp
        option dest_port        500
        option target           ACCEPT

config rule
        option name             Allow-NATT
        option src              wan
        option proto            udp
        option dest_port        4500
        option target           ACCEPT

The WAN interface needs to accept packets unwrapped from IPsec tunnels which can be recognised by their »ipsec« policy using the »policy module«. In order for clients connected via IPsec to be reachable from the LAN, packets bound for an IPsec tunnel must not be subjected to NAT. This can be accomplished using the following rule in /etc/firewall.user, for example:

# Accept tunnelled traffic.
iptables \
        -t filter \
        -A input_wan_rule \
        -m policy \
        --dir in \
        --pol ipsec \
        --mode tunnel \
        -j ACCEPT \

# Prevent NATting traffic bound for IPsec tunnel.
iptables \
        -t nat \
        -A postrouting_wan_rule \
        -m policy \
        --dir out \
        --pol ipsec \
        --mode tunnel \
        -j ACCEPT \

Debugging

Activating the line charondebug in /etc/ipsec.conf (above) or adding the following section to /etc/strongswan.d/charon-logging.conf is helpful when debugging issues:

charon {
    syslog {
        daemon {
            default = 1
        }
    }
}
# logread -f

The following commands can help with routing and firewall debugging:

# ip -f inet route list table all
# iptables -t [filter|nat] -L -v
# iptables -t filter -I reject --log-prefix 'reject ' -j LOG
# /etc/init.d/firewall stop

Other settings

In order to provide DNS to VPN clients, the DNS server must not be configured as »local only« (localservice=0).

config dnsmasq
        option domainneeded      1
        option rebind_protection 1
        option rebind_localhost  1
        option local             /lan/
        option domain            lan
        option authoritative     1
        option readethers        1
        option leasefile         /tmp/dhcp.leases
        option resolvfile        /tmp/resolv.conf.auto
        option nonwildcard       1
        option localservice      0
        option add_local_fqdn    3

Key and certificate generation

Generating certificates requires strongswan-pki which is a separate install. First, generate the key for your certificate authority.

# ipsec pki --gen --outform pem >caKey.pem

The CA key is particularly sensitive and must never leak. Next, create a certificate for your certificate authority.

# cacert=/etc/ipsec.d/cacerts/caCert.pem
# ipsec pki --self \
        --in caKey.pem \
        --dn 'C=CH, O=rienajouter, CN=rienajouter CA' \
        --ca \
        --outform pem \
        >"$cacert"

The »distinguished name« for every certificate you create must be unique – otherwise the certificates will be considered interchangeable and authentication will fail. Next, create a key and certificate for the VPN server.

# key=/etc/ipsec.d/private/serverKey.pem
# cert=/etc/ipsec.d/certs/serverCert.pem
# ipsec pki --gen --outform pem >"$key"
# ipsec pki --pub --in "$key" \
| ipsec pki --issue \
        --cacert "$cacert" \
        --cakey caKey.pem \
        --dn 'C=CH, O=rienajouter, CN=vpn.example.com' \
        --san 'vpn.example.com' \
        --flag serverAuth \
        --flag ikeIntermediate \
        --outform pem \
        >"$cert"

For the VPN server certificate to work reliably with macOS, the CN of the distinguished name as well as the subject alt name (--san) must match the DNS name of the VPN gateway and the ikeIntermediate flag must be present. Windows on the other hand requires the serverAuth flag.

Last, for each client create a certificate to be shared with the client.

# key=/etc/ipsec.d/private/clientKey.pem
# cert=/etc/ipsec.d/certs/clientCert.pem
# ipsec pki --gen --outform pem >"$key"
# ipsec pki --pub --in "$key" \
| ipsec pki --issue \
        --cacert "$cacert" \
        --cakey caKey.pem \
        --dn 'C=CH, O=rienajouter, CN=client' \
        --outform pem \
        >"$cert"

Generating keys and certificates in PEM format helps when exporting them to the clients.

Doing the same with openssl is a nightmare because openssl was created in order to prevent the widespread use of cryptography, and quite successfully so far.

$ openssl req \
        -new \
        -newkey rsa:2048 \
        -subj '/C=CH/O=rienajouter/CN=client' \
        -keyout "$key" \
        -nodes \
| openssl x509 \
        -req \
        -CA "$cacert"  \
        -CAkey caKey.pem \
        -sha256 \
        -days $((3 * 365)) \
        >"$cert"

In case you forget, here's how to find out what's inside one of the key or certificate files:

$ ipsec pki --print --in "$cert"
$ openssl rsa -in "$key" -text -noout
$ openssl x509 -in "$cert" -text -noout

Certificate distribution

In order to distribute the certificates generated in the previous step, they must be packaged together into PKCS#12 files. The command to do so is:

$ openssl pkcs12 \
        -certfile "$cacert" \
        -inkey "$key" \
        -in "$cert" \
        -export \
        -out client.p12 \

When exporting for macOS, make sure to use a non-empty password when prompted by the above command. After importing the CA and client certificates into the system keychain on macOS, set the CA certificate's »trust« for »IPsec« to »always trust«. You also need to grant access to the private key inside the client certificate to /usr/sbin/racoon. The »access control« tab is only shown for keys, which in turn only appear when selecting »keys« or »certificates« in the left-hand pane of »Keychain Access«.

Saturday, 25 November 2017

Dynamic DNS using dynv6.com and DD-WRT

As of DD-WRT v3.0-r33772 (16/11/2017), DD-WRT's DDNS settings do not offer presets for dynv6.com. Unfortunately, the instructions for the »custom« settings of DD-WRT's DDNS feature are even more opaque than inadyn's man page. After some trial and error, I ended up with the following working setup.

DDNS Service
Custom
DYNDNS Server
dynv6.com
Username
user
Password
password
Hostname
your host name
URL
/api/update?ipv4=auto&ipv6=auto&token=your token&hostname=

Note that the username and password settings aren't used by dynv6.com, but they cannot be empty because DD-WRT then refuses to start the inadyn service.

You can find out the value for token by logging into your dynv6.com account. The settings are chosen to update the IPv4 or IPv6 address to the address from which the request is received. I have not investigated how to update both protocols at the same time.

The host name you enter into the corresponding field is automatically appended to the URL, which is why that parameter comes last without a value.

If you would like to see what's happening, you can add --verbose 5 to the »Additional DDNS Options« and the log file shown at the bottom of the page will contain more information.

Sunday, 19 November 2017

Windows 10 setup steps

Remove OneDrive:

C:\Windows\SysWOW64\OneDriveSetup.exe -uninstall
Set HKEY_CLASSES_ROOT\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\System.IsPinnedToNameSpaceTree and HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}\System.IsPinnedToNameSpaceTree to 0.
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}]
"System.IsPinnedToNameSpaceTree"=dword:00000000

[HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}]
"System.IsPinnedToNameSpaceTree"=dword:00000000

Run Protec'tor.

Thursday, 16 November 2017

Ad filtering setup for DD-WRT

In order to set up ad filtering by host blocking on DD-WRT, you can create a cron(1) script to download a hosts file and point dnsmasq(1) to it.

The first step is accomplished by a crontab entry in Administration, Cron like the following (line broken for readability). Note that this file is in cron.d format, i.e. the sixth field is the user name and the command is the seventh field.

0 0 * * * root mkdir -p /tmp/adhosts;
    i=0;
    for url in "http://hosts-file.net/download/hosts.txt";
    do
        /usr/bin/curl -s "$url" > /tmp/adhosts/$i;
        i=$((1 + i));
    done;
    kill -hup $(cat /var/run/dnsmasq.pid)

You can add any number of files to download, but since cron(1) does not support line continuation you will have to write the entire script in one line (or store it somewhere in the filesystem).

In order for dnsmasq to pick up the list, the following setting is needed in Services, DNSMasq:

addn-hosts=/tmp/adhosts

Monday, 30 October 2017

PHP and MariaDB on OpenBSD

First, create a /etc/httpd.conf configuration file.

server "default" {
        directory index "index.php"
        listen on * port 80
        location "*.php" {
                fastcgi socket "/run/php-fpm.sock"
        }
}

Next, enable and start httpd.

# rcctl enable httpd
# rcctl start httpd

Then install PHP.

# pkg_add php

In order for httpd to be able to run PHP scripts, the PHP FastCGI server must be enabled and started.

# rcctl enable php70_fpm
# rcctl start php70_fpm

As a test, accessing your server from a browser should work after creating a file /var/www/htdocs/index.php with the following contents:

<?php
phpinfo();

Don't forget to delete this again after testing.

# rm /var/www/htdocs/index.php

Next, install and configure MariaDB.

# pkg_add mariadb-server php-pdo_mysql

MariaDB requires some initial configuration.

# rcctl enable mysqld
# rcctl start mysqld
# mysql_install_db --user=_mysql
# mysql_secure_installation

This must be done before changing the MariaDB socket (below).

Edit the file /etc/my.cnf and change the socket variable to /var/www/run/mysql/mysql.sock in both the [client] and [server] sections in order to make it accessible to processes running with chroot inside /var/www. While you're here, you might want to enable skip-networking if you don't intend to access your database remotely.

# rcctl restart mysqld

Activate the PDO database driver.

# ln -s ../php-7.0.sample/pdo_mysql.ini /etc/php-7.0/

Configure the PDO database driver accordingly to connect to the database at the correct socket. Note the missing /var/www prefix due to the chroot done by php70_fpm!

# echo "pdo_mysql.default_socket=/run/mysql/mysql.sock" >> /etc/php-7.0/pdo_mysql.ini
# rcctl restart php70_fpm

Changes to the PHP configuration may require restarting the FastCGI server.

As pointed out in the PHP manual, if your web app needs to do DNS lookups it's going to need a copy of your /etc/resolv.conf and /etc/services.

# mkdir /var/www/etc
# cp /etc/resolv.conf /etc/services /var/www/etc

And likewise, in order to enable SSL connections:

# cp -R /etc/ssl /var/www/etc/

Then install any additional PHP modules your apps require.

# pkg_add php-curl php-zip
# rcctl restart php70_fpm

OpenBSD on Hyper-V

Installing OpenBSD on Hyper-V shouldn't really be an issue since the OS even contains specific driver for virtualised drives (hvs(4)) and network cards (hvn(4)).

However, I did not succeed installing OpenBSD 6.2 on Hyper-V because it hung while attaching the disk driver at the line

hvs0 at hyperv0 controller 1: ide
This occurred both when attaching the disk through an IDE and SCSI controller. After disable hvs in the user kernel configurator the kernel boots.

OpenBSD 6.1 recognises the attached disk as a standard IDE drive as opposed to a virtualised hvs drive and works.

The standard network adaptor is not recognised by OpenBSD 6.1, so it is necessary to use the compatibility network adaptor.

Note that according to a remark in Microsoft's instructions for creating an OpenBSD disk for Azure, only »fixed« disk images are supported. Since the »Create VM« wizard of the Hyper-V manager creates dynamic disk images by default, it makes more sense to choose the option to »create and attach a disk image later« and then creating a fixed disk manually.

Friday, 21 July 2017

Installing and removing python packages on macOS

Since python on macOS comes without the pip package manager, I was wondering how to install and remove packages.

As it turns out, there's an older »package manager« called easy-install that can be used to install, but not remove packages.

If you're happy installing packages system-wide, i.e. inside /Library/Python on macOS, you can run

# easy_install pyyaml

Installing into the user's package directory in $HOME/Library/Python can be done by

$ easy_install --user pyyaml

Removing packages isn't quite as straightforward as easy_install doesn't offer a command to do so. The manual (linked above) suggests to run

# easy_install -mxN pyyaml
prior to deleting a package, but I have not looked into what that entails.

Essentially, all that seems to be necessary is to delete the corresponding line from the package database, located at /Library/Python/2.7/site-packages/easy-install.pth, for example, and then delete the .egg file (a ZIP).