跳到主要内容

WireGuard

搭建 WireGuard VPN 服务器的步骤包括在服务器上安装 WireGuard、配置 WireGuard、生成密钥、以及在客户端配置连接。下面是一个基本的搭建过程:

1. 安装 WireGuard

分别在云服务器和内网服务器上安装 WireGuard:

sudo apt update
sudo apt install wireguard

云服务器充当服务器,内网服务器充当客户端。

2. 生成密钥对

WireGuard 使用公钥和私钥进行加密通信。分别在云服务器和内网服务器上执行以下命令:

wg genkey | tee privatekey | wg pubkey > publickey

两台服务器都生成了秘钥文件:

privatekey
publickey

3. 配置 WireGuard 服务器

配置 WireGuard 服务器的配置文件 /etc/wireguard/wg0.conf。假设服务器使用 51820 端口。


第一,编辑服务器配置文件:

sudo nano /etc/wireguard/wg0.conf

贴入配置:

[Interface]
Address = 10.0.0.1/24 # 服务器的虚拟 IP 地址
ListenPort = 51820 # 监听的端口
PrivateKey = <服务器的私钥> # 从生成的私钥文件中获取

[Peer]
PublicKey = <客户端的公钥> # 客户端的公钥
AllowedIPs = 10.0.0.2/32 # 客户端的虚拟 IP 地址
  • Address:为服务器分配一个虚拟 IP 地址。
  • ListenPort:WireGuard 使用的端口。
  • PrivateKey:从生成的 privatekey 文件中获取。
  • [Peer]:每个客户端的配置。你需要为每个连接的客户端添加一项。

第二,启动 WireGuard 服务:

sudo wg-quick up wg0
sudo systemctl enable wg-quick@wg0

4. 配置客户端

客户端也需要配置 WireGuard,并使用服务器的公钥和自己的私钥。


第一,编辑客户端配置文件:

sudo nano /etc/wireguard/wg0.conf

客户端配置示例:

[Interface]
Address = 10.0.0.2/24 # 客户端的虚拟 IP 地址
PrivateKey = <客户端的私钥> # 从生成的私钥文件中获取

[Peer]
PublicKey = <服务器的公钥> # 服务器的公钥
Endpoint = <服务器的公网 IP>:51820 # 服务器的公网 IP 和端口
AllowedIPs = 0.0.0.0/0 # 允许客户端访问所有 IP 地址
PersistentKeepalive = 25 # 保持连接(适用于 NAT 环境)
  • Address:为客户端分配一个虚拟 IP 地址。
  • PrivateKey:从生成的 privatekey 文件中获取。
  • PublicKey:服务器的公钥(从服务器的配置中获得)。
  • Endpoint:服务器的公网 IP 地址和端口。
  • AllowedIPs:客户端允许访问的 IP 地址范围(通常设置为 0.0.0.0/0 以便访问所有 IP)。

第二,启动 WireGuard 客户端:

sudo wg-quick up wg0

5. 配置防火墙和路由

确保服务器上的防火墙允许 WireGuard 使用的端口(51820)。

第一,允许端口 51820:

sudo ufw allow 51820/udp

如果服务器与客户端之间的通信需要通过 NAT,你还需要配置 IP 转发和适当的防火墙规则。

第二,启用 IP 转发:

# 临时启用 IP 转发
sudo sysctl -w net.ipv4.ip_forward=1

# 永久启用 IP 转发(修改 sysctl 配置)
sudo nano /etc/sysctl.conf

# 添加或确保存在以下行
net.ipv4.ip_forward=1
sudo sysctl -p

第三,配置 NAT 规则:

# 通过 iptables 配置 NAT 转发
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

6. 测试连接

内网服务器查看 WireGuard 状态:

sudo wg

image-20250408223028141

云服务器 ping 内网服务器:

image-20250408223249209

7. 添加多个客户端

如果需要添加更多的客户端,只需为每个客户端生成一对密钥,并将其公钥添加到服务器配置的 [Peer] 部分,同时为每个客户端配置一个不同的 IP 地址。

服务器配置示例(添加多个客户端):

[Peer]
PublicKey = <客户端1的公钥>
AllowedIPs = 10.0.0.2/32

[Peer]
PublicKey = <客户端2的公钥>
AllowedIPs = 10.0.0.3/32

客户端配置文件的 [Peer] 部分也要相应修改。


总结:WireGuard 配置成功率还是蛮高的,一次成功,而且也很简单。