CFI, Shadow Stacks & Safe Languages
Exploit Mitigations · Exploitation Fundamentals track
9 min read
In this module
Beyond Canaries and ASLR
Canaries catch sequential overwrites. ASLR hides addresses. DEP blocks code injection. ROP, plus a handful of other tricks, picks all three locks. So the next wave of defences goes after the thing exploits actually need: a hijacked control flow.
Control Flow Integrity (CFI)
Control Flow Integrity narrows where indirect jumps and calls are allowed to go. A function pointer or virtual method call in a healthy program should always land on a real function entry. CFI checks that at runtime.
The compiler does the legwork up front, working out which targets are valid for each indirect call site. At runtime, every indirect call or jump checks the destination against the allowed set first. Anything off the list aborts execution.
That protects the forward edge: indirect calls and jumps can only land on targets CFI has blessed, so a corrupted function pointer can't send execution to a random gadget mid-instruction. Returns are the backward edge, and compiler CFI such as Clang's doesn't check them; protecting returns takes a shadow stack or pointer authentication, covered below. You need both halves before ROP gets truly hard.
Coarse-grained CFI groups all valid targets into a single set - any function entry point is considered valid. This is better than nothing but still allows an attacker to call any function. Fine-grained CFI restricts each call site to only the specific functions it could legitimately target, dramatically reducing the attacker's options. Modern implementations (like LLVM's CFI) aim for fine-grained enforcement.
Shadow Stacks
A shadow stack is a second, protected copy of the call stack that holds nothing but return addresses. On every call, the return address gets pushed twice: once onto the normal stack, once onto the shadow. On return, the regular stack's value is compared against the shadow copy. Mismatch means tampering, and execution stops.
Canaries fall to a leak. Shadow stacks don't, because they live in a memory region that ordinary program code can't write. Intel's Control-flow Enforcement Technology (CET) wires the whole mechanism into hardware, which makes the overhead almost free.
CFI in Software: Clang's -fsanitize=cfi
Clang ships a fine-grained CFI scheme for forward edges, the indirect calls and jumps. You switch it on with -fsanitize=cfi, and it needs link-time optimisation (-flto) plus, for most of its checks, -fvisibility=hidden. The reason for both is that the compiler has to see the whole program to know every legitimate target for every call site.
Two of its checks map neatly onto the callout above:
cfi-icallchecks indirect calls through function pointers. The target must be a function whose type matches the pointer's type. A pointer declared asvoid (*)(char *)can reach any function with that signature, and nothing else.cfi-vcallchecks C++ virtual calls. Before calling through a vtable, the program checks that the vtable belongs to the object's static type or a class derived from it.
A failed check traps by default, typically on a ud2 instruction, so the process dies at the bad call rather than at some random later point. It's precise, and it's real engineering work to deploy: every indirect call in the program and its libraries has to type-check, and code that casts function pointers to "close enough" types will trip it. Clang CFI says nothing about return addresses, either. That's the shadow stack's job.
Intel CET in Hardware
CET has two halves, one for each direction of control flow.
Before the details, here's one indirect call and its return, with each defence pinned to the edge it polices. The dotted lines say who checks what; the bottom path is a ROP chain trying its luck:
Shadow Stack (Backward Edges)
With the shadow stack enabled, every call pushes the return address to two places: the normal stack, and a separate shadow stack pointed to by a register the program can't move with ordinary instructions. Every ret pops both and compares them. If they differ, the CPU raises a control-protection exception (#CP), and on Linux the process receives SIGSEGV.
What stops an attacker just overwriting the shadow copy too? The page tables. Shadow-stack pages use a special permission encoding that ordinary mov and push instructions can't write to; only call, ret and a few dedicated shadow-stack instructions touch them. An overflow that rewrites the return address on the regular stack, even with a perfect canary leak, gets caught at the very next ret.
That's a problem for ROP. Every gadget ends in ret, and every ret gets checked against a shadow stack that only contains addresses real calls pushed. The first gadget fails.
Indirect Branch Tracking (Forward Edges)
IBT handles indirect call and jmp. When it's enforced, the instruction at the target of an indirect branch must be endbr64 (bytes f3 0f 1e fa). Land anywhere else and the CPU raises #CP. On processors without CET, endbr64 decodes as a no-op, so the same binary runs everywhere.
If you've disassembled a binary from a recent mainstream Linux distribution, you've seen this already:
main: endbr64 push rbp mov rbp, rsp ...IBT is coarse-grained in the sense of the callout above. Any function that starts with endbr64 is a valid target for any indirect call, so a hijacked function pointer can still reach system. What it removes is the ability to jump into the middle of a function, which is where most useful gadgets live.
Turning It On: -fcf-protection
gcc and Clang both accept -fcf-protection. With no value it means full; you can also ask for branch (IBT only), return (shadow stack only) or none. The compiler inserts endbr64 at function entries and other indirect-branch targets, and marks each object file with a GNU property note saying which features it supports. The linker only keeps a feature in the final binary's note if every input object has it, so a single old object file built without the flag quietly switches the feature off for the whole program. You can check the result:
$ readelf -n ./vuln | grep feature Properties: x86 feature: IBT, SHSTKThe extra SHSTK and IBT lines in newer checksec versions read this same note. The walkthrough of the other checksec lines is in DEP / NX.
What Linux Actually Enforces
This is the part people most often get wrong. A binary marked SHSTK and IBT is only ready for CET. Whether anything is enforced depends on the CPU, the kernel and the C library together.
- Shadow stacks for user space arrived in the Linux kernel relatively recently, for x86-64 only, and they're opt-in. The kernel provides the mechanism; glibc decides whether to switch it on for a process, and only when the program and every library it loads carry the
SHSTKmarker. Support in glibc is also recent, and distributions differ on whether they enable it by default. You also need a CPU that implements CET, which means fairly recent Intel and AMD parts. - IBT for user space isn't something you can count on yet on Linux. The kernel can use IBT to protect its own code on supporting hardware, but enforcement for ordinary user-space programs isn't generally available.
So for most Linux targets you'll meet today, those endbr64 instructions are there but nothing faults if you skip them. Check the platform before assuming either way: CET is a moving target, and the honest answer for a given machine depends on its CPU, kernel version, glibc version and distribution policy.
Predict: on a system that does enforce IBT, you overwrite a function pointer. Will the call succeed if you point it at (a) system, (b) a pop rdi; ret gadget halfway through some libc function?
(a) succeeds, (b) faults. system is an ordinary exported function, so it starts with endbr64 and is a legal target for any indirect call. The gadget sits in the middle of a function with no endbr64 in front of it, so the CPU raises #CP the moment the call lands. That's IBT's coarse-grained trade-off in one example: it kills mid-function gadgets but leaves whole-function reuse alone, which is why fine-grained schemes like Clang CFI exist alongside it.
Memory-Safe Languages: The Ultimate Mitigation
Every defence we've covered (canaries, ASLR, DEP, CFI, shadow stacks) exists because C and C++ let programs scribble over their own memory. Memory-safe languages like Rust, Go, Java, and Swift block buffer overflows, use-after-free, and type confusion at the language level. The bug class never reaches the compiler.
Rust pulls this off with its ownership and borrowing model, enforced at compile time for zero runtime cost. Go and Java take the garbage-collected-plus-bounds-checks route. Either way, writing the kinds of bugs all these mitigations defend against becomes either impossible or wildly difficult.
Defence in Depth
No single defence holds the line on its own. Exploitation has always been an arms race; every mitigation breeds a bypass, every bypass breeds a new mitigation. The strongest posture stacks them:
- Stack canaries to catch simple overflows
- ASLR to hide memory layout
- DEP to prevent code injection
- CFI and shadow stacks to protect control flow
- Memory-safe languages to eliminate the root cause
Each layer forces the attacker to solve an extra independent problem. One falls, the others keep standing.
Defensive Thinking
Starting a new project? Pick a memory-safe language and entire bug classes disappear. Stuck maintaining a C/C++ codebase? Turn on everything you can: -fstack-protector-strong, PIE, RELRO, CFI. The per-mitigation performance hit is tiny. The combined security payoff is hard to overstate.
In concrete terms, a hardened gcc build on x86-64 Linux looks something like this:
gcc -O2 -D_FORTIFY_SOURCE=2 -fstack-protector-strong \ -fPIE -pie -Wl,-z,relro,-z,now \ -fcf-protection \ -o server server.cEach flag maps to a line you've learnt to read: FORTIFY, Stack: Canary found, PIE enabled, Full RELRO, and the IBT/SHSTK feature note. NX comes free, since the linker marks the stack non-executable unless something asks otherwise. Run checksec on the output and make sure it says what you think it says, then run it again in CI, because one stray object file or a changed default can silently drop a protection.
Then flip to the attacker's side. Take the ROP Chain lab and work out, gadget by gadget, which steps of your solution would survive an enforced shadow stack, and which would survive IBT. (Spoiler: the shadow stack stops it at the first ret.) That exercise is the clearest way to see why the industry spent so long moving these checks into hardware.
Try the Simulations
Stack Canary Detection
Place a canary value between a buffer and return address. A simulated overflow corrupts the canary, and the check detects the corruption before the function returns.
DEP / NX Concept
Write the bytes of two instructions into a data area and jump there. Our simulator has no NX bit, so the injected code runs; a real CPU with DEP would fault and terminate the process.