在 CentOS 系统上搭建 L2TP/IPsec VPN 服务详解(含配置步骤与常见问题排查)

随着远程办公和网络安全需求的不断增长,构建一个稳定、安全的虚拟私有网络(VPN)成为企业与个人用户的刚需,L2TP(Layer 2 Tunneling Protocol)结合 IPsec(Internet Protocol Security)是一种广泛使用的协议组合,它既支持点对点隧道传输,又提供强大的加密机制,非常适合用于在 CentOS 这类 Linux 发行版中部署企业级远程访问服务。

本文将详细介绍如何在 CentOS 7/8 系统上搭建 L2TP/IPsec VPN 服务,涵盖安装、配置、防火墙设置及故障排查等关键环节,帮助网络工程师快速完成部署并保障连接稳定性。

第一步:准备工作
确保系统已更新至最新版本,执行以下命令:

sudo yum update -y

第二步:安装必要的软件包
L2TP/IPsec 的实现依赖于 xl2tpd(L2TP 守护进程)和 ipsec(IKE 协议栈),我们使用 StrongSwan 作为 IPsec 实现(比 Openswan 更现代且兼容性更好):

sudo yum install -y xl2tpd strongswan

第三步:配置 IPsec(StrongSwan)
编辑主配置文件 /etc/ipsec.conf

config setup
    plutostart=no
    protostack=netkey
    dumpdir=/var/run/pluto/
    nat_traversal=yes
    virtual_private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12
conn %default
    keylife=20m
    rekeymargin=3m
    keyingtries=1
    keyexchange=ikev1
    ike=aes256-sha1-modp1024!
    esp=aes256-sha1!
conn l2tp-psk
    auto=add
    left=%any
    leftid=@your-vpn-server.com   # 替换为你的公网域名或IP
    leftsubnet=192.168.100.0/24  # 客户端分配的子网
    right=%any
    rightsourceip=192.168.100.0/24
    rightdns=8.8.8.8,8.8.4.4
    authby=secret
    pfs=yes
    type=transport
    modecfgdns=8.8.8.8,8.8.4.4

/etc/ipsec.secrets 中添加预共享密钥(PSK):

%any %any : PSK "your_strong_pre_shared_key"

第四步:配置 L2TP 服务器(xl2tpd)
编辑 /etc/xl2tpd/xl2tpd.conf

[global]
port = 1701
listen-addr = 0.0.0.0
[lns default]
ip range = 192.168.100.100-192.168.100.200
local ip = 192.168.100.1
require chap = yes
refuse pap = yes
require authentication = yes
name = l2tpd
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes

第五步:设置 PPP 身份验证
创建 /etc/ppp/options.xl2tpd 文件,内容如下:

ipcp-accept-local
ipcp-accept-remote
noccp
noauth
mtu 1400
mru 1400
proxyarp
lcp-echo-interval 30
lcp-echo-failure 4

第六步:配置用户账号
编辑 /etc/ppp/chap-secrets


第七步:启动服务并启用开机自启

sudo systemctl start ipsec xl2tpd
sudo systemctl enable ipsec xl2tpd

第八步:开放防火墙端口

sudo firewall-cmd --add-port=500/udp --permanent
sudo firewall-cmd --add-port=4500/udp --permanent
sudo firewall-cmd --add-port=1701/tcp --permanent
sudo firewall-cmd --reload

第九步:测试连接
使用 Windows 或 macOS 客户端通过 L2TP/IPsec 连接,输入服务器地址、用户名和密码即可,如遇连接失败,请检查日志:

journalctl -u ipsec -f
tail -f /var/log/messages

常见问题包括:IPsec 握手失败、客户端无法获取 IP、DNS 不可用等,通常可通过调整 NAT 设置、确认 PSK 一致性和检查 SELinux 策略来解决。

通过以上步骤,你可以在 CentOS 上成功搭建一个功能完整的 L2TP/IPsec VPN 服务,满足远程接入与数据加密需求,建议定期备份配置文件,并根据实际网络环境优化性能参数。

Secrets for authentication using CHAP  第1张

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