wireguard 使用
我有三台 VPS,希望通过 wireguard 将他们组成内网。
安装
在所有机器上安装 wireguard
(我使用的是 debian,下面的 centos 命令没有测试过)
# Debian/Ubuntu
apt update
apt install wireguard
# CentOS/RHEL
yum install epel-release elrepo-release
yum install kmod-wireguard wireguard-tools
在所有机器上生成密钥对
# 在每台服务器上执行
cd /etc/wireguard
wg genkey | tee privatekey | wg pubkey > publickey
chmod 600 privatekey
配置
这里使用 VPS1 作为主节点,其余机器都连它。
# /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <VPS1的私钥>
Address = 10.0.0.1/24
ListenPort = 51820
# VPS2配置
[Peer]
PublicKey = <VPS2的公钥>
AllowedIPs = 10.0.0.2/32
# VPS3配置
[Peer]
PublicKey = <VPS3的公钥>
AllowedIPs = 10.0.0.3/32
VPS2
# /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <VPS2的私钥>
Address = 10.0.0.2/24
[Peer]
PublicKey = <VPS1的公钥>
Endpoint = <VPS1的公网IP>:51820
AllowedIPs = 10.0.0.0/24
PersistentKeepalive = 25
VPS3
# /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <VPS3的私钥>
Address = 10.0.0.3/24
[Peer]
PublicKey = <VPS1的公钥>
Endpoint = <VPS1的公网IP>:51820
AllowedIPs = 10.0.0.0/24
PersistentKeepalive = 25
启动 wireguard
# 启动服务
wg-quick up wg0
# 设置开机自启
systemctl enable wg-quick@wg0
星型拓扑和网状拓扑
上面的配置方式是星型拓扑,即所有节点连向一个中心节点,所以 VPS2 和 VPS3 之间的流量也会经过 VPS1。如果希望 VPS2 和 VPS3 可以直接连接(即网状拓扑),可以这样修改配置(本质上是在每个节点上都加上其余节点的信息)。
VPS2
# /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <VPS2的私钥>
Address = 10.0.0.2/24
ListenPort = 51820
# VPS1 配置
[Peer]
PublicKey = <VPS1的公钥>
Endpoint = <VPS1的公网IP>:51820
AllowedIPs = 10.0.0.1/32
PersistentKeepalive = 25
# VPS3 配置
[Peer]
PublicKey = <VPS3的公钥>
Endpoint = <VPS3的公网IP>:51820
AllowedIPs = 10.0.0.3/32
PersistentKeepalive = 25
VPS3
# /etc/wireguard/wg0.conf
[Interface]
PrivateKey = <VPS3的私钥>
Address = 10.0.0.3/24
ListenPort = 51820
# VPS1 配置
[Peer]
PublicKey = <VPS1的公钥>
Endpoint = <VPS1的公网IP>:51820
AllowedIPs = 10.0.0.1/32
PersistentKeepalive = 25
# VPS2 配置
[Peer]
PublicKey = <VPS2的公钥>
Endpoint = <VPS2的公网IP>:51820
AllowedIPs = 10.0.0.2/32
PersistentKeepalive = 25
问题
报错 RTNETLINK answers: Operation not supported
启动时报这个错
RTNETLINK answers: Operation not supported
Unable to access interface: Protocol not supported
排查
# 检查 wireguard 模块是否加载
lsmod | grep wireguard
# 尝试手动加载模块
modprobe wireguard
# 检查加载是否有错误信息
dmesg | grep wireguard
安装必要的包
# debian
# 安装必要的包
apt update
apt install linux-headers-$(uname -r)
apt install wireguard-dkms wireguard-tools
# 重新加载模块
modprobe wireguard
# centos
# 确保已安装 EPEL 源
yum install epel-release
# 安装必要的包
yum install kernel-devel-$(uname -r) kernel-headers-$(uname -r)
yum install kmod-wireguard wireguard-tools
# 重新加载模块
modprobe wireguard
怎么查看连接
$ wg
# 正常情况下应该看到下面的内容
interface: wg0
public key: your_public_key
private key: (hidden)
listening port: 51820
peer: peer_public_key
endpoint: 192.168.1.100:51820
allowed ips: 10.0.0.2/32
latest handshake: 1 minute ago
transfer: 1.23 MiB received, 456.78 KiB sent
怎么查看路由信息
$ ip route
# 应该会看到这样的内容
10.0.0.0/24 dev wg0 proto kernel scope link src 10.0.0.1
怎么重启
wg-quick down wg0
wg-quick up wg0
Read other posts