Why I'm forced to use raw socket to write ebpf programs with BCC?

别说谁变了你拦得住时间么 提交于 2019-12-11 16:45:35

问题


GOAL: write an eBPF packet filter program that doesn't require high privileges.

PROBLEM: from what I understood I have to use attach_raw_socket function to attach my filter to an interface. This functions invokes bpf_open_raw_sock libbpf function which open a raw_socket that requires high privileges (https://github.com/iovisor/bcc/blob/10dae9eac33287c1df9e6645933b608c2d2c5640/src/cc/libbpf.c#L674-L678).

QUESTION: Is there a way to attach an ebpf filter to another socket type, like SOCK_DGRAM (with cBPF is possible)?.

#!/usr/bin/python

from bcc import BPF
import socket
import os

# backend part
# ebpf program written using restricted C
c_ebpf = """
#include <uapi/linux/if_ether.h>
#include <uapi/linux/ip.h>
#include <linux/in.h>
#include <linux/if_packet.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; }
}
"""

# loader
bpf = BPF(text=c_ebpf)
ffilter = bpf.load_func("icmp_filter", BPF.SOCKET_FILTER)
BPF.attach_raw_socket(ffilter, "enp0s3")

# frontend part
socketfd = ffilter.sock

sockobj = socket.fromfd(socketfd, socket.AF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
sockobj.setblocking(True)

while 1:
    pkt_str = os.read(socketfd, 2048)
    pkt_bytearray = bytearray(pkt_str)
    ip_protocol = pkt_bytearray[23]
    print ("%s" % hex(ip_protocol))

来源:https://stackoverflow.com/questions/57219423/why-im-forced-to-use-raw-socket-to-write-ebpf-programs-with-bcc

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