Oamc

WireGuard 配置

本页目录

场景

要让几台在外面的机器(或自己的笔记本)安全地访问内网,比 OpenVPN 轻、配置短。

前置条件

  • 一台有公网 IP 的服务器做服务端
  • 服务端能开 UDP 端口(默认 51820)
  • 规划 VPN 网段(比如 10.8.0.0/24),别和内网冲突

配置

dnf install -y wireguard-tools

# 生成密钥
cd /etc/wireguard
wg genkey | tee server.key | wg pubkey > server.pub
chmod 600 server.key

cat >/etc/wireguard/wg0.conf <<'EOF'
[Interface]
Address = 10.8.0.1/24
ListenPort = 51820
PrivateKey = <server.key 内容>
PostUp = firewall-cmd --add-port=51820/udp
PostDown = firewall-cmd --remove-port=51820/udp

[Peer]
PublicKey = <客户端公钥>
AllowedIPs = 10.8.0.2/32
EOF

systemctl enable --now wg-quick@wg0

客户端:

[Interface]
Address = 10.8.0.2/24
PrivateKey = <client.key>
DNS = 10.0.0.2

[Peer]
PublicKey = <server.pub>
Endpoint = vpn.example.com:51820
AllowedIPs = 10.0.0.0/8, 192.168.0.0/16
PersistentKeepalive = 25

验证

wg show

latest handshake 有时间、transfer 有流量,说明通了。

ping 10.8.0.1

回滚

systemctl disable --now wg-quick@wg0

坑

  • UDP 被防火墙挡了,wg show 一直没握手。
  • 客户端 AllowedIPs 写 0.0.0.0/0 会抢默认路由,导致 SSH 断线,先确认。
  • 服务端没开 net.ipv4.ip_forward=1,客户端之间和内网都通不了。
  • 需要 NAT 时在 PostUp 里加 masquerade。
  • 网段和公司内网冲突,连上后访问内网反而失败。
  • 密钥泄露只能换一对,没有吊销列表。