Skip to content

Instantly share code, notes, and snippets.

@ethercflow
Last active December 22, 2020 10:45
Show Gist options
  • Save ethercflow/f410f8f48ad8d04209d5e39b45c8c859 to your computer and use it in GitHub Desktop.
Save ethercflow/f410f8f48ad8d04209d5e39b45c8c859 to your computer and use it in GitHub Desktop.
ns.py
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
from __future__ import print_function
from bcc import BPF
import sys, os
from bcc.utils import printb
# define BPF program
prog = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
#include <linux/nsproxy.h>
#include <linux/mount.h>
#include <linux/pid_namespace.h>
#define MY_READ(P) ({ typeof(P) _val; \
memset(&_val, 0, sizeof(_val)); \
bpf_probe_read(&_val, sizeof(_val), &P); \
_val; \
})
struct data_t {
u64 ts;
char comm[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(events);
static inline bool my_ns_match(struct pid_namespace *ns, dev_t dev, ino_t ino)
{
dev_t s_dev = MY_READ(MY_READ(MY_READ(ns->proc_mnt)->mnt_sb)->s_dev);
unsigned int proc_inum = MY_READ(ns->proc_inum);
return (proc_inum == ino) && (s_dev == dev);
}
static inline struct pid_namespace *my_ns_of_pid(struct pid *pid)
{
struct pid_namespace *ns = NULL;
if (pid)
ns = MY_READ(pid->numbers[MY_READ(pid->level)].ns);
return ns;
}
static inline struct pid *my_task_pid(struct task_struct *task)
{
return MY_READ(task->pids[PIDTYPE_PID].pid);
}
static inline struct pid_namespace *my_task_active_pid_ns(struct task_struct *tsk)
{
return my_ns_of_pid(my_task_pid(tsk));
}
static inline bool container_allowed(u64 dev, u64 ino)
{
struct task_struct *task = (void*)bpf_get_current_task();
struct pid_namespace *pidns;
if ((u64)(dev_t)dev != dev)
return -1;
if (!task)
return -1;
pidns = my_task_active_pid_ns(task);
if (!pidns)
return -1;
return my_ns_match(pidns, (dev_t)dev, ino);
}
int hello(struct pt_regs *ctx) {
struct bpf_pidns_info ns = {};
struct data_t data = {};
if (!container_allowed(DEV, INO))
return 0;
data.ts = bpf_ktime_get_ns();
bpf_get_current_comm(&data.comm, sizeof(data.comm));
events.perf_submit(ctx, &data, sizeof(data));
return 0;
}
"""
devinfo = os.stat("/proc/self/ns/pid")
for r in (("DEV", str(devinfo.st_dev)), ("INO", str(devinfo.st_ino))):
prog = prog.replace(*r)
# load BPF program
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello")
# header
print("%-18s %-16s %s" % ("TIME(s)", "COMM", "MESSAGE"))
# process event
start = 0
def print_event(cpu, data, size):
global start
event = b["events"].event(data)
if start == 0:
start = event.ts
time_s = (float(event.ts - start)) / 1000000000
printb(
b"%-18.9f %-16s %s"
% (time_s, event.comm, b"Hello, perf_output!")
)
# loop with callback to print_event
b["events"].open_perf_buffer(print_event)
while 1:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment