「Linux」- 通过 strongSwan 与 xl2tpd 连接 L2TP over IPSec 服务

第一步、安装软件包

#!/bin/bash

apt-get -y install strongswan xl2tpd

第二步、修改配置文件

定义环境变量

#!/bin/bash

VPN_SERVER_IP='your_vpn_server_ip'
VPN_IPSEC_PSK='your_ipsec_pre_shared_key'
VPN_USER='your_vpn_username'
VPN_PASSWORD='your_vpn_password'

设置IPSec参数

#!/bin/bash

cat > /etc/ipsec.conf <<EOF
# ipsec.conf - strongSwan IPsec configuration file

# basic configuration

config setup
  # strictcrlpolicy=yes
  # uniqueids = no

# Add connections here.

# Sample VPN connections

conn %default
  ikelifetime=60m
  keylife=20m
  rekeymargin=3m
  keyingtries=1
  keyexchange=ikev1
  authby=secret
  ike=aes128-sha1-modp1024,3des-sha1-modp1024!
  esp=aes128-sha1-modp1024,3des-sha1-modp1024!

conn myvpn
  keyexchange=ikev1
  left=%defaultroute
  auto=add
  authby=secret
  type=transport
  leftprotoport=17/1701
  rightprotoport=17/1701
  right=$VPN_SERVER_IP
EOF

cat > /etc/ipsec.secrets <<EOF
: PSK "$VPN_IPSEC_PSK"
EOF

chmod 600 /etc/ipsec.secrets

# For CentOS/RHEL & Fedora ONLY
mv /etc/strongswan/ipsec.conf /etc/strongswan/ipsec.conf.old 2>/dev/null
mv /etc/strongswan/ipsec.secrets /etc/strongswan/ipsec.secrets.old 2>/dev/null
ln -s /etc/ipsec.conf /etc/strongswan/ipsec.conf
ln -s /etc/ipsec.secrets /etc/strongswan/ipsec.secrets

设置L2TP参数

#!/bin/bash

cat > /etc/xl2tpd/xl2tpd.conf <<EOF
[lac myvpn]
lns = $VPN_SERVER_IP
ppp debug = yes
pppoptfile = /etc/ppp/options.l2tpd.client
length bit = yes
EOF

cat > /etc/ppp/options.l2tpd.client <<EOF
ipcp-accept-local
ipcp-accept-remote
refuse-eap
require-chap
noccp
noauth
mtu 1280
mru 1280
noipdefault
defaultroute
usepeerdns
connect-delay 5000
name $VPN_USER
password $VPN_PASSWORD
EOF

chmod 600 /etc/ppp/options.l2tpd.client

到此连接的参数设置已经完成。接下来就是执行连接动作。

创建xl2tpd控制文件

#!/bin/bash

mkdir -p /var/run/xl2tpd
touch /var/run/xl2tpd/l2tp-control

第三步、重启本地的服务

#!/bin/bash

service strongswan restart
service xl2tpd restart

第四步、建立连接

#1 建立IPSec连接

#!/bin/bash

# Ubuntu & Debian
ipsec up myvpn

#2 建立L2TP连接

#!/bin/bash

echo "c myvpn" > /var/run/xl2tpd/l2tp-control

至此,运行ifconfig(8)并检查输出,现在应该看到一个名为“ppp0”的新接口。

第五步、网络配置及测试

至此,L2TP/IPSec的连接已经成功建立,剩下的任务就是将指定网络的数据包路由到ppp0接口即可。

执行如下命令进行检查:

# wget -qO- http://ipv4.icanhazip.com; echo***

如果命令输出是VPN服务器的地址,那就表示连接成功。

参考文献

Configure IPsec/L2TP VPN Clients/Linux VPN Clients