Stack Canaries and Guard Pages
Stack canaries are a compiler trick aimed squarely at stack buffer overflows. The idea: park a secret value, the canary, between your locals and the saved return address. Just before returning, check it. If the value has shifted, something overflowed, and the program kills itself rather than jumping somewhere an attacker chose.
Once you've seen what the compiler emits, both sides — the defender writing safer code and the researcher poking at it — make a lot more sense.
How GCC's -fstack-protector Works
When you compile with -fstack-protector, GCC inserts canary setup code in the function prologue and a canary check in the epilogue.
Here is what the compiler generates for a function with a local buffer:
; Function prologue WITH stack canaryvulnerable_function: push rbp mov rbp, rsp sub rsp, 80 ; allocate local variables
; === Canary insertion === mov rax, qword [fs:0x28] ; load canary value from TLS mov qword [rbp - 8], rax ; store canary just below saved rbp
; ... function body ... ; local buffer is at [rbp - 72] (64 bytes) ; canary is at [rbp - 8] (8 bytes) ; saved rbp is at [rbp] ; return address is at [rbp + 8]
; === Canary check (epilogue) === mov rax, qword [rbp - 8] ; load canary from stack xor rax, qword [fs:0x28] ; compare with original value jne .canary_fail ; if different, overflow detected!
leave ret
.canary_fail: call __stack_chk_fail ; terminates the programThe Stack Layout with a Canary
The canary sits between the local variables (which a buffer overflow would overwrite first) and the saved frame pointer and return address (which the attacker wants to overwrite). Offsets in the view count up from the start of the buffer at rbp - 72: the buffer is bytes 0-63, the 8-byte canary is 64-71 (its first byte is the zero), saved rbp is 72-79, and the return address starts at 80. The view colours only the canary's first byte and the return address's first byte; the rest of each 8-byte value appears under "Saved Regs".
Stack Frame View
To see why the ordering matters, type into the simulator below, which models a 64-byte buffer with the canary straight after it. Up to 64 characters stay in the buffer. Character 65 starts eating the canary, and that happens before any byte can reach the saved rbp or the return address. The function's epilogue compares the canary against the original copy and calls __stack_chk_fail instead of returning. The simulator shows a placeholder canary value. A real glibc canary is random, with its lowest byte forced to zero so string functions stop at it.
Buffer Overflow Simulator
Input: 0 bytes | Buffer: 64 bytes | Overflow: 0 bytes
Stack (high addresses at top):
Where the Canary Value Comes From
The canary is stored in the thread control block (TCB) at the start of the thread-local storage area, which the fs segment register points at, so it lives at fs:0x28. The kernel doesn't write it there directly. At execve it places 16 random bytes on the new process's stack and passes their address in the AT_RANDOM auxiliary vector entry; glibc's startup code reads those bytes, zeroes the lowest one, and stores the result in the TCB before main runs. New threads copy the same value.
; Load the canary from TLS mov rax, [fs:0x28] ; fs:0x28 = thread-local canary value ; This value is: ; - Random (set at process startup) ; - Contains a null byte in the least significant byte position (0xXXXXXXXXXXXX00) ; - Different for every exec'd process (fork() children inherit it)The null byte in the canary is deliberate: it prevents string functions like strcpy from reading past the canary. Since strcpy stops at null bytes, an attacker cannot use strcpy to read the canary value through the overflow itself.
__stack_chk_fail
When the canary check fails, the function calls __stack_chk_fail, which prints an error message and terminates the process with SIGABRT:
*** stack smashing detected ***: terminatedAborted (core dumped)This is a controlled crash. The program terminates before the corrupted return address is used, preventing the attacker from gaining code execution. The crash is intentional - a dead process is safer than a compromised one.
GCC Protection Levels
GCC offers several levels of stack protection:
| Flag | Behavior |
|---|---|
-fstack-protector | Protect functions with local buffers > 8 bytes |
-fstack-protector-strong | Protect functions with any arrays, address-taken locals |
-fstack-protector-all | Protect every function (performance cost) |
-fno-stack-protector | Disable protection entirely |
Most distributions default to -fstack-protector-strong, which provides good coverage with minimal performance impact.
Guard Pages
Guard pages complement stack canaries by detecting stack overflows that are too large for the canary to catch (e.g., overflowing past the entire stack frame).
A guard page is a page of memory mapped with PROT_NONE (no read, write, or execute permissions) placed at the boundary of the stack. Any access to this page causes an immediate segmentation fault.
The two kinds of stack get their guards from different places. For the main thread, the kernel keeps a gap below the stack (256 pages, 1 MiB with 4 KiB pages, tunable with the stack_guard_gap= boot parameter) where it won't place any other mapping. Thread stacks are allocated by glibc's pthread_create, which puts a PROT_NONE guard page at the end of each one (one page by default, changeable with pthread_attr_setguardsize).
Neither guard is infinite. A function that allocates a frame bigger than the gap, through a huge local array or alloca, can move rsp straight past the guard and land in the heap or another mapping without ever touching it. Qualys published this as Stack Clash in 2017, which is why the kernel's gap grew from one page to 256. The compiler-side fix is -fstack-clash-protection (GCC 8+, Clang 11+), which makes large stack allocations probe each page in turn so the guard is always hit first. Canaries do nothing against this, so you want both.
Hover over each step to see details
Implementing a Manual Canary
To truly understand the mechanism, here is a manual canary implementation:
section .data safe_msg db "SAFE", 10 safe_len equ $ - safe_msg corrupt_msg db "CORRUPT", 10 corrupt_len equ $ - corrupt_msg
section .text global _start
_start: push rbp mov rbp, rsp
; Place our canary value sub rsp, 8 mov rax, 0xDEADBEEFCAFEBABE ; a 64-bit immediate only fits in a register load mov [rbp - 8], rax ; store the canary
; Allocate buffer space sub rsp, 64 ; 64-byte buffer at [rbp - 72]
; Simulate some buffer operation ; (In a real scenario, this is where an overflow might occur) lea rdi, [rbp - 72] mov byte [rdi], 'A' ; safe: writing within buffer bounds
; Check canary before returning mov rax, [rbp - 8] mov rcx, 0xDEADBEEFCAFEBABE cmp rax, rcx jne .corrupted
; Canary intact - print SAFE mov rax, 1 mov rdi, 1 lea rsi, [safe_msg] mov rdx, safe_len syscall jmp .exit
.corrupted: ; Canary corrupted - print CORRUPT mov rax, 1 mov rdi, 1 lea rsi, [corrupt_msg] mov rdx, corrupt_len syscall
.exit: mov rsp, rbp pop rbp mov rax, 60 xor rdi, rdi syscallStack canaries detect that an overflow has occurred, but only at the function epilogue. If the attacker's overflow writes past the canary and also corrupts function pointers, vtable pointers, or other data that is used BEFORE the function returns, the canary check never runs. This is why canaries are one layer in a defense-in-depth strategy, not a complete solution.
Security Perspective: How Attackers Defeat Canaries
Canaries are effective but not invincible. Attackers have developed several techniques:
-
Information leaks: If the attacker can read memory (e.g., via a format string vulnerability or an out-of-bounds read), they can discover the canary value, then include the correct canary in their overflow payload.
-
Byte-at-a-time brute force: In forking servers, each child process has the same canary. The attacker can overwrite the canary one byte at a time, using the crash/no-crash response to determine each byte. With a null byte plus 7 random bytes, this takes at most 7 * 256 = 1792 attempts.
-
Overwriting variables before the canary: If the overflow can reach a function pointer or other critical data that is stored between the buffer and the canary, the attacker can redirect execution before the canary is checked.
-
Non-sequential overwrites: Write-what-where primitives (e.g., from a heap corruption) can overwrite the return address directly without touching the canary.
For deeper coverage of stack canaries as an exploit mitigation, see Stack Canaries.
What is Next
Stack canaries protect individual functions, but ASLR and DEP/NX protect the entire address space. The next lesson covers how these system-wide defenses work together to make exploitation significantly harder.