Valid HTML 4.01 Transitional

Setting Up Strongswan

James F. Carter <jimc@math.ucla.edu>, 2013-08-09

StrongSwan is for secure communication between computers. The software itself manages authenticating peers and establishing security assocations (SA's), using the Linux kernel's intrinsic ability to use these SA's for secure communication, referred to as IPsec.

StrongSwan has these important characteristics (and many others):

StrongSwan fits into these niches in the computing ecosystem:

Web resources:

IPsec Requirements

Cryptography, particularly real crypto that resists hackers, secret police, and similar lowlife, is far from simple, and getting it to work is not a plug and play experience. Nonetheless, with care and with some understanding of what it needs to accomplish, you can give StrongSwan a configuration that will meet your needs. Fortunately the Charon daemon does most of the hard parts for you: checking the peer's credential, negotiating (safely) the crypto algorithms with the peer, and telling the kernel which one you're going to use.

My situation is relatively simple but common:

StrongSwan Configuration

Here is my configuration file /etc/ipsec.conf (minus some comments) followed by the same thing with interspersed line by line commentary.

# basic configuration
config setup
	charondebug = "dmn 0,mgr 1,ike 0,chd 1,job 1,cfg 0,knl 1,net 1,tls 1,lib 0,enc 0,tnc 0"

conn roadwarrior
	auto = add		# We're a responder only, do not start
	compress = no		# is the default
	dpdaction = clear	# Clear everything if the peer dies
	# esp = cipher,suites	# Rely on the extensive default cipher list
	# ike = cipher,suites
	type = tunnel		# is the default, vs. transport etc.
	#
	# left defines the local server's behavior
	left = %any		# Use IP adr of incoming NIC
	leftid = @xmpp.jfcarter.net
	leftauth = pubkey
	leftcert = /etc/ssl/hostcerts/jfcarter.crt
	# /etc/ipsec.secrets needs a line: 
	# xmpp.jfcarter.net : RSA /etc/ssl/private/jfcarter.key "passphrase"
	leftca = "C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority"
	leftsendcert = always
	leftsubnet = 192.9.200.192/26,2001:470:1f05:844::/64
	#
	# right defines behavior expected of the remote client
	right = %any		# Remote peer could have literally any address
	rightauth = pubkey
	# Any client cert signed by this CA is acceptable:
	rightca = "C=US, ST=California, L=Los Angeles, O=The Carter Family Trust, OU=CFT Certificate Authority, CN=CFT Root Certificate, E=jimc@math.ucla.edu"
	rightsendcert = ifasked
	# rightsubnet = $rightIP/32 or 128 by default.
	rightdns = 192.9.200.193
	# Assign the client's IP from these pool(s)
	rightsourceip = 192.9.200.240/29,2001:470:1f05:844::c8f0/125

The syntax of /etc/ipsec.conf:

config setup

The name setup is required. The only feature I needed to change from the default was:

charondebug = "dmn 0,mgr 1,ike 0,chd 1,job 1,cfg 0,knl 1,net 1,tls 1,lib 0,enc 0,tnc 0"

Controls what level of message is logged for each of 12 categories. The distributed default has 2 for each, which is pretty chatty, several hundred lines in the log file to start up and make a connection. With the settings shown, starting the daemon logs 7 lines, a new connection takes 10 lines, and closing it takes 7 lines. Of course there is enough there to monitor who is connecting but not to debug problems in the client's or server's setup.

I believe the level numbers are: 0 = serious errors, 1 = errors, 2 = info, 3 = net traffic and other debug messages, 4 = traffic including secret keys.

conn roadwarrior

The conn sections define how peers connect to our host. Road Warrior is the term for an employee travelling away from the enterprise's site who nonetheless needs to use home resources as if local. The name of the section is arbitrary except that it must be unique.

auto = add

The conn should be configured in the Charon daemon at startup, but the connection should not be started. In my use case, clients take the initiative to start a connection, and this host is always a responder.

compress = no

This is the default. It is possible to compress the network traffic, which saves bandwidth and makes cryptographic attacks much harder, at the cost of CPU time at both ends. Later when all problems are worked through, I could try turning this on.

dpddelay = 0

If the tunnel has no traffic for this long (default 30 secs), Charon will send a dead peer detection packet. The value 0 means to not send such packets, relying on ordinary traffic, which will occur at least once an hour, which is the default rekeying lifetime.

dpdaction = clear

If a packet needing a response remains unanswered after several retries, the peer is assumed to be dead. The selected action in that case is to clear all state and resources for the connection.

# esp = cipher,suites
# ike = cipher,suites

Charon has an extensive list of crypto algorithms that the kernel knows how to do, ordered by strength. It will negotiate with the peer the strongest cipher and message integrity hash (HMAC) that both can do. If you have studied cryptography you may want to avoid or give extra preference to particular ciphers. Otherwise, it is reasonable to rely on Charon's default list.

type = tunnel

Tunnel means that packets at the third protocol layer are sent down the IPsec tunnel by routing rules which Charon installs. An alternative is transport mode, where packets at the second layer are sent out promiscuously. The tunnel could then be made part of a network bridge. But this isn't what I'm doing.

Left and Right

Many conn parameters are prefixed by the keywords left or right. They describe the behavior of one or the other end of the connection. By convention, left is the local host and right is remote, but if there is clear identification of the peers, Charon will know to reverse the polarity on the other host. In this way the identical configuration file could be used on both peers, easing distribution and maintenance problems. In my case this is irrelevant, since I can't officially influence the configuration on the Android clients.

left = %any

This is the IP address of the left end. %any means, for a responder, to use the IP address of the network interface through which the initiator is sending packets, e.g. the wild side or the internal LAN.

leftid = @xmpp.jfcarter.net

This defaults to the Distinguished Name (the whole thing double quoted) in the left certificate. Alternatively, if the certificate has a Subject Alternate Name (SAN) for the hostname, you can specify it here prefixed by '@'. It's an error if the SAN is missing.

I'm not completely sure whether the peer is going to look up leftid and see if it has the IP address that the peer is sending to: it could not do that for the Distinguished Name, and NAT traversal adds complication. But such a check would succeed in my case.

leftauth = pubkey

Pubkey means that the left peer will authenticate itself to the right peer by using Public Key Cryptography, i.e. X.509 certificates.

leftcert = /etc/ssl/hostcerts/jfcarter.crt

This is the filename of the (public) X.509 certificate certifying the left peer's right to use the included Distinguished Name and/or hostname (SAN).

Since the left peer needs to decrypt a cryptographic challenge encrypted with the public key in this certificate, it has to be able to read the corresponding private (secret) key. This is found in /etc/ipsec.secrets. It needs a line like this; omit the quoted passphrase in the usual case that the key has none:

xmpp.jfcarter.net : RSA /etc/ssl/private/jfcarter.key "passphrase"
leftca = "C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority"

This is the Distinguished Name of the certificate authority that signed leftcert. When one or more intermediate certificate authorities are involved, as with StartCom, you need to specify an authority that the peer actually trusts, which invariably is the trust anchor, the self-signed root certificate.

Finding the CA certificate(s) may be a challenge. They should be available on the Certificate Authority's website. To identify which one you need, start with this command line (illustrated for my own host certificate):

openssl x509 -in /etc/ssl/hostcerts/jfcarter.crt -noout -nameopt sname,sep_comma_plus_space -subject -issuer

Repeat for each certificate in the chain until you reach one for which the subject and issuer are identical: this is the self-signed trust anchor.

The given -nameopt is the one StrongSwan uses to print Distinguished Names in log messages and which StrongSwan accepts. I don't actually know how much freedom you have in formatting, but openssl's default is to use slashes to separate fields, and StrongSwan didn't like it. (I can't be sure if the issue was formatting, or if it was just the wrong certificate.)

See below under File Configuration for where to put the certificate files. You will need the trust anchor and all of the intermediate CA certificates.

leftsendcert = always

There are choices for whan to send your certificate to the peer. Likely ifasked is sufficient, but I know that the client will always need the cert, so I avoid client screwups by always sending it.

leftsubnet = 192.9.200.192/26,2001:470:1f05:844::/64

This is a comma separated list of CIDR address ranges which the client should be told to route through the tunnel. The Android StrongSwan client (or an API that it uses) politely posts a warning that your address range is being diverted, and asking if you trust the app to do so.

If the two peers do not agree on the leftsubnet (or rightsubnet), or even if they do, the intersection of the two address ranges is used.

If the client should send its default route through the tunnel, specify leftsubnet = 0.0.0.0/0,::/0 . Perhaps a more sanitary set of subnets is 0.0.0.0/1,128.0.0.0/1,::/1,8000::/1 . The half internets are a more specific route than the default route and therefore are preferred over it. The result is that the default route remains in place but unused, and you don't have to think about whether the client will re-establish the correct default route when the IPsec connection goes down. Pluto in FreeS/WAN used this maneuver.

With the above default route, both IPv4 and IPv6 traffic to the wild side (as well as the internal LAN) is sent to the gateway and is retransmitted, with NAT if needed, and replies find their way back to the Android client. With the leftsubnet in the title line, only traffic to the internal LAN goes through the gateway, but it is functional. The Android client asks for the default route to be tunneled, and its intersection with the server's leftsubnet is used: equal to the server's leftsubnet.

right = %any

Now we're specifying the characteristics of the remote peer. %any means that any host in the whole Internet can use this conn. Of course there are authentication requirements too.

rightauth = pubkey

The client is going to use Public Key Cryptography, that is it will present an X.509 certificate as a credential.

rightca = "C=US, ST=California, L=Los Angeles, O=The Carter Family Trust, OU=CFT Certificate Authority, CN=CFT Root Certificate, E=jimc@math.ucla.edu"

Any client cert signed by this CA is acceptable. If you have several differing conns, e.g. routing to different subnets, you could specify an intermediate certificate here and issue user certificates signed by the one corresponding to the net that the user is supposed to get access to.

rightsendcert = ifasked

This parameter is probably unnecessary since the peer will determine whether it has a certificate and whether to send it.

# rightsubnet = $rightIP/32 or 128

The default is for the left peer to install a host route to the right peer, but if there are entire subnets behind the right peer, specify a comma separated list here.

rightdns = 192.9.200.193

A truly paranoid sysop does not make DNS available publicly describing the hosts on the internal subnet. The rightdns parameter tells the left peer to send over the address(es) of DNS servers that the right peer will find useful.

rightsourceip = 192.9.200.240/29,2001:470:1f05:844::c8f0/125

If the client tries to send from its wild-side address, it is most likely dynamic and would change during the life of the tunnel, and most likely it is in RFC 1918 address space (192.168.0.0/16 etc.) so could be used by several clients. It is much more useful for the server to assign a unique address on the local subnet. Specify a comma separated list of address pools from which to pick addresses. If both IPv4 and IPv6 pools are specified, an address from each family will be assigned.

File Configuration

StrongSwan's Linux package provides several subdirectories under /etc/ipsec.d . When ipsec.conf mentions a certificate-related file of the corresponding type, a full path may be used, or a relative path is relative to these subdirectories:

/etc/ipsec.conf may have CA sections to specify parameters of particular certificate authorities, such as how revoked certificates are reported. The cacert parameter, specifying the certificate filename of that authority, is what distinguishes them. However, StrongSwan does not actually use certificates only mentioned in a cacert parameter. It loads all the certificates in /etc/ipsec.d/cacerts instead, and uses the CA sections to know parameters related to each one. Therefore you need to make a symbolic link in /etc/ipsec.d/cacerts to each Certificate Authority certificate, or put the actual file there. Since my certificates are used by several services I have them in /etc/ssl and I put symbolic links into /etc/ipsec.d/cacerts.

Firewall Rules and Other Setup Issues

StrongSwan is able to adjust firewall rules dynamically as connections come and go, but my net is simple enough that static rules are sufficient. The clients need to authenticate, and thus are given as much trust as physically local hosts. The firewall rules are sensitive to the IPsec tunnel as a packet source, and direct those packets through the same chains as local packets.

In older kernels (2.4 I think) IPsec packets would come out of an ipsec0 tunnel device. In recent kernels IPsec is just extra mangling of the packet and the source interface is unchanged. Thus with my /etc/ipsec.conf and network geometry, the client with an internal address is sending its packets in from the wild-side interface, a very threatening situation. To recognize the IPsec packets and mark them as (equivalent to) tunneled, I use this firewall rule.

iptables -t nat -A IFCLASS -m policy --dir in --pol ipsec -j CONNMARK --set-mark 1/1

IFCLASS is one of my user-defined chains called from nat PREROUTING (IPv4) or filter INPUT (IPv6) to set connmarks which divert connection-beginning packets to chains implementing policies appropriate to the various source categories. Subsequent packets in the connection do not go through IFCLASS because the nat table only applies to connection-beginning packets (IPv4) and a connmark bit cues filter INPUT to accept or drop subsequent packets without further inspection (both families).

When the client directs its IPv4 default route down the tunnel, the gateway needs to do NAT on them, same as it would for hosts on the local LAN. For IPv6 all that's necessary is for the client to have an address on the local net, and the wild side will route through the gateway (subject to the gateway's rules strictly limiting thru traffic originating on the wild side).

In truth, Android's custody of the client's secret key is not necessarily adequate. A truly paranoid sysop will use non-programmatic methods to insist that clients be secured by an actual password of adequate strength. Even then, I am not sure that the keystore is secured by the same password so as to resist burglary if the Android device is stolen.

The gateway's various secret keys have a similar problem: power failures are a fact of life, and my server is expected afterward to reboot unattended, with nobody to tell it any passphrases for the secret keys. Thus a James Bond type who sneaks in and gets his hands on the gateway hardware, or a hacker who gets past multiple layers of defense in depth and perpetrates a root exploit, can steal the secret keys, possibly without being detected. A competent and armed datacenter supervisor, present 24/7, can solve the reboot problem, but introduces another one: bribeability. The nexus of security, availability and useability is intractibly tangled and you can't push all three factors to their maxima at once.

A suggestion for testing: I initially tested the Android client on a WiFi-only tablet. To get it on the wild side without leaving the house, I activated the WiFi hotspot on my pocket computer (cellphone running Android/CyanogenMod).

Glossary

I've seen in forum posts that some people coming to secure communication for the first time could be helped by a brief explanation of some of the basic principles.

Peer, Server, Client

Much of the configuration and behavior of StrongSwan and IPsec implementations in general are closely similar between the two ends of the communication channel. The term peer means a person of equal rank to another of his peers, and so this term is used to describe the two IPsec endpoints. Nonetheless, a common mode of using IPsec is that one host, called the server, waits for connections but initiates none itself. Clients initiate connections to it.

Initiator, Responder

Necessarily one of the endpoint hosts has to act first to start up the connection, and this one is called the initiator, while the other one is the responder. Only a few parts of the protocol, such as the preference order for crypto algorithms, are asymmetric between the initiator and responder.

Open Source

An open source license requires all those who distribute the software to make the source code available by reasonable channels. This includes derivative works, i.e. modified versions of the software. The open source paradigm has many advantages (high profit is not one of them), but it is particularly important for cryptographic software because every user can audit the software, and there is a cottage industry of people who actually do so.

If you have valuable secrets that you know adversaries are trying to steal, you are advised to review the source code of your crypto package, including the supporting libraries and kernel modules, and then build them yourself from the actual code that you reviewed. If you use a closed source package, particularly on a dedicated crypto appliance, you have to assume that weak algorithms are being chosen (that you can't influence), and that trapdoors and Trojan horses have been slipped in by your geopolitical competitors and by your local secret police organization.

Paranoia is the most important job requirement in a system administrator who manages cryptography.

Wild Side

Refers to the entire Internet except for the local part that is under your administrative control. Hackers live there.

Public Key Cryptography

See this Wikipedia article on Public Key Cryptography.

In World War II major effort was put into cryptography. The algorithms used a symmetric key, a secret number or byte string. The person sending a message would do a complicated operation that combined the plaintext and the key, resulting in ciphertext that looked like complete gibberish. The recipient would do a related operation with the ciphertext and the same key to recover the plaintext. A major problem was key distribution: when the key changed it had to be sent to the recipient and was stealable (and in important cases, actually stolen) in transit. The algorithms were also kept very secret and were not scrutinized extensively (see Open Source), but nonetheless were stolen.

In 1977 Rivest, Shamir and Adleman (RSA) invented a crypto algorithm with separate keys for encryption and decryption. (Theirs is not the only public key system but was the first to be widely applied.) One key is private, never to be revealed; in the RSA algorithm its main content is two large prime numbers. The other is made available to anyone with which you want to communicate; for RSA it is the product of the prime numbers, and factorizing that product is outrageously expensive, so in practice the private key cannot be deduced from the public one. Thus it is much easier, than for a symmetric key, to keep the private key out of the hands of adversaries. Also, the algorithm and its software implementations are publicly known and they are continuously reviewed for weaknesses.

If the plaintext is encrypted with the recipient's public key, only the person who can wield the private key (you hope this means the intended recipient) can decrypt the ciphertext. If the plaintext is encrypted with the sender's private key, anyone can use the sender's public key to decrypt it, and can be assured that the sender was the one who encrypted it.

Hybrid Cryptosystem

Public key cryptography is not particularly efficient; modern symmetric key algorithms are much faster. Therefore it is common for the peers to use public keys to safely send each other temporary symmetric keys (one for each direction) which are used to encrypt the bulk data. In IPsec the symmetric key is replaced once an hour (with default settings).

Diffie-Hellman key exchange is another way to put the same symmetric key on both peers without revealing it to eavesdroppers.

Digital Signature

To sign a document, the signer first makes a hash sum of the document; this is an intricate combination of the content into an integer of limited size such as 256 bits, such that it is very hard to fraudulently alter the document so the fraud is overlooked, so the document performs the nefarious purpose (e.g. changing a name or a payment amount), and so it has the same hash as the original.

Then the signer encrypts the hash with his private key and appends the resulting signature to the document. A recipient who wants to verify the document can decrypt the signature using the public key of the signer, recompute the hash, and compare. If the results are equal, the recipient can be sure that the document has not been fraudulently altered and that the signer (or someone who has stolen his private key) is the person who signed it.

X.509

The International Telecommunication Union, Telecommunication Standardization Sector (ITU-T) has adopted standard X.509 which specifies a mode of Public Key Infrastructure (authentication and encryption) and Privilege Management (authorization). The standard specifies the format for public key certificates, and the procedure for trusting such a certificate given a relevant trust anchor. See this Wikipedia article about the X.509 standard.

An X.509 certificate consists of a public key, the Distinguished Name of its owner, the Distinguished Name of a Certificate Authority, and a digital signature over all of these made by that authority. It will also have a separate private key which only its owner can wield. If you trust the Certificate Authority, e.g. because it is under your administrative control, when you receive a message encrypted with or signed with that private key, you can decrypt it using the public key and you can be sure that the named owner sent it.

This is how StrongSwan (or any IPsec implementation) knows to allow a client to connect, or how the client knows that it has connected to the actual gateway server and not a man in the middle that will steal the secret traffic.

Certificate Authority (CA)

This is a company or entity whose purpose is to sign X.509 certificates. The first one it signs is its own certificate, which is called a trust anchor. It then signs certificates for end entities (users and hosts) which will then be used to communicate with a peer, referred to as a Relying Party. The RP will need to trust the CA to honestly verify the right of the end entity to use the Distinguished Name in its signed certificate, and to keep its private key safe from thieves who would issue certificates not to the RP's advantage. The Relying Party will then install the trust anchor so it can be used to verify the signature on the proffered end entity certificate.

In important cases the Certificate Authority signs an intermediate CA certificate, which signs the end entity certificate. There could be more than one intermediate certificate in the chain of trust. The Relying Party needs to use the intermediate certificate to verify the end entity's certificate, repeat if there are more intermediate certificates, and finally use the trust anchor to verify the intermediate certificate. This means that the end entity will need to send the intermediate certificate(s) together with its own certificate. It is not necessary to send the trust anchor because the Relying Party either already has it installed, or will not believe in it.

Charon

The name of the key management daemon for StrongSwan 2.x. Earlier versions used the name Pluto.