Racoon vs. OpenSWAN: Configure HOST-TO-SITE IPSEC VPN Tunnel with Cisco and L2TP over IPSEC for Windows, iOS, and Android

Good deeds, dear Khabravchians!

In this article, I would like to captivate you with a story about my adventures in finding reliable and secure IPSec connections, where there are many amazing discoveries and disappointments, riddles and answers, stories of faithful service and treacherous betrayals. So, my dear reader, get ready, begin the story.

To the reader who needs urgent help, and not stories about my misfortunes that led to the writing of this topic, I recommend scrolling to the heading “Actually the subject”

About six months ago, I needed to raise a server for payment terminals with connection to the payment system via IPSec. My choice fell on Debian Squeeze and KAME ipsec-tools, in the common people racoon. Oh, and I don’t know why my soul became attached to this application. First, superficially studying the IPSec theory, I took up the practice:

apt-get install racoon

Raccoon successfully downloaded, installed, pulling along a bunch of packages and joyfully notified me that he was here.

On the other side, his beloved CISCO was waiting for him, which, however, consistently supported a couple of dozen secure connections, but was looking forward to our hero knocking on her, calling PreShared Key and embracing her in the arms of his reliable IPSec channel.

But before that, it was necessary to pass a difficult test, because the strict but fair father of CISCO - the system administrator on the other side, did not give access to his ward without successfully passing the test. The conditions of passage were as follows:

IKE 3DES
	HASH SHA-1
	Diffie Hellman Grupo 2
	Life Time 86400 seconds
	Authentication by Preshared Key
IPSec	 3DES
	Integrity : ESP/SHA1
	Mode: Tunel
	Perfect Forward Secrecy (Active)
	Lifetime 3600 seconds
x.x.x.x - IP адрес моего сервера, он же сервер приложений
y.y.y.y - IP Cisco
z.z.z.z - IP сервера приложений за Cisco


To help the lovers, it took about a couple of days to create a more or less working config. And finally, love triumphed. One of the problems was redoing the configs from the existing site-to-site, I had to strain my brain a bit and remember that one host is the same network, only with a subnet mask of 255.255.255.255, i.e. / 32.

But the happiness was not long. There was a task to connect client hosts via L2TP over IPSec, and here Rakun could not cope. First, an ipsec-tools rebuild operation was required so that it could support wildcard (*) for the preshared key, since the IP addresses of the client machines are unknown. This outrage looked something like this:

diff -ur a/ipsec-tools-0.7.1/src/racoon/localconf.c b/ipsec-tools-0.7.1/src/racoon/localconf.c
--- a/ipsec-tools-0.7.1/src/racoon/localconf.c	2006-09-09 11:22:09.000000000 -0500
+++ b/ipsec-tools-0.7.1/src/racoon/localconf.c	2010-08-06 16:35:18.000000000 -0500
   -211,7 +211,8   
 		if (*p == '\0')
 			continue;	/* no 2nd parameter */
 		p--;
-		if (strncmp(buf, str, len) == 0 && buf[len] == '\0') {
+		if (strncmp(buf, "*", 2) == 0 ||
+		    (strncmp(buf, str, len) == 0 && buf[len] == '\0')) {
 			p++;
 			keylen = 0;


The banal resolution of dependencies during assembly required another week of painstaking smoking of mana, because it could not go further ./configure. In the end, I came across a BenV article that pointedly broadcast: And you trust your security to these clowns (And you trust your safety to these clowns) . Without attaching much importance to these words, because the article solved my problem, I successfully assembled, connected and made Raccoon work now in the Road Warrior configuration.


L2TP Settings


There were no problems with L2TP:

Installed xl2tp and ppp
apt-get install xl2tp ppp


Configured according to a lot of How-to:
# /etc/xl2tpd/xl2tpd.conf
[global]
ipsec saref = yes
force userspace = yes
[lns default]
local ip = 10.1.2.1
ip range = 10.1.2.10-10.1.2.254 # пул адресов для клиентов
refuse pap = yes
require authentication = yes
ppp debug = yes
length bit = yes
pppoptfile = /etc/ppp/options
# /etc/ppp/options:
ms-dns  10.1.2.1
ms-dns  8.8.8.8
require-mschap-v2
asyncmap 0
auth
crtscts
lock
hide-password
modem
debug
name l2tpd
defaultroute
proxyarp
lcp-echo-interval 10
lcp-echo-failure 100
#/etc/ppp/chap-secrets:
# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
username        *       userpass                *
# имя пользователя и пароль в подключении. Вместо звездочки в колонке IP addresses можно вставить адрес, который вы хотите присвоить определенному логину. У меня например для пользователя alvelig задается адрес 10.1.2.7
alvelig               *        alvelig                 10.1.2.7


But I had to tinker with ipsec-tools. I will give a working config rakuna:

# /etc/racoon/racoon.conf:
path include "/etc/racoon";
path pre_shared_key "/etc/racoon/psk.txt"; # путь до PreShared Keys файла (см. чуть ниже)
path certificate "/etc/racoon/certs";
# конфиг IKE для Road Warrior
remote anonymous {
        exchange_mode aggressive,main;
        passive on;
        proposal_check obey;
        support_proxy on;
        nat_traversal on;
        ike_frag on;
        dpd_delay 20;
        proposal
        {
                encryption_algorithm aes;
                hash_algorithm sha1;
                authentication_method pre_shared_key;
                dh_group modp1024;
        }
        proposal
        {
                encryption_algorithm 3des;
                hash_algorithm sha1;
                authentication_method pre_shared_key;
                dh_group modp1024;
        }
}
# IPSEC для Road Warrior и CISCO
sainfo anonymous {
        pfs_group 2;
        lifetime time 3600 sec;
        encryption_algorithm 3des;
        authentication_algorithm hmac_sha1;
        compression_algorithm deflate ;
}
# IKE для CISCO
remote y.y.y.y {
        exchange_mode main, aggressive;
        my_identifier address;
        lifetime time 86400 sec;
        nat_traversal on;
        dpd_delay     20;
        proposal {
                encryption_algorithm 3des;
                hash_algorithm sha1;
                authentication_method pre_shared_key;
                dh_group 2;
        }
}


# /etc/racoon/psk.txt:
# PSK для Cisco
200.68.5.131            CiscoPSK
# PSK для клиентов за NAT
*                       RoadWarrior


# /etc/ipsec-tools.conf
#!/usr/sbin/setkey -f
#
# Flush SAD and SPD
flush; spdflush;
# Create policies for racoon
spdadd x.x.x.x/32 z.z.z.z/32 any -P out ipsec
esp/tunnel/x.x.x.x-y.y.y.y/require;
spdadd z.z.z.z/32 x.x.x.x/32 any -P in ipsec
esp/tunnel/y.y.y.y-x.x.x.x/require;
##########################
##      XL2TP           ##
##########################
spdadd 0.0.0.0/0[0] 0.0.0.0/0[1701] udp -P in ipsec
esp/transport//require;
spdadd 0.0.0.0/0[1701] 0.0.0.0/0[0] udp -P out ipsec
esp/transport//require;


But after a week of successful operation, the tunnel suddenly turned out to be inactive, and the only tool that helped was restart racoon or reboot.

The project was a pilot, a cloud of other things, and, in general, stretched out a couple of months on crutches and patches.

Finally, my hands reached the point of thoroughly understanding the issue, and in the hope of bug-fixes and other elusive things, I put together a fresh version of ipsec-tools 0.8.1. And right after the start, racoon informed me of a serious illness - segmentation fault.

I could not bear such a blow. The night did not sleep: I thought how could it be ...

Waking up in the morning, drank tea, ate a sandwich and sat at the computer. Suddenly a thought flashed through my head: OpenSWAN! Oh yes, let's try!


Actually a subject



apt-get install openswan


Aptitude swore that OpenSWAN is not friends with racoon, and we will have to say goodbye to a former friend. Well, it wasn’t, I thought and confirmed the installation of OpenSWAN.

After much torture setting up racoon, setting up OpenSWAN turned out to be easier than easy (or maybe I already gained experience):

# /etc/ipsec.conf
config setup # Общий раздел для всех подключений
        nat_traversal=yes # для клиентов за NAT
conn cisco # Туннель к циске
        forceencaps=yes 
        dpddelay=30 # Dead peer detection - 30 секунд - интервал между keep-alive пакетами
        dpdtimeout=120 # dpd таймаут 120 секунд, после которого хост будет объявлен недоступным
        dpdaction=restart_by_peer # перезапустить процесс подключения к хосту
        # IKE alg 3DES - HASH sha1 - DH group 2 (1024) 
        ike=3des-sha1-modp1024 
        # IKE lifetime 86400 seconds (24 hours)
        ikelifetime=86400s 
        # IKE auth method Pre-Shared Key (PSK secret)
        authby=secret
        # IPSEC params
        # Закомментированные настройки уже по умолчанию установлены в OpenSWAN
        # phase2=esp # by default
        # phase2=3des-sha1 # by default the same as IKE
        # IPSec type tunnel
        type=tunnel # режим - туннель
        # IPSEC (key) lifetime
        salifetime=3600s
        # Perfect Forward Secrecy PFS group the same as IKE (1024)
        pfs=yes # включить Perfect Forward Secrecy
        #left side (myside)
        left=x.x.x.x # OpenSWAN side
        # в моем случае хост был один, и он же был и шлюзом IPSec, поэтому netmask x.x.x.x/32
        leftsubnet=x.x.x.x/32 #net subnet on left side to assign to right side
        leftnexthop=y.y.y.y # CISCO side
        #right security gateway (CISCO side)
        right=y.y.y.y #CISCO side
        rightsubnet=z.z.z.z/32 #net on right side
        rightnexthop=x.x.x.x # OpenSWAN side
        auto=start
# Road Warrior
conn L2TP
        authby=secret
        pfs=no
        auto=add
        keyingtries=3
        rekey=no
        ikelifetime=8h
        keylife=1h
        type=transport
        left=x.x.x.x
        leftprotoport=17/%any # до этого стояло 1701, но iOS не подключался. Поменял на %any и, о чудо: теперь мой iPad тоже был в сети для мониторинга терминалов!
        right=%any
        rightprotoport=17/%any
        compress=no
        dpddelay=30
        dpdtimeout=120
        dpdaction=clear 
# dpdaction=clear это важное замечание, т.к. ipsec здесь восстанавливается 
#только по инициации со стороны клиента, то есть, если обнаружили "мертвый peer", 
#то все записи по нему надо очистить, чтобы успешно подключить его снова


The L2TP settings did not even have to be changed: everything worked right away. L2TP Settings .
ipsec setup start
ping z.z.z.z
64 bytes from z.z.z.z: icmp_req=1 ttl=254 time=7.53 ms
64 bytes from z.z.z.z: icmp_req=2 ttl=254 time=6.59 ms
64 bytes from z.z.z.z: icmp_req=3 ttl=254 time=6.41 ms
64 bytes from z.z.z.z: icmp_req=4 ttl=254 time=6.77 ms


And it took me about half an hour against a week and a half of torment with racoon.

Conclusion


Unfortunately, as often happens, the capricious Tsiska often quarreled and broke off relations with Rakun, but with OpenSWAN (I wonder what gender this application is, maybe female, then it explains a lot) for the third week now, stable and without conflicts and scandals.

P.S


If VPN connections with clients are connected, but hosts within the network are inaccessible to each other, then you are missing:
echo 1 > /proc/sys/net/ipv4/ip_forward
Or see your iptables.

Here you can take the settings for iOS and Windows clients.

I would be grateful for comments on why racoon dropped into segfault and lost connection after a week of stable operation.

Special thanks to UFO for invite.

Update:

After 2 months, the infection still fell ...
I found on the Openswan forums that dpdaction = restart_by_peer is highly recommended. Corrected in configs.

Update 2:

As the admin on the tsiska side admitted to me, the drop was caused by communication problems on their side.
But it didn’t make me any easier, because the tunnel had to go up.
I found in another how that forceencaps = yes can help in such cases. Added to the config.

Update 3:

Added by:
# / etc / ppp / options:
defaultroute

see comments

Also popular now: