一、为什么选择 WireGuard?

WireGuard 由 Jason A. Donenfeld 创建,2020 年正式并入 Linux 5.6 内核。相比传统的 IPsec 和 OpenVPN,它的代码量仅约 4,000 行(OpenVPN 约 70,000 行),这使得安全审计变得可行,也带来了显著的性能优势。

对比维度 WireGuard OpenVPN IPsec
代码量~4,000 行~70,000 行~400,000 行
吞吐量 (1Gbps)~980 Mbps~300 Mbps~600 Mbps
连接建立< 100ms3-8s1-3s
漫游支持✅ 无缝需重连需 IKEv2 MOBIKE
内核态运行✅ 是否(用户态)✅ 是
WireGuard 虚拟网络 (10.0.0.0/24) 公司总部 10.0.0.1/24 wg0 interface 远程员工 10.0.0.2/24 wg0 interface 端到端加密隧道 (Curve25519) 中间公网服务器(可选 — 仅用于 NAT 穿透时的初始握手) WireGuard 点对点组网 — 公钥交换后直接建立加密隧道,无需中心服务器中转

二、安装与密钥生成

# Ubuntu/Debian 安装
sudo apt update && sudo apt install wireguard -y

# 生成密钥对(每台机器执行)
umask 077
wg genkey | tee privatekey | wg pubkey > publickey

# 查看密钥
cat privatekey
# 输出: 2BKgJ4wHrFE...(44 字符 Base64)
cat publickey
# 输出: jPzO3tBVMf...(44 字符 Base64)

三、中心辐射型组网(Hub-Spoke)

中心节点(公司服务器)

# /etc/wireguard/wg0.conf — Hub 节点
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <hub-private-key>

# 开启 IP 转发(让远程员工通过中心节点访问公司内网)
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# 远程员工 A 的公钥
[Peer]
PublicKey = <employee-a-publickey>
AllowedIPs = 10.0.0.2/32

# 远程员工 B 的公钥
[Peer]
PublicKey = <employee-b-publickey>
AllowedIPs = 10.0.0.3/32

分支节点(远程员工)

# /etc/wireguard/wg0.conf — Spoke 节点
[Interface]
Address = 10.0.0.2/24
PrivateKey = <employee-private-key>
# DNS 可选:通过 VPN 隧道使用公司 DNS
DNS = 10.0.0.1

[Peer]
PublicKey = <hub-publickey>
Endpoint = hub.company.com:51820
AllowedIPs = 10.0.0.0/24, 192.168.1.0/24  # 公司 VPN 网段 + 公司内网
PersistentKeepalive = 25  # 保持 NAT 映射活跃

启动与管理

# 启动 WireGuard 接口
sudo wg-quick up wg0

# 设置开机自启
sudo systemctl enable wg-quick@wg0

# 查看连接状态
sudo wg show
# interface: wg0
#   public key: jPzO3tBVMf...
#   private key: (hidden)
#   listening port: 51820
# peer: 8xWqY7aLpR...
#   endpoint: 203.0.113.5:51820
#   allowed ips: 10.0.0.2/32
#   latest handshake: 5 seconds ago
#   transfer: 2.31 GiB received, 1.87 GiB sent

# 停止
sudo wg-quick down wg0

四、全互联组网(Mesh)

在需要低延迟直连的场景(如分布式数据库同步),可以配置全互联拓扑。每个节点配置所有其他节点为 Peer:

# 三节点 Mesh 示例 — 节点 A 的配置
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <node-a-private>

[Peer]  # 节点 B
PublicKey = <node-b-public>
Endpoint = node-b.example.com:51820
AllowedIPs = 10.0.0.2/32

[Peer]  # 节点 C
PublicKey = <node-c-public>
Endpoint = node-c.example.com:51820
AllowedIPs = 10.0.0.3/32

五、性能优化参数

# 在 /etc/sysctl.conf 中添加
net.core.rmem_default = 134217728
net.core.rmem_max = 134217728
net.core.wmem_default = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.ip_forward = 1

# 应用
sudo sysctl -p
💡 生产部署要点

WireGuard 是无状态协议,不会自动建立连接——双方必须有人先发包。通过 PersistentKeepalive 参数确保 NAT 后的节点保持可达。对于超过 50 个节点的网络,推荐使用 NetmakerTailscale 进行集中管控。