是否可以使用libnetfilter_queue访问ip片段

时间:2015-04-27 15:39:24

标签: c linux iptables netfilter ip-fragmentation

我在C中使用libnetfilter_queue来捕获数据包。我正在设置一个iptable规则来对稍后由用户空间实现处理的传入数据包进行排队,如下所示:iptables -A INPUT -j NFQUEUE --queue-num 0。我使用nfqnl_test示例作为实现捕获的框架。一切都按预期工作。但是,我注意到在ip片段级别检查队列是不可能的。也就是说,如果数据包进入片段,则在被放入队列之前首先重新组装。但我想处理碎片。那么有没有办法强制执行这种行为?我想要的是一个队列,我可以观察原始传入的数据包(碎片和未碎片),这样我就可以相应地对它们采取行动。

我读到重新装配确实发生过。另一方面,使用iptables可以有-f标志,因此应该有一个"碎片粒度"这是我要找的。我也尝试调整iptable规则(例如iptables -t raw -D PREROUTING -i eth0 -j NFQUEUE --queue-num 0),但结果仍然相同。我只能观察已经重新组装的数据包,我肯定知道它是以片段形式到达的。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

所以我找到了问题的解决方案,我在这里分享,以防有些人感兴趣。归功于来自netfilter邮件列表的Adel,他建议了可行的解决方法。基本上,解决方案是使用nftables并设置优先级低于碎片整理优先级的链。我用C代码测试了这个设置,它看起来效果很好(我没有注意到任何副作用)。但是,我必须提到我仅将它用于观察IP片段,并且我没有篡改它们。

下面有两个函数来设置nftables然后删除它们。

void set_nftable() {

    int status = 0;

    // Create a nftable 
    status = system("nft add table ip filter");

    // Add a chain to the nftable called "predefrag" which has lower priority than the defragmentation -450 < -400
    status = system("nft add chain ip filter predefrag { type filter hook prerouting priority -- -450 \\; }");

    // Set the nftable rule (queue packets to be accessed by a user-space application)
    status = system("nft add filter predefrag meta iif eth0 counter queue num 0 bypass"); 
}

void remove_nftable() {

    int status = 0;

    // Flush the rules that are stored in the chains that belong to the nftable
    status = system("nft flush table ip filter");

    // Delete the chain from the nftable
    status = system("nft delete chain ip filter predefrag");

    // Delete the nftable
    status = system("nft delete table ip filter");
}

使用这些功能,nfqnl_test代码可用于捕获IP片段。下面是有用的链接,用于设置nftables并低估它们的工作方式(一旦熟悉nftables手册,函数中的注释就非常明显)。

http://wiki.nftables.org/wiki-nftables/index.php/Building_and_installing_nftables_from_sources

http://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables

http://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains

http://wiki.nftables.org/wiki-nftables/index.php/Simple_rule_management

http://wiki.nftables.org/wiki-nftables/index.php/Queueing_to_userspace

答案 1 :(得分:0)

在其他任何事情之前,请确保您的网卡不是进行重组的人。

现代网卡(如LROUFO等)执行的各种卸载技术可以重新组合IP级别的片段。我建议使用ethtool -k检查相关界面上哪些卸载处于活动状态,然后使用ethtool -K逐个关闭它们。