上下文:我试图跟踪特定端口的数据包并重定向它,但针对特定进程。现在它在整个界面上进行跟踪。
#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 packetn");
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 7999n");
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'
有没有任何函数可以输出nc
,如果udp端口7999被跟踪,我可以使用XDP_DROP来丢弃数据包。
像这样的如果进程==nc&;udp->dest==ntohs(7999(XDP_DROP
XDP程序中的进程信息不可靠。通常只是进程的PID被中断来处理接收到的数据包,所以它最终可能是任何东西。如果在接收服务器上添加一点负载,您可能会注意到报告的是各种用户空间进程,而不是nc
。