深色模式
VPN 基础 WireGuard
摘要:WireGuard 轻量、配置简单、性能高。本文在两台机器间搭一条点对点加密隧道,配好密钥与 AllowedIPs,理解「隧道路由」的核心。
适用环境
bash
# 两端都需要 root 与 wireguard 内核模块/工具
which wg wg-quick || sudo apt install wireguard
lsmod | grep wireguard || sudo modprobe wireguard
ip -br link1
2
3
4
2
3
4
操作步骤
1. 两端各自生成密钥对
bash
wg genkey | tee privatekey | wg pubkey > publickey
cat privatekey publickey
# 每台机器各生成一组,互相交换 publickey1
2
3
2
3
2. A 端配置(/etc/wireguard/wg0.conf)
ini
[Interface]
Address = 10.0.0.1/24
PrivateKey = <A的privatekey>
ListenPort = 51820
[Peer]
PublicKey = <B的publickey>
AllowedIPs = 10.0.0.2/32
Endpoint = <B的公网IP>:518201
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. B 端配置(/etc/wireguard/wg0.conf)
ini
[Interface]
Address = 10.0.0.2/24
PrivateKey = <B的privatekey>
ListenPort = 51820
[Peer]
PublicKey = <A的publickey>
AllowedIPs = 10.0.0.1/32
Endpoint = <A的公网IP>:518201
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
4. 启动并放行端口
bash
sudo wg-quick up wg0
sudo ss -lntp | grep 51820 # UDP,需用 -un 看
sudo firewall-cmd --permanent --add-port=51820/udp && sudo firewall-cmd --reload1
2
3
2
3
验证
bash
# 两端互 ping 隧道地址
ping -c3 10.0.0.2 # 在 A 上执行
wg show # 看 latest handshake 与 transfer 是否有字节1
2
3
2
3
能 ping 通且 wg show 显示握手时间刚更新、transfer 有增长,说明隧道已建立并传数据。
常见坑
WARNING
AllowedIPs 决定「哪些目的 IP 走隧道」。点对点场景写对方 /32 即可;若写成 0.0.0.0/0 会把所有流量导向隧道,配置不当会导致两端双双断网。改全局路由前务必想清。
DANGER
PrivateKey 是机密,配置文件权限应设为 600(默认 wg-quick 会处理)。不要把 privatekey 提交到代码仓库或贴到公开地方;泄露等于把隧道交给他人。
参考资料
- WireGuard 官方站点与文档
- WireGuard 快速上手(Quickstart)
- [阿里云:WireGuard 搭建 VPN](https://help.aliyun.com/document_detail/)