Linux VPN 与隧道技术实战(IPsec、WireGuard、GRE 等)
一、VPN 与隧道技术概述
常见需求:
主流技术:
- IPsec(IKEv2 / ESP / AH):标准、兼容性强
- GRE / IPIP / VXLAN:纯隧道(常结合 IPsec 加密)
- ZeroTier / Tailscale:基于 WireGuard 的 SaaS 简化方案
内核支持:Linux 原生支持 WireGuard(5.6+)、IPsec(XFRM)、GRE 等。
二、WireGuard 快速部署与配置
安装:
# Ubuntu/Debian
apt install wireguard wireguard-tools
# RHEL/CentOS
dnf install wireguard-tools
生成密钥:
wg genkey | tee privatekey | wg pubkey > publickey
服务器配置(/etc/wireguard/wg0.conf):
[Interface] Address = 10.0.0.1/24 PrivateKey = <服务器私钥> ListenPort = 51820 PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE [Peer] PublicKey = <客户端公钥> AllowedIPs = 10.0.0.2/32
客户端配置:
[Interface] Address = 10.0.0.2/24 PrivateKey = <客户端私钥> [Peer] PublicKey = <服务器公钥> Endpoint = server_public_ip:51820 AllowedIPs = 0.0.0.0/0 # 全流量走隧道 PersistentKeepalive = 25
启动:
wg-quick up wg0
systemctl enable wg-quick@wg0
验证:
wg show
ping 10.0.0.2
ip route show table all
防火墙放行(nftables/iptables):
# UDP 51820
nft add rule inet filter input udp dport 51820 accept
三、IPsec 经典配置(StrongSwan)
安装:
apt install strongswan strongswan-swanctl
swanctl 配置示例(/etc/swanctl/swanctl.conf):
connections {
site-to-site {
local_addrs = server_public_ip
remote_addrs = client_public_ip
local {
auth = pubkey
certs = server.crt
}
remote {
auth = pubkey
}
children {
net-net {
local_ts = 192.168.10.0/24
remote_ts = 192.168.20.0/24
esp_proposals = aes256gcm16
}
}
}
}
启动:
swanctl --load-all
swanctl --initiate --child net-net
ipsec statusall
XFRM 状态:
ip xfrm state
ip xfrm policy
四、GRE / VXLAN 隧道配置
GRE 简单隧道:
ip tunnel add gre0 mode gre remote 203.0.113.1 local 198.51.100.1 ttl 255
ip addr add 10.8.0.1/30 dev gre0
ip link set gre0 up
结合 IPsec 加密:先建 GRE,再通过 IPsec 保护 GRE 流量。
VXLAN(适用于大规模 Overlay):
ip link add vxlan0 type vxlan id 100 dstport 4789 remote 192.168.1.100 local 192.168.1.50
ip addr add 10.0.1.1/24 dev vxlan0
五、性能对比与调优
WireGuard 优势:
- 现代加密(ChaCha20-Poly1305 / Curve25519)
测试命令:
iperf3 -c 10.0.0.2
调优:
- MTU 调整(WireGuard 默认 1420,考虑封装开销)
PersistentKeepalive 防 NAT 超时
IPsec 性能相对较低,但兼容性更好。
六、生产高可用与安全实践
高可用:
安全加固:
- 启用 WireGuard 的 PostUp 脚本做额外过滤
- 日志审计:
journalctl -u wg-quick@wg0 - 避免全流量代理(0.0.0.0/0)时的 DNS 泄漏
监控:
- Prometheus wireguard_exporter
- 流量统计:
wg show wg0 transfer
常见故障排查:
- 握手失败:密钥不匹配、公网 IP 变化、端口不通 →
tcpdump udp port 51820 - 路由不对:
ip route + AllowedIPs - NAT 穿越问题:PersistentKeepalive + 防火墙
- 性能差:MTU 黑洞 → 降低 MTU 或启用 Path MTU Discovery