1. BPF简介
BPF(Berkeley Packet Filter)是一个数据包的过滤器,它使用一种内核代码注入技术。在不修改内核代码的情况下,可以灵活修改内核处理策略。
tcpdump的过滤规则会被转化成一段bpf指令并加载到内核中的bpf虚拟机器上执行, libpcap 允许用户书写高层的、容易理解的过滤字符串,然后调用libpcap库函数将其编译为BPF代码。
tcpdump “udp and port 67 and port 68” -d可以生成匹配信息包(也就是规则),以人们能够理解的汇编格式给出;
tcpdump “udp and port 67 and port 68” -dd 可以将匹配信息包的代码以c语言程序段的格式给出
2. tcpdump实现代码解析
实现步骤:
- 传入参数argv = “udp and port 67 and port 68” -dd;
- getopt_long( ):获得dd选项;
- while循环,switch操作中使用整型dflag标识d选项的个数,dflag = 2;
- 配置下一步中创建pcap_t结构体所需要的变量的值;
- pcap_open_dead( ):在还没开始捕获时,创建一个pcap_t的结构体并返回;
- copy_argv( ):获得cmd命令参数指定的过滤规则——“udp and port 67 and port 68”;
- pcap_compile( ):用于将用户制定的过滤策略编译到过滤程序中;
- bpf_dump( ):将上一步中编译得到的汇编结果按照格式进行输出;
- 资源释放,以S_SUCCESS结果退出tcpdump。
存放过滤策略编译后的汇编结果的结构体为
struct bpf_program {
u_int bf_len;
struct bpf_insn *bf_insns;
};
struct bpf_insn {
u_short code;
u_char jt;
u_char jf;
bpf_u_int32 k;
};