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:
To create your first ebpf program with rebpf library you can copy and rename an empty project template and edit it changing
Copy this content in
```rust
use rebpf::{xdp::XdpAction, LICENSE, VERSION, rebpfmacro::sec, libbpf::xdpmd};
pub static _license: [u8; 4] = LICENSE;
pub static _version: u32 = VERSION;
fn xdpdrop(ctx: *const xdpmd) -> XdpAction { XdpAction::DROP } ``` Note: this ebpf program drop every packets.
Copy this content in
```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(_) => {} }; }
```
Move into
cd <your_project_name>
./build.sh
cd <your_project_name>/ebpf_output
sudo user
Expected output:
Success Loading
XDP prog name: _xdp_drop, id 33 on device: 2
link.
Licensed under GNU Lesser General Public License (LGPL), version 3 https://www.gnu.org/licenses/lgpl-3.0.html
link.