WireGuard VPN
WireGuard 是一种现代、简单且高效的 VPN 技术,使用公钥加密和端到端加密通信来保护网络流量。当您拥有一台公网服务器时,可以使用 WireGuard 创建虚拟专用网络 (VPN),您的每台 KVM 都可以加入 WireGuard 创建的虚拟局域网,从而实现不同地点的远程访问。
- 如果您的 KVM 需要从不同国家访问,并且不确定如何选择合适的服务器和线路,可以加入 Discord 寻求支持。
安装步骤
安装 WireGuard
- 在 Linux 上安装 WireGuard
对于大多数基于 Debian 的系统(如 Ubuntu),您可以运行以下命令安装 WireGuard。要在 KVM 上安装,请参考此方法。KVM 是只读系统,因此您需要先使用rw
命令将其更改为可读写系统:
sudo apt update
sudo apt install wireguard
对于其他 Linux 发行版,您可以根据相应的包管理器安装,或使用 WireGuard 官方安装指南。
- 在 Windows 或 macOS 上安装 WireGuard
直接从 WireGuard 官方网站 下载适合您 PC 系统的安装包。安装后,通过图形界面进行配置。
配置 WireGuard
WireGuard 配置包括两部分:
服务器端配置:运行 WireGuard 服务器的机器(通常是公网服务器)。
客户端配置:连接到 WireGuard VPN 的客户端机器(通常是 KVM 设备和控制计算机,而不是被控计算机)。
!!! info "配置服务器"
- 在服务器上生成 WireGuard 私钥和公钥。在任意可读写路径下,执行以下命令以获取 server_private_key 和 server_public_key 文件。
wg genkey | tee server_private_key | wg pubkey > server_public_key
- 创建或编辑 /etc/wireguard/wg0.conf 文件以配置 WireGuard 接口。以下是示例配置:
[Interface]
PrivateKey = <服务器私钥>
Address = 10.0.0.1/24 # 这是 VPN 网络中的 IP 地址池,10.0.0.1 是 WireGuard 服务器的虚拟 IP
ListenPort = 51820 # WireGuard 默认端口,可更改为所需端口
# 允许的客户端 1,假设是 KVM
[Peer]
PublicKey = <客户端公钥>
AllowedIPs = 10.0.0.2/32 # 客户端的 IP 地址
# 允许的客户端 2,假设是 MAC
[Peer]
PublicKey = <客户端公钥>
AllowedIPs = 10.0.0.3/32 # 客户端的 IP 地址
- 此处的 服务器私钥 是指上面生成的 server_private_key 的内容。您需要将 server_private_key 的内容复制粘贴到配置文件中,而不是文件路径。
- 此处的 客户端公钥 是客户端配置步骤中生成的 client_public_key 的内容。您需要将 client_public_key 的内容复制粘贴到配置文件中。
- 注意,对于每个额外的客户端,服务器配置需要添加相应的 [Peer] 部分。
!!! info "配置客户端" 在客户端生成 WireGuard 私钥和公钥。以 KVM Linux 系统为例:
wg genkey | tee client_private_key | wg pubkey > client_public_key
创建或编辑 /etc/wireguard/wg0.conf 文件以配置 WireGuard 客户端接口。Windows/macOS 图形界面配置的内容相同。
[Interface]
PrivateKey = <客户端私钥>
Address = 10.0.0.2/32 # 客户端的 IP 地址
[Peer]
PublicKey = <服务器公钥>
Endpoint = <服务器 IP 地址>:51820 # 服务器的 IP 和端口
AllowedIPs = 10.0.0.0/24 # 通过 VPN 路由所有流量
PersistentKeepalive = 25 # 保活间隔,适用于 NAT 网络
- 客户端私钥 是上述 client_private_key 文件的内容,服务器公钥 是服务器配置部分生成的 server_public_key 文件的内容。
- 同样,假设在 MAC 上的配置,配置文件内容如下:
[Interface]
PrivateKey = <客户端私钥>
Address = 10.0.0.3/32 # 客户端的 IP 地址
[Peer]
PublicKey = <服务器公钥>
Endpoint = <服务器 IP 地址>:51820 # 服务器的 IP 和端口
AllowedIPs = 10.0.0.0/24 # 通过 VPN 路由所有流量
PersistentKeepalive = 25 # 保活间隔,适用于 NAT 网络
启动 WireGuard
启动 WireGuard 服务器。在服务器上(示例服务器为 Ubuntu 系统),使用以下命令启动 WireGuard 服务:
sudo wg-quick up wg0
这将根据 /etc/wireguard/wg0.conf 配置文件启动服务器端接口。
启动客户端。在客户端启动 WireGuard 服务。以 KVM 为例,其他系统如 MAC 或 Windows 通常通过 UI 操作启动。
sudo wg-quick up wg0
配置防火墙(如有需要)
- 在服务器端配置文件中打开 ListenPort 端口。
- 如果客户端可以 ping 通服务器但无法互相 ping 通,则需要在服务器上启用转发,使用以下命令:
echo "net.ipv4.ip_forward=1" | tee -a /etc/sysctl.conf
sysctl -p
测试连接
在 KVM 客户端上,使用 ping 命令测试与服务器和 MAC 的连接:
# 测试与服务器的连接,IP 为 10.0.0.1
ping 10.0.0.1
# 测试与 MAC 的连接,IP 为 10.0.0.3
ping 10.0.0.3
此外,您可以直接使用命令检查状态:
sudo wg show
如果一切配置正确,您应该会看到客户端成功连接并交换密钥。
启用开机自启
为了确保 WireGuard 配置在系统重启后自动启动,请使用以下命令:
sudo systemctl enable wg-quick@wg0
总结
使用 WireGuard 设置网络包括安装、密钥配置、接口配置、启动服务以及确保正确的路由和防火墙配置。只要每个客户端和服务器配置正确,并且网络允许,它们就可以通过 WireGuard VPN 成功建立连接。