Skip to content

Instantly share code, notes, and snippets.

@umutbasal
Last active April 27, 2024 13:12
Show Gist options
  • Save umutbasal/330dced7ed70008ce30fa52b876d0771 to your computer and use it in GitHub Desktop.
Save umutbasal/330dced7ed70008ce30fa52b876d0771 to your computer and use it in GitHub Desktop.
ebpf syscall count by user
#!/usr/bin/python3
from bcc import BPF
from time import sleep
from bcc.syscall import syscall_name, syscalls
program = r"""
RAW_TRACEPOINT_PROBE(sys_enter) {
u64 uid;
u64 counter = 0;
u64 *p;
uid = bpf_get_current_uid_gid() & 0xFFFFFFFF;
int opcode = ctx->args[1];
bpf_trace_printk("%d, %d", uid, opcode);
return 0;
}
"""
counter = {}
b = BPF(text=program)
import time
import pwd
from tabulate import tabulate
import os
#b.trace_print()
# | userid | syscall | count |
# |--------|---------|-------|
# | root | execv | 10 |
# | | | |
# | | | |
head = ["userid", "syscall", "count"]
start_time = time.time()
while 1:
try:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
(uid, opcode) = msg.split(b", ")
except ValueError:
continue
if uid not in counter:
counter[uid] = {}
if opcode not in counter[uid]:
counter[uid][opcode] = 0
counter[uid][opcode] += 1
current_time = time.time()
if current_time - start_time > 1:
data = []
for uid in counter:
user = pwd.getpwuid(int(uid)).pw_name
for opcode in counter[uid]:
data.append([user, syscall_name(int(opcode)), counter[uid][opcode]])
os.system('clear')
print(tabulate(data, headers=head))
print("\n")
start_time = current_time
@umutbasal
Copy link
Author

userid            syscall             count
----------------  ---------------  --------
root              rt_sigreturn           14
root              write                 157
root              openat                520
root              newfstatat            737
root              ioctl                  23
root              lseek                 105
root              fcntl                 158
root              read             10582613
root              close                 352
root              mmap                  208
root              getdents               14
root              munmap                134
root              mprotect              114
root              futex                 187
root              clock_nanosleep        23
root              nanosleep             208
root              socket                 39
root              connect                 3
root              epoll_ctl             111
root              getsockname            36
root              getpeername             1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment