基础环境介绍 云服务器:腾讯云1h2g轻量云服务器 本地:DellR230机架式服务器(电信家用宽带) 均使用Linux系统(经测试不适用于windows系统)
实战步骤 安装wireguard 首先我们要在两台机器间建立一个虚拟局域网(除了wireguard,zerotier之类的软件也是可以的),先在本地与远程两台机器上安装wireguard,并生成公钥和私钥。
1 2 3 4 apt install wireguard wg genkey | tee privatekey | wg pubkey > publickey
开启转发规则 【重点】公网服务器端开启端口转发规则,修改 /etc/sysctl.conf 添加 net.ipv4.ip_forward = 1 执行 sysctl -p 开启转发
写入配置文件 然后在两台服务器/etc/wireguard/ 下创建配置文件 wg.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [Interface] ListenPort = 16000 Address = 10.0 .0.1 /24 PrivateKey = $PRIVATEKEY PostUp = iptables -A FORWARD -i %i -j ACCEPTPostDown = iptables -D FORWARD -i %i -j ACCEPT[Peer] PublicKey = $PUBLICKEY AllowedIPs = 10.0 .0.2 /32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [Interface] Address = 10.0 .0.2 /32 PrivateKey = CLIENTA_PRIVATE_KEY[Peer] PublicKey = SERVER_PUBLICKEYEndpoint = 公网服务器IP:16000 AllowedIPs = 10.0 .0.0 /24 PersistentKeepalive = 20
启动wireguard 1 2 3 wg-quick up wg# 或者 systemctl start wg-quick@wg
疑难杂症 虚拟网不通 按照前面的步骤写入的配置文件中,云服务器的wg虚拟地址为10.0.0.1,本地服务器的wg虚拟地址为10.0.0.2
如果从云服务器中使用ping命令验通10.0.0.2时存在问题,就应该先检查wg客户端于服务端之间的通信
常见问题如AllowedIPs =10.0.0.0/24,24代表的是相应的子网掩码,也就是说10.0.0.0/24代表了10.0.0.1~10.0.0.254中的所有地址,如果将24更改为32(即10.0.0.1/32)为仅指向10.0.0.1一个地址
这种情况下应当优先检查客户端和服务端的wg.conf配置文件
外网不通 如果在确认配置文件中没有问题的情况下,外网依旧不通,优先检查iptables。通过iptables-save命令查看当前iptables规则,然后搭配tcpdump工具检查网卡流量情况来判断问题出现位置。
如果确定问题不出在配置文件中的情况时,可通过reboot重启服务器来实现清空iptables规则(剩下的交给玄学QAQ)
我使用的配置文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [Interface] Address = 10.0 .0.2 /24 PrivateKey = 客户端私钥Table = 1 PostUp = ip rule add from 10.0 .0.2 table 1 PostDown = ip rule del from 10.0 .0.2 table 1 [Peer] PublicKey = 服务器公钥Endpoint = 服务器公网IP:16000 AllowedIPs = 10.0 .0.1 /32 , 0.0 .0.0 /0 PersistentKeepalive = 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [Interface] ListenPort = 16000 Address = 10.0 .0.1 /24 PrivateKey = 公网服务器私钥PostUp = iptables -t nat -A PREROUTING -d 10.0 .16.16 -p tcp -m multiport --dports 22 ,16000 -j ACCEPTPostDown = iptables -t nat -D PREROUTING -d 10.0 .16.16 -p tcp -m multiport --dports 22 ,16000 -j ACCEPT[Peer] PublicKey = 本地服务器公钥AllowedIPs = 10.0 .0.2 /32
参考 https://fuckcloudnative.io/posts/wireguard-docs-practice/#-dns https://www.cnblogs.com/wanstack/p/7728785.html https://www.liuvv.com/p/a8480986.html https://aoyouer.com/posts/wireguard-l3-forward/