配置 Wireguard 接口 (wg)

来自 Alpine Linux

WireGuard 已成为几乎无处不在的 VPN 解决方案,适用于多个平台,并且自 Alpine 3.10 起在社区仓库中可用。WireGuard 本身现在已集成到 linux kernel v5.6 以后的版本中。只需要用户空间配置工具。

安装所需软件包

最直接的方法,也是 WireGuard 文档中推荐的方法,是使用 wg-quick

安装 wireguard-tools、iptables 和 sysctl

apk add wireguard-tools-wg-quick
apk add iptables

创建服务器密钥和接口配置

创建服务器私钥和公钥

wg genkey | tee server.privatekey | wg pubkey > server.publickey

然后,我们使用这些新密钥创建一个新的配置文件 /etc/wireguard/wg0.conf

[Interface]
Address = 192.168.2.1/24
ListenPort = 45340
PrivateKey = <server private key value> # the key from the previously generated privatekey file
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE;iptables -A FORWARD -o %i -j ACCEPT
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE;iptables -D FORWARD -o %i -j ACCEPT

[Peer]
PublicKey = <client public key value> # obtained from client device via wireguard connection setup process
AllowedIPs = 192.168.2.2/32

PostUp 和 PostDown iptables 规则将来自 wg0 子网 (192.168.2.1/24) 的流量转发到接口 eth0 上的 lan 子网。

有关向配置文件添加对等方的信息,请参阅此 WireGuard 文档

启动新的 wg0 接口:,

wg-quick up wg0

要关闭它,我们可以使用 wg-quick down wg0,这将清理接口并删除 iptables 规则。注意:如果在 Docker 容器中运行,您需要使用 --cap-add=NET_ADMIN 运行才能修改您的接口。

与网络接口一起使用

要在启动时启用 Wireguard 连接,请打开您的 /etc/network/interfaces 并在您的 auto 其他网络接口之后添加此信息

auto wg0
iface wg0 inet static
pre-up wg-quick up /etc/wireguard/wg0.conf

作为 OpenRC 服务

自 Alpine 3.20 起,有 wireguard-tools-openrc,它提供了一个 OpenRC initd 服务文件。首先安装软件包

apk add wireguard-tools-openrc

要使用 WireGuard OpenRC 脚本,您需要创建一个指向它的符号链接,并带有配置名称,就像这样

ln -s /etc/init.d/wg-quick /etc/init.d/wg-quick.wg0
# Add it to the default runlevel:
rc-update add wg-quick.wg0
# Finally, start the service:
rc-service wg-quick.wg0 start

启用 IP 转发

在您的路由器上配置了 NAT 目标规则后,您应该能够连接到 wireguard 实例并访问主机。但是,如果您希望对等方能够访问外部资源(包括互联网),您将需要启用 IP 转发。

编辑文件 /etc/sysctl.conf (或 /etc/sysctl.d/ 下的 .conf 文件)并添加以下行

net.ipv4.ip_forward = 1

添加 sysctl 服务以在启动时运行

rc-update add sysctl 

然后重新启动或运行 sysctl -p /etc/sysctl.conf 以重新加载设置。要确保转发已打开,请运行 sysctl -a | grep ip_forward 并确保 net.ipv4.ip_forward 设置为 1

使用 modloop 运行

如果您从 RAM 磁盘运行,则无法修改 modloop。

您可以通过解包 modloop、挂载解包的模块文件夹,然后安装 WireGuard 来解决此问题。

#!/bin/sh
apk add squashfs-tools # install squashfs tools to unpack modloop
unsquashfs -d /root/squash /lib/modloop-lts # unpack modloop to root dir
umount /.modloop # unmount existing modloop
mount /root/squash/ /.modloop/ # mount unpacked modloop
apk del wireguard-lts # uninstall previous WireGuard install
apk add wireguard-lts
apk add wireguard-tools

您可以重新打包 squash 文件系统或将此脚本放在 /etc/local.d/ 路径中,以便它在启动时运行。