架构

graph BT
内网服务器 <--> 云服务器
云服务器 <--> 客户端A
云服务器 <--> 客户端B

在内网服务器(需要被穿透的机器)、拥有公网 IP 的云服务器、以及各个客户端(笔记本、iPhone 等)上分别安装 Wireguard ,以云服务器作为中心节点组建虚拟局域网。各个客户端通过向云服务器发送 keepalive 的心跳保持活跃。局域网中各个终端可以实现互联。

安装

ubuntu 安装

sudo apt install wireguard

# check
wg version

iPhone 可以在美区 AppStore 下载

配置

云服务器配置

生成密钥

# 生成节点公私钥
wg genkey | tee yourhost_privatekey | wg pubkey > yourhost_publickey

# 生成 preshared key
# preshared key 是可选配置,配置后可以加一层对称加密更加安全
wg genpsk

配置文件

[Interface]
# Name = host
Address = 192.168.168.1/24		# define the local IP for the server
ListenPort = 51820				# listen port of the server
PrivateKey = ... 				# private key of the server

# 配置 IP 伪装
#PostUp = iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
#PreDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
# Name = nas
PublicKey = ... 				# public key of the machine behind NAT
PresharedKey = ... 				# preshared key of server <-> NAS
AllowedIPs = 192.168.168.2/32 	# the peer's local IP

[Peer]
# Name = iphone
PublicKey = ... 				# public key of client A
PresharedKey = ... 				# preshared key of server <-> client A
AllowedIPs = 192.168.168.3/32 	# the peer's local IP

[Peer]
# Name = notebook
PublicKey = ... 				# public key of client B
PresharedKey = ... 				# preshared key of server <-> client B
AllowedIPs = 192.168.168.4/32	# the peer's local IP

将上述文件放到 /etc/wireguard/wg.conf 路径

IP 转发配置

  1. 开启 IP 转发:将 /etc/sysctl.conf 中的 net.ipv4.ip_forward=1 注释去掉,运行 sudo sysctl -p 使配置生效

  2. 防火墙配置:sudo ufw status 查看防火墙状态,如果没有启用则不用配置

  3. 云服务器安全组放通:在云服务商的控制台上,放通 UDP:51820

  4. 重启服务器:sudo reboot

启动

假设配置文件名为 mywg.conf

# 启动
wg-quick up mywg

# 启动后通过 ipconfig 可以看到多了一个虚拟网卡
ipconfig

# 停止
wg-quick down mywg

配置开机自动启动

sudo systemctl enable wg-quick@mywg.service

sudo systemctl start wg-quick@mywg

# 查看运行状态
sudo systemctl status wg-quick@mywg

内网服务器配置

生成密钥

wg genkey | tee nas_privatekey | wg pubkey > nas_publickey

配置文件

[Interface]
# Name = mynas
Address = 192.168.168.2/24 		# define the local IP of node
PrivateKey = ... 				# private key of node
MTU = 1400              # default is 1420, if SSH cannot connect, lower this value

[Peer]
# Name = host					# server's name
PublicKey = ...					# server's public key
PresharedKey = ...				# preshared key with server
Endpoint = {domain_or_public_ip}:51820	# domain/public:port of the public server
AllowedIPs = 192.168.168.0/24	# route 192.168.168.X traffic to the server
PersistentKeepalive = 25		# send keepalive to the server every 25 seconds

启动或配置开机自动启动同上

其他客户端配置

以 iPhone 为例,下载 Wireguard APP 后类似上面填好 Interface 与 Peer 配置即可

问题

  1. Ubuntu 节点无法通过 SSH 连接,需要修改 MTU ,详细见 StackOverflow - Only SSH not working over Wireguard

参考