Netfilter编程系列(一):Netfilter介绍

Introduction

Kernel Module实战指南(四):系统调用劫持中,我们对系统调用进行了劫持。今天我们将要介绍,如何劫持网络数据包的技术。
从Linux 2.4开始,引入了Netfilter作为Linux Kernel的包过滤框架。目前市面上的大部分网络设备,如路由器、硬件防火墙、嵌入式系统等,都使用Netfilter进行数据包的过滤器的开发。

Netfilter

Netfilter的功能有很多,如包过滤(packet filtering),NAT地址转换(natwork address translation)以及端口转发(port translation)。在Linux Kernel级别提供了网络包处理框架。
Netfilter的实现原理,就是在Linux Kernel中的网络协议栈中,关键点部分进行hook,通过提供的回调函数,进行相应的逻辑处理。在包过滤的编程开发中,Netfilter是最方便的框架之一。
除了使用Netfilter提供的libnetfilter进行开发以外,网络管理员使用iptables工具也能简单的进行一些网络配置。

Iptables

Iptables工具通常在/usr/sbin/iptables或者/sbin/iptables下,使用iptables,不仅可以配置网络规则,还可以将数据包发送到用户编写的Kernel Module中,用于网络包过滤。
查看iptables配置:

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target    prot opt source    destination

Chain FORWARD (policy ACCEPT)
target    prot opt source    destination

Chain OUTPUT (policy ACCEPT)
target    prot opt source    destination

初始的iptables,什么策略都没有,我们加一条策略:

$ sudo iptables -A INPUT -p udp --dport 53 -j REJECT

上面的策略的意思是,拒绝所有目的端口号为53的udp数据包,也就是dns查询的数据包。
再查看一下iptables的配置:

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target    prot opt source    destination
REJECT    udp  --  anywhere  anywhere     udp:dpt:domain reject-with icmp-port-unreachable

Chain FORWARD (policy ACCEPT)
target    prot opt source    destination

Chain OUTPUT (policy ACCEPT)
target    prot opt source    destination

现在,所有的发送到53端口的UDP数据包将被拒绝,udp:dpt:domain就是53端口的udp的意思,这里iptables将53转义成了domain。
我们ping一下:

$ ping www.google.com
ping: unknown host www.google.com

最后我们还原iptables,为了简单这里直接清空iptables:

sudo iptables -F

再ping一下:

$ ping www.google.com
PING www.google.com (216.58.221.100) 56(84) bytes of data.
...

恢复正常。

Summary

通过一个iptables的配置,我们简单的进行了53端口的udp报文过滤,透过用户层的iptables程序接触到了内核层的netfilter框架。

(本文出自csprojectedu.com,转载请注明出处)