Stack Canaries
Exploit Mitigations · Exploitation Fundamentals track
9 min read
In this module
A Tripwire on the Stack
In Stack-Based Buffer Overflows, you saw how a buffer overflow can overwrite the saved return address on the stack, hijacking control flow when the function returns. Stack canaries are the first line of defence against this attack.
The idea is disarmingly simple: plant a random value (the canary) between the local buffer and the saved return address. Before the function returns, check whether the canary is intact. A buffer overflow that reaches the return address has to trample it first — and the program catches that, aborts, and never hands control to the attacker.
How Canaries Work
When a function begins, compiler-inserted code copies the canary onto the stack between the buffer and the saved registers. Here's what a frame looks like after an attacker has sent a long run of A characters (0x41) into a 16-byte buffer. The visualiser shows one row per byte, with the canary and return address each squeezed into a single row:
Stack Frame View
The flood of 0x41 bytes has run straight through the canary and the saved rbp, and stopped one byte short of the return address. The return address is still intact, but it doesn't matter: the canary has changed, so the check will fail before ret ever runs.
Before the function executes its RET instruction, it compares the canary on the stack to the original value. If they differ, the program calls a termination handler (typically __stack_chk_fail) and the process aborts. The attacker's corrupted return address is never used.
The name comes from the practice of bringing canaries into coal mines. If toxic gas was present, the canary would die first, warning the miners. A stack canary serves the same purpose - it "dies" (gets overwritten) before the return address does, alerting the program to danger.
Worked Example: The Code gcc Adds
Compile a function with a local array on x86-64 Linux and look at the disassembly. The canary costs a few extra instructions at each end:
; prologuemov rax, QWORD PTR fs:0x28 ; load this thread's canarymov QWORD PTR [rbp-0x8], rax ; store it just below saved rbpxor eax, eax ; wipe it from the register
; ... function body ...
; epiloguemov rdx, QWORD PTR [rbp-0x8] ; read the canary back off the stacksub rdx, QWORD PTR fs:0x28 ; compare with the originaljne .Lfail ; different? don't returnleaveret.Lfail:call __stack_chk_fail ; prints "*** stack smashing detected ***" and abortsA few details worth knowing:
- Where it comes from.
fs:0x28is in thread-local storage. glibc fills it once at program start from random bytes the kernel hands every new process, then sets the lowest byte to00so string functions can't easily copy or print past it. - It's the same for every function. One value per process, reused by every protected frame. Leak it once from any function and you can forge it in all of them.
fork()copies it. A child process inherits its parent's memory, canary included. That matters a lot for servers that fork a fresh child per connection.- Not every function gets one.
-fstack-protectorcovers functions with character arrays of 8 bytes or more;-fstack-protector-strong(the usual distro default) adds any function with a local array or a local whose address is taken;-fstack-protector-allcovers everything.
Predict: a server forks a new child for every connection, and an overflow lets you overwrite the canary one byte at a time. How many attempts does it take, at most, to learn the whole canary?
1,792. Every child has the same canary, so a crash only costs one connection. Guess the first unknown byte: if the child survives, you've got it right. You need at most 256 tries per byte, and the lowest byte is already known to be 00, so it's 7 × 256 = 1,792 attempts in the worst case. This byte-by-byte attack is why forking servers are a favourite target, and why some software re-randomises the canary in the child after fork().
Spotting a Canary Before You Start
You don't have to read disassembly to get a first answer. Run checksec on the binary (pwntools ships one, so pwn checksec ./vuln works) and look at the Stack: line:
Stack: Canary foundchecksec never runs the program to decide this. It looks for __stack_chk_fail among the symbols the binary references: if nothing can call the failure handler, nothing is checking a canary. That's a heuristic, and it can mislead you both ways. A binary built with plain -fstack-protector can report Canary found because one function qualified, while the function with your bug had only an int array and went unprotected. A stripped, statically linked binary can hide the symbol altogether. So treat the checksec line as a hint, then open the function you're actually attacking and look for the fs:0x28 load in its prologue. That load is the ground truth.
The full checksec walkthrough, with RELRO, NX, PIE and FORTIFY alongside this line, lives in DEP / NX.
See It in Action
The simulator below is a model of the idea, run on our 8-bit teaching CPU. It has no fs segment and no thread-local storage, so a fixed address (203) and a fixed value (7) stand in for the random fs:0x28 canary in the gcc epilogue above. A function places a known canary value at a specific stack location. When a simulated overflow writes through the buffer and corrupts the canary, the check detects the corruption before the function returns.
For the best simulation experience, use a desktop browser.
Assembly
Registers
ALU
Memory
| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 10 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 20 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 30 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 40 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 50 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 60 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 70 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 80 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| 90 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| A0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| B0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| C0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| D0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| E0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
| F0 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
Pipeline
Cycle 0Limitations
Stack canaries are not bulletproof. If an attacker can leak the canary value (for example, through a format string vulnerability as described in Integer Overflows & Type Confusion), they can include the correct canary in their overflow payload, leaving it intact while still overwriting the return address.
Canaries also only protect against sequential overwrites that must pass through the canary to reach the return address. If an attacker has an arbitrary write primitive (writing to a specific address without overflowing sequentially), they can overwrite the return address directly, skipping the canary entirely. And they protect only the return address and what lies behind them: local variables sitting next to the buffer, such as a function pointer or a length, can still be overwritten before the check ever runs.
Bypassing It in Practice: Leak, Then Replay
The leak attack from the limitations above has a very concrete shape on x86-64 Linux. It comes in two stages, and the program has to give you both in the same run, because a restart means a fresh canary.
Stage one: get the canary out. With a format string bug, a string of %p.%p.%p walks through printf's argument slots. On x86-64 the format string itself sits in rdi, so the first five %p values come from rsi, rdx, rcx, r8 and r9, and from the sixth onwards printf starts reading the stack. Somewhere in that dump is a value like 0x9c1e4f2b7a6d3800: eight bytes of noise ending in 00. That's your canary. Once you've counted which position it sits at, a positional specifier such as %15$p reads it directly (the 15 is illustrative; count it for your own binary).
No format string? If the program echoes your input back with puts or %s, overflow by exactly one byte past the buffer, so you overwrite the canary's 00. The string no longer stops there, and the print runs on into the seven random bytes. You then rebuild the canary as 00 plus whatever came out. This only works if the program keeps going after the echo, since that frame's canary is now wrong and will trip the check when the function returns.
Stage two: put it back. Lay the overflow out so the canary lands on its own slot with its original value. For the gcc frame above, the canary sits at rbp-0x8, so if the buffer starts at rbp-0x50 the padding is 0x48, which is 72 bytes:
payload = b"A" * 72 # fill the buffer up to rbp-0x8payload += p64(canary) # the leaked value, written back unchangedpayload += b"B" * 8 # saved rbp: junk is fine if nothing uses it before your chain runspayload += p64(target) # the return address you actually wantThe epilogue reads the canary, finds it unchanged, and executes ret straight into target. The check was never fooled about the overwrite; it simply never looked anywhere but its own eight bytes.
The Canary Bypass lab has exactly this two-stage structure: a format string in stage one, an overflow in stage two. Find the canary's position, read it with %N$p, and build the payload above around it.
Predict: you overwrite the canary's low 00 byte and the program echoes your input with puts. Sometimes you get all seven random bytes back, and sometimes fewer. Why?
One of the random bytes was itself 00. puts stops at the first null byte, wherever it falls. Each random byte has a 1 in 256 chance of being zero, so most runs give you all seven, but now and then the leak cuts short. The usual fix is to notice the short read and restart the program, which gives you a fresh canary to try again.
Defensive Thinking
Modern compilers (GCC, Clang, MSVC) enable stack canaries by default or with -fstack-protector. The overhead is small: a load and a store on entry, and a compare on the way out of each protected function. They're bypassable, but they catch a lot of sloppy overflow attempts and raise the bar enough to matter.
Try the Simulations
Stack Canary Detection
Place a canary value between a buffer and return address. A simulated overflow corrupts the canary, and the check detects the corruption before the function returns.
DEP / NX Concept
Write the bytes of two instructions into a data area and jump there. Our simulator has no NX bit, so the injected code runs; a real CPU with DEP would fault and terminate the process.