Stack canary

Also known as: stack cookie

On this page 7

A stack canary, also called a stack cookie, is a secret value that the compiler places on the call stack between local buffers and the saved return address, and checks again just before the function returns. If a stack buffer overflow has overwritten the canary, the check fails and the program is terminated immediately, before the attacker can redirect execution.

In OS security, stack canaries are one of the oldest and most widely deployed exploit mitigations. Modern operating systems compile their kernels, system libraries and most packaged applications with canary protection, and it works alongside ASLR, executable space protection and control-flow integrity as part of a layered defense against memory corruption.

How a stack canary detects an overflow

A stack canary works because a linear overflow that writes past the end of a buffer toward higher addresses must cross the canary before it reaches the saved return address. The compiler inserts a short prologue that copies a secret value into the stack frame and an epilogue that compares the stored copy with the original before the ret instruction.

On Linux with glibc, the reference value is generated at process start from kernel-supplied randomness and stored in thread-local storage, for example at fs:0x28 on x86-64. When the comparison fails, the code calls __stack_chk_fail, which prints a diagnostic such as “stack smashing detected” and aborts. Microsoft compilers implement the same idea with __security_cookie and a failure handler that ends the process.

The table below shows the simplified layout of a protected stack frame on a system where the stack grows downward.

PositionContentPurpose
Higher addressesFunction argumentsValues passed by the caller
NextSaved return addressWhere execution resumes after return
NextSaved frame pointerRestores the caller’s frame
NextCanary valueDetects overwrites from below
Lower addressesLocal buffersArrays that an overflow may exceed
Simplified layout of a protected stack frame

The canary therefore acts as a tripwire: it does not prevent the overflow itself, but it detects the corruption of control data at the last moment before that data would be used.

Types of canary values

Canary designs differ in how the secret value resists forgery. Early research systems such as StackGuard introduced several variants, and modern runtimes combine their strengths, for example by using a random value whose lowest byte is zero.

VariantValueStrengthWeakness
Terminator canaryBytes such as null, CR, LF and 0xFFStops string-copy overflowsValue is public and known
Random canaryUnpredictable value chosen at startupAttacker must guess or leak itFails if memory is disclosed
Random XOR canaryRandom value mixed with control dataBinds canary to the return addressMore complex and less common
Hybrid canaryRandom value with a zero low byteCombines secrecy and string stoppingGives up a few bits of entropy
Main canary variants and their properties

The null byte in the hybrid design is significant: functions such as strcpy stop copying at a null character, so an attacker cannot write the full canary with a string-based overflow, and string functions also cannot easily leak the canary by printing past a buffer.

Compiler and operating system support

Stack canaries are implemented by compilers and runtime libraries, while the operating system supplies randomness and enables protection by default in its build policies. Because instrumenting every function costs time, compilers offer selective protection levels.

FlagFunctions protectedTypical use
-fstack-protectorFunctions with character arrays of 8 bytes or moreOlder default, limited coverage
-fstack-protector-strongFunctions with any local array or address-taken localDefault in many Linux distributions
-fstack-protector-allEvery functionHardened builds that accept overhead
-fstack-protector-explicitFunctions marked with an attributeTargeted protection in special code
Common protection levels in GCC-compatible compilers

Microsoft Visual C++ enables the equivalent /GS option by default, and Windows system binaries are built with it. The Linux kernel uses CONFIG_STACKPROTECTOR_STRONG to protect its own functions, and macOS toolchains enable stack protection in standard builds. The runtime overhead is usually small, commonly a low single-digit percentage, because only a load, a store and a comparison are added per protected call.

Stack canaries cover one specific attack pattern, so they are effective only in combination with other protections. The table summarizes how they relate to neighboring mitigations.

MitigationWhat it protectsDetection or prevention
Stack canaryReturn address against linear overflowsDetection at function exit
Shadow stackReturn addresses in a separate protected stackPrevention of return tampering
ASLRPredictability of memory addressesMakes targets hard to locate
Executable space protectionStack and heap from running codeBlocks injected shellcode
Control-flow integrityIndirect calls and jumpsRestricts valid branch targets
Stack canaries and neighboring exploit mitigations

Hardware shadow stacks, such as those in Intel CET, are stronger for return addresses because they do not depend on a secret. However, canaries remain valuable because they also detect corruption of the saved frame pointer and run on hardware without shadow stack support.

Limitations and known bypass techniques

A stack canary is only as strong as the secrecy of its value and the assumption that an overflow is linear. Experienced attackers rely on several well-documented bypasses:

  • Information leaks, such as format string bugs or out-of-bounds reads, reveal the canary so that an overflow can rewrite it with the correct value.
  • Byte-by-byte brute forcing works against forking servers, because each child process inherits the same canary as its parent.
  • Non-linear writes, such as an arbitrary pointer write, can modify the return address without touching the canary.
  • Overwriting adjacent locals or function pointers placed below the canary can hijack control before the epilogue check runs.
  • Heap overflows and use-after-free bugs are outside the scope of stack canaries entirely.

Compilers reduce the local-variable risk by reordering stack variables so that buffers sit directly below the canary, an idea popularized by the ProPolice design. A common mistake is to treat a canary as complete protection; it is a detection layer, and the process still crashes, which can enable a denial of service.

Stripped to the essentials

A stack canary is a hidden check value that a program places in memory. It sits right next to the information that tells the program where to go next. If an attacker overflows a buffer, the check value gets damaged first.

Before the program uses that information, it compares the check value with the original. If they differ, the program stops at once. The name comes from canaries that miners carried as an early warning of danger.

Where it is applied

A Linux distribution security team builds several thousand packages with -fstack-protector-strong as a default compiler flag. One package, a network daemon that parses configuration messages, contains an old bug: it copies a client-supplied name into a 64-byte local buffer without checking its length.

An attacker sends a 300-byte name to overwrite the return address. The overflow first damages the canary, and when the parsing function returns, the epilogue check fails and the daemon aborts with a stack smashing message instead of running attacker code. The service restarts automatically, and the log entry leads administrators to the bug. The outcome is a crash rather than a compromise, and a patch that adds proper length checking follows within days.