Skip to content
systemcoding.dev
Security

How Stack Canaries Catch Buffer Overflows at Runtime

A stack canary is a secret value placed before the return address and checked before ret. See how GCC emits it, where glibc stores it, and what it misses.

6 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the C, GNU and OWASP logos.

A stack canary is a secret number the compiler places on the stack between your local arrays and the saved return address. When the function is about to return, it compares the number with the original copy. If they differ, something wrote through the array and over the canary, and the program aborts instead of jumping to a corrupted address. The name comes from the canary in a coal mine. This post shows the instructions GCC emits, where the secret lives, which functions get one, and what the technique cannot catch. Examples target GCC 15 on x86-64 Linux 6.12 with glibc 2.41.

The idea in four steps

  1. At function entry, copy a secret value from a known location onto the stack, below the saved frame pointer and return address.

  2. Run the function body. Arrays are laid out below the canary, so an overflow climbs toward it.

  3. Before ret, read the stack copy and compare it with the original.

  4. If they differ, call __stack_chk_fail, which prints a message and aborts. If they match, return normally.

The attacker's problem is that a linear overflow cannot reach the return address without crossing the canary, and the attacker does not know its value. This is why the secret is chosen at random when the process starts.

What the compiler emits

Take a function with a local array:

copy.cc
#include <string.h>

void copy(const char *s)
{
    char buf[16];
    strcpy(buf, s);
}

Compile it to assembly with gcc -std=c17 -O1 -fstack-protector-strong -D_FORTIFY_SOURCE=0 -S -o - copy.c. The relevant parts on x86-64, trimmed and annotated, look like this:

asm
copy:
    subq    $40, %rsp
    movq    %fs:40, %rax        ; load the canary from the thread control block
    movq    %rax, 24(%rsp)      ; store it above buf
    ...                         ; strcpy(buf, s)
    movq    24(%rsp), %rax      ; reload the stack copy
    subq    %fs:40, %rax        ; compare with the original
    jne     .L4
    addq    $40, %rsp
    ret
.L4:
    call    __stack_chk_fail@PLT

%fs:40 is offset 0x28 in the thread control block, the per-thread structure that glibc keeps addressed by the fs segment register on x86-64. The stack copy sits at 24(%rsp), above the 16-byte buf at 0(%rsp) and below the return address. The exact register choices and offsets vary with the optimization level and compiler version, so treat the listing as the pattern, not the literal text. On 32-bit x86 the same value is read through %gs:20.

Where the secret comes from

At startup, glibc fills the canary slot in the thread control block with random bytes taken from the kernel through the auxiliary vector (AT_RANDOM), which the kernel provides at execve. glibc then clears the lowest byte, so the canary always ends in a zero byte on a little-endian machine. That choice is deliberate: a string copy stops at the first NUL, so an overflow that is a C-string copy cannot write the full canary value back, and an attacker who tries to reproduce it with strcpy cannot include the zero byte without terminating the copy early. It also stops a string read from leaking the canary past that point.

Because the value is chosen per process, a forked child that serves requests inherits the same canary as its parent. That detail matters for network servers: an attacker who can crash a worker repeatedly, and learn from each crash whether a guessed byte was right, can reconstruct the canary one byte at a time. Servers that fork without re-executing are the exposed case.

The failure message

When the check fails, glibc's __stack_chk_fail prints a message and calls abort. On glibc 2.41, with a terminal, it looks like this:

Text
*** stack smashing detected ***: terminated
Aborted (core dumped)

The second line comes from the shell. If you see it in a log, a function in that process wrote past a local array, and the backtrace in the core file names which function's epilogue noticed.

Which functions get a canary

Placing a canary costs a load, a store, a load and a compare, so GCC lets you choose how widely to apply it.

FlagFunctions that get a canary
-fstack-protectorfunctions with a char array of 8 bytes or more, or a call to alloca
-fstack-protector-strongthe above plus any local array, any address-taken local and any use of local register variables
-fstack-protector-allevery function
-fstack-protector-explicitonly functions marked __attribute__((stack_protect))

Distributions such as Ubuntu and Fedora enable the strong variant by default in their compilers' build flags. The next post in this subcluster compares the three levels in detail. Here the point is that a function without a local array, such as one that only adds two integers, has no canary, and that is correct, since nothing in it can overflow.

GCC also reorders locals when the protector is on: arrays are placed closest to the canary, and pointer and scalar locals below the arrays, so an overflow reaches the canary before it reaches a pointer variable that could be used to write elsewhere. Function arguments that are pointers are copied below the arrays for the same reason.

What a canary catches and what it does not

A canary detects a contiguous write that runs through it before the function returns. That covers the textbook strcpy, gets and memcpy overflows. It does not catch:

  • An overwrite that skips the canary. A write through an attacker-controlled index, such as buf[i] = x with a large i, can land on the return address without touching the canary. This is an arbitrary write, not an overflow.

  • Corruption of other data. An overflow into a neighboring local, a function pointer in a struct, or a heap object does not touch the canary and may be exploitable without ever reaching the return address.

  • A leaked canary. An information leak, such as a format string bug or an out-of-bounds read, can disclose the value, and the attacker then writes it back in place.

  • Corruption that happens before the check is reached. If the function calls through a corrupted pointer before returning, the attacker has control before __stack_chk_fail runs.

  • The cost of a crash. A canary turns code execution into a denial of service, which is a fair trade but still a bug.

For these reasons the canary sits beside other defenses, such as ASLR, non-executable stacks, shadow stacks and bounds checking, and it is not a substitute for fixing the copy.

Seeing it yourself

You can confirm a binary has the protector without disassembling it. readelf -s ./a.out | grep stack_chk shows an undefined reference to __stack_chk_fail, and objdump -d ./a.out shows the %fs:0x28 loads in the functions that have one. If a build is supposed to be protected and the symbol is missing, the flag did not reach the compiler, often because a build system replaced CFLAGS. A later post in this series covers checksec and readelf checks for the whole set of mitigations.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.