🔑 WireGuard

現代高效能 VPN 協定,設定極簡

WireGuard 是新一代 VPN,核心程式碼僅約 4000 行,設定比 OpenVPN 簡單數倍,連線建立速度快,效能接近原生網路,已成為許多發行版的預設 VPN 選擇。

安裝

$ sudo apt update && sudo apt install -y wireguard wireguard-tools
wg --version

金鑰生成

每個節點(伺服器和客戶端)各需要一對公私金鑰:

$ # 伺服器端
wg genkey | sudo tee /etc/wireguard/server_private.key | \
  wg pubkey | sudo tee /etc/wireguard/server_public.key
sudo chmod 600 /etc/wireguard/server_private.key

# 客戶端
wg genkey | tee client_private.key | wg pubkey | tee client_public.key

伺服器設定(/etc/wireguard/wg0.conf)

$ sudo vim /etc/wireguard/wg0.conf
[Interface]
# 伺服器的私鑰
PrivateKey = 
# VPN 子網的伺服器 IP
Address    = 10.0.0.1/24
# 監聽 port
ListenPort = 51820

# 啟動時開啟 NAT(讓客戶端可以存取 Internet)
PostUp   = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# 每個客戶端都要加一段 [Peer]
[Peer]
# 客戶端的公鑰
PublicKey  = 
# 分配給這個客戶端的 IP
AllowedIPs = 10.0.0.2/32
$ sudo chmod 600 /etc/wireguard/wg0.conf

客戶端設定(wg0.conf)

[Interface]
PrivateKey = 
Address    = 10.0.0.2/32
DNS        = 1.1.1.1

[Peer]
# 伺服器的公鑰
PublicKey  = 
# 伺服器的公開 IP 與 port
Endpoint   = 你的伺服器IP:51820
# 路由所有流量通過 VPN
AllowedIPs = 0.0.0.0/0, ::/0
# 保持 NAT 連線活躍(每 25 秒發送保活封包)
PersistentKeepalive = 25

伺服器路由與防火牆

$ # 開啟 IP 轉發
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv6.conf.all.forwarding=1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

# UFW 防火牆開放 WireGuard port
sudo ufw allow 51820/udp
⚠️ 注意 PostUp/PostDown 中的網路介面名稱(eth0)要與實際的外網介面相符,可用 ip route | grep default 確認。

啟動與管理

操作指令
啟動 VPN 介面sudo wg-quick up wg0
停止 VPN 介面sudo wg-quick down wg0
設定開機自動啟動sudo systemctl enable --now wg-quick@wg0
查看連線狀態sudo wg show
查看傳輸統計sudo wg show wg0 transfer
新增客戶端(動態)sudo wg set wg0 peer <pubkey> allowed-ips 10.0.0.3/32