Trust
Kernel code runs with full power over the machine. Every system call hands it numbers and pointers chosen by a program, which may be hostile. If the kernel trusts them and has a bug, the program borrows that power.
Our toy system call set_name(buf, len) copies a name into an 8-byte field in kernel memory. Right after it sits uid, the program's user id. A uid of 0 means root, which bypasses every permission check.
The attack
Line 1 asks politely: 4 bytes, b, o, b and an end marker. The trap carries the call through the gate, and the handler copies the 4 bytes into name. The uid stays 1000.
Line 2 sends 12 bytes: eight letter A's, then four zero bytes. copy_from_user checks where the bytes come from, and they are in user memory, so that is fine. Nobody checks how many bytes fit.
So the handler copies all 12. Eight bytes fill name, and the last four spill past its end into uid, which now reads 0. This is a buffer overflow: a write past the end of a buffer.
Back in user mode, the program asks for its user id and gets 0. The kernel now treats it as root: it may read any file and load code into the kernel. One missing check gave away the whole machine.
The defences
The fix is one line: if len is more than 8, return EINVAL, invalid argument, before copying anything. Replay line 2 on the fixed kernel and the call fails. The name and uid are untouched.
Line 3 tries another trick: buf points into kernel memory, hoping the kernel copies its own secrets for it. copy_from_user checks the address first. It is not user memory, so the call fails with EFAULT, bad address.
Bugs still slip through, so the CPU helps. SMEP stops kernel mode from running code in user pages. SMAP stops it touching user pages unless the kernel says it expects to. A hijacked kernel cannot just jump into attacker code.
More layers make the next bug harder to use. KASLR moves the kernel to a random address each boot, and stack canaries catch overwrites before a function returns. But checking every argument stays the first line.
What happens
;; step 1/10 · trust attack surface every way in: system calls, files, devices arguments chosen by the caller, so treat them as hostile a system call handler must (Berkeley CS162): copy arguments from user memory into kernel memory validate arguments copy results back a kernel bug runs in kernel mode: no wall stops it
set_name is a toy system call made up for this lesson, and its memory layout is a toy too. Real Linux keeps a process's user ids in a credentials structure, and real exploits take more steps. The shape is the same: a missing check lets user data overwrite kernel data that decides privilege. This lesson shows how an attack works so you can spot and prevent it. Testing attacks on systems you do not own, or without permission, is illegal in most countries.