The Kernel is the core. It talks to the hardware. User applications (Ring 3) like Chrome or Python talk to the Kernel to ask for resources ("Open a file", "Send a packet"). Kernel Hacking is the ability to intercept, modify, or subvert these conversations.
Warning
You are about to write code that runs in Kernel Space. There is no segmentation fault protection here. If you write to a NULL pointer, the system does not close your program; the system Panics (Blue Screen/Kernel Panic) and reboots immediately.
1. User Space vs Kernel Space
| Feature | User Space (Ring 3) | Kernel Space (Ring 0) |
|---|---|---|
| Privilege | Low. Cannot touch hardware directly. | Absolute infinite power. |
| Crash Impact | "Segmentation Fault". App dies. OS lives. | "Kernel Panic". Entire OS halts. |
| Memory Access | Virtual Memory (Private). | Physical Memory (Shared). |
2. Writing a Loadable Kernel Module (LKM)
The Linux Kernel is monolithic but modular. You can insert code into a running kernel without rebooting. This is called a Module (`.ko` file).
2.1. The "Hello World" of Ring 0
You need the kernel headers installed: `sudo apt install linux-headers-$(uname -r)`.
2.2. Compiling and Loading
You need a Makefile.
Commands:
1. `make` (Generates `hello_kernel.ko`)
2. `sudo insmod hello_kernel.ko` (Insert module)
3. `dmesg | tail` (View kernel logs. You should see "Hello Ring 0!")
4. `sudo rmmod hello_kernel` (Remove module)
3. Rootkits: The Dark Side of LKMs
A Rootkit is just a malicious LKM. It hides files and processes.
3.1. Hooking the Syscall Table
When you run `ls`, it calls `getdents64` (Get Directory Entries).
A rootkit overwrites the pointer in the system call table.
Now, when the admin runs `ls -la`, the file is physically there, but the OS refuses to admit it exists.
4. Dirty PIPE (CVE-2022-0847)
A recent famous kernel exploit. It allowed any user to overwrite any READ-ONLY file.
How? It abused the `splice()` syscall and how the kernel manages "Pipe Buffers" in memory.
Impact: A user could overwrite `/etc/passwd` to remove the root password, becoming root instantly.
Defense
1. Kernel Signing: Enable "Secure Boot". This prevents loading unsigned `.ko` files (modules).
2. Lockdown Mode: A Linux feature that prevents root from modifying kernel memory.
3. eBPF Monitoring: Use tools like Falco to monitor syscalls for deep anomalies.