缘由

WireGuard 一般使用内核空间模块, 但在 OpenVZ 容器系统中无法直接使用。

准备

检查宿主内核版本及已载入的模块

本示例使用 Linux Kernel 5.x 系列,低于该版本的内核可能无法正常工作。

检查 tun 模块载入状态

➜  ~ lsmod|grep tun                     
tun                    69632  0

若无法找到该模块,请咨询服务器提供商在宿主启用。

安装 BoringTun

BoringTun 是 Cloudflare 开发的一种用户空间的 WireGuard 实现。我们可以使用它很方便的创建虚拟网卡,并将其作为 WireGuard 接口使用。

注意,需要正确安装 rust 及其配套组件以执行下列步骤(推荐使用 rustup 自动安装)。

使用 Cargo 安装

cargo install boringtun-cli

从源编译安装 / 安装服务

请参阅此项目中 README 指示的步骤。

WireGuard 配置

注意,子节点端系统为 OpenVZ 容器环境。

生成密钥及公钥

wg genkey | tee privatekey | wg pubkey > publickey

执行以上命令后,你的工作目录将生成以下文件。

  • privatekey
  • publickey

使用 chmod go= *key 限制根用户外的访问性以提高密钥对安全性。

注意,WireGuard 仅支持 Base64 编码字符数据。

主节点

在 Interface 段中指定该 VPN 的网段及服务端分配的 IP、监听端口、私钥(或额外参数)。

单个节点可以有多个 Peer,在段中指定该 Peer 节点的公钥(需要与实际使用公钥对应)及需要的 IP(或额外参数)。

我们可使用 wg-quick up wg0 进行方便的启动。

[Interface]
PrivateKey = PrivateKey_base64_string
Address = 10.0.0.1/24
ListenPort = 51820

[Peer]
PublicKey = PublicKey_base64_string
AllowedIPs = 10.0.0.2/32Code language: PHP (php)

可选的 NAT 配置

iptables -t nat -A POSTROUTING -o eth0 -s 10.0.0.0/24 -j MASQUERADE

子节点

注意,Peer 段中指定的 AllowedIPs 为主节点设定的网络地址。

[Interface]
PrivateKey = PrivateKey_base64_string
ListenPort = 51820

[Peer]
PublicKey = PublicKey_base64_string
EndPoint = 123.123.123.123:51820
AllowedIPs = 10.0.0.0/24

由于 wg-quick 在此不适用(在 Interface 段中的 Address 不被识别),我们需要使用 wg 来指定 boringtun 接口配置,并进行 IP 地址绑定和接口启用。

wg setconf wg0 /etc/wireguard/wg0.conf
ip addr add 10.0.0.2/24 dev wg0
ip link set up wg0Code language: JavaScript (javascript)

注意,请根据需要编写(实际使用的虚拟接口名、网段分配等),妥善保管密钥对以避免可能的中间人攻击。

验证

# ping 10.0.0.1 -c 4
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
64 bytes from 10.0.0.1: icmp_seq=1 ttl=64 time=3.43 ms
64 bytes from 10.0.0.1: icmp_seq=2 ttl=64 time=3.43 ms
64 bytes from 10.0.0.1: icmp_seq=3 ttl=64 time=3.43 ms
64 bytes from 10.0.0.1: icmp_seq=4 ttl=64 time=3.97 ms

--- 10.0.0.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 3.427/3.564/3.969/0.233 ms

# wg
interface: wg0
  listening port: 51820

peer: MAIN_NODE_PUBKEY_BASE64
  endpoint: 123.123.123.123:51820
  allowed ips: 10.0.0.0/24
  latest handshake: 53 years, 149 days, 15 hours, 44 minutes, 42 seconds ago
  transfer: 208.77 MiB received, 121.00 MiB sent

References


0 条评论

发表回复

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据