rebpf

rebpf is a Rust library built on top of libbpf (no bcc dependency) that allows to write and load bpf program, in details this library provides:

Usage

To create your first ebpf program with rebpf library you can copy and rename an empty project template and edit it changing /src/kern.rs and /src/user.rs files.

write your ebpf program

Copy this content in /src/kern.rs:

```rust

![no_std]

use rebpf::{xdp::XdpAction, LICENSE, VERSION, rebpfmacro::sec, libbpf::xdpmd};

[sec("license")]

pub static _license: [u8; 4] = LICENSE;

[sec("version")]

pub static _version: u32 = VERSION;

[sec("xdp_drop")]

fn xdpdrop(ctx: *const xdpmd) -> XdpAction { XdpAction::DROP } ``` Note: this ebpf program drop every packets.

write your ebpf loader program

Copy this content in /src/user.rs:

```rust use rebpf::{self, xdp, interface, error as rebpf_error}; use std::path::Path;

const DEFAULTFILENAME: &str = "kern.o"; const DEFAULTDEV: &str = "wlan0"; // replace with your device name

fn loadbpf(interface: &interface::Interface, bpfprogrampath: &Path, xdpflags: &[xdp::XdpFlags]) -> Result<(), rebpferror::Error> { let (bpfobject, bpffd) = rebpf::bpfprogload(bpfprogrampath, rebpf::BpfProgType::XDP)?; xdp::bpfsetlinkxdpfd(&interface, Some(&bpffd), &xdpflags)?; let info = rebpf::bpfobjgetinfobyfd(&bpffd)?; println!("Success Loading\n XDP prog name: {}, id {} on device: {}", info.name()?, info.id(), interface.ifindex());

Ok(())

}

fn unloadbpf(interface: &interface::Interface, xdpflags: &[xdp::XdpFlags]) -> Result<(), rebpferror::Error> { xdp::bpfsetlinkxdpfd(&interface, None, &xdpflags)?; println!("Success Unloading.");

Ok(())

}

fn run(bpfprogrampath: &Path, interfacename: &str, unloadprogram: bool) -> Result<(), rebpferror::Error> { let interface = interface::getinterface(interfacename)?; let xdpflags = vec![xdp::XdpFlags::UPDATEIFNOEXIST, xdp::XdpFlags::SKBMODE]; if unloadprogram == false { loadbpf(&interface, bpfprogrampath, &xdpflags) } else { unloadbpf(&interface, &xdpflags) }
}

fn main() { let bpfprogrampath = Path::new(DEFAULTFILENAME); let unloadprogram = false; match run(&bpfprogrampath, DEFAULTDEV, unloadprogram) { Err(err) => println!("{:?}", err), Ok(_) => {} }; }

```

compile ebpf and loader programs

Move into folder and run the script build.sh: cd <your_project_name> ./build.sh

load and run ebpf program

cd <your_project_name>/ebpf_output sudo user Expected output: Success Loading XDP prog name: _xdp_drop, id 33 on device: 2

Documentations

link.

Requirements

License

Licensed under GNU Lesser General Public License (LGPL), version 3 https://www.gnu.org/licenses/lgpl-3.0.html

Examples

link.