0

上下文:我正在尝试跟踪特定端口的数据包并将其重定向但针对特定进程。现在它跟踪整个界面。

#define KBUILD_MODNAME "filter"
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/udp.h>

int udpfilter(struct xdp_md *ctx) {
  bpf_trace_printk("got a packet\n");
  void *data = (void *)(long)ctx->data;
  void *data_end = (void *)(long)ctx->data_end;
  struct ethhdr *eth = data;
  if ((void*)eth + sizeof(*eth) <= data_end) {
    struct iphdr *ip = data + sizeof(*eth);
    if ((void*)ip + sizeof(*ip) <= data_end) {
      if (ip->protocol == IPPROTO_UDP) {
        struct udphdr *udp = (void*)ip + sizeof(*ip);
        if ((void*)udp + sizeof(*udp) <= data_end) {
          if (udp->dest == ntohs(7999)) {
            bpf_trace_printk("udp port 7999\n");
            udp->dest = ntohs(7998);
          }
        }
      }
    }
  }
  return XDP_PASS;
}

我得到的输出

vagrant@vagrant:~$ sudo python3 main.py
/virtual/main.c:1:9: warning: 'KBUILD_MODNAME' macro redefined [-Wmacro-redefined]
#define KBUILD_MODNAME "filter"
        ^
<command line>:3:9: note: previous definition is here
#define KBUILD_MODNAME "bcc"
        ^
1 warning generated.
b'              nc-1508    [000] ..s1  2564.611068: 0: got packet'
b'              nc-1508    [000] ..s1  2564.611082: 0: udp port 7999'
b'              nc-1508    [000] ..s1  2564.611090: 0: got packet'
b'              nc-1508    [000] ..s1  2564.611093: 0: got packet'
b'              nc-1508    [000] ..s1  2564.611094: 0: udp port 7999'
b'              nc-1508    [000] ..s1  2564.611095: 0: got packet'
b'              nc-1508    [000] ..s1  2565.611593: 0: got packet'
b'              nc-1508    [000] ..s1  2565.611605: 0: udp port 7999'
b'              nc-1508    [000] ..s1  2565.611618: 0: got packet'
b'              nc-1508    [000] ..s1  2566.612184: 0: got packet'
b'              nc-1508    [000] ..s1  2566.612195: 0: udp port 7999'
b'              nc-1508    [000] ..s1  2566.612207: 0: got packet'
b'              nc-1508    [000] ..s1  2567.611801: 0: got packet'
b'              nc-1508    [000] ..s1  2567.611812: 0: udp port 7999'
b'              nc-1508    [000] ..s1  2567.611825: 0: got packet'

是否有任何功能可以 grepnc并且如果跟踪 udp 端口​​ 7999 我可以使用 XDP_DROP 丢弃数据包。

如果 process == nc && udp->dest == ntohs(7999) XDP_DROP 是这样的

4

1 回答 1

1

XDP 程序中的进程信息不可靠。通常只是进程的 PID 被中断以处理接收到的数据包,因此它最终可能是任何东西。如果您在接收服务器上增加一点负载,您可能会注意到报告了各种用户空间进程,而不是nc.

于 2021-11-27T19:02:53.337 回答