Wireguard简易教程--以内网穿透为例
wireguard官网:
https://www.wireguard.com/
参考教程:
①https://icloudnative.io/posts/wireguard-docs-practice/
②https://gitee.com/spoto/wireguard
1.安装(以ubuntu为例):
# 其他系统参考官网 https://www.wireguard.com/install/
# root权限
sudo -i
# 安装wireguard软件
apt install wireguard resolvconf -y
# 开启IP转发
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p
2.进入配置路径,并调整权限(建议)
cd /etc/wireguard/
umask 077
3.生成机器的私钥和公钥
wg genkey > private.key
wg pubkey < private.key
4.创建编写机器的配置文件
# 配置文件的命名形式必须为 ${WireGuard 接口的名称}.conf
# WireGuard 接口的名称为 ^[a-zA-Z0-9_=+.-]{1,15}$
# WireGuard 接口的名称常用为 wg[0-9]{1,3}
vim wg0.conf
配置文件样例(内网穿透)
机器A在公网,机器B、C在内网
机器A需要开启一个UDP端口用来监听
机器A配置文件wg0.conf

[Interface]
PrivateKey = # 机器A的私钥
Address = 10.0.8.1/28 # 机器A的虚拟局域网地址
ListenPort = 51000 # 机器A的UDP监听端口
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE # wg0开启后,启用端口转发和nat
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE # wg0关闭后,关闭端口转发和nat
MTU = 1420 #可以不设置
[Peer]
PublicKey = # 机器B的公钥
AllowedIPs = 10.0.8.2 # 机器B的虚拟局域网地址
[Peer]
PublicKey = # 机器C的公钥
AllowedIPs = 10.0.8.3 # 机器C的虚拟局域网地址

机器B配置文件wg0.conf

[Interface]
PrivateKey = # 机器B的私钥
Address = 10.0.8.2/28 # 机器B的虚拟局域网地址
MTU = 1420 # 可以不设置
[Peer]
PublicKey = # 机器A的公钥
AllowedIPs = 10.0.8.0/28 # 虚拟局域网地址的地址段
Endpoint = ip:port # 机器A的ip及wireguard中配置的监听端口
PersistentKeepalive = 60 # 每隔 60s / 1minute保持连接 该选项只需要对被访问的机器配置,如果要双向访问建议都配置

机器C配置文件wg0.conf
[Interface]
PrivateKey = # 机器C的私钥
Address = 10.0.8.3/28 # 机器C的虚拟局域网地址
MTU = 1420 # 可以不设置
[Peer]
PublicKey = # 机器A的公钥
AllowedIPs = 10.0.8.0/28 # 虚拟局域网地址的地址段
Endpoint = ip:port # 机器A的ip及wireguard中配置的监听端口
PersistentKeepalive = 60 # 每隔 60s / 1min 保持连接

5.设置服务开机自启动
# wg0为相应配置文件的前缀
systemctl enable wg-quick@wg0
6.启动和关闭wireguard配置的网口
# 启动, wg0为相应配置文件的前缀
wg-quick up wg0
# 关闭
wg-quick down wg0
# 如果开始只安装了wireguard,该步骤可能出现无法解析问题,需要安装 resolvconf 解决