Why ebpf program inside samples/bpf doesn't work?

时光毁灭记忆、已成空白 提交于 2019-12-24 18:31:20

问题


GOAL: write a new ebpf example within samples/bpf directory in the kernel source tree of 4.18.0, compile and execute it.

PROBLEM: after compiling it when I run sudo ./mine it just terminates.

mine_kern.c

#include <uapi/linux/bpf.h>
#include <uapi/linux/if_ether.h>
#include <uapi/linux/ip.h>
#include <linux/in.h>
#include <linux/if_packet.h>
#include "bpf_helpers.h" 

int icmp_filter(struct __sk_buff *skb){

        int proto = load_byte(skb, ETH_HLEN + offsetof(struct iphdr, protocol));
        if(proto == IPPROTO_ICMP && skb->pkt_type == PACKET_OUTGOING){
           return -1;
        } else {
           return 0;
        }
}

char _license[] SEC("license") = "GPL";

mine_user.c

#include <stdio.h>
#include <assert.h>
#include <linux/bpf.h>
#include <bpf/bpf.h>
#include "bpf_load.h"
#include "sock_example.h"
#include <unistd.h>
#include <arpa/inet.h>    

int main(int ac, char **argv)
{
    char filename[256];
    FILE *f;
    int i, sock;

    snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);

    if (load_bpf_file(filename)) {
        printf("%s", bpf_log_buf);
        return 1;
    }   

    sock = open_raw_sock("lo");

    assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, prog_fd,
              sizeof(prog_fd[0])) == 0);

    f = popen("ping -c5 localhost", "r");
    (void) f;

    char buf[65535];

    for(i=0; i<20; i++){
           int res = recvfrom(sock, buf, sizeof(buf), 0, NULL, 0);
           printf("res=%d\n", res);
     } 

     return 0;
}

I've also modified the Makefile inside samples/bpf adding mine_user.c and mine_kern.c where required. QUESTIONS: what is wrong with this code?


回答1:


Because of the way load_bpf_file() loads the function, you need to put your BPF program function in a separate ELF section. For example, I could load the program with:

SEC("socket")
int icmp_filter(struct __sk_buff *skb){
        ...
}

After that, I see a succession of res=-1 when running the program. This is because your socket is set as non-blocking by open_raw_sock(), from sock_example.h:

sock = socket(PF_PACKET, SOCK_RAW|SOCK_NONBLOCK|SOCK_CLOEXEC, htons(ETH_P_ALL));

So when there is no packet to receive, recvfrom() simply returns with -1 (and sets errno to -EGAIN -- you should consider printing strerror(errno) by the way) instead of waiting for a packet. So you may want to change that too.



来源:https://stackoverflow.com/questions/57291946/why-ebpf-program-inside-samples-bpf-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!