我正在尝试编写一个绑定到 NFQUEUE 套接字的用户空间应用程序,内核模块会将传入的数据包转发到该套接字(通过标记它们 NF_QUEUE)。这是通过使用 iptables 规则来实现的,例如:
iptables -A INPUT -j NFQUEUE --queue-num 0
iptables ACCEPT 链如下所示:
iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT icmp -- anywhere anywhere
ACCEPT all -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited
NFQUEUE all -- anywhere anywhere NFQUEUE num 0
这是轮询 NFQUEUE 套接字的代码(QNUM 为 0):
printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n");
if (nfq_bind_pf(h, AF_INET) < 0)
{
fprintf(stderr, "error during nfq_bind_pf()\n");
return 1;
}
/* Register a callback function for our queue number */
qh = nfq_create_queue(h, QNUM, &cb_func, NULL);
if (!qh)
{
fprintf(stderr, "error during creating nf_queue\n");
return 1;
}
/* See if we have received a packet and send it to our cb func */
fd = nfq_fd(h);
if (fd < 0)
return 1;
#if 1
for (;;)
{
if ((rv = recv(fd, buf, sizeof(buf), 0)) >= 0) {
nfq_handle_packet(h, buf, sizeof(buf)); /* send packet to callback */
continue;
}
}
#endif
问题是 /proc/net/netfilter/nf_queue 列出了正在使用的队列号 2 而不是号 0,因此我的用户空间程序没有检测到相关套接字中的任何传入数据包。这是为什么?
cat /proc/net/netfilter/nf_queue
0 NONE
1 NONE
2 nf_queue
3 NONE
4 NONE
5 NONE
6 NONE
7 NONE
8 NONE
9 NONE
10 NONE
11 NONE
12 NONE