通过 Wireguard 实现内网穿透

2024-03-09 23:43:49 浏览数 (1)

架构

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

安装

ubuntu 安装

代码语言:bash复制
sudo apt install wireguard

# check
wg version

iPhone 可以在美区 AppStore 下载

配置

云服务器配置

生成密钥

代码语言:bash复制
# 生成节点公私钥
wg genkey | tee yourhost_privatekey | wg pubkey > yourhost_publickey

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

配置文件

代码语言:plain复制
[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

代码语言:bash复制
# 启动
wg-quick up mywg

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

# 停止
wg-quick down mywg

配置开机自动启动

代码语言:bash复制
sudo systemctl enable wg-quick@mywg.service

sudo systemctl start wg-quick@mywg

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

内网服务器配置

生成密钥

代码语言:bash复制
wg genkey | tee nas_privatekey | wg pubkey > nas_publickey

配置文件

代码语言:plain复制
[Interface]
# Name = mynas
Address = 192.168.168.2/24 		# define the local IP of node
PrivateKey = ... 				# private key of node

[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 配置即可

0 人点赞