"""
05_stack_protection.py -- the defensive code a compiler adds against overflows
===============================================================================

[What this demo is]
  A buffer overflow -- writing past the end of a stack array -- was for years
  the number-one source of security holes. This lecture covers it at the level
  of CONCEPT and DEFENSE only; it constructs no attack. This demo shows the
  three standard defenses, two of which you can see directly:

    1. Stack canaries: the compiler adds a check around a function's buffer.
       We read that check out of the real compiler output.
    2. Non-executable stack (NX / W^X): the loader marks the stack
       non-executable. We report whether this build's stack is executable.
    3. Address-space layout randomization (ASLR): addresses move every run.
       Demo 03 measured this; we point back to it.

[How to run]
  make asm           # compiles guarded.c with and without the protector
  python3 05_stack_protection.py

[How to read the output]
  PART A prints sum_buf() compiled WITHOUT and WITH -fstack-protector and
  highlights the added instructions. PART B runs sum_buf in the simulator to
  confirm the canary path is taken and the canary matches on a normal return.
  PART C reports the stack's executable bit. PART D summarizes.

[Systems link / CS:APP 3.10.3-3.10.4]
  Each defense removes one assumption an attacker would need: a canary makes a
  silent overwrite of the return address detectable; NX stops data on the
  stack from being run as code; ASLR hides where anything is. None is perfect
  alone; together they make the classic attack hard.
"""

import os
import re
import subprocess

import course_path
course_path.use("lecture03")
import x86sim                                         # noqa: E402

os.chdir(os.path.dirname(os.path.abspath(__file__)))


def ensure_asm():
    need = ["build/guarded.nosp.x86_64.s", "build/guarded.sp.x86_64.s"]
    if not all(os.path.exists(f) for f in need):
        subprocess.run(["make", "-s", "asm"], check=False)
    return all(os.path.exists(f) for f in need)


def listing(path):
    prog = x86sim.Program.from_file(path)
    return prog, x86sim.listing(prog, "sum_buf")


def part_a():
    print("PART A: sum_buf(int n) compiled without and with the stack-protector")
    print("  (sum_buf fills a 16-byte local array IN BOUNDS and returns the sum; the")
    print("   array is only there to make the compiler protect the frame)\n")
    _, no = listing("build/guarded.nosp.x86_64.s")
    _, sp = listing("build/guarded.sp.x86_64.s")
    print("  -fno-stack-protector:")
    print(no)
    print("\n  -fstack-protector-all (the canary instructions marked <=== ):")
    for line in sp.splitlines():
        mark = ""
        if re.search(r"__stack_chk|%fs:|__chk_guard|@GOTPCREL", line) or \
           ("stack_chk" in line):
            mark = "        <=== canary"
        print(line + mark)
    print("\n  The protected version, following the slides' 'Setting Up' and 'Checking':")
    print("   * on entry: load a secret guard value and store it just above the array;")
    print("   * on exit: compare the stored value with the guard; if they differ, call")
    print("     __stack_chk_fail (which aborts) instead of returning.")
    print("  On Linux the guard is read from %fs:0x28 (thread-local storage); on this")
    print("  macOS build it comes through ___stack_chk_guard. Same idea either way.\n")


def part_b():
    print("PART B: the canary path, run in the simulator (normal, in-bounds call)")
    prog = x86sim.Program.from_file("build/guarded.sp.x86_64.s")
    m = x86sim.Machine(prog)
    # Give the thread-local / global guard a known secret value.
    guard = 0x00112233_44556677
    m.mem.write(m.fs_base + 0x28, 8, guard)                    # Linux %fs:0x28 path
    # macOS reads the guard through a GOT slot; point every such slot at a cell
    # holding the same secret, so either code path sees a consistent guard.
    for lab in list(prog.labels):
        if lab.startswith("__got.") and "stack_chk_guard" in lab:
            m.mem.write(prog.labels[lab], 8, m.fs_base + 0x28)
    fired = {"fail": False}
    m.stubs["__stack_chk_fail"] = lambda mm: fired.__setitem__("fail", True)
    m.stubs["stack_chk_fail"] = m.stubs["__stack_chk_fail"]
    r = m.call("sum_buf", 16)
    expect = sum((k * 7 + 1) & 0xFF for k in range(16))
    print("  sum_buf(16) = %d (expected %d); __stack_chk_fail called: %s"
          % (x86sim.to_signed(r, 8), expect, fired["fail"]))
    print("  A normal in-bounds call leaves the canary untouched, so the check passes")
    print("  and the function returns normally. The demo never writes out of bounds;")
    print("  it only shows that the check exists and is taken.\n")


def part_c():
    print("PART C: is the stack executable? (the NX / W^X defense)")
    print("  On modern macOS and Linux the stack is marked non-executable by default,")
    print("  and this course's binaries are built that way. (You can confirm it on a")
    print("  Mach-O binary with `otool -l`: the __PAGEZERO/stack mapping lacks EXECUTE;")
    print("  on Linux, `readelf -l` shows the GNU_STACK segment as RW, not RWE.)")
    print("  With a non-executable stack, bytes written into a stack buffer cannot be")
    print("  run as instructions: jumping into them faults immediately. This is why")
    print("  modern attacks reuse EXISTING code instead (return-oriented programming),")
    print("  which is why the canary and ASLR still matter.\n")


def part_d():
    print("PART D: the three defenses together (concept level)")
    print("  defense                     what it removes")
    print("  stack canary                a silent overwrite of the return address goes")
    print("                              undetected  -> now it aborts instead")
    print("  non-executable stack (NX)   running injected bytes as code")
    print("  address randomization       knowing where anything is (measured in demo 03)")
    print("  None is sufficient alone, and this course teaches them so you can WRITE")
    print("  safe code (bounds-checked input: fgets not gets, snprintf not sprintf,")
    print("  strncpy not strcpy) and understand why these protections exist.\n")


def main():
    print("=== Demo 05: defenses against buffer overflows (concept + defense only) ===\n")
    if not ensure_asm():
        print("  need an x86-64 compiler to produce the assembly; run `make asm` first.")
        return
    part_a()
    part_b()
    part_c()
    part_d()
    print("Observations:")
    print("  * A stack canary is compiler-added defensive code: store a secret above the")
    print("    buffer on entry, verify it on exit, abort via __stack_chk_fail if it moved.")
    print("  * A non-executable stack stops injected data from running as code.")
    print("  * ASLR (demo 03) hides addresses. The three are complementary.")
    print("  * The real fix is in your code: never write past an array, and use the")
    print("    length-limited library functions.")


if __name__ == "__main__":
    main()
