How kernel attacks work and how kernels defend
About this lesson
The kernel runs with full power, and every system call hands it numbers and pointers chosen by a program that may be hostile. Follow a toy system call with one missing check: a program sends 12 bytes into an 8-byte field, the extra 4 bytes overwrite its user id, and it becomes root. Then watch the defences: the one-line fix, copy_from_user refusing kernel addresses, the CPU's SMEP and SMAP guards, KASLR and stack canaries. User mode and kernel mode explains the wall and the gate, and Protection, privilege and sandboxing covers user ids and permission checks.
Kernel code has full power
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.
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
Read the lesson step by step
Kernel code has full power
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.
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 itA toy system call
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.
kernel memory (toy layout): 0x9000 name[8] 8 bytes 0x9008 uid 4 bytes = 1000 (an ordinary user) uid 0 = root: "Privileged processes bypass all kernel permission checks" (capabilities(7)) the whole toy, kernel and attacker, as C99: #include <stdint.h> #include <stdio.h> #include <string.h> /* A toy machine: user memory below USER_END, kernel memory above. */ #define USER_END 0x8000u #define NAME 0x9000u /* kernel: char name[8] */ #define UID 0x9008u /* kernel: uint32_t uid, next */ #define SECRET 0xA000u /* kernel: something private */ static unsigned char mem[0x10000]; static int checked = 0; /* 0: buggy handler, 1: fixed */ /* returns how many bytes it could NOT copy (0 = all copied) */ static unsigned copy_from_user(unsigned dst, unsigned src, unsigned len) { if (src >= USER_END || len > USER_END - src) return len; memcpy(&mem[dst], &mem[src], len); return 0; } static const char *set_name(unsigned buf, unsigned len) { if (checked && len > 8) return "EINVAL"; if (copy_from_user(NAME, buf, len)) return "EFAULT"; return "0"; } static uint32_t uid(void) { uint32_t u; memcpy(&u, &mem[UID], 4); return u; } static void boot(void) { uint32_t u = 1000; memset(&mem[NAME], 0, 8); memcpy(&mem[UID], &u, 4); } int main(void) { const char *r; memcpy(&mem[0x1000], "bob", 4); /* user memory */ memcpy(&mem[0x2000], "AAAAAAAA\0\0\0\0", 12); /* user memory */ memcpy(&mem[SECRET], "s3cret!", 7); boot(); r = set_name(0x1000, 4); printf("line 1: %s, uid %u\n", r, (unsigned)uid()); r = set_name(0x2000, 12); printf("line 2: %s, uid %u\n", r, (unsigned)uid()); boot(); checked = 1; r = set_name(0x2000, 12); printf("fixed line 2: %s, uid %u\n", r, (unsigned)uid()); r = set_name(SECRET, 8); printf("line 3: %s, uid %u\n", r, (unsigned)uid()); return 0; }Line 1: a polite call
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 1 set_name("bob", 4); trap syscall: user mode -> kernel mode copy 4 bytes from user memory into name name b o b \0 . . . . (4 of 8 bytes used) uid 1000 return 0 (success)Line 2: too many bytes
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.
line 2 set_name(evil, 12); evil A A A A A A A A 00 00 00 00 (12 bytes) handler copy_from_user(name, buf, len); where? buf .. buf+12 in user memory ok how many fit in name? never askedThe bytes spill over
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.
name (8 bytes) uid (4 bytes) before b o b 00 . . . . 1000 after A A A A A A A A 00 00 00 00 = 0 bytes 9 to 12 land on the next field in memory. C does not stop a copy at the end of a field: only the length the code passes does.The program is now root
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.
getuid() 0 kernel uid 0 = root: permission checks bypassed read /etc/shadow, load a kernel module, ... this is privilege escalation: a user program gains powers it was never givenThe fix: one check
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.
fixed if (len > 8) return -EINVAL; copy_from_user(name, buf, len); line 2 set_name(evil, 12); check 12 > 8 -> -EINVAL (Invalid argument) copy never happens uid 1000Line 3: a kernel pointer
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.
line 3 set_name(kptr, 8); kptr 0xA000, in kernel memory (user ends at 0x8000) copy_from_user checks the source range first: 0xA000 >= 0x8000 -> -EFAULT (Bad address) Linux: the kernel "has to verify this address" before touching user memory (access_ok)The CPU guards the kernel
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.
x86-64 guards (ARM: PXN and PAN): SMEP kernel mode may not run user pages SMAP kernel mode may not read or write user pages, except inside copy routines like copy_from_user "The kernel must never execute userspace memory." (kernel.org, Kernel Self-Protection)Defence in depth
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.
KASLR kernel base address randomized at boot stack canary a guard value before the return address, checked before the function returns SMEP / SMAP hardware wall around user pages checks validate every argument (the real fix) the toy as a Python simulation: mem = bytearray(0x10000) # toy machine: user < 0x8000 <= kernel USER_END, NAME, UID = 0x8000, 0x9000, 0x9008 mem[0x1000:0x1004] = b"bob\0" mem[0x2000:0x200c] = b"A" * 8 + bytes(4) checked = False def copy_from_user(dst, src, n): # refuses kernel addresses if src >= USER_END or n > USER_END - src: return n mem[dst:dst + n] = mem[src:src + n] return 0 def set_name(buf, n): if checked and n > 8: return "EINVAL" return "EFAULT" if copy_from_user(NAME, buf, n) else "0" uid = lambda: int.from_bytes(mem[UID:UID + 4], "little") mem[UID:UID + 4] = (1000).to_bytes(4, "little") print("line 1:", set_name(0x1000, 4) + ", uid", uid()) print("line 2:", set_name(0x2000, 12) + ", uid", uid()) mem[UID:UID + 4] = (1000).to_bytes(4, "little") checked = True # the fix print("fixed line 2:", set_name(0x2000, 12) + ", uid", uid()) print("line 3:", set_name(0xA000, 8) + ", uid", uid()) prints: line 1: 0, uid 1000 line 2: 0, uid 0 fixed line 2: EINVAL, uid 1000 line 3: EFAULT, uid 1000
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Why must a system call handler treat its arguments as hostile?
Any program can make a system call with any values it likes. The handler runs in kernel mode, so a bug that trusts those values lets the caller use the kernel's power.
02set_name copies len bytes into an 8-byte field, and uid sits right after it. The caller passes 12 bytes: eight A's then four zero bytes. Without a length check, what happens?
C does not stop a copy at the end of a field: only the length passed in does. Bytes 9 to 12 land on uid, and uid 0 is root.
03What is the right fix in the handler?
Validating every argument is the first line of defence. A bigger field just moves the problem: an attacker would send 16 bytes.
04Line 3 passes a pointer into kernel memory as buf. What stops it?
copy_from_user checks the address range first (Linux uses access_ok) and returns the number of bytes it could not copy. A non-zero result means the handler returns -EFAULT.
05Which pair is matched correctly?
SMEP stops kernel mode running user pages, SMAP stops it touching user pages it did not expect to, KASLR randomizes where the kernel sits, and a stack canary catches an overwrite before a function returns.
Glossary
- Attack surface
- Every way a program can reach kernel code: system calls, files, devices and more. Each one takes input the kernel must check.
- Buffer overflow
- Writing past the end of a buffer, so the extra bytes overwrite whatever sits next to it in memory.
- Privilege escalation
- When a program gains powers it was never given, for example an ordinary user becoming root.
- uid (user id)
- The number the kernel uses to decide what a process may do. 0 is root, which bypasses permission checks.
- copy_from_user
- The Linux kernel routine that copies bytes from a program's memory into kernel memory. It checks that the source is user memory and returns how many bytes it could not copy.
- EINVAL / EFAULT
- Error codes a system call returns: EINVAL means invalid argument, EFAULT means bad address.
- SMEP and SMAP
- x86-64 CPU features. SMEP stops kernel mode running code in user pages; SMAP stops it touching user pages unless the kernel says it expects to.
- KASLR
- Kernel address space layout randomization: the kernel is placed at a random address at each boot, so an attacker cannot know where to aim.
Notes and sources
- 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.
- The toy splits its 64 KiB address space at 0x8000: user memory below, kernel memory above. Linux on x86-64 splits it the same way in spirit, with user space in the low half and the kernel in the high half.
- In Linux, copy_from_user returns the number of bytes it could not copy, so a non-zero result means failure and the handler returns -EFAULT. The toy does the same. The errors are returned as negative numbers inside the kernel; the C library turns them into -1 and sets errno.
- SMEP and SMAP are features of x86-64 CPUs; ARM CPUs have similar ones called PXN and PAN. With SMAP on, the kernel's copy routines such as copy_from_user mark the moments when they expect to touch user memory; any other touch faults.
- 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.
- Berkeley CS162, Lecture 4 (slide: Kernel System Call Handler: Safe Entry into Kernel)
- Linux kernel documentation: Kernel Self-Protection
- Linux kernel documentation: x86 exception tables (verifying user addresses, access_ok, -EFAULT)
- Linux source: include/linux/uaccess.h (copy_from_user)
- MIT 6.1810 (2024), lecture notes: System call entry/exit
- Linux man-pages: capabilities(7)
- Linux man-pages: credentials(7)
- Linux man-pages: errno(3)
- Linux man-pages: write(2)
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution
Quiz Unlocks after the last step.