Debian 配置 Wireguard

准备&依赖安装

  • 安装 lsb-release

    1
    apt install lsb-release -y
  • 添加 backports

    1
    2
    3
    echo "deb http://deb.debian.org/debian $(lsb_release -sc)-backports main" | sudo tee /etc/apt/sources.list.d/backports.list

    apt update
  • 准备相关工具

    1
    apt install iproute2 openresolv -y
  • 开启 IP_Forwarding

    1
    2
    echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
    sysctl -p

安装 Wireguard

检查内核版本

Debian10默认使用的4.19内核版本,该版本没有集成Wireguard,因此我们需要安装新版内核。

1
apt -t $(lsb_release -sc)-backports install linux-image-$(dpkg --print-architecture) linux-headers-$(dpkg --print-architecture) --install-recommends -y

安装Wireguard

1
apt install wireguard-tools --no-install-recommends

如果是Debian11 则一般内核都已集成了Wireguard,无需更新。

创建配置文件

Wire­guard 使用 INI 的语法配置网络,配置文件默认放在 /etc/wireguard/ 下,一般文件名为 wg0.confwg1.conf…… 表示该配置文件创建的 Wire­guard 网卡(in­ter­face)的名称为 wg0等。

中心节点配置

这里的中心节点,也常常被人称为” 服务端 “,因为它作为整个网络的中心,其他节点的流量都要通过它,好像一个向众多用户提供服务的服务器。不过需要注意的是,在 Wire­guard 中,所有节点都叫做 “Peer”,意即他们是对等的,并不是传统的 C-S(Client-Server)模型,不论是 “服务端” 还是 “客户端”,Wire­guard 都是一视同仁的,他们之间只存在配置文件的不同而已。

生成公私钥

1
2
3
4
cd /etc/wireguard/
wg genkey | tee wg0 | wg pubkey > wg0.pub
cat wg0 # 私钥
cat wg0.pub # 公钥

创建配置文件

1
2
3
4
5
6
7
8
[Interface]
Address = 192.168.233.1/32
PrivateKey = <Server_Private_Key>
ListenPort = <Listen_Port>

[Peer]
PublicKey = <Peer_Pub_Key>
AllowedIPs = 192.168.233.2/32

整个配置文件分为两部分,[Interface] 部分配置本机的网络接口(网卡),而 [Peer] 部分配置可以与本机连接的节点。

[Interface] 部分:

  • Address 是当前配置的 Wireguard 网卡在组建的局域网中的地址,遵循 CIDR 表示法。/24 表示了子网大小,具体含义请自行查询。
  • PrivateKey 是当前网卡的私钥。其他节点发往当前节点的流量都会用该私钥对应的公钥加密,本地网卡收到后使用私钥解密。
  • ListenPort 是当前网卡监听的端口。该端口收到的 UDP 流量会被 Wireguard 处理,该网卡也使用这个端口向外发送数据,所以需要确保这个端口没有被防火墙拦截或者被其他程序占用。

[Peer] 部分:

  • PublicKey 是 Peer 节点的公钥。当前节点向 Peer 节点发送数据时会使用对方的公钥进行加密,对方收到后会使用自己的私钥解密。现在我们还没有配置 Peer 节点,可以暂时留空,稍后回来补充。
  • AllowedIPs 有两个功能:
    • 首先,它会为本机添加路由规则,本机匹配 AllowedIPs 的数据包会被路由到这个 Peer。
    • 其次,来源于这个 Peer 的数据包的源地址必须在 AllowedIPs 中,否则本机的 Wireguard 会忽略这些数据包。

可参考:What does WireGuard AllowedIPs actually do? – TechOverflow

Peer节点配置

其他节点可以看作传统 C-S 模型中的客户端。生成密钥对、创建配置文件的过程和中心节点完全相同,注意中心节点和其他节点的配置文件名 不必相同

1
2
3
4
5
6
7
8
9
[Interface]
Address = 192.168.233.2/32
PrivateKey = <Peer_Private_Key>

[Peer]
PublicKey = <Server_Pub_Key>
AllowedIPs = 192.168.233.1/32
Endpoint = <Server_IP>:<Port>
PersistentKeepalive = 25

启动 Wireguard

wire­guard-tools 提供了 wg-quick 工具,可以快速部署 Wire­guard。

启动 /etc/wireguard/wg0.conf:

1
wg-quick up wg0

关闭 /etc/wireguard/wg0.conf

1
wg-quick down wg0

如果配置文件不在默认的 /etc/wireguard/ 下,需要输入完整的路径。

启动完毕后可以使用 wg 工具查看当前的连接情况,详情请参考:wg(8) — wireguard-tools — Debian unstable — Debian Manpages


Debian 配置 Wireguard
http://example.com/2022/09/18/Debian-10-Buster-配置Wireguard/
作者
Rae
发布于
2022年9月18日
许可协议