Skip to content

Instantly share code, notes, and snippets.

@Kr328
Last active June 10, 2023 10:37
Show Gist options
  • Save Kr328/63ba840dd71d9e97169ed8402018b66a to your computer and use it in GitHub Desktop.
Save Kr328/63ba840dd71d9e97169ed8402018b66a to your computer and use it in GitHub Desktop.
bpf program to store inode to pid mapping.
#include "bpf.h"
#include "external.h"
#include "helpers.h"
#include "ptrace.h"
#include "types.h"
enum module_config_index {
NAMESPACE_DEV,
NAMESPACE_INODE,
};
struct {
UINT(type, BPF_MAP_TYPE_ARRAY);
UINT(key_size, 4);
UINT(value_size, sizeof(u64));
UINT(max_entries, 2);
} module_config SEC(".maps");
struct {
UINT(type, BPF_MAP_TYPE_PERCPU_ARRAY);
UINT(key_size, 4);
UINT(value_size, sizeof(uintptr));
UINT(max_entries, 1);
} local_socket SEC(".maps");
struct {
UINT(type, BPF_MAP_TYPE_LRU_HASH);
UINT(key_size, sizeof(u64));
UINT(value_size, sizeof(u32));
UINT(max_entries, 512);
} inodes SEC(".maps");
SEC("kprobe/sock_alloc_file")
int sock_alloc_file_marker(struct pt_regs *regs) {
u32 index = 0;
uintptr *socket_addr = (uintptr *)bpf_map_lookup_elem(&local_socket, &index);
if (socket_addr == 0) {
return 0;
}
*socket_addr = (uintptr)PT_REGS_PARM1(regs);
return 0;
}
SEC("kretprobe/sock_alloc_file")
int sock_alloc_file_extractor() {
u32 index = 0;
uintptr *socket_addr = (uintptr *)bpf_map_lookup_elem(&local_socket, &index);
if (socket_addr == 0) {
return 0;
}
uintptr file_addr = 0;
if (bpf_probe_read(&file_addr, sizeof(uintptr), *socket_addr + exoffsetof(struct socket, file))) {
return 0;
}
uintptr inode_addr = 0;
if (bpf_probe_read(&inode_addr, sizeof(uintptr), file_addr + exoffsetof(struct file, f_inode))) {
return 0;
}
uintptr inode = 0;
if (bpf_probe_read(&inode, sizeof(uintptr), inode_addr + exoffsetof(struct inode, i_ino))) {
return 0;
}
index = NAMESPACE_DEV;
u64 *self_ns_dev = (u64 *)bpf_map_lookup_elem(&module_config, &index);
if (!self_ns_dev) {
return 0;
}
index = NAMESPACE_INODE;
u64 *self_ns_inode = (u64 *)bpf_map_lookup_elem(&module_config, &index);
if (!self_ns_inode) {
return 0;
}
u64 inode_64 = (u64)inode;
if (*self_ns_dev == 0 && *self_ns_inode == 0) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
bpf_map_update_elem(&inodes, &inode_64, &pid, BPF_ANY);
} else {
struct bpf_pidns_info pid_info = {};
if (bpf_get_ns_current_pid_tgid(*self_ns_dev, *self_ns_inode, &pid_info, sizeof(pid_info))) {
return 0;
}
bpf_map_update_elem(&inodes, &inode_64, &pid_info.tgid, BPF_ANY);
}
return 0;
}
// This file use helpers function that licensed with GPL, so *THIS FILE* should be open sourced
// Source: https://gist.github.com/Kr328/63ba840dd71d9e97169ed8402018b66a
SEC("license")
char LICENSE[] = "GPL";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment