880 字
4 分钟
WireGuard
WireGuard® 是一种极其简单但快速且现代的 VPN,它利用了最先进的加密技术。它的目标是比 IPsec 更快、更简单、更精简、更有用,同时避免了巨大的麻烦。它旨在比 OpenVPN 性能好得多。WireGuard 旨在作为通用 VPN,适用于嵌入式接口和超级计算机,适用于许多不同的情况。最初为 Linux 内核发布,现在它是跨平台的(Windows、macOS、BSD、iOS、Android),并且可以广泛部署。它目前正处于积极开发中,但即使如此,它可能被认为是行业内最安全、最容易使用和最简单的 VPN 解决方案。
配置
服务器端
- 安装 WireGuard
apt update && apt install wireguard -y
- 配置服务器
- 生成密钥对
wg genkey | tee private.key | wg pubkey > public.key- 创建配置文件
vim /etc/wireguard/wg0.conf[Interface]PrivateKey = <服务器私钥>Address = 10.0.1.1/24ListenPort = 51820PostUp = sysctl -w net.ipv4.ip_forward=1;PostDown = sysctl -w net.ipv4.ip_forward=0;[Peer]PublicKey = <客户端1的公钥>AllowedIPs = 10.0.1.2/32[Peer]PublicKey = <客户端2的公钥>AllowedIPs = 10.0.1.3/32PostUp = sysctl -w net.ipv4.ip_forward=1; # 启动 WireGuard 接口时开启 IP 转发
PostDown = sysctl -w net.ipv4.ip_forward=0; # 关闭 WireGuard 接口时停止 IP 转发 - 启动 WireGuard
systemctl start wg-quick@wg0systemctl enable wg-quick@wg0
- 检查状态
wg show
- 防火墙配置
- ufw
ufw allow 51820/udpufw allow in on wg0 to 10.0.1.0/24ufw allow out on wg0 to 10.0.1.0/24- iptables
iptables -A INPUT -p udp --dport 51820 -j ACCEPTiptables -A INPUT -i wg0 -s 10.0.1.0/24 -j ACCEPTiptables -A OUTPUT -o wg0 -d 10.0.1.0/24 -j ACCEPT
客户端
- 客户端配置
[Interface]PrivateKey = <客户端的私钥>Address = 10.0.1.2/24[Peer]PublicKey = <服务器的公钥>Endpoint = <服务器公网IP>:51820AllowedIPs = 10.0.1.0/24PersistentKeepalive = 10
PersistentKeepalive = 10 # 客户端会向服务器发送一个 keep-alive 数据包时间间隔
- 验证
- 服务端连接状态
sudo wg show- 客户端互通
- 客户端 1 Ping 客户端 2
ping 10.0.1.3- 客户端 2 Ping 客户端 1
ping 10.0.1.2
进阶配置
- 公网访问内网服务
- 服务端
ip addriptables -t nat -A PREROUTING -p tcp -d <服务器公网IP> --dport <服务器端口> -j DNAT --to-destination <客户端IP>:<客户端端口>如果服务器是弹性公网 IP,服务器公网 IP 可能需要改成服务商的私网 IP,IP 和服务器公网 IP 一致用公网 IP,否则使用刚查到的私网 IP
- 删除规则
iptables -t nat -D PREROUTING -p tcp -d <服务器公网IP> --dport <服务器端口> -j DNAT --to-destination <客户端IP>:<客户端端口> - 客户端通过服务端访问外网
- 服务端
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE- 客户端
[Interface]PrivateKey = <客户端的私钥>Address = 10.0.1.2/24[Peer]PublicKey = <服务器的公钥>Endpoint = <服务器公网IP>:51820AllowedIPs = 0.0.0.0/0PersistentKeepalive = 10AllowedIPs = 0.0.0.0/0 # 通过 WireGuard 隧道发送和接收任何目的地的 IP 流量,根据情况进行修改
- 删除服务端规则
iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE - 保存规则
- 通过 iptables-persistent 保存
apt install iptables-persistent -ynetfilter-persistent save- 直接写入服务端配置
[Interface]PrivateKey = <服务器私钥>Address = 10.0.1.1/24ListenPort = 51820PostUp = sysctl -w net.ipv4.ip_forward=1;iptables -t nat -A PREROUTING -p tcp -d <服务器公网IP> --dport <服务器端口> -j DNAT --to-destination <客户端IP>:<客户端端口>;iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEPostDown = sysctl -w net.ipv4.ip_forward=0;iptables -t nat -D PREROUTING -p tcp -d <服务器公网IP> --dport <服务器端口> -j DNAT --to-destination <客户端IP>:<客户端端口>; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE[Peer]PublicKey = <客户端1的公钥>AllowedIPs = 10.0.1.2/32[Peer]PublicKey = <客户端2的公钥>AllowedIPs = 10.0.1.3/32
部分信息可能已经过时









