1 // SPDX-License-Identifier: GPL-2.0 2 3 /* 4 * Copyright 2020 Google LLC. 5 */ 6 7 #include "vmlinux.h" 8 #include <bpf/bpf_helpers.h> 9 #include <bpf/bpf_tracing.h> 10 #include <errno.h> 11 12 struct { 13 __uint(type, BPF_MAP_TYPE_ARRAY); 14 __uint(max_entries, 1); 15 __type(key, __u32); 16 __type(value, __u64); 17 } array SEC(".maps"); 18 19 struct { 20 __uint(type, BPF_MAP_TYPE_HASH); 21 __uint(max_entries, 1); 22 __type(key, __u32); 23 __type(value, __u64); 24 } hash SEC(".maps"); 25 26 struct { 27 __uint(type, BPF_MAP_TYPE_LRU_HASH); 28 __uint(max_entries, 1); 29 __type(key, __u32); 30 __type(value, __u64); 31 } lru_hash SEC(".maps"); 32 33 char _license[] SEC("license") = "GPL"; 34 35 int monitored_pid = 0; 36 int mprotect_count = 0; 37 int bprm_count = 0; 38 39 SEC("lsm/file_mprotect") 40 int BPF_PROG(test_int_hook, struct vm_area_struct *vma, 41 unsigned long reqprot, unsigned long prot, int ret) 42 { 43 if (ret != 0) 44 return ret; 45 46 __u32 pid = bpf_get_current_pid_tgid() >> 32; 47 int is_stack = 0; 48 49 is_stack = (vma->vm_start <= vma->vm_mm->start_stack && 50 vma->vm_end >= vma->vm_mm->start_stack); 51 52 if (is_stack && monitored_pid == pid) { 53 mprotect_count++; 54 ret = -EPERM; 55 } 56 57 return ret; 58 } 59 60 SEC("lsm.s/bprm_committed_creds") 61 int BPF_PROG(test_void_hook, struct linux_binprm *bprm) 62 { 63 __u32 pid = bpf_get_current_pid_tgid() >> 32; 64 char args[64]; 65 __u32 key = 0; 66 __u64 *value; 67 68 if (monitored_pid == pid) 69 bprm_count++; 70 71 bpf_copy_from_user(args, sizeof(args), (void *)bprm->vma->vm_mm->arg_start); 72 bpf_copy_from_user(args, sizeof(args), (void *)bprm->mm->arg_start); 73 74 value = bpf_map_lookup_elem(&array, &key); 75 if (value) 76 *value = 0; 77 value = bpf_map_lookup_elem(&hash, &key); 78 if (value) 79 *value = 0; 80 value = bpf_map_lookup_elem(&lru_hash, &key); 81 if (value) 82 *value = 0; 83 84 return 0; 85 } 86 SEC("lsm/task_free") /* lsm/ is ok, lsm.s/ fails */ 87 int BPF_PROG(test_task_free, struct task_struct *task) 88 { 89 return 0; 90 } 91 92 int copy_test = 0; 93 94 SEC("fentry.s/__x64_sys_setdomainname") 95 int BPF_PROG(test_sys_setdomainname, struct pt_regs *regs) 96 { 97 void *ptr = (void *)PT_REGS_PARM1(regs); 98 int len = PT_REGS_PARM2(regs); 99 int buf = 0; 100 long ret; 101 102 ret = bpf_copy_from_user(&buf, sizeof(buf), ptr); 103 if (len == -2 && ret == 0 && buf == 1234) 104 copy_test++; 105 if (len == -3 && ret == -EFAULT) 106 copy_test++; 107 if (len == -4 && ret == -EFAULT) 108 copy_test++; 109 return 0; 110 } 111