Quiz Entry - updated: 2026.07.07
What is a stack canary and how does it protect against buffer overflows?
A random "canary" value placed between the buffer and the return address; if an overflow corrupts it, the function aborts before returning.
* A random canary sits between the buffer and the return address so an overflow must corrupt it first, letting the function detect the change and abort before returning. *
Stack layout with canary:
+------------------+
| Return address |
+------------------+
| Saved frame ptr |
+------------------+
| CANARY VALUE | ← Random value set at function entry
+------------------+
| Local buffer[32] | ← Overflow would overwrite canary first!
+------------------+
How it works:
- Function prologue: compiler inserts code to place random canary value
- Function runs normally
- Before return: check if canary still has expected value
- If canary changed → buffer overflow detected → program terminates
Why it works:
- Attacker must overflow through the canary to reach return address
- Canary is random, attacker doesn't know what value to preserve
- Any overflow that reaches return address will corrupt canary
Limitations:
- Only detects overflow, doesn't prevent the initial write
- Can be bypassed if attacker can leak the canary value
- Doesn't protect against overflows that don't hit the canary
Enable in GCC: -fstack-protector (on by default in many distros)
Go deeper:
Buffer overflow protection / stack canaries (Wikipedia) — terminator, random, and XOR canaries placed before the return address to detect stack smashing before return.