Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
eBPF hello world
#!/usr/bin/python
from bcc import BPF
from time import sleep
# This outputs a count of how many times the clone and execve syscalls have been made
# showing the use of an eBPF map (called syscall).
program = """
BPF_HASH(syscall);
int kprobe__sys_clone(void *ctx) {
u64 counter = 0;
u64 key = 56;
u64 *p;
p = syscall.lookup(&key);
// The verifier will reject access to a pointer if you don't check that it's non-null first
// Try commenting out the if test (and its closing brace) if you want to see the verifier do its thing
if (p != 0) {
counter = *p;
}
counter++;
syscall.update(&key, &counter);
return 0;
}
int kprobe__sys_execve(void *ctx) {
u64 counter = 0;
u64 key = 59;
u64 *p;
p = syscall.lookup(&key);
if (p != 0) {
counter = *p;
}
counter++;
syscall.update(&key, &counter);
return 0;
}
"""
b = BPF(text=program)
while True:
sleep(2)
line = ""
for k, v in b["syscall"].items():
line += "syscall {0}: {1}\t".format(k.value, v.value)
print(line)
#!/usr/bin/python
from bcc import BPF
prog = """
int hello(void *ctx) {
bpf_trace_printk("Hello world\\n");
return 0;
}
"""
b = BPF(text=prog)
b.attach_kprobe(event="sys_clone", fn_name="hello")
b.trace_print()
# This prints out a trace line every time the clone system call is called
# If you rename hello() to kprobe__sys_clone() you can delete the b.attach_kprobe() line, because bcc can work
# out what event to attach this to from the function name.
@lizrice

This comment has been minimized.

Copy link
Owner Author

lizrice commented Jun 4, 2019

These examples use bcc which makes it easy to load eBPF programs into the kernel. I would recommend starting with hello_world.py and then hello_map.py.

Try running them under strace to see the system calls that are happening! For example strace -e bpf ./hello_world.py will show you the bpf() system call that loads the program into the kernel (BPF_PROG_LOAD).

You can see the accompanying slides from DockerCon here

@lizrice

This comment has been minimized.

Copy link
Owner Author

lizrice commented Nov 5, 2019

See also Aqua Security's Tracee project

@yashbhutwala

This comment has been minimized.

Copy link

yashbhutwala commented Dec 15, 2019

@lizrice can you please also attach the Vagrantfile used for this?

@surajkjai

This comment has been minimized.

Copy link

surajkjai commented Jan 30, 2020

Seems BPF's class method attach_kprobe() is broken: the current hello_map.py throws the following exception in python2.7:
Exception: Failed to attach BPF program hello to kprobe__sys_clone

Workaround: as mentioned in the code, comment out b.attach_kprobe() and rename hello to kprobe__sys_clone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.