Featured image of post Wireguard Multihop 路由

Wireguard Multihop 路由

两个没有公网ip的wireguard节点通过中继节点建立连接,并通过其中一个节点路由另一个节点的流量。

写这篇文章主要是因为有这么一个需求——办公室里有一台Linux的机器,但是办公室无公网ip,而我想要让不在办公室的人也可以连接到办公室的网络上,并通过办公室的网络访问内部或外部的一些资源。

我们姑且把这个场景中的设备用字母代替:

  • 本地的机器A 192.168.60.2
  • 具有公网ip的服务器B 192.168.60.1
  • 办公室的机器C 192.168.60.3

由于A和C都是没有公网ip的机器,不考虑打洞的情况,他们的连接需要一个中继节点(Bounce Server),在这里使用了具有公网ip的服务器B。

下面的几条命令都用得到,所以贴一下

1
2
3
4
5
6
7
8
#生成密钥
wg genkey | tee privatekey | wg pubkey > publickey 
# 中继节点开启包转发
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
echo "net.ipv4.conf.all.proxy_arp = 1" >> /etc/sysctl.conf
echo "net.ipv6.conf.default.forwarding=1" >> /etc/sysctl.conf
echo "net.ipv6.conf.all.forwarding=1" >> /etc/sysctl.conf
sysctl -p /etc/sysctl.conf

本地节点A设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[Interface]
PrivateKey = a-privatekey
Address = 192.168.60.2/32
DNS = 192.168.60.3

[Peer]
PublicKey = c-publickey
AllowedIPs = 192.168.60.0/24
Endpoint = example.com:10000
PersistentKeepalive = 16

中继节点B设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[Interface]
ListenPort = 10000
Address = 192.168.60.1/24
PrivateKey = b-privatekey
# 注意这里,只让 192.168.60.0/24 网络下的流量按照wg进行路由,不影响自身其他的网络通信
PostUp = ip rule add not from 192.168.60.0/24 table main 
PostDown = ip rule delete not from 192.168.60.0/24 table main
[Peer]
# 远程节点C
PublicKey = c-publickey
AllowedIPs = 192.168.60.3/32,0.0.0.0/0 # 注意,所有流量都将转发到C上
[Peer]
# 本地节点A
PublicKey = a-publickey
AllowedIPs = 192.168.60.2/32

远程节点C设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Interface]
PrivateKey = c-privatekey
Address = 192.168.60.3/32
# 为了访问到办公室网络 192.168.61.0/24 以及公网上的资源,我们需要做一次NAT
PostUp = iptables -t nat -I POSTROUTING -s 192.168.60.0/24 -j MASQUERADE
PostDown = iptables -t nat -D POSTROUTING -s 192.168.60.0/24 -j MASQUERADE

[Peer]
PublicKey = b-publickey
AllowedIPs = 192.168.60.0/24

Endpoint = example.com:10000
PersistentKeepalive = 16
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
本站访客数:
Built with Hugo
主题 StackJimmy 设计