C
Stack canary
Learn protection with stack canaries.
What is a stack canary?
A stack canary is a random value placed before the return address. On return, if the value changed, the program detects an overflow and aborts.
The compiler adds this protection with -fstack-protector. At function entry the prologue writes a random canary onto the stack; at exit the epilogue expects the same value. If an overflow changed it, __stack_chk_fail is called and the program terminates. The canary differs on every run, so attackers cannot predict it. This method is known as SSP (Stack Smashing Protector).
Canary check
The canary check works in two steps: on function entry the canary is written to the stack; on exit it is compared with the expected value. If they differ, the program terminates safely.
The compiler adds this check automatically; the programmer does not write canary code. Still, safe functions matter: a canary detects overflow, it does not prevent it. So a canary is an alarm, not a guard. Some attacks look for ways to bypass it; that is why additional protections (ASLR, PIE) are used together. Multiple layers strengthen the defense.
Exercise Check the canary
Define int check_canary(unsigned int saved, unsigned int expected). If saved == expected, return 1;; otherwise return 0;. In main call it twice: 0xDEADBEEF, 0xDEADBEEF and 0xDEADBEEF, 0xCAFEBABE. Print the results with printf("ok=%d\n", ...) and printf("bad=%d\n", ...).
Show example solution
#include <stdio.h>
int check_canary(unsigned int saved, unsigned int expected) {
if (saved == expected) {
return 1;
}
return 0;
}
int main(void) {
int ok = check_canary(0xDEADBEEF, 0xDEADBEEF);
int bad = check_canary(0xDEADBEEF, 0xCAFEBABE);
printf("ok=%d\n", ok);
printf("bad=%d\n", bad);
return 0;
}
Test yourself
-
Match canary concepts
- canary
- Random value
- SSP
- Stack protector
- prologue
- Function entry
- epilogue
- Function exit
-
What does a stack canary detect?
- Memory leaks
- Loop errors
- Type mismatch
- Stack overflow
Show answer
Stack overflow — A canary catches stack overflow and aborts the program.
-
Complete the canary check
if (canary != ____) abort();
Show answer
if (canary != expected) abort();
Next lesson: ASLR