1 // SPDX-License-Identifier: GPL-2.0 2 /* Copyright (C) 2023 Chuyi Zhou <zhouchuyi@bytedance.com> */ 3 4 #include "vmlinux.h" 5 #include <errno.h> 6 #include <bpf/bpf_helpers.h> 7 #include <bpf/bpf_tracing.h> 8 #include "bpf_misc.h" 9 #include "bpf_experimental.h" 10 11 char _license[] SEC("license") = "GPL"; 12 13 struct cgroup *bpf_cgroup_acquire(struct cgroup *p) __ksym; 14 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym; 15 void bpf_cgroup_release(struct cgroup *p) __ksym; 16 17 pid_t target_pid; 18 int css_task_cnt; 19 u64 cg_id; 20 21 SEC("lsm/file_mprotect") 22 int BPF_PROG(iter_css_task_for_each, struct vm_area_struct *vma, 23 unsigned long reqprot, unsigned long prot, int ret) 24 { 25 struct task_struct *cur_task = bpf_get_current_task_btf(); 26 struct cgroup_subsys_state *css; 27 struct task_struct *task; 28 struct cgroup *cgrp; 29 30 if (cur_task->pid != target_pid) 31 return ret; 32 33 cgrp = bpf_cgroup_from_id(cg_id); 34 35 if (!cgrp) 36 return -EPERM; 37 38 css = &cgrp->self; 39 css_task_cnt = 0; 40 41 bpf_for_each(css_task, task, css, CSS_TASK_ITER_PROCS) 42 if (task->pid == target_pid) 43 css_task_cnt++; 44 45 bpf_cgroup_release(cgrp); 46 47 return -EPERM; 48 } 49 50 static inline u64 cgroup_id(struct cgroup *cgrp) 51 { 52 return cgrp->kn->id; 53 } 54 55 SEC("?iter/cgroup") 56 int cgroup_id_printer(struct bpf_iter__cgroup *ctx) 57 { 58 struct seq_file *seq = ctx->meta->seq; 59 struct cgroup *cgrp = ctx->cgroup; 60 struct cgroup_subsys_state *css; 61 struct task_struct *task; 62 63 /* epilogue */ 64 if (cgrp == NULL) { 65 BPF_SEQ_PRINTF(seq, "epilogue\n"); 66 return 0; 67 } 68 69 /* prologue */ 70 if (ctx->meta->seq_num == 0) 71 BPF_SEQ_PRINTF(seq, "prologue\n"); 72 73 BPF_SEQ_PRINTF(seq, "%8llu\n", cgroup_id(cgrp)); 74 75 css = &cgrp->self; 76 css_task_cnt = 0; 77 bpf_for_each(css_task, task, css, CSS_TASK_ITER_PROCS) { 78 if (task->pid == target_pid) 79 css_task_cnt++; 80 } 81 82 return 0; 83 } 84 85 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid") 86 int BPF_PROG(iter_css_task_for_each_sleep) 87 { 88 u64 cgrp_id = bpf_get_current_cgroup_id(); 89 struct cgroup *cgrp = bpf_cgroup_from_id(cgrp_id); 90 struct cgroup_subsys_state *css; 91 struct task_struct *task; 92 93 if (cgrp == NULL) 94 return 0; 95 css = &cgrp->self; 96 97 bpf_for_each(css_task, task, css, CSS_TASK_ITER_PROCS) { 98 99 } 100 bpf_cgroup_release(cgrp); 101 return 0; 102 } 103