ENع
→Kernel attacks and defences
الدرس S5 · Special topics

How kernel attacks work and how kernels defend

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل S5 · تفاعلي
01 / 10

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. A 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;
    }
  3. 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)
  4. 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 asked
  5. The 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.
  6. 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 given
  7. The 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      1000
  8. Line 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)
  9. 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)
  10. 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

اختبار يتاح بعد الخطوة الأخيرة.