wg异地组网

发布于 2022-05-03  97 次阅读


安装wg

apt install wireguard

生成公钥私钥

wg genkey |  tee /etc/wireguard/privatekey | wg pubkey |  tee /etc/wireguard/publickey

编辑配置文件

vim /etc/wireguard/wg0.conf
#公网gateway配置
[Interface]
#wireguard网段
Address = 10.0.2.1/24
ListenPort = 12345
PrivateKey = {Server_PrivateKey}
#通过ip addr获得主网卡名称,一般为eth0
#放行虚拟网卡
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
#内网节点的公钥
PublicKey = {NAT-A_PublicKey}
# 下面非常重要,相当于是添加路由表,在启动wireguard的时候也能看到
AllowedIPs = 10.0.2.2/32, 192.168.123.0/24

[Peer]
#外部网络节点的公钥
PublicKey = {NAT-B_PublicKey}
AllowedIPs = 10.0.2.3/32
#内网gateway
[Interface]
PrivateKey = {PrivateKey}
Address = 10.0.2.2/24
#通过ip addr获得主网卡名称,unraid的虚拟机可能为enp1s0
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens18 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ens18 -j MASQUERADE

[Peer]
PublicKey = {Server_PublicKey}
AllowedIPs = 10.0.2.0/24
Endpoint = {Server_ip}:12345
PersistentKeepalive = 15
#外网节点
[Interface]
PrivateKey = {PrivateKey}
Address = 10.0.2.3/24

[Peer]
PublicKey = {Server_PublicKey}
# 下面的路由非常重要,不然系统不知道这个ip要从那个网卡走
AllowedIPs = 10.0.2.0/24, 192.168.123.0/24
Endpoint = {Server_ip}:12345
PersistentKeepalive = 15

打开流量转发

echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf && sysctl -p

载入wg模块并运行wg

modprobe wireguard && systemctl enable wg-quick@wg0 && systemctl start wg-quick@wg0

面向ACG编程