From 8b7352f290945b4faf174fb5a09b264d9eaa6f8e Mon Sep 17 00:00:00 2001 From: li-long315 Date: Mon, 26 Jun 2023 09:21:53 +0800 Subject: [PATCH] Set up a BPF program to track and record tty write operations --- observation/src/ttysnoop/ttysnoop.bpf.c | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 observation/src/ttysnoop/ttysnoop.bpf.c diff --git a/observation/src/ttysnoop/ttysnoop.bpf.c b/observation/src/ttysnoop/ttysnoop.bpf.c new file mode 100644 index 00000000..ce328575 --- /dev/null +++ b/observation/src/ttysnoop/ttysnoop.bpf.c @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) +#include "vmlinux.h" +#include +#include +#include +#include "ttysnoop.h" +#include "compat.bpf.h" +#include "core_fixes.bpf.h" + +#define WRITE 1 +#define ITER_UBUF 6 + +const volatile int user_data_count = 16; +const volatile int pts_inode = -1; + +static int +do_tty_write(void *ctx, const struct file *file, const char *buf, size_t count) +{ + if (BPF_CORE_READ(file, f_inode, i_ino) != pts_inode) + return 0; + + if (count < 0) + return 0; + + for (int i = 0; i < user_data_count && count; i++) { + struct event *event = reserve_buf(sizeof(*event)); + + if (!event) + break; + + /** + * bpf_probe_read_user() can only use a fixed size, so truncate + * to count in user space + */ + if (bpf_probe_read_user(&event->buf, BUFSIZE, (void *)buf)) { + discard_buf(event); + break; + } + + if (count > BUFSIZE) { + event->buf[BUFSIZE] = 0; + event->count = BUFSIZE; + } else { + event->count = count; + event->buf[count] = 0; + } + + submit_buf(ctx, event, sizeof(*event)); + + if (count < BUFSIZE) + break; + + count -= BUFSIZE; + buf += BUFSIZE; + } + + return 0; +} + -- Gitee