Skip to main content

WireGuard

Server installation

apt

sudo apt install wireguard resolvconf

config

# sudo nano /etc/wireguard/wg0.conf
[Interface]
# 服务器的私钥
PrivateKey = <服务器私钥内容>
# WireGuard监听的端口
ListenPort = 51820
# 服务器的虚拟IP地址
Address = 10.24.0.1/24
# 可选:服务器重启后保持配置
# SaveConfig = true
# 可选:设置MTU(通常不需要修改)
# MTU = 1420

# 可选:配置转发和防火墙规则
# PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
# (仅允许VPN内网通信)
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT

# 注意:将上面的 eth0 替换为你的服务器公网网卡名称
# 可以使用 ip route | grep default 查看

# 客户端配置示例(稍后添加)
[Peer]
# 客户端1的公钥
PublicKey = CLIENT1_PUBLIC_KEY
# 客户端的虚拟IP
AllowedIPs = 10.24.0.2/32

[Peer]
# 客户端2的公钥
PublicKey = CLIENT2_PUBLIC_KEY
AllowedIPs = 10.24.0.3/32

启用IP转发

# 永久启用
echo 'net.ipv4.ip_forward=1' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

key generate

# 生成私钥
wg genkey | sudo tee /etc/wireguard/private.key

# 设置权限
sudo chmod 600 /etc/wireguard/private.key

# 从私钥生成公钥
sudo cat /etc/wireguard/private.key | wg pubkey | sudo tee /etc/wireguard/public.key
# print private key
wg genkey

# print public key
echo {key} | wg pubkey

management

# 启用服务(开机自启)
sudo systemctl enable wg-quick@wg0

# 启动服务
sudo systemctl start wg-quick@wg0

# 检查状态
sudo systemctl status wg-quick@wg0

# 查看WireGuard接口状态
sudo wg show

# 测试监听端口
sudo netstat -ulnp | grep 51820

Client

config

[Interface]
PrivateKey = {pk}
Address = 10.24.0.3/32
DNS = 1.1.1.1

[Peer]
PublicKey = {pk}
# 仅允许隧道段流量进入
AllowedIPs = 10.24.0.0/24
Endpoint = sh.cloud.server.nip.io:51820
# 如果Client端NAT类型不为Open
PersistentKeepalive = 25

Conclusion

  • wg 的配置文件都需要配置 Interface 和 Peer,只是说根据端点的不同而配置的不同
  • 表示设定范围IP的 需要设置xxxx/24, 表示 只属于某一个IP 设置 xxxx/32
  • UDP测通断: nc -vzu {server} {port}
  • tcpdump抓包:tcpdump -i wg0 -n host 10.24.0.3tcpdump -i eth0 -n port 51820, tcpdump -i wg0 -n
  • SaveConfig=True时,直接修改配置文件,会在wg重启后被清除。