三.ipfw的动态规则
Netfilter有ip_conntrack机制可以追踪每一个流。这个ip_conntrack机制让人欢喜让人愁,于是可以在PREROUTING的raw表上配置notrack。ipfw就不一样了,它可以在任意地方针对任意流进行track,这就是其state机制,ipfw通过keep-state来追踪一个流,并且建立针对该包反向包的动态规则,通过check-state来匹配keep-state建立的动态规则,ipfw的state可以在任意匹配的地方被keep,所谓的keep就是建立一条动态规则,其动作就是keep-state的动作,这个比较类似Netfilter的ip_conntrack和state match的联动机制。以下是一个man手册中的实例,我在前面加上了注释:对每一个包check所有的动态创建的rule:
ipfw add check-state
对本地子网始发的TCP流量放行且保持连接,创建动态rule:
ipfw add allow tcp from my-subnet to any setup keep-state
禁用其它地方始发的TCP连接:
ipfw add deny tcp from any to any
上述实例的分析:
内网始发一个TCP,由于没有任何动态rule,因此直接匹配到第二个rule并且保持了这个conntrack创建了反向动态rule,该连接的返回包到达这个Box时,由于匹配到了动态rule,因此通过。如果是外网始发的TCP到达内网,将直接匹配到第三条rule。如果使用iptables的话,则如下配置:
iptables -t raw -A PREROUTING -p tcp -s ! my-subbet -j NOTRACK
iptables -A FORWARD -p tcp -m state --state ESTABLISHED -j ACCEPT
iptables -A FORWARD -p tcp -s my-subnet -j ACCEPT
iptables -A FORWARD -p tcp -j DROP
使用ipfw,就不用非要在特定的HOOK点来进行track了,它可以随时进行track,随时进行check。ipfw可以将track和target结合在一条rule中,可以针对特定的filter rule进行track,而Netfilte的iptables却必须将这些关联解除。
四.ipfw和natd
使用iptables,我们可以使用nat表来配置NAT,然而使用ipfw却不能做到这一点,在BSD中,nat只是一个target,存在用户态的natd进程来进行nat,也可以使用ipnat来完成,不管哪种方式,都使用了divert这个动作,所谓divert,其实就是其字面含义,将控制转发到其它的逻辑,对于nat,很常见的就是将控制转发到natd进程。我在Mac OS上,配置以下的nat:ipfw add divert natd all from any to any via en1
natd -interface en1
其中divert natd将匹配的数据包“路由”到natd进程。至于natd进程,也可以man一下,有下列关键的叙述:
The natd normally runs in the background as a daemon. It is passed raw IP packets as they travel into and out of the machine, and will possibly change these before re-injecting them back into the IP packet stream.
It changes all packets destined for another host so that their source IP number is that of the current machine. For each packet changed in this manner,an internal table entry is created to record this fact. The source port number is also changed to indicate the table entry applying to the packet. Packets that are received with a target IP of the current host are checked against this internal table. If an entry is found, it is used to determine the correct target IP number and port to place in the packet.
可见natd本身就是保持状态的,不需要keep-state和check-state,然而如果你想小实验一把keep-state和check-state,那么你可能会注意到ipfw有一via/recv/xmit系列match,上例中是使用via,如果使用xmit的话,那么只能适用于out方向的数据包,man ipfw中有下述:
The recv interface can be tested on either incoming or outgoing packets, while the xmit interface can only be tested on outgoing packets. So out is required (and in is invalid) whenever xmit is used.
注意,in/out匹配的是数据包方向,而via/recv/xmit匹配的是接口。xmit时已经确定了接口,对于in方向的数据包,由于还没有路由,所以不能确定出口设备,进而不能用于xmit。如果我们创建以下的rule:
ipfw add divert natd all from any to any xmit en1
natd -interface en1
如此一来,对于返回的数据包将全部放过,虽然natd是保持状态的,然而并没有rule将数据包divert到natd,所以仅仅为了将数据包divert到natd,需要使用keep-state:
ipfw add check-state
ipfw add divert natd all from any to any xmit en1 keep-state
这样就可以对付返回的数据包了。然而问题是,内核保持的state状态可能会和natd中的状态相冲突,因此对于有状态的协议比如TCP,此方式工作的很好,对于UDP和ICMP会有不稳定的问题。
