BPF and kernel tracing¶
Live answers from the running kernel: no restart, no recompiling, no agent. All of these need root and exit on their own after a few seconds. bpftrace comes first; ftrace, which needs nothing installed, is at the end.
Tested with bpftrace 0.20.2 on Ubuntu 24.04, kernel 6.8. fentry probes need
a kernel with BTF (/sys/kernel/btf/vmlinux exists), which every current
major distribution ships.
Find what a process is actually waiting on¶
# Syscall latency histogram (µs) for one PID, for 30 seconds.
sudo bpftrace -e '
tracepoint:raw_syscalls:sys_enter /pid == '"$PID"'/ {
@s[tid] = nsecs; @nr[tid] = args->id;
}
tracepoint:raw_syscalls:sys_exit /pid == '"$PID"' && @s[tid]/ {
@us[@nr[tid]] = hist((nsecs - @s[tid]) / 1000);
delete(@s[tid]); delete(@nr[tid]);
}
interval:s:30 { exit(); }
END { clear(@s); clear(@nr); }'
Keys are syscall numbers; ausyscall 220 (from auditd) names them, and they
differ per architecture. The number is recorded on entry because on arm64
rt_sigreturn reports -1 on exit. The answer is usually one syscall you
were not thinking about.
Which kernel functions can I trace?¶
sudo bpftrace -l 'kprobe:tcp_*' # every traceable function matching tcp_*
sudo bpftrace -lv 'fentry:tcp_connect' # its typed arguments (needs BTF)
Count calls to a family of kernel functions¶
# Which VFS functions run most over 5 seconds?
sudo bpftrace -e 'kprobe:vfs_* { @[func] = count(); } interval:s:5 { exit(); }'
Keep wildcards narrow. vfs_* is about 80 probes; tcp_* is about 500,
and attaching that many takes a while and costs real overhead on a busy host.
How long does a kernel function take?¶
# vfs_read latency (µs), per process, for 10 seconds.
sudo bpftrace -e '
kprobe:vfs_read { @start[tid] = nsecs; }
kretprobe:vfs_read /@start[tid]/ {
@us[comm] = hist((nsecs - @start[tid]) / 1000); delete(@start[tid]);
}
interval:s:10 { exit(); }
END { clear(@start); }'
Swap vfs_read for any function from bpftrace -l. Inlined functions do not
appear in the list and cannot be traced this way.
Who calls this function?¶
# Kernel stacks leading into tcp_v4_connect, counted per process.
sudo bpftrace -e 'kprobe:tcp_v4_connect { @[comm, kstack(6)] = count(); } interval:s:10 { exit(); }'
The stack is the fastest way to learn which code path you are actually on before reading kernel source.
Which processes fail to open files, and why?¶
# Failed opens per process and errno (-2 = ENOENT, -13 = EACCES).
sudo bpftrace -e '
kretprobe:do_sys_openat2 /(int64)retval < 0/ { @[comm, (int64)retval] = count(); }
interval:s:10 { exit(); }'
With the file names, using typed arguments:
sudo bpftrace -e '
fexit:do_sys_openat2 /retval < 0/ {
printf("%-16s %4d %s\n", comm, retval, str(uptr(args->filename)));
}
interval:s:10 { exit(); }'
uptr() matters: the file name lives in user memory, and without it the name
prints empty.
Every outgoing TCP connection, as it happens¶
# Process, PID and destination of each new IPv4 TCP connection.
sudo bpftrace -e '
fentry:tcp_connect {
$sk = args->sk;
if ($sk->__sk_common.skc_family == 2) { // AF_INET
printf("%-16s %-7d -> %s:%d\n", comm, pid,
ntop($sk->__sk_common.skc_daddr), bswap($sk->__sk_common.skc_dport));
}
}
interval:s:30 { exit(); }'
Good for answering "what is this host talking to?" during an investigation,
including connections that close before ss would ever see them. The port is
stored in network byte order, hence bswap.
ftrace: kernel tracing without BPF¶
ftrace is built into the kernel and driven by writing to files in
/sys/kernel/tracing. Nothing to install, which makes it the tool for hosts
where you cannot add bpftrace. Run these from a root shell (sudo -i); each
one cleans up after itself. Kernels in lockdown "confidentiality" mode block
it.
Tested on kernel 6.8 and trace-cmd 3.2.
Every program executed on the host, live¶
cd /sys/kernel/tracing
echo 1 > events/sched/sched_process_exec/enable
timeout 30 cat trace_pipe
echo 0 > events/sched/sched_process_exec/enable
Catches short-lived processes that ps never shows: the cron job, the
curl | sh, the shell an attacker spawns.
Call graph with timings for one kernel function¶
cd /sys/kernel/tracing
echo do_sys_openat2 > set_graph_function
echo 3 > max_graph_depth
echo function_graph > current_tracer
sleep 5
echo 0 > tracing_on # stop first: changing the tracer wipes the buffer
grep -v '^#' trace | head -40
echo nop > current_tracer; echo 1 > tracing_on
echo > set_graph_function; echo 0 > max_graph_depth
Output reads like code: each child call with its time, and + marks calls
over 10 µs. Here it shows that most of an open is spent in path_openat.
Hit counts for a family of functions¶
cd /sys/kernel/tracing
echo 'tcp_*' > set_ftrace_filter
echo 1 > function_profile_enabled
sleep 10
echo 0 > function_profile_enabled
cat trace_stat/function* | awk '$2 ~ /^[0-9]+$/ { hits[$1] += $2 } END { for (f in hits) print hits[f], f }' \
| sort -nr | head -20
echo > set_ftrace_filter
The profiler keeps one table per CPU; the awk adds them up.
Failed opens, with a kretprobe and a filter¶
cd /sys/kernel/tracing
echo 'r:snip/open_fail do_sys_openat2 ret=$retval:s64' >> dynamic_events
echo 'ret < 0' > events/snip/open_fail/filter
echo 1 > events/snip/open_fail/enable
timeout 10 cat trace_pipe
echo 0 > events/snip/open_fail/enable
echo '-:snip/open_fail' >> dynamic_events
The filter runs in the kernel, so only failures reach the buffer.
Function arguments, with a kprobe event¶
cd /sys/kernel/tracing
echo 'p:snip/open do_sys_openat2 path=+0($arg2):ustring' >> dynamic_events
echo 1 > events/snip/open/enable
timeout 10 cat trace_pipe
echo 0 > events/snip/open/enable
echo '-:snip/open' >> dynamic_events
$arg2 is the second argument, +0(…):ustring reads it as a string from user
memory. An occasional path=(fault) is a page not yet in memory, not an
error.
The same with trace-cmd¶
trace-cmd wraps all of the above and handles the cleanup. It writes
trace.dat to the current directory.
# Call graph of every open made by one command.
sudo trace-cmd record -p function_graph -g do_sys_openat2 --max-graph-depth 3 -F cat /etc/hostname
sudo trace-cmd report | head -40
# Or an already running process and the children it starts (-c).
sudo trace-cmd record -p function_graph -g do_sys_openat2 --max-graph-depth 3 -P "$PID" -c sleep 10
sudo trace-cmd report | less
If a session is interrupted and leaves tracing switched on, sudo trace-cmd
reset puts everything back.