Stack canary
- C course
- Expert
- Lesson 20/47
- 5 min
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.
Practice 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", ...).
Starter code
#include <stdio.h>
// Define check_canary function
// Call it for two cases and print ok=/bad=
int main(void) {
return 0;
}Sample 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;
}Expected output
ok=1 bad=0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match canary concepts
| Term | Meaning |
|---|---|
canary |
Random value |
SSP |
Stack protector |
prologue |
Function entry |
epilogue |
Function exit |
2 What does a stack canary detect?
- Memory leaks
- Loop errors
- Type mismatch
- Stack overflow Correct answer
Explanation: A canary catches stack overflow and aborts the program.
3 Complete the canary check
if (canary != ____) abort();
if (canary != expected) abort();
Explanation: expected is the canary written at function entry.