随着远程办公和分布式团队的普及,安全可靠的虚拟私人网络(VPN)成为企业与个人用户不可或缺的工具,L2TP(Layer 2 Tunneling Protocol)结合IPsec加密机制,是一种成熟、稳定且跨平台的VPN解决方案,尤其适合Linux服务器环境,本文将详细介绍如何在Ubuntu操作系统上部署一个功能完整的L2TP/IPsec VPN服务,适用于家庭、小型企业和开发者测试场景。

确保你拥有一个运行Ubuntu Server或Desktop版本(建议使用18.04 LTS或20.04 LTS以上版本)的机器,并具备公网IP地址和基本的网络配置权限,我们使用的软件栈是OpenSwan(IPsec实现)和xl2tpd(L2TP守护进程),二者配合可提供端到端的安全隧道。

第一步:系统准备
更新系统并安装必要依赖包:

sudo apt update && sudo apt upgrade -y
sudo apt install xl2tpd strongswan libstrongswan-standard-plugins -y

第二步:配置IPsec(StrongSwan)
编辑 /etc/ipsec.conf 文件,添加如下内容:

config setup
    plutostart=no
    protostack=netkey
    charondebug="ike 1, knl 1, cfg 1"
conn %default
    ikelifetime=60m
    keylife=20m
    rekeymargin=3m
    rekeyfuzz=5s
    keyingtries=1
    keyexchange=ikev1
    authby=secret
    ike=aes256-sha1-modp1024!
    esp=aes256-sha1!
conn l2tp-psk
    left=%any
    leftid=@your-server-ip-or-hostname
    right=%any
    rightauth=pubkey
    rightauthordomain=%any
    auto=add
    type=transport
    compress=yes
    dpddelay=30
    dpdtimeout=120
    dpdaction=restart

/etc/ipsec.secrets 中设置预共享密钥(PSK):

%any %any : PSK "your_strong_pre_shared_key_here"

第三步:配置L2TP守护进程(xl2tpd)
编辑 /etc/xl2tpd/xl2tpd.conf

[global]
port = 1701
ip range = 192.168.100.100-192.168.100.200
local ip = your_server_public_ip
require chap = yes
refuse pap = yes
require authentication = yes
name = ubuntu-l2tp
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
[lns default]
ip range = 192.168.100.100-192.168.100.200
local ip = your_server_public_ip
require chap = yes
refuse pap = yes
require authentication = yes
name = ubuntu-l2tp
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd

第四步:创建PPP选项文件
新建 /etc/ppp/options.xl2tpd

+mschap-v2
ms-dns 8.8.8.8
ms-dns 8.8.4.4
noccp
noauth
proxyarp
lock
ncomp

第五步:添加用户认证
/etc/ppp/chap-secrets 中添加用户名和密码(格式:用户名 密码 IP):

username * password *

第六步:启用IP转发与防火墙规则
修改 /etc/sysctl.conf 启用转发:

net.ipv4.ip_forward=1

执行 sudo sysctl -p 生效。

配置iptables(或ufw)允许流量通过:

sudo iptables -A INPUT -p udp --dport 500 -j ACCEPT
sudo iptables -A INPUT -p udp --dport 4500 -j ACCEPT
sudo iptables -A INPUT -p udp --dport 1701 -j ACCEPT
sudo iptables -A FORWARD -s 192.168.100.0/24 -d 0.0.0.0/0 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE

重启服务:

sudo systemctl restart ipsec xl2tpd
sudo systemctl enable ipsec xl2tpd

至此,你的Ubuntu服务器已成功部署L2TP/IPsec VPN服务,客户端可通过Windows、macOS、Android或iOS设备连接,输入服务器IP、用户名和密码即可建立安全隧道,注意:为保障安全性,建议定期更换PSK和用户密码,并考虑使用证书认证替代预共享密钥,此方案无需额外付费软件,完全开源,非常适合对成本敏感但又追求稳定性的用户。

在Ubuntu系统中搭建L2TP/IPsec VPN服务的完整指南  第1张

VPN加速器|半仙VPN加速器-免费VPN梯子首选半仙VPN