BruceFan's Blog

Stay hungry, stay foolish

0%

eBPF LSM阻断文件系统挂载

编写eBPF程序

本文主要介绍eBPF LSM在文件系统挂载方面的基本用法,hook点为sb_mount,对文件系统挂载操作进行监控。这里尝试对tmpfs类型的文件系统挂载操作进行阻断:

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
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_endian.h>

char LICENSE[] SEC("license") = "GPL";

#define EACCES 13
#define BLOCKED_FS "tmpfs"


SEC("lsm/sb_mount")
int BPF_PROG(restricted_mount, const char *dev_name, struct path *path, const char *type, unsigned long flags, void *data)
{
if (type != NULL) {
char kbuf[6] = "";
bpf_probe_read_kernel(kbuf, 5, type);
if (bpf_strncmp(kbuf, 5, BLOCKED_FS) == 0) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
bpf_printk("[LSM] PID %d, Block mount of filesystem type: %s", pid, kbuf);
return -EACCES;
}
}
return 0;
}

编写用户态程序

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
#include <stdio.h>
#include <unistd.h>
#include <sys/resource.h>
#include <bpf/libbpf.h>
#include "lsm_mount.skel.h"

static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
{
return vfprintf(stderr, format, args);
}

int main(int argc, char **argv)
{
struct lsm_mount_bpf *skel;
int err;
/* Set up libbpf errors and debug info callback */
libbpf_set_print(libbpf_print_fn);
/* Open, load, and verify BPF application */
skel = lsm_mount_bpf__open_and_load();
if (!skel) {
fprintf(stderr, "Failed to open and load BPF skeleton\n");
goto cleanup;
}
/* Attach lsm handler */
err = lsm_mount_bpf__attach(skel);
if (err) {
fprintf(stderr, "Failed to attach BPF skeleton\n");
goto cleanup;
}
printf("Successfully started! Please run `sudo cat /sys/kernel/tracing/trace_pipe` "
"to see output of the BPF programs.\n");

for (;;) {
/* trigger our BPF program */
fprintf(stderr, ".");
sleep(1);
}

cleanup:
lsm_mount_bpf__destroy(skel);
return -err;
}

编译运行

将程序放到libbpf-bootstrap中,在Makefile中添加lsm_mount选项,执行:

1
2
3
4
5
6
7
8
9
10
$ make lsm_mount
BPF .output/lsm_mount.bpf.o
GEN-SKEL .output/lsm_mount.skel.h
CC .output/lsm_mount.o
BINARY lsm_mount
$ sudo ./lsm_mount
libbpf: map 'lsm_mount.rodata': created successfully, fd=3
libbpf: map '.rodata.str1.1': created successfully, fd=4
Successfully started! Please run `sudo cat /sys/kernel/tracing/trace_pipe` to see output of the BPF programs.
.........

另起一个终端,尝试挂载tmpfs文件系统:

1
2
3
$ sudo mkdir -p /mnt/tmp
$ sudo mount -t tmpfs tmpfs /mnt/tmp
mount: /mnt/tmp: cannot mount tmpfs read-only.

查看eBPF输出:

1
2
3
$ sudo cat /sys/kernel/tracing/trace_pipe
<...>-2354462 [002] ...11 5532081.669910: bpf_trace_printk: [LSM] PID 2354462, Block mount of filesystem type: tmpfs
<...>-2354462 [002] ...11 5532081.669915: bpf_trace_printk: [LSM] PID 2354462, Block mount of filesystem type: tmpfs

可以看到挂载tmpfs的操作被LSM阻断了。