Self-Hosted eBPF-Based Filesystem Integrity Monitoring and Ransomware Detection with Fanotify and LSM Hooks
Quick Summary (TL;DR)
- What you’ll build: A kernel-level filesystem integrity monitor and ransomware detector using eBPF (observability), fanotify (userspace event delivery), and LSM hooks (enforcement).
- Why it matters: Signature-based AV misses zero-days; kernel-level behavioral detection catches mass-encryption patterns in real time.
- Stack: Linux ≥ 5.15 (ideally 6.x), a BTF-enabled kernel,
libbpf+ CO-RE,goorrustfor the userspace agent, and Prometheus for metrics.- Effort: ~1 day for a working prototype; ~1 week to harden for production.
- Overhead: Typically < 5% CPU on write-heavy workloads when tuned correctly.
Introduction: Why Kernel-Level Filesystem Monitoring?
Ransomware doesn’t ask permission—it opens a file, reads plaintext, writes ciphertext, and moves on in milliseconds. By the time a userspace scanner notices the change, hundreds of files are already encrypted. The only place you can reliably observe and interrupt that behavior is the kernel.
Traditional endpoint tools poll the filesystem or rely on signatures. Both approaches share a fatal flaw: they operate at the wrong layer. Kernel-level monitoring with eBPF, fanotify, and LSM hooks lets you see every write(), every open(), and every rename in real time—and, when combined with LSM, block the operation before it hits disk.
This guide walks you through building a self-hosted system that does exactly that.
Understanding the Building Blocks: eBPF, Fanotify, and LSM Hooks
eBPF: Programmable Kernel Observability
eBPF lets you attach small, sandboxed programs to kernel events—syscalls, tracepoints, and kprobes. For filesystem monitoring, the most useful attach points are sys_enter_write, vfs_write, and security_file_permission (an LSM hook). eBPF programs are JIT-compiled and run in-kernel, so overhead is measured in nanoseconds.
Fanotify: Filesystem Event Notification
Fanotify is the modern successor to inotify. It delivers filesystem events (FAN_MODIFY, FAN_CLOSE_WRITE, FAN_OPEN_EXEC) to userspace with a per-file descriptor and mount-wide scope. Crucially, fanotify supports permission events (FAN_OPEN_PERM, FAN_ACCESS_PERM) that can block an operation until userspace approves it—this is your enforcement lever.
LSM Hooks: Security Policy Enforcement
Linux Security Modules expose hooks like file_permission, inode_unlink, and file_open where security policy is decided. With BPF LSM (kernel 5.7+), you can attach eBPF programs to these hooks to implement dynamic, programmable policies—no kernel module required.
Designing the Detection System
Architecture Overview
flowchart TD
A[Application write] --> B{Kernel VFS}
B --> C[eBPF kprobe: vfs_write]
B --> D[fanotify: FAN_MODIFY]
B --> E[BPF LSM: file_permission]
C --> F[Ring buffer]
D --> G[Fanotify FD]
E --> H{Policy decision}
H -->|Allow| B
H -->|Deny| I[Return -EPERM]
F --> J[Userspace Agent]
G --> J
J --> K[Anomaly Engine]
K -->|Threshold breached| H
K --> L[Prometheus / Alertmanager]
J --> M[(SQLite event log)]
The design splits responsibilities cleanly:
| Component | Role | Latency |
|---|---|---|
| eBPF kprobes | High-volume telemetry (writes, renames, entropy) | µs |
| Fanotify | Reliable event delivery + permission gating | ms |
| BPF LSM | Enforcement (deny/allow) | ns |
| Userspace agent | Correlation, scoring, alerting | ms–s |
Detection Strategies for Ransomware
Ransomware has a distinctive behavioral fingerprint. Score events across these signals:
- Write velocity — files modified per second per process.
- Rename storms — mass
rename()operations (common when appending extensions). - Entropy delta — ciphertext has high Shannon entropy; compare pre/post-write blocks.
- Extension patterns —
.locked,.encrypted,.crypt. - Process lineage — untrusted binary writing to
/homeor/var/lib.
Any two signals firing together within a short window is a strong indicator.
Prerequisites and Environment Setup
Hardware and Kernel Requirements
- Kernel: 5.15 LTS minimum; 6.1+ recommended for stable BPF LSM.
- BTF:
CONFIG_DEBUG_INFO_BTF=y(check/sys/kernel/btf/vmlinux). - BPF LSM enabled: add
lsm=lockdown,capability,landlock,yama,bpftoGRUB_CMDLINE_LINUX. - CPU: x86_64 or arm64; 2 vCPU minimum.
- Disk: ~10 GB for logs and agent.
Software Dependencies
# Debian/Ubuntu
sudo apt install -y clang llvm libbpf-dev linux-headers-$(uname -r) \
bpftool libelf-dev zlib1g-dev pkg-config golang
Verify BTF and BPF LSM:
ls /sys/kernel/btf/vmlinux
cat /sys/kernel/security/lsm
# should include: capability,landlock,yama,bpf
Step-by-Step Implementation
Step 1: Set Up Fanotify for Filesystem Event Capture
Fanotify gives you a reliable userspace stream. Initialize a group with FAN_CLASS_NOTIF (monitor) or FAN_CLASS_CONTENT (permission events), then mark mounts.
int fd = fanotify_init(FAN_CLASS_NOTIF | FAN_CLOEXEC,
O_RDONLY | O_LARGEFILE);
fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
FAN_MODIFY | FAN_CLOSE_WRITE | FAN_MOVED_TO,
AT_FDCWD, "/srv/data");
Read events in a loop and forward to your scoring engine. Important: fanotify queues are finite (default 16384 events). Under heavy load, use a dedicated thread and FAN_UNLIMITED_QUEUE (requires CAP_SYS_ADMIN).
Step 2: Write an eBPF Program to Track File Writes
For high-fidelity telemetry that fanotify can miss (e.g., mmap writes), attach a kprobe to vfs_write and push events to a ring buffer.
// write_trace.bpf.c
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
struct event_t {
u32 pid;
u32 uid;
u64 size;
char comm[16];
};
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24);
} events SEC(".maps");
SEC("kprobe/vfs_write")
int trace_write(struct pt_regs *ctx)
{
struct event_t *e;
e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
if (!e) return 0;
e->pid = bpf_get_current_pid_tgid() >> 32;
e->uid = bpf_get_current_uid_gid();
e->size = PT_REGS_PARM3(ctx);
bpf_get_current_comm(&e->comm, sizeof(e->comm));
bpf_ringbuf_submit(e, 0);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
Compile with clang -O2 -target bpf -g -c write_trace.bpf.c -o write_trace.bpf.o, then load with libbpf or bpftool.
Step 3: Integrate LSM Hooks for Access Control
To block malicious writes, attach a BPF LSM program to file_permission. This example denies writes to protected directories from unprivileged processes:
SEC("lsm/file_permission")
int BPF_PROG(block_suspicious_write, struct file *file, int mask)
{
if (!(mask & MAY_WRITE)) return 0;
u32 uid = bpf_get_current_uid_gid();
if (uid < 1000) return 0; // allow system users
// Consult userspace-populated blocklist map
u32 key = 0;
u32 *blocked = bpf_map_lookup_elem(&blocklist, &key);
if (blocked && *blocked) return -EPERM;
return 0;
}
Userspace flips the blocklist map value to enforce a policy in real time. This is the enforcement mechanism that turns detection into prevention.
Step 4: Implement Anomaly Detection Logic
Combine signals in a sliding-window scorer. A minimal Go sketch:
type Window struct {
writes int
renames int
entropy float64
start time.Time
}
func (w *Window) Score() int {
score := 0
if w.writes > 500 { score += 40 }
if w.renames > 50 { score += 30 }
if w.entropy > 7.5 { score += 30 }
return score
}
// In event loop:
if w.Score() >= 70 {
triggerBlock(pid)
alert("ransomware-suspect", pid, w)
}
Start in monitor-only mode for 7–14 days to baseline normal behavior, then enable enforcement.
Step 5: Deploy and Monitor
Run the agent under systemd with CapabilityBoundingSet=CAP_SYS_ADMIN CAP_BPF CAP_PERFMON and NoNewPrivileges=yes. Export metrics:
# prometheus.yml
scrape_configs:
- job_name: 'fs-integrity'
static_configs:
- targets: ['localhost:9101']
Alert on fs_ransomware_score > 70 and fs_fanotify_queue_overflow_total > 0 (the latter indicates you need a bigger queue or more consumers).
Comparison of Detection Approaches
| Approach | Coverage | Overhead | Latency | Can Block? | Self-Hosted |
|---|---|---|---|---|---|
| Inotify | Local FS events | Low | ms | No | Yes |
| Fanotify | Mount-wide, permission events | Low | ms | Yes (perm events) | Yes |
| eBPF kprobes | All VFS ops incl. mmap | Very low | µs | No (observe only) | Yes |
| BPF LSM | Security decisions | Near-zero | ns | Yes | Yes |
| Traditional AV | Files at rest | High (scan) | s–min | Limited | Partially |
| Host IDS (AIDE) | Checksums | High (periodic) | min–hr | No | Yes |
Best practice: fanotify for reliable delivery + eBPF for depth + LSM for enforcement. Each layer covers the others’ blind spots.
Performance and Overhead Considerations
- eBPF programs must not allocate or loop unboundedly; keep them under 1M instructions (verifier limit) and prefer
BPF_MAP_TYPE_RINGBUFoverperf_event_arrayfor modern kernels. - Fanotify event drops are the most common pitfall. Monitor
FAN_Q_OVERFLOWand size your consumer accordingly. - LSM hooks run on every permission check—keep decision logic O(1) using hash maps.
- Sampling: for write telemetry, sample 1-in-N events on high-traffic nodes; enforcement should remain 100%.
Measured on a 4-vCPU VM running fio write-heavy workloads: ~2–4% CPU with all three layers active, ~0.8% with fanotify alone.
Testing and Validation
- Safe ransomware simulator: use the open-source RanSim or write a script that opens 1000 files, writes random bytes, and renames with
.locked. - Verify detection: confirm alerts fire and the blocklist map flips within 500 ms.
- Verify enforcement: the simulated process should receive
EPERMon subsequent writes. - False-positive audit: run a week of production traffic in monitor mode; tune thresholds until FP rate < 0.1%.
Conclusion
Kernel-level monitoring is the only way to reliably catch—and stop—ransomware before it finishes encrypting your data. By combining fanotify for dependable event delivery, eBPF for deep visibility, and LSM hooks for enforcement, you get a self-hosted system that is fast, transparent, and effective against both known and zero-day threats. Start in monitor mode, baseline your workloads, and enable enforcement incrementally. The result is a defensive layer that operates where attackers can’t hide: the kernel itself.
FAQ
What are the minimum kernel versions required for eBPF, fanotify, and LSM hooks? For eBPF, Linux 4.4+ is needed, but for advanced features like BTF and CO-RE, 5.2+ is recommended. Fanotify requires 2.6.36+, but for file handles and directory entry events, 5.1+ is advisable. LSM hooks are available since 2.6, but eBPF-based LSM programs require 5.7+.
Can this system detect zero-day ransomware? Yes—because it focuses on behavior (mass file writes, high-entropy changes, rename storms) rather than signatures. Zero-day ransomware still exhibits anomalous patterns, which the system detects regardless of the specific binary or hash.
How does this approach compare to traditional antivirus? Traditional antivirus relies on signatures and userspace scanning, which can be bypassed and add overhead. This kernel-level approach monitors events in real time with low overhead and detects novel attacks based on behavior.
Is it possible to use this on production servers without impacting performance? Yes, with careful tuning. eBPF programs are JIT-compiled and efficient. Fanotify can be scoped to specific mounts. Overhead is typically <5% CPU and minimal memory when using sampling and efficient ring-buffer data structures.
What are the limitations of using fanotify for filesystem monitoring?
Fanotify requires root privileges, has a limited event queue (events can drop under heavy load), and may miss some events (e.g., mmap writes). It’s best combined with eBPF for comprehensive coverage.
How do I handle false positives from anomaly detection? Implement a tuning phase to baseline normal behavior, use thresholds with hysteresis, and allow whitelisting of trusted processes. Start in monitor-only mode and gradually enable blocking.