Last active
November 21, 2022 14:15
-
-
Save rzikm/c2f8010ed1ee2275ff839fa8ab8471b4 to your computer and use it in GitHub Desktop.
KRSI - prevent access to "xyz.log"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* MDE Sensor BPF Kernel Program | |
* @achinbha | |
*/ | |
#include <vmlinux.h> | |
//#include <linux/bpf.h> | |
#include <bpf/bpf_helpers.h> | |
#include <bpf/bpf_tracing.h> | |
#include <string.h> | |
#include <sys/errno.h> | |
#include "mde_sensor.h" | |
char LICENSE[] SEC("license") = "Dual BSD/GPL"; | |
struct trie_key { | |
u32 prefixlen; // first member must be u32 | |
char name[128]; // rest can are arbitrary | |
}; | |
struct { | |
__uint(type, BPF_MAP_TYPE_LPM_TRIE); | |
__uint(max_entries, 128); | |
__type(key, struct trie_key); // key is the file name | |
__type(value, int); // value is the length of the name | |
__uint(map_flags, BPF_F_NO_PREALLOC); | |
} denylist SEC(".maps"); | |
int stringLength(const char* text, int size) | |
{ | |
int i = 0; | |
for (; i < size; i++) | |
{ | |
if (text[i] == '\0') | |
break; | |
} | |
return i; | |
} | |
SEC("lsm/file_permission") | |
int BPF_PROG(lsm__file_permission, struct file *file, int mask) | |
{ | |
struct trie_key key; | |
bpf_probe_read_str((void*)key.name, sizeof(key.name), file->f_path.dentry->d_name.name); | |
key.prefixlen = stringLength(key.name, sizeof(key.name)) + 1; | |
// bpf_printk("File permission check for %d:%s", key.prefixlen, key.name); | |
int* value = bpf_map_lookup_elem(&denylist, &key); | |
if (value && *value == key.prefixlen) // check against the name since it may return closest possible match | |
{ | |
bpf_probe_read_str(&args.fname, sizeof(args.fname), file->f_path.dentry->d_name.name); | |
args.flags = mask; | |
bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &args, sizeof(args)); | |
bpf_printk("Denying access to %s", key.name); | |
return -EPERM; | |
} | |
return 0; | |
} | |
/* Populating the map from the userspace: | |
// populate the deny-list map | |
struct trie_key key; | |
strcpy(key.name, "xyz.log"); | |
key.prefixlen = strlen(key.name) + 1; | |
fprintf(stderr, "Adding %d:%s to denylist\n", key.prefixlen, key.name); | |
err = bpf_map_update_elem(bpf_map__fd(skel->maps.denylist), &key, &key.prefixlen, BPF_ANY); | |
if (err) | |
{ | |
fprintf(stderr, "Failed to populate the denylist - %s\n", strerror(errno)); | |
err = -errno; | |
goto cleanup; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment