首页 / 操作系统 / Linux / iptables规则绑定在端口而不是拦截在协议栈
是不是要重新设计Netfilter的HOOK点位置了?无疑这是一个没有意义的问题,因为你无法证明新的方案更好,你可能只是看上了另一个平台的方案而已,而这个方案和Netfilter的方案是不同的。事实上,我就是这样一个人。Cisco的ACL可以被编译在端口上,事实上Cisco设备的网络端口角色是可以被定义的,Linux的理念和此完全不同,Linux内核认为定义角色这种事是用户态的职责,如何要实现一个具有完备性的,不依赖用户态配置的数据包拦截机制,那就必须在协议栈路径上进行拦截。换句话说,Netfilter是完全基于skb本身来拦截并处理数据包的,这一点可以从NF_HOOK宏的参数看得出来,但是你可以看到,它还有两个net_device参数,基于这一点,我们就可以模仿Cisco设备的方式将规则绑定到设备了,这么做是有好处的,可以大大提高效率。比如如果你配置了10000条规则,如果有不相关网口设备进来的数据包,那么这些数据包就不必经过iptables规则的过滤。需要修改的地方比较少,这里只给出ipt_hook的修改:static unsigned int
ipt_hook(unsigned int hook,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{ struct netns_table_per_dev {
struct list_head list;
struct net_device *dev;
struct xt_table *table;
};
// dev_net(in)->ipv4.iptable_filter不再是一个xt_table,而是一个list
struct wrap_table {
struct list_head *tb_list;
};
struct xt_table *table;
struct netns_table_per_dev *table_dev;
struct list_head *pos;
struct wrap_table *tb_list = (struct wrap_table *)dev_net(in)->ipv4.iptable_filter;
list_for_each(pos, tb_list->tb_list) {
table_dev = list_entry(pos, struct netns_table_per_dev, dev);
if (table_dev->dev == in) {
table = table_dev->table;
}
}
if (table == NULL) {
return NF_ACCEPT;
}
return ipt_do_table(skb, hook, in, out, table);
}一个在协议栈拦截,一个在设备拦截,该手术做的有点大,颠覆了既有的理念,不知道会不会有后遗症。不管怎样,不能走火入魔。相关阅读:iptables使用范例详解 http://www.linuxidc.com/Linux/2014-03/99159.htmiptables—包过滤(网络层)防火墙 http://www.linuxidc.com/Linux/2013-08/88423.htmLinux防火墙iptables详细教程 http://www.linuxidc.com/Linux/2013-07/87045.htmiptables+L7+Squid实现完善的软件防火墙 http://www.linuxidc.com/Linux/2013-05/84802.htmiptables的备份、恢复及防火墙脚本的基本使用 http://www.linuxidc.com/Linux/2013-08/88535.htmLinux下防火墙iptables用法规则详解 http://www.linuxidc.com/Linux/2012-08/67952.htm本文永久更新链接地址