-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.bpf.c
64 lines (54 loc) · 1.87 KB
/
main.bpf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "main.h"
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 10240);
__type(key, pid_t);
__type(value, struct event_t);
} execs SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(key_size, sizeof(u32));
__uint(value_size, sizeof(u32));
} events SEC(".maps");
SEC("fentry/__x64_sys_execve")
int BPF_PROG(fentry_sys_execve, struct pt_regs *regs) {
pid_t tid;
struct task_struct *task;
struct event_t event = {};
tid = (pid_t)bpf_get_current_pid_tgid();
task = (struct task_struct*)bpf_get_current_task();
// 执行操作的进程 id
event.ppid = (pid_t)BPF_CORE_READ(task, real_parent, tgid);
// 获取进程 id
event.pid = bpf_get_current_pid_tgid() >> 32;
// 执行 execve 的进程名称
bpf_get_current_comm(&event.comm, sizeof(event.comm));
// 获取被执行的程序的名称
char *filename = (char *)PT_REGS_PARM1_CORE(regs);
bpf_core_read_user_str(event.filename, sizeof(event.filename), filename);
// 保存获取到的 event 信息
bpf_map_update_elem(&execs, &tid, &event, BPF_NOEXIST);
return 0;
}
SEC("fexit/__x64_sys_execve")
int BPF_PROG(fexit_sys_execve, struct pt_regs *regs, long ret) {
pid_t tid;
struct event_t *event;
// 获取 fentry_sys_execve 中保存的 event 信息
tid = (pid_t)bpf_get_current_pid_tgid();
event = bpf_map_lookup_elem(&execs, &tid);
if (!event)
return 0;
// 保存执行结果
event->ret = (int)ret;
// 将事件提交到 events 中供用户态程序消费
bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, event, sizeof(*event));
// 删除保存的 event 信息
bpf_map_delete_elem(&execs, &tid);
return 0;
}
char _license[] SEC("license") = "GPL";