在现代企业网络中,远程办公已成为常态,而保障员工通过公网安全访问内网资源的需求也日益迫切,L2TP(Layer 2 Tunneling Protocol)结合IPsec(Internet Protocol Security)是一种成熟、稳定且广泛支持的虚拟私人网络(VPN)协议组合,尤其适合中小型企业或个人用户搭建私有远程接入通道,本文将详细介绍如何在Linux系统(以Ubuntu Server为例)上搭建一个L2TP/IPsec VPN服务器,确保数据传输加密、身份认证可靠,并提供常见问题排查建议。
第一步:环境准备
确保你有一台运行Ubuntu Server 20.04或更高版本的物理机或云服务器(如阿里云、AWS EC2),并具备公网IP地址,你需要提前在路由器上开放UDP端口:500(IKE)、4500(NAT-T)和1701(L2TP),若使用防火墙(如UFW),可执行以下命令开放端口:
sudo ufw allow 500/udp sudo ufw allow 4500/udp sudo ufw allow 1701/udp
第二步:安装OpenSwan或strongSwan
OpenSwan是较老但稳定的IPsec实现,而strongSwan是现代首选,我们推荐使用strongSwan,因为它对IPv6和证书管理更友好,安装命令如下:
sudo apt update && sudo apt install strongswan xl2tpd -y
第三步:配置IPsec(strongSwan)
编辑主配置文件 /etc/ipsec.conf,添加以下内容:
config setup
plutostart=yes
plutodebug=control
uniqueids=no
conn %default
ikelifetime=60m
keylife=20m
rekeymargin=3m
keyingtries=1
keyexchange=ikev1
authby=secret
ike=aes256-sha1-modp1024!
esp=aes256-sha1!
conn l2tp-psk
left=%any
leftid=@your-vpn-domain.com
right=%any
rightid=%any
auto=add
type=transport
modecfgdns=8.8.8.8,8.8.4.4
fragmentation=yes
dpddelay=30
dpddelay=10
dpdtimeout=120
然后编辑密钥文件 /etc/ipsec.secrets,添加预共享密钥(PSK):
%any %any : PSK "your-strong-password"
第四步:配置L2TP(xl2tpd)
编辑 /etc/xl2tpd/xl2tpd.conf:
[lns default]
ip range = 192.168.100.100-192.168.100.200
local ip = 192.168.100.1
require authentication = yes
refuse pap = yes
refuse chap = yes
require encryption = yes
require compression = yes
length bit = yes
第五步:设置用户账号
创建用户数据库文件 /etc/ppp/chap-secrets,格式为:用户名 服务 密码 IP地址:
user1 l2tp password1 *
第六步:启用转发与NAT
编辑 /etc/sysctl.conf,取消注释并修改:
net.ipv4.ip_forward=1
执行 sysctl -p 生效,再配置iptables规则,使客户端流量能正确路由:
sudo iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE sudo iptables -A FORWARD -s 192.168.100.0/24 -d 192.168.100.0/24 -j ACCEPT sudo iptables -A FORWARD -i eth0 -o ppp0 -j ACCEPT sudo iptables -A FORWARD -i ppp0 -o eth0 -j ACCEPT
第七步:启动服务并测试
重启IPsec和L2TP服务:
sudo systemctl restart strongswan sudo systemctl restart xl2tpd sudo systemctl enable strongswan xl2tpd
客户端可通过Windows、iOS或Android自带的L2TP/IPsec连接功能进行测试,输入服务器IP、用户名密码及PSK即可建立安全隧道。
注意事项:
- 建议使用证书而非PSK提升安全性(需配置PKI);
- 定期更新软件包防止漏洞;
- 监控日志
/var/log/syslog或journalctl -u strongswan排查连接失败问题。
通过以上步骤,你就能拥有一个高可用、加密可靠的L2TP/IPsec VPN服务,满足远程办公、分支机构互联等场景需求。

半仙加速器-海外加速器|VPN加速器|vpn翻墙加速器|VPN梯子|VPN外网加速


