先解释WireGuard使用的iptables配置

1
2
3
iptables -A FORWARD -i %i -j ACCEPT
iptables -A FORWARD -o %i -j ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

开始以为-i/o %i后面的%i是iptables的用法,查了下没找到资料,后来看wg-quick命令的说明得知是wg-quick的一个约定写法,%i用于指代INTERFACE,而这个INTERFACE即为/etc/wireguard/INTERFACE.conf中得到这个INTERFACE,所以假如使用的是/etc/wiregurad/wg0.conf上面也就会被解释成这样:

1
2
3
4
5
6
7
8
# filter 表 FORWARD 链 从 wg0 接口进来的包 都接受
iptables -A FORWARD -i wg0 -j ACCEPT

# filter 表 FORWARD 链 将从 wg0 接口送出的包 都允许
iptables -A FORWARD -o wg0 -j ACCEPT

# nat 表 POSTROUTING 链 伪装成公网IP从eth0接口送出
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

读了一些有关文章,得知以下事实:

  • 常用的只有filternat
  • 不指定-t TABLE的情况下,默认是-t filter
  • 简化的(常用的)iptables图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
                             XXXXXXXXXXXXXXXXXX
XXX Network XXX
XXXXXXXXXXXXXXXXXX
+
|
v
+-------------+ +------------------+
|table: filter| <---+ | table: nat |
|chain: INPUT | | | chain: PREROUTING|
+-----+-------+ | +--------+---------+
| | |
v | v
[local process] | **************** +--------------+
| +---------+ Routing decision +------> |table: filter |
v **************** |chain: FORWARD|
**************** +------+-------+
Routing decision |
**************** |
| |
v **************** |
+-------------+ +------> Routing decision <---------------+
|table: nat | | ****************
|chain: OUTPUT| | +
+-----+-------+ | |
| | v
v | +-------------------+
+--------------+ | | table: nat |
|table: filter | +----+ | chain: POSTROUTING|
|chain: OUTPUT | +--------+----------+
+--------------+ |
v
XXXXXXXXXXXXXXXXXX
XXX Network XXX
XXXXXXXXXXXXXXXXXX

参考:
iptables详解(1):iptables概念 (第二张图非常好!)
iptables - Arch Linux Wiki
7.4. FORWARD and NAT Rules - RedHat
What is MASQUERADE in the context of iptables? - askubuntu