环境要求
- 一台 Windows 或 Linux 设备充当服务器
- 多台 Windows 或 Linux 或 Mac 或 Android 或 iOS 设备充当客户端
- 作为 WireGuard 服务器的设备需要有公网 IP 或者能被客户端访问
1. 安装 WireGuard
首先,在你的 Linux 系统上安装 WireGuard。你可以通过 apt、dnf、yum 或其他包管理器进行安装,具体取决于你的发行版。
1 2
| sudo apt update sudo apt install wireguard
|
1 2
| sudo yum install epel-release sudo yum install wireguard-tools
|
如果你的 CentOS/RHEL 系统使用的是 8 及以上版本,你可能需要额外的仓库支持:
1
| sudo dnf install wireguard-tools
|
1
| sudo dnf install wireguard-tools
|
1
| sudo pacman -S wireguard-tools
|
手动下载Windows安装包
2. 生成密钥对
WireGuard 使用公钥和私钥来进行加密通信。你可以通过以下命令生成密钥对:
1
| wg genkey | tee privatekey | wg pubkey > publickey
|
密钥文件说明
这将在当前目录下生成 privatekey 和 publickey 文件。
- 私钥:为机密,不可共享给他人
- 公钥:可以共享给其他 WireGuard 节点
3. 配置 WireGuard
在 /etc/wireguard/ 目录下创建一个配置文件(例如 wg0.conf)。
1
| sudo vim /etc/wireguard/wg0.conf
|
1 2 3 4 5 6 7 8 9
| [Interface] PrivateKey = <客户端私钥> Address = *.*.*.*/*
[Peer] PublicKey = <服务器公钥> Endpoint = <服务器IP地址>:51820 AllowedIPs = *.*.*.*/* PersistentKeepalive = 25
|
[Interface] 部分包含本机配置。你需要用你自己的私钥替换 <你的私钥>,并设置适当的 IP 地址。
[Peer] 部分是对端的配置,<对端公钥> 是对方的公钥,AllowedIPs 是允许的 IP 范围。
1 2 3 4 5 6 7 8 9
| [Interface] Address = *.*.*.*/* ListenPort = 51820 PrivateKey = <服务器私钥> [Peer] PublicKey = <客户端公钥> AllowedIPs = *.*.*.*/.* PersistentKeepalive = 25
|
- Address:为服务器分配一个 IP 地址(通常选择 10.0.0.1/24)。
- ListenPort:设置 WireGuard 监听的端口(默认是 51820)。
- PrivateKey:填入你为服务器生成的私钥。
[Peer] 部分是客户端的配置,公钥需要在客户端生成并提供给服务器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| [Interface] Address = *.*.*.*/* ListenPort = 51820 PrivateKey = <服务器私钥> [Peer]
PublicKey = <客户端1公钥> AllowedIPs = *.*.*.*/* PersistentKeepalive = 25 [Peer]
PublicKey = <客户端2公钥> AllowedIPs = *.*.*.*/* PersistentKeepalive = 25
|
如果有多个客户端,可以在 [Peer] 部分添加多个 PublicKey 和 AllowedIPs 条目。
4. 启动 WireGuard 服务
使用以下命令启动 WireGuard 接口:
这将启用 wg0 配置文件中的设置并启动 VPN 服务。
5. 配置自动启动
为了让 WireGuard 在系统启动时自动启动,使用以下命令启用服务:
1
| sudo systemctl enable wg-quick@wg0
|
6. 配置防火墙
确保防火墙允许 WireGuard 的 UDP 端口(默认是 51820)
1 2
| sudo ufw allow 51820/udp sudo ufw enable
|
1
| sudo iptables -A INPUT -p udp --dport 51820 -j ACCEPT
|
如果你使用 iptables,确保保存规则,否则它们会在重启后丢失。
7. 启用 IP 转发(仅服务器)
如果你希望通过 VPN 连接进行路由,需启用 IP 转发:
打开 /etc/sysctl.conf 文件:
1
| sudo vim /etc/sysctl.conf
|
添加以下行以启用 IPv4 和 IPv6 转发:
1 2
| net.ipv4.ip_forward=1 net.ipv6.conf.all.forwarding=1
|
使更改生效:
8. 配置 NAT(仅服务器)
如果你想通过 VPN 为客户端提供 Internet 访问,还需要配置 NAT。假设你使用的是 eth0 网络接口(根据实际网络接口名称调整):
使用 iptables 配置 NAT:
1
| sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
|
保存 iptables 规则(根据你的 Linux 发行版选择适当方法):
1
| sudo iptables-save > /etc/iptables/rules.v4
|
1
| sudo service iptables save
|
9. 测试连接
确保客户端可以成功连接到服务器
使用 ping 命令测试:(从客户端 ping 服务器的虚拟 IP)
文中未提及的常用命令
本作品由 Pavilion_Cat 于 2024-12-11 17:03:39 发布
