使用 libnetfilter_queue 动态重写网络数据包
我正在尝试编写一个用户空间应用程序,它可以连接到操作系统的网络堆栈,嗅探飞过的数据包并编辑它感兴趣的数据包。
经过多次谷歌搜索,在我看来,最简单(但相当稳健)的方法(在任何平台上)是 Linux 的 libnetfilter_queue
项目。但是,除了有限的官方之外,我无法找到该项目的任何合理文档文档。它的主要功能(如第一个链接所述)是
- 从内核 nfnetlink_queue 子系统接收排队的数据包,
- 发出判决和/或重新注入更改的数据包到内核 nfnetlink_queue 子系统
重点是我自己的。我到底想怎么做呢?我尝试修改提供的 示例 代码,但也许我误解了某些内容。该代码在 NFQNL_COPY_PACKET 模式下运行,因此我正在接收整个数据包 - 但我对其的修改似乎仅限于我自己的应用程序 - 正如人们所期望的那样,给出“复制”语义。
我的感觉是我应该以某种方式使用NF_QUEUE
,但我还没有完全理解它。有什么指点吗?
(如果有一个更简单的机制可以做到这一点,而且也是跨平台的,我很想听听!)
I am attempting to write a userspace application that can hook into an OS's network stack, sniff packets flying past and edit ones that its interested in.
After much Googling, it appears to me that the simplest (yet reasonably robust) method of doing so (on any platform) is Linux's libnetfilter_queue
project. However, I'm having trouble finding any reasonable documentation for the project, outside of the limited official documentation. Its main features (as stated by the first link are)
- receiving queued packets from the kernel nfnetlink_queue subsystem
- issuing verdicts and/or reinjecting altered packets to the kernel nfnetlink_queue subsystem
Emphasis is my own. How exactly am I meant go about this? I've tried modifying the sample code provided, but perhaps I am misunderstanding something. The code is operating in NFQNL_COPY_PACKET
mode, so I am receiving the whole packet -- but my modifications to it seem to be restricted to my own application -- as one would expect, given the "copy" semantics.
My feeling is that I am meant to make use of NF_QUEUE
somehow, but I haven't quite grokked it. Any pointers?
(If there is a simpler mechanism for doing this, which is also cross-platform, I'd love to hear about it!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不敢相信我之前错过了这个。尽管我不太愿意在 SO 上发表问题,但我想我自己永远也解决不了这个问题。 :)
我没有正确查看函数原型。事实证明,在“verdict”函数(如下所述)中,
最后两个参数用于将数据返回到网络堆栈。事后看来很明显,但我完全错过了它,因为 print_pkt 函数不将数据包数据作为参数,而是从 struct nfq_data 中提取它。
关键是
NF_ACCEPT
数据包并将经过适当修改的数据包传递回内核。I can't believe I missed this previously. As reticent as I am to post questions on SO, I thought I would never work this one out myself. :)
I didn't look at the function prototype properly. It turns out in the "verdict" function (outlined below),
The last two parameters are for the data to be returned to the network stack. Obvious in hindsight, but I missed it completely as the
print_pkt
function doesn't take the packet data as a parameter, but extracts it from thestruct nfq_data
.The key is to
NF_ACCEPT
the packet and pass the suitably modified packet back to the kernel.只是通过挖掘源代码进行的疯狂猜测:尝试使用 nfnl_addattr_l(..., NFQA_PAYLOAD, ...) 显式添加损坏的有效负载?
Just a wild guess from digging around the source code: try explicitly adding the mangled payload using
nfnl_addattr_l(…, NFQA_PAYLOAD, …)
?