TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Stack Canaries, NX and Why ROP Exists

Stack Canaries, NX and Why ROP Exists

The classic stack-overflow attack of the 1990s had three steps: overflow a local buffer, overwrite the saved return address, and make it point back into the buffer, where the attacker had placed machine code. Two mitigations broke that recipe. Stack canaries detect the overwrite before the function returns. NX (no-execute, called DEP on Windows) makes the stack and heap non-executable, so bytes placed there can't run. Attackers answered NX with return-oriented programming (ROP), which reuses code that is already executable instead of injecting new code; ROP is why the later mitigations of this section (CFI, shadow stacks, pointer authentication) exist. This lesson explains each step as a concept, shows the protections in your sandbox and on the stack-frame model, and deliberately stops there: no shellcode, no gadgets, no chains. Security Foundations' Memory Protection already showed checksec and an executable-stack build; this lesson goes one level deeper.

Stack canaries

A canary (from the canary in a coal mine) is a random word the compiler places between a function's local arrays and its saved registers. The prologue copies it from a per-thread location (fs:0x28 on x86-64 Linux); the epilogue compares it before ret and calls __stack_chk_fail if it changed, which prints *** stack smashing detected *** and aborts. You saw this code in Stack Frames.

Instrumenting every function would cost a few instructions each, so compilers choose:

Option Protects functions that have Default
-fstack-protector char arrays of 8 bytes or more (or alloca) older distributions
-fstack-protector-strong any local array, or any local whose address is taken Ubuntu's gcc; Debian, Fedora and Android package builds
-fstack-protector-all every function rarely; costly
-fno-stack-protector none kernels and firmware sometimes

The session compiles one file with six small functions under each option and lists the functions whose code calls __stack_chk_fail, i.e. the functions that got a canary. It runs in your sandbox:

bash · try it yourself
cat > funcs.c <<'SRC'
#include <stdio.h>
#include <string.h>
int add(int a, int b) { return a + b; }                                   /* no locals in memory */
int sum4(const int *v) { int s = 0; for (int i = 0; i < 4; i++) s += v[i]; return s; }
void greet(const char *n) { char buf[16]; strcpy(buf, n); puts(buf); }    /* char array */
void count(int *out) { int local = 0; int *p = &local; *p = 3; *out = local; }  /* address taken */
int table(int i) { int t[4] = {1, 2, 3, 4}; return t[i & 3]; }           /* int array */
int main(void) { int x; count(&x); greet("lab"); int v[4] = {1, 2, 3, 4}; return add(x, sum4(v)) + table(1) > 100; }
SRC
for p in -fno-stack-protector -fstack-protector -fstack-protector-strong -fstack-protector-all; do
  gcc -O0 $p funcs.c -o f
  printf "%-26s" "$p"
  for fn in add sum4 greet count table main; do
    objdump -d --no-show-raw-insn f | awk -v f="<$fn>:" '$2==f{on=1;next} /^$/{on=0} on' | grep -q __stack_chk_fail && printf " %s" $fn
  done; echo
done
-fno-stack-protector
-fstack-protector          greet
-fstack-protector-strong   greet count table main
-fstack-protector-all      add sum4 greet count table main

-fstack-protector covers only greet (the char buf[16]); -strong adds count (address taken), table (an int array) and main (it has the array v and takes the address of x). Only -all adds the two functions with nothing to protect. -strong is the usual compromise.

What canaries don't stop: overwrites that skip the canary (an indexed write buf[i] = x with a chosen i), overwrites of locals between the buffer and the canary (a function pointer in the same frame), overflows on the heap, and any attack where the canary value has leaked (it is the same for the whole process, so a format string leak or an over-read reveals it). A forking server that doesn't re-randomise after fork lets an attacker guess it byte by byte through crashes.

NX / DEP

Every page has an execute permission bit (NX on x86-64, XN on Arm). The loader maps the stack, heap and data rw- and code r-x; the CPU refuses to fetch instructions from a page without execute permission and the kernel kills the process with SIGSEGV. A binary can still ask for an executable stack (GNU_STACK with RWE, produced by -z execstack or by old assembly files without a .note.GNU-stack section); checksec reports it as NX disabled. JIT compilers are the legitimate exception: they need memory that is writable while code is generated and executable afterwards; hardened JITs switch permissions (W^X) rather than map pages rwx, though some still use rwx pages, a known weak spot.

The model: where would the return go?

The model extends the stack-frame model with a tiny address map. After an overflow, the overwritten return address points somewhere, and the program's fate depends on what is there. Nothing is executed: the model only classifies the target the way the CPU and the mitigations would. Targets are labels, not real addresses. It runs in your browser:

python · try it yourself
REGIONS = {                          # name: (permissions, what it holds)
    "program code": ("r-x", "the program's own functions"),
    "libc code":    ("r-x", "library functions already in memory"),
    "stack":        ("rw-", "local variables, including the overflowed buffer"),
    "heap":         ("rw-", "malloc'd data"),
    "unmapped":     ("---", "nothing"),
}

def outcome(target, nx=True, canary_intact=False, canary=True, shadow_stack=False):
    if canary and not canary_intact:
        return "stopped: canary changed -> stack smashing detected"
    if shadow_stack:
        return "stopped: return address differs from the shadow stack"
    perms, _ = REGIONS[target]
    if perms == "---":
        return "crash: SIGSEGV, nothing mapped there"
    if "x" not in perms:
        return "stopped by NX: SIGSEGV, page not executable" if nx else "INJECTED CODE RUNS (no NX)"
    return "runs EXISTING code: NX can't help -> the reason for ROP, CFI and shadow stacks"

print("1. no canary, no NX (the 1990s):")
for t in ("stack", "unmapped"):
    print(f"   return into {t:12} -> {outcome(t, nx=False, canary=False)}")
print("2. NX on, still no canary:")
for t in ("stack", "heap", "libc code", "program code"):
    print(f"   return into {t:12} -> {outcome(t, canary=False)}")
print("3. canary on (linear overflow destroyed it):")
print(f"   return into {'libc code':12} -> {outcome('libc code')}")
print("4. canary leaked and rewritten intact, shadow stack on:")
print(f"   return into {'libc code':12} -> {outcome('libc code', canary_intact=True, shadow_stack=True)}")
1. no canary, no NX (the 1990s):
   return into stack        -> INJECTED CODE RUNS (no NX)
   return into unmapped     -> crash: SIGSEGV, nothing mapped there
2. NX on, still no canary:
   return into stack        -> stopped by NX: SIGSEGV, page not executable
   return into heap         -> stopped by NX: SIGSEGV, page not executable
   return into libc code    -> runs EXISTING code: NX can't help -> the reason for ROP, CFI and shadow stacks
   return into program code -> runs EXISTING code: NX can't help -> the reason for ROP, CFI and shadow stacks
3. canary on (linear overflow destroyed it):
   return into libc code    -> stopped: canary changed -> stack smashing detected
4. canary leaked and rewritten intact, shadow stack on:
   return into libc code    -> stopped: return address differs from the shadow stack

Read the four cases as the history of the arms race. Without protections, returning into the stack runs whatever the attacker put there. NX stops that, but a return into code that is already executable (the program's own functions, or the C library's) is still allowed: from the CPU's point of view it is an ordinary return. The canary stops linear overflows before the return happens, unless the canary leaked. A shadow stack stops the corrupted return in any case, because the return address no longer matches the copy the CPU kept.

The stack-frame lab shows where in the epilogue each check fires. A 40-byte write into a 16-byte buffer overwrites the canary, the saved rbp and the return address, and the canary check aborts before leave. Turn the canary off and the shadow stack on: the write now reaches the return address and the caller's frame, leave runs, and the CPU raises a control-protection fault at ret. With both off, ret pops a return address made of 0x41 bytes.

offsetbytes, address →contents (rows grow ↑)rbp+0x58rbp+0x50rbp+0x48rbp+0x40rbp+0x38rbp+0x30rbp+0x28rbp+0x20rbp+0x18rbp+0x10caller's frame (main)rbp+0x08AAAAAAAAret → 0x4141414141414141rbp+0x00AAAAAAAAsaved rbp: 8 bytes = 0x41rbp−0x08AAAAAAAAcanary: 8 bytes changedrbp−0x10AAAAAAAArbp−0x18AAAAAAAAchar buf[16]void greet(int fd) {char buf[16];read(fd, buf, 40);}✓ copy input✕ check canary– leave (pop rbp)– retcaught: canarycanary check failsbefore leave: "stacksmashing detected",abortabstract model: placeholder values, only 'A' (0x41) bytes are written

Return-oriented programming, as a concept

Case 2 is the opening ROP uses. Executable memory is full of short instruction sequences that end in ret, each doing some small thing (move a value, add two registers). If an attacker can write a series of return addresses on the stack, each ret jumps to the next sequence, and the sequences together behave like a program built from pieces of existing code. No byte of new code is executed, so NX never fires. Return-to-libc, its simpler ancestor, returns directly into one library function.

return addr 1 return addr 2 return addr 3 overwritten stack (rw-) existing code ... ret existing code ... ret existing code ... ret program and library code (r-x) stopped by:shadow stackPAC on retCFI (calls) NX is never triggered: every instruction that runs was already executable

ROP needs two things the defences now attack: knowing where code is (ASLR hides it, so ROP needs an address leak first) and being allowed to return anywhere (shadow stacks and pointer authentication allow returns only to the real caller; CFI restricts indirect calls and jumps). The next lessons cover them: ASLR, PIE and RELRO and CFI, Shadow Stacks and Pointer Authentication.

How weak builds are detected

checksec --file=prog shows Canary found and NX enabled; readelf -lW prog | grep GNU_STACK must show RW, not RWE; objdump -d prog | grep __stack_chk_fail shows instrumented functions. Build pipelines should fail on a missing canary or NX for any shipped binary (Mitigations Compared).

Pitfalls

  • Canary failures are bugs, not noise. A stack smashing detected crash proves an out-of-bounds write; investigate it as a vulnerability.
  • Mixing old objects. One assembly file without .note.GNU-stack can make the linker mark the whole program's stack executable. Link with -Wl,-z,noexecstack and check.
  • "NX makes overflows harmless." It removes code injection, not control of the return address.

Practice

1. Why did main get a canary under -fstack-protector-strong but not under -fstack-protector?

main has an int array v[4] and passes &x to count. -strong protects functions with any local array or address-taken local; plain -fstack-protector only those with char arrays of 8 bytes or more.

2. In the model, which mitigation would have stopped case 2 (return into libc code)?

A canary (if the overflow was linear and the canary didn't leak) or a shadow stack / return-address signing. NX can't, because the target is legitimately executable.

3. Why does ROP usually need an information leak first?

With ASLR, the addresses of the program and its libraries are random at each start. Without a leaked pointer the attacker doesn't know where the existing code fragments are.

Test yourself

Which functions get a canary with -fstack-protector-strong?

  1. All functions
  2. Functions with any local array or an address-taken local
  3. Only functions with char arrays of 8+ bytes
  4. Only main

What does NX prevent?

  1. Overwriting the return address
  2. Executing instructions from pages that are not marked executable, such as the stack and heap
  3. Reading the stack
  4. Library calls

Why doesn't NX stop return-oriented programming?

  1. ROP disables NX
  2. ROP only executes code that is already in executable pages
  3. ROP runs in the kernel
  4. NX is off by default

What can defeat a stack canary?

  1. Nothing
  2. A leak of the canary value, or a write that skips over it (indexed write)
  3. Compiling with -O2
  4. Using printf

In the stack-frame lab, the canary is off and the shadow stack is on. At which step does a 40-byte overflow of the 16-byte buffer get stopped?

  1. During the copy
  2. At the canary check
  3. At leave
  4. At ret, when the return address doesn't match the shadow copy