点击展开更新日志

2026

title

xxxxx

nexttime

会有些什么呢(❁´◡`❁)

源起

原本想要直接使用 OpenVPN 的,但是没有找到绿色版的软件(笔记本限制装不了软件),于是换到了 Wire
Guard。

服务端安装配置

服务端安装 WireGuard

1
2
3
4
5
6
7
8
# Ubuntu/Debian
sudo apt install wireguard -y

# CentOS
sudo yum install epel-release -y
sudo yum install wireguard-tools -y
# 某些系统可能需要安装DKMS包
sudo yum install wireguard-dkms -y

生成密钥对并开启IP转发

WireGuard使用公钥/私钥对进行身份验证,每个设备都需要生成一对。

1
2
3
4
5
6
7
8
9
10
# 配置目录权限
chmod 700 /etc/wireguard/

# 进入目录并生成服务器的私钥和公钥
cd /etc/wireguard/
wg genkey | tee server_private.key | wg pubkey > server_public.key

# 开启系统的IPv4流量转发功能
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-wireguard.conf
sudo sysctl -p /etc/sysctl.d/99-wireguard.conf

创建服务端配置文件

1
2
vim /etc/wireguard/wg0.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[Interface]
# 服务器的私钥(替换为 server_private.key 的内容)
PrivateKey = <SERVER_PRIVATE_KEY>
# WireGuard VPN 网络内服务器的虚拟IP地址
Address = 10.0.0.1/24
# 监听的UDP端口(必须与云服务器安全组中开放的端口一致)
ListenPort = 51820
# 接口启动时执行的防火墙和NAT规则
# 将 eth0 替换为你云服务器实际使用的网卡名称(可通过 ip addr 命令查看)
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
# 客户端(家庭设备)的公钥(稍后从客户端获取并替换此处)
PublicKey = <CLIENT_PUBLIC_KEY>
# 允许通过该Peer访问的VPN网络IP范围,这里是分配给客户端的固定IP
AllowedIPs = 10.0.0.2/32
# 可选:如果需要让家庭设备访问云服务器内网其他资源,可在此添加路由,如 172.17.0.0/16

启动服务

1
2
3
4
5
6
root@VM-0-3-ubuntu:/etc/wireguard# wg-quick up wg0
[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.0.0.1/24 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

客户端配置

客户端配置

我们将家中的设备配置为WireGuard的Spoke(节点),它会主动连接腾讯云服务器,建立加密隧道。

安装 WireGuard 并生成密钥:

Linux

1
2
3
cd /etc/wireguard
umask 077
wg genkey | tee client_private.key | wg pubkey > client_public.key

Windows

安装客户端之后,选择【新建隧道-新建空隧道】,系统会自动生成一对密钥,并显示公钥和私钥。复制这个公钥,稍后需要填入腾讯云服务器的配置文件中。

创建客户端配置文件

Linux

1
2
# 创建配置文件 /etc/wireguard/wg0.conf(或 client.conf)
sudo vim /etc/wireguard/wg0.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[Interface]
# 客户端的私钥(替换为 client_private.key 的内容)
PrivateKey = <CLIENT_PRIVATE_KEY>
# 分配给客户端的VPN虚拟IP地址
Address = 10.0.0.2/24
# DNS服务器,可选(例如谷歌DNS)
DNS = 8.8.8.8, 8.8.4.4
# 接口启动时执行的规则(通常不需要)
# PostUp = ...
# PostDown = ...

[Peer]
# 服务器的公钥(替换为从云服务器 server_public.key 文件中复制的内容)
PublicKey = <SERVER_PUBLIC_KEY>
# 服务器的公网IP地址和WireGuard监听端口
Endpoint = <腾讯云服务器公网IP>:51820
# 指定通过此隧道转发所有流量(0.0.0.0/0 表示所有IPv4流量)
# 或者只允许访问家庭内网网段,例如 192.168.1.0/24(更安全)
AllowedIPs = 10.0.0.1/32, 192.168.1.0/24
# 保持连接活跃的间隔(秒),防止NAT会话超时断开连接
PersistentKeepalive = 25

启动服务

启动服务。