环境h2
| 设备 | 说明 |
|---|---|
| Debian9 4.9 内核服务器 | 部署 WireGuard 服务端 |
| OpenWrt x86 64 | 内网网关 |
| Windows10 | 内网设备 |
部署 WireGuard 服务端h2
配置软件源并安装 WireGuard。
apt-get install wireguard wireguard-tools切换到 WireGuard 配置目录。
cd /etc/wireguard/生成服务端与客户端密钥h3
分别生成服务端和客户端的密钥对。
mkdir server; wg genkey | tee server/privatekey | wg pubkey > server/publickeymkdir client; wg genkey | tee client/privatekey | wg pubkey > client/publickey创建服务端配置文件h3
创建服务端配置文件 wg0.conf。
cat > wg0.conf <<-EOF[Interface]Address = 172.16.220.1/24SaveConfig = falsePostUp = (echo 1 > /proc/sys/net/ipv4/ip_forward); iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens5 -j MASQUERADEPostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ens5 -j MASQUERADEListenPort = 12138PrivateKey = `cat server/privatekey`
[Peer] # ClientPublicKey = `cat client/publickey`AllowedIPs = 172.16.220.2/32EOF创建客户端配置文件h3
创建客户端配置文件 client.conf,并可生成连接二维码。
cat > client.conf <<-EOF[Interface]PrivateKey = `cat client/privatekey`Address = 172.16.220.2/24DNS = 8.8.8.8MTU = 1420
[Peer]PublicKey = `cat server/publickey`# AllowedIPs = 0.0.0.0/0 # 将所有流量路由到服务端AllowedIPs = 172.16.220.0/24 # 仅允许 WireGuard 虚拟网段互通Endpoint = example.com:12138PersistentKeepalive = 25EOF生成客户端配置二维码。
qrencode -t ansiutf8 < client.conf如需添加多个客户端,只需在服务端配置文件中增加相应的
[Peer]区块即可。
进阶配置:站点间内网互通h2
通过 WireGuard 实现两个局域网(站点)间的直接访问。
| 主机 | 公网/IP | WireGuard IP | 内部网段 | 角色 |
|---|---|---|---|---|
| ServerA | 169.254.0.1 | 172.16.220.1 | 172.21.161.0/20 | 公网服务器,WireGuard 服务端 |
| ClientB | 192.168.2.142 | 172.16.220.3 | 192.168.2.0/24 | 内网服务器,WireGuard 客户端 |
| ClientC | 192.168.2.102 | 无 | 192.168.2.0/24 | 目标内网服务器 |
目标:使 ServerA 能够直接访问 ClientC 的内网 IP 192.168.2.102。
ServerA 配置修改h3
-
修改服务端对等端配置:在 ServerA 的
wg0.conf中,修改 ClientB 对等端的AllowedIPs,添加 ClientB 所在的内网网段。Terminal window AllowedIPs = 172.16.220.3/32, 192.168.2.0/24 -
在 ClientB 上添加静态路由:登录 ClientB 服务器,添加一条路由,将前往 ServerA 公网 IP 的流量指向其本地网关(此处假设为
192.168.2.142,通常为 ClientB 自身或路由器)。Terminal window ip route add 169.254.0.1/32 via 192.168.2.142注:此步骤的具体网关地址需根据 ClientB 的实际网络环境调整。
-
在 ClientB 上配置 IP 转发与 NAT:在 ClientB 上启用内核转发,并设置 iptables 规则,允许转发来自 WireGuard 网段的流量到其内网,并进行源地址转换。
Terminal window echo 1 > /proc/sys/net/ipv4/ip_forwardiptables -A FORWARD -d 192.168.2.0/24 -j ACCEPTiptables -t nat -A POSTROUTING -s 172.16.220.0/24 -d 192.168.2.0/24 -j MASQUERADE
完成以上配置后,ServerA 即可通过 WireGuard 隧道直接访问 192.168.2.102。