Skip to main content
Be Bitwise
x86 AssemblySecurity Foundations

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:

nasm
; Function prologue WITH stack canary
vulnerable_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 program

The 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

0041Buffer← SP
0141Buffer
0241Buffer
0341Buffer
0441Buffer
0541Buffer
0641Buffer
0741Buffer
0800Buffer
0900Buffer
0A00Buffer
0B00Buffer
0C00Buffer
0D00Buffer
0E00Buffer
0F00Buffer
1000Buffer
1100Buffer
1200Buffer
1300Buffer
1400Buffer
1500Buffer
1600Buffer
1700Buffer
1800Buffer
1900Buffer
1A00Buffer
1B00Buffer
1C00Buffer
1D00Buffer
1E00Buffer
1F00Buffer
2000Buffer
2100Buffer
2200Buffer
2300Buffer
2400Buffer
2500Buffer
2600Buffer
2700Buffer
2800Buffer
2900Buffer
2A00Buffer
2B00Buffer
2C00Buffer
2D00Buffer
2E00Buffer
2F00Buffer
3000Buffer
3100Buffer
3200Buffer
3300Buffer
3400Buffer
3500Buffer
3600Buffer
3700Buffer
3800Buffer
3900Buffer
3A00Buffer
3B00Buffer
3C00Buffer
3D00Buffer
3E00Buffer
3F00Buffer
4000Canary
417ACanary
423FCanary
4391Canary
44C4Canary
451ECanary
468BCanary
475DCanary
48E0Saved rbp
49DESaved rbp
4AFFSaved rbp
4BFFSaved rbp
4CFFSaved rbp
4D7FSaved rbp
4E00Saved rbp
4F00Saved rbp
5096Return addr
5111Return addr
5240Return addr
5300Return addr
5400Return addr
5500Return addr
5600Return addr
5700Return addr
Regions
Buffer64 B
Canary8 B
0x5d8b1ec4913f7a00
Saved rbp8 B
0x00007fffffffdee0
Return addr8 B
0x0000000000401196
Overflow direction
Buffer→Canary→Saved rbp→Return addr

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):

0x7fffffffe04000buffer[0..63]
0x7fffffffe04400
0x7fffffffe04800
0x7fffffffe04c00
0x7fffffffe05000
0x7fffffffe05400
0x7fffffffe05800
0x7fffffffe05c00
0x7fffffffe06000
0x7fffffffe06400
0x7fffffffe06800
0x7fffffffe06c00
0x7fffffffe07000
0x7fffffffe07400
0x7fffffffe07800
0x7fffffffe07c00
0x7fffffffe0800x9c3d5e1a7b2f4400Stack Canary
0x7fffffffe0880x00007fffffffe0d0Saved RBP
0x7fffffffe0900x00005555555551a9Return Address
Buffer
Canary
Saved RBP
Return Addr

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.

nasm
; 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:

bash
*** stack smashing detected ***: terminated
Aborted (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:

FlagBehavior
-fstack-protectorProtect functions with local buffers > 8 bytes
-fstack-protector-strongProtect functions with any arrays, address-taken locals
-fstack-protector-allProtect every function (performance cost)
-fno-stack-protectorDisable 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.

Attacker Input
Buffer
Overflow
Return Addr
RET Executes
Attacker Code

Hover over each step to see details

Implementing a Manual Canary

To truly understand the mechanism, here is a manual canary implementation:

nasm
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
syscall
Canaries Detect, They Do Not Prevent

Stack 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.