Chapter 8: Control-Flow Integrity
The last four chapters were an arms race. Stack smashing let an attacker overwrite a return address and jump to injected shellcode (Chapter 4, Chapter 5). Non-executable memory took away the injected code, so attackers reused code that was already there — first whole libc functions, then short instruction sequences chained into return-oriented programs (Chapter 7). Canaries and ASLR (Chapter 6) raised the bar, but they are probabilistic defenses: leak the canary or one code address and they fall.
This chapter takes a different approach. Instead of hiding the targets or detecting one particular kind of corruption, Control-Flow Integrity (CFI) asks a direct question at every indirect branch: is this a place the program was ever supposed to go? If not, the program is stopped. CFI does not prevent memory corruption, but it sharply limits what an attacker can do with it.
Learning objectives. After this chapter you should be able to:
- Distinguish forward-edge from backward-edge control-flow transfers, and say which attacks abuse each.
- Build the control-flow graph (CFG) of a small function from its basic blocks.
- Explain how CFI instruments indirect branches and checks them against a CFG, and how a shadow stack protects returns.
- Explain why coarse-grained CFI can be bypassed, and why precision costs performance.
- Describe Code-Pointer Integrity, Clang/LLVM’s forward-edge CFI, context-sensitive CFI, and hardware CFI (Intel CET, ARM PAC/BTI).
8.1 What the Attacker Is After
Every control-flow hijacking attack we have seen ends the same way: the processor
loads an attacker-chosen value into the instruction pointer. The attacker wants
arbitrary computation — running a shell, calling mprotect, writing to a file —
and the only way to get it without injecting code is to steer the existing code.
The processor changes %eip in only a few ways, and they differ sharply in how
much an attacker can influence them:
| Transfer | Example | Target comes from | Attackable? |
|---|---|---|---|
| Direct jump / call | jmp 0x8049196, call foo | the instruction bytes (read-only code) | No — code pages are not writable |
| Conditional branch | je loop | instruction bytes + flags | Only by changing data the condition depends on |
| Indirect call / jump | call *%eax, jmp *(%ebx) | a register or memory | Yes — forward edge |
| Return | ret | the top of the stack | Yes — backward edge |
The last two rows are the attack surface. They split naturally into two groups:
- Forward edges — indirect calls and jumps. In C these come from function
pointers (
fp()),switchjump tables, and in C++ from virtual calls through a vtable. Overwriting a function pointer (Chapter 4, “level 02”) or a GOT entry (Chapter 10) is a forward-edge attack. - Backward edges — returns. Overwriting a saved return address, and every ROP chain, is a backward-edge attack.
Defenses so far, and what they leave open
| Defense | What it stops | How it is bypassed |
|---|---|---|
| Stack canary | Contiguous overwrites of the return address | Leak the canary; write past it with a non-linear write (format string, pointer write); attack a function pointer instead |
| NX / DEP | Executing injected code | Code reuse (ret2libc, ROP) |
| ASLR | Knowing where code and data are | Information leaks; brute force on 32-bit; non-randomized modules |
| CFI | Indirect branches to targets outside the CFG | Attacks that stay inside an imprecise CFG (§8.4) |
CFI is the first defense in this list that reasons about where control is allowed to go, which is exactly the property code-reuse attacks violate.
8.2 Control-Flow Graphs
CFI borrows its central data structure from compilers. A basic block is a straight-line sequence of instructions with one entry (the first instruction) and one exit (the last): no jumps out of the middle, no jump targets into the middle. A control-flow graph has one node per basic block and an edge for every possible transfer between blocks.
Consider this function:
int classify(int x, void (*log)(int))
{
int r;
if (x < 0)
r = -1;
else
r = 1;
log(r); /* indirect call */
return r;
}
Its CFG, together with the inter-procedural edges CFI cares about, looks like this:
caller: ... call classify ... (return site R)
|
v
+------------------------+
| B1: prologue |
| cmp $0, x |
| jge B3 |
+------------------------+
| x < 0 | x >= 0
v v
+---------------+ +---------------+
| B2: r = -1 | | B3: r = 1 |
| jmp B4 | | |
+---------------+ +---------------+
\ /
v v
+------------------------+
| B4: push r | forward edge
| call *log --------+-----------------> { log_stdout,
+------------------------+ log_file, ... }
|
v
+------------------------+
| B5: mov r, %eax | backward edge
| ret --------------+-----------------> R (only!)
+------------------------+
Edges inside the function (B1→B2, B1→B3, …) are direct: their targets are
encoded in read-only instructions and cannot be changed at runtime. The two
interesting edges are the indirect call in B4, which may go only to functions that
could legitimately be stored in log, and the ret in B5, which should go only back
to the instruction after whichever call classify invoked it.
A stack buffer overflow in classify that rewrites the return address so that ret
goes to, say, the middle of system() creates an edge that does not exist in the
CFG. That observation is the whole idea of CFI.
8.3 The CFI Principle
Control-Flow Integrity was introduced by Abadi, Budiu, Erlingsson, and Ligatti in 2005. Its policy is simple to state:
Every indirect control-flow transfer at runtime must follow an edge of the program’s statically computed CFG.
Enforcing it takes two steps:
- Offline: compute the CFG — from source code in a compiler, or from the binary by disassembly — and, for each indirect branch, the set of allowed targets.
- Instrumentation: rewrite the program so that every indirect
call,jmp, andretchecks its actual target against the allowed set before transferring control. If the check fails, abort.
Two assumptions make this sound. First, code is not writable (NX/W⊕X, from Chapter 6): otherwise the attacker could simply rewrite the checks. Second, data is not executable: otherwise the attacker could jump to injected code that contains no checks. CFI is designed to hold even against an attacker who can read and write all of data memory at will — a much stronger attacker than ASLR or canaries assume.
Implementing the check with labels
How do you check “target ∈ allowed set” cheaply? The original CFI design assigns a label (ID) to each equivalence class of targets and embeds that label in the code at the start of each valid target. Before each indirect branch, the instrumentation checks that the destination carries the expected label.
A sketch of the instrumented code, with the target address in %ecx (as on the
slides):
Call site (before): Call site (after CFI):
cmpl $ID_LOG, LABEL_OFF(%ecx) # target labeled?
call *%ecx jne cfi_violation
call *%ecx
Destination (before): Destination (after CFI):
log_stdout: log_stdout:
push %ebp <label instruction encoding ID_LOG>
mov %esp, %ebp push %ebp
... mov %esp, %ebp
The label must be something the processor can execute harmlessly when control
legitimately arrives. The original paper encoded it inside an instruction with no
architectural effect — a prefetchnta whose memory operand contains the ID bytes —
so normal execution simply runs through it. Two details make the scheme sound:
- IDs must not appear anywhere else in the code. If the 32-bit ID value occurred by accident in the middle of some other instruction, the attacker could jump there and pass the check. The rewriter chooses IDs that are unique in the binary.
- Returns are instrumented the same way.
retis replaced by “pop the return address into a register, check the label at the return site, thenjmpto it.”
Notice the cost: every indirect branch gains a memory load, a compare, and a
conditional jump. Notice also the precision limit: all targets that share a label
are interchangeable. If log and qsort’s comparator both point into functions
labeled with the same ID, an attacker who corrupts log can redirect it to any
comparator. Precision is only as good as the label assignment.
Shadow stacks for the backward edge
Labels work poorly for returns. A popular function like memcpy is called from
hundreds of sites, so all those return sites must share one label — and then a
corrupted return in memcpy may go to any of them. Statically, that is the best
any CFG can do: the static CFG cannot know which caller is active right now.
The dynamic answer is a shadow stack: a second stack, kept in memory the attacker cannot write, that records return addresses only.
call f: push return address on the normal stack
push return address on the shadow stack
ret: pop A from the normal stack
pop S from the shadow stack
if A != S: abort # return address was tampered with
jump to A
normal stack (writable, shadow stack (protected,
contains buffers) only return addresses)
+------------------+ +------------------+
| buf[64] | | |
| saved %ebp | | |
| ret addr = 0x... |<-- compared->| ret addr = 0x... |
| args | | ... |
+------------------+ +------------------+
A shadow stack enforces the precise backward-edge policy: every return goes to the call site that invoked it. Software shadow stacks must hide or protect the shadow region (for example, at a randomized location or in a separate segment), and they pay a few percent of overhead; hardware shadow stacks (§8.8) make this nearly free.
Note. Programs that legitimately break call/return pairing —
setjmp/longjmp, C++ exceptions, coroutines, user-level threads — need special handling, which is a large part of why shadow stacks took decades to deploy.
8.4 Precision: Coarse-Grained vs. Fine-Grained CFI
The security of CFI depends entirely on how many targets each indirect branch is allowed. Computing exact target sets for function pointers requires a precise points-to analysis, which is undecidable in general and expensive in practice, so real systems over-approximate. The spectrum looks like this:
| Policy | Indirect call may go to… | Return may go to… |
|---|---|---|
| None | anywhere | anywhere |
| Coarse-grained (e.g., binary-only CFI) | any function entry | any instruction following a call |
| Type-based (fine-grained forward edge) | any address-taken function with a matching type signature | (separate mechanism) |
| Points-to-based | functions the analysis says this pointer may hold | — |
| Shadow stack | — | exactly the active caller’s return site |
| Context-sensitive | depends on the execution path so far | — |
Coarse-grained CFI was attractive because it could be applied to binaries
without source code and cost little. But it leaves a very large number of legal
targets: every call-preceded instruction in libc is a valid return target. Research
in 2014–2015 showed that this was enough. Göktaş et al. (“Out of Control,” IEEE S&P
2014) built Turing-complete gadget sets out of call-preceded gadgets and
whole-function “entry-point” gadgets that satisfied the coarse policies of the time.
Carlini et al. (“Control-Flow Bending,” USENIX Security 2015) went further and
showed that even fully precise static CFI — the best a static CFG can give — often
still lets an attacker reach system()-like functionality, because functions such as
memcpy and printf have so many legitimate callers and can themselves be abused to
perform arbitrary writes. Their conclusion: static CFI must be combined with a shadow
stack to be meaningful.
Type-based forward-edge CFI is the practical middle ground used today (§8.6). An
indirect call through a void (*)(int) may only reach address-taken functions of type
void (int). This is an over-approximation — any void (int) function whose address
is taken anywhere in the program is allowed — but it removes the vast majority of
targets, and it is cheap.
Going deeper. Precision can be measured. A common metric is the average indirect target reduction (AIR): the average fraction of targets removed, over all indirect branches, relative to an unprotected program. Nearly every CFI scheme scores above 99% on AIR, which is why later work argued that AIR is a poor metric: the question is not how many targets were removed but whether the remaining targets still let an attacker do something useful.
8.5 Cheaper Alternatives: Code-Pointer Separation and Integrity
Software CFI on every indirect branch has a measurable cost, and for years the overhead of precise schemes was cited as the reason they were not deployed. Kuznetsov et al. (“Code-Pointer Integrity,” OSDI 2014) attacked the problem from a different angle. Instead of checking every control transfer, protect the data that control transfers depend on.
The key observation is that only a small fraction of memory accesses touch code pointers — function pointers, return addresses, vtable pointers — or pointers that eventually lead to code pointers. If those values could never be corrupted, then control-flow hijacking would be impossible, no matter how badly the rest of memory were corrupted.
- Code-Pointer Integrity (CPI) uses static analysis to identify all sensitive pointers (code pointers and pointers through which code pointers are reached), moves them into an isolated safe region, and adds memory-safety (bounds) checks only to accesses of those sensitive pointers. Regular memory accesses cannot reach the safe region, so corrupting a buffer cannot change a code pointer. The paper reported overheads around 8% on SPEC CPU2006 for CPI.
- Code-Pointer Separation (CPS) is a relaxed version: it isolates only the code pointers themselves (not pointers to code pointers) in the safe region, with lower overhead (under 2% in the paper) and weaker but still strong guarantees.
- The SafeStack component — moving return addresses and spill slots onto a
separate stack from address-taken local buffers — shipped in Clang as
-fsanitize=safe-stack.
regular memory safe region
+-----------------------------------+ +-------------------------+
| buffers, ints, strings, ... | | function pointers |
| (may be corrupted by an overflow) | | return addresses |
| | | vtable pointers |
| struct handler { | | (+ bounds metadata) |
| char name[16]; ------------- | -X-> | accessed only by |
| <fp moved out> ---------------|----->| instrumented code |
| }; | | |
+-----------------------------------+ +-------------------------+
The central idea of CPI, in one sentence: protect code pointers and their related metadata from unauthorized modification, rather than encrypt every pointer or forbid code pointers from existing.
Going deeper. The safe region must be hidden or hardware-isolated. On 64-bit x86 without segmentation, CPI relied on hiding the region at a random address; later work showed that this information hiding could be defeated with timing side channels that probe for the region’s location. Hardware isolation mechanisms such as Intel MPK (memory protection keys) have since been proposed to protect such regions.
8.6 CFI in Production: Clang/LLVM Forward-Edge CFI
Tice et al. (“Enforcing Forward-Edge Control-Flow Integrity in GCC & LLVM,” USENIX
Security 2014) brought type-based forward-edge CFI into production compilers. Its
descendant ships in Clang today as -fsanitize=cfi and is deployed in Chrome and
Android. The idea, as the slides put it: create an indirect jump table for all
function-call targets, and make the check at each call site a cheap range test on
that table.
“All problems in computer science can be solved by another level of indirection.” — David Wheeler (often quoted together with “…except for the problem of too many layers of indirection”)
How it works for C indirect calls (-fsanitize=cfi-icall):
- At link time (CFI needs the whole program, hence LTO), the compiler collects every address-taken function and groups them by type signature.
- For each type, it emits a jump table: a contiguous array of equally sized
entries, each of which is just
jmp real_function. - Every place the program takes a function’s address now gets the address of its jump-table entry instead.
- Before each indirect call through a pointer of type T, the compiler inserts a check that the pointer lies inside T’s jump table and is properly aligned to an entry boundary — a subtraction, a rotate, and a compare.
jump table for type void(int): call site: fp(10) with fp : void(*)(int)
+--------------------------+
| entry 0: jmp log_stdout | <-- base off = fp - base
| entry 1: jmp log_file | if off not multiple of entry size
| entry 2: jmp set_level | or off >= 3*entry size: trap (ud2)
+--------------------------+ call *fp
C++ virtual calls (-fsanitize=cfi-vcall) are handled the same way: the vtable
pointer loaded from an object must point into the set of vtables valid for the
static type of the object at the call site.
A small experiment:
/* cfi_demo.c */
#include <stdio.h>
#include <string.h>
struct handler {
char name[16];
void (*cb)(int);
};
void greet(int x) { printf("hello %d\n", x); }
int not_a_callback(long x) { printf("pwned (x=%ld)\n", x); return 0; }
int main(int argc, char *argv[])
{
struct handler h = { "demo", greet };
void *evil = (void *)not_a_callback; /* address-taken, wrong type */
if (argc > 1)
memcpy(&h.cb, &evil, sizeof evil); /* simulate a corrupted pointer */
h.cb(42);
return 0;
}
$ clang -O1 cfi_demo.c -o nocfi
$ ./nocfi x
pwned (x=42) # the wrong-type call "worked"
$ clang -O1 -flto -fuse-ld=lld -fvisibility=hidden -fsanitize=cfi cfi_demo.c -o withcfi
$ ./withcfi
hello 42
$ ./withcfi x
Illegal instruction (core dumped)
Without CFI the corrupted pointer is called blindly. With CFI the check at h.cb(42)
sees that not_a_callback is not a void (int) function and executes a trap
instruction. (Adding -fno-sanitize-trap=cfi produces a diagnostic message instead of
a bare trap, which is useful while debugging.) Note what CFI did not do: the
memcpy still corrupted memory. Had the attacker redirected cb to another
address-taken void (int) function, the call would have been allowed.
Note. On Ubuntu 20.04, install
lld(sudo apt install lld) for the-fuse-ld=lldlink step. The default linker cannot do Clang’s LTO.-fltois required because the jump tables and type sets must be computed over the whole program, and-fvisibility=hiddentells the compiler that classes and functions are not shared with other shared objects, so it can see all legitimate targets. Cross-DSO CFI (-fsanitize-cfi-cross-dso) relaxes this at some cost.
8.7 Context-Sensitive CFI
Type-based CFI over-approximates because a static, type-based analysis must allow every target that any execution might use. But at runtime, the program has already taken a particular path, and that history often pins the target down to one function.
void (*handler)(int);
if (is_admin(user))
handler = admin_action; /* type void(int) */
else
handler = guest_action; /* type void(int) */
...
handler(req); /* type-based CFI allows BOTH, regardless of the path taken */
Context-sensitive CFI uses execution history to make the policy more precise:
- Path sensitivity: the allowed target depends on the path the program took to reach the call. PITTYPAT (Ding et al., USENIX Security 2017) uses Intel Processor Trace to record the executed path efficiently and runs a points-to analysis along that path in parallel, so at the indirect call it knows exactly which function the pointer can legitimately hold.
- Call-site / origin sensitivity: the allowed target depends on where the pointer value came from. OS-CFI (Khandaker et al., USENIX Security 2019) tracks the origin of each code pointer — the instruction that last wrote it — and checks the (target, origin) pair, which removes most of the remaining ambiguity for C function pointers and C++ virtual calls.
The trade-off is the usual one: more precision costs more runtime machinery, and these designs typically rely on hardware tracing or protected metadata to stay efficient.
8.8 Hardware-Assisted CFI
Software CFI pays for every check in instructions. Since the mid-2010s, CPU vendors have added CFI primitives that make the common cases nearly free and, crucially, work with no change to the source of legacy code — only a recompile.
Intel Control-flow Enforcement Technology (CET)
CET has two parts:
Indirect Branch Tracking (IBT) — a coarse forward-edge policy. Two new
instructions, endbr32 and endbr64 (collectively ENDBRANCH), mark valid targets
of indirect calls and jumps. After an indirect call or jmp, the CPU enters a
“wait-for-ENDBRANCH” state; if the next instruction executed is not an endbr, it
raises a control-protection fault (#CP). The encodings were chosen to be nops on
older processors, so CET-compiled binaries still run everywhere.
log_stdout:
endbr32 # f3 0f 1e fb -- "valid indirect-branch target"
push %ebp
mov %esp, %ebp
...
call *%ecx --> lands on endbr32? yes: continue
no: #CP fault, process killed
IBT alone is coarse-grained — any function entry is allowed — but it eliminates jumps into the middle of functions, which is where most useful ROP/JOP gadgets live.
Shadow Stack (SHSTK) — a hardware backward-edge policy. On call, the CPU pushes
the return address on both the normal stack and a shadow stack, whose pages are
marked with a special page-table type that ordinary mov instructions cannot write.
On ret, it pops both and raises #CP on a mismatch. This is exactly the shadow
stack of §8.3, with the protection problem solved by the MMU.
Compiler support is a single flag:
$ gcc -fcf-protection=full prog.c -o prog # emit endbr + mark the ELF as CET-ready
$ objdump -d prog | grep -m3 endbr
1040: f3 0f 1e fa endbr64
...
$ readelf -n prog | grep -i feature
Properties: x86 feature: IBT, SHSTK
Ubuntu’s GCC enables -fcf-protection by default, so you will see endbr64 at the
top of almost every function you disassemble on a modern Ubuntu system — now you know
why. Whether the protection is enforced depends on the CPU (Intel since Tiger Lake,
AMD since Zen 3 for shadow stacks), the kernel, and the C library. On Linux,
user-space shadow stack support for x86 was merged in kernel 6.6 and is enabled per
process by glibc; you can check CPU support with:
$ grep -o -w -E 'ibt|shstk|user_shstk' /proc/cpuinfo | sort -u
Try it. The slides’
cet-support.cprogram queries CPUID for the CET feature bits directly. CPUID leaf 7, subleaf 0 reports shadow-stack support inECXbit 7 and IBT support inEDXbit 20.
ARM: Pointer Authentication and BTI
ARM took a cryptographic route for the backward edge. Pointer Authentication
(PAC), added in ARMv8.3-A, stores a short MAC — computed from the pointer, a
context value (typically the stack pointer), and a secret key held in system
registers — in the unused high bits of a 64-bit pointer. A function signs its return
address in the prologue (paciasp) and verifies it before returning (autiasp); a
corrupted return address fails authentication. Branch Target Identification
(BTI), added in ARMv8.5-A, is the analogue of IBT: indirect branches must land on a
bti landing-pad instruction. Apple’s arm64e platform and recent Android/Linux
kernels use these features.
Going deeper. Hardware CFI does not end the arms race. IBT is coarse, so whole-function reuse (calling
systemormprotectthrough a corrupted function pointer) still works; data-only attacks that never touch a code pointer are outside CFI’s threat model entirely. Research continues on combining hardware primitives with finer-grained type checks — for example, the Linux kernel’s kCFI combines a type-hash check at each indirect call with IBT.
8.9 Where CFI Stands
| Approach | Edge | Precision | Cost | Status |
|---|---|---|---|---|
| Original label-based CFI (2005) | both | static CFG, label classes | 10–20%+ | research |
| Coarse binary CFI | both | any function / any call-preceded site | low | bypassed (2014–15) |
Clang -fsanitize=cfi | forward | type signature | ~1% | deployed (Chrome, Android) |
| CPI / CPS / SafeStack | both (via data) | protects code pointers | 1–8% | SafeStack in Clang |
| Context-sensitive CFI | forward | path / origin | higher; needs tracing | research |
| Intel CET (IBT + SHSTK) | both | coarse fwd + precise back | ~0 | shipping hardware |
| ARM PAC + BTI | both | MAC on pointers + landing pads | ~0 | shipping hardware |
The lesson is the one from Chapter 1: no mechanism is free, and deployment follows cost. CFI was published in 2005; it became mainstream only when compiler-integrated type-based checks and hardware shadow stacks drove its overhead toward zero. And because CFI does not stop memory corruption itself, the long-term answer remains eliminating the corruption — the subject of memory-safe languages such as Rust (Optional Rust lab).
Check Your Understanding
1. What does Control-Flow Integrity primarily enforce? A. Every memory access stays within the allocated object. B. Every control-flow transfer goes to a valid destination according to a predefined policy. C. Return addresses are encrypted before being stored on the stack. D. Code pages cannot be modified at runtime.
Answer
B. (A) is spatial memory safety; (C) describes one hardware technique (pointer authentication) that can be used for backward-edge protection; (D) is W⊕X, which CFI assumes as a prerequisite but does not itself enforce.
2. What is the central idea behind Code-Pointer Integrity (CPI)? A. Encrypt every pointer in the program. B. Prevent code pointers from ever being stored in memory. C. Protect code pointers and related metadata from unauthorized modification. D. Restrict all pointers to point to the heap.
Answer
C. CPI identifies sensitive pointers (code pointers and pointers used to reach them), stores them in an isolated safe region, and enforces memory safety only for accesses to them. Code pointers still live in memory — just in a region that ordinary, possibly corrupted, accesses cannot reach.
3. Consider this indirect call. With forward-edge CFI, which attack is the system mainly trying to prevent?
void (*fp)(int);
...
fp(10);
A. Changing 10 to another integer. B. Changing fp so that it points to an invalid
function. C. Changing the machine code of the called function. D. Causing a stack
overflow in fp.
Answer
B. Forward-edge CFI checks the target of the indirect call. Changing the argument (A) is a data attack CFI does not address; changing machine code (C) is prevented by W⊕X; (D) is unrelated.
4. Why is a shadow stack more precise than any static CFG for return instructions?
Answer
A static CFG must allow a function’s ret to go to every return site of every call
to that function, because it cannot know which call is active. For widely used
functions such as memcpy, that is hundreds of targets. A shadow stack records the
actual return address pushed by the actual call, so at runtime exactly one target
is allowed.
5. A program is compiled with Clang’s -fsanitize=cfi. An attacker with a heap
overflow overwrites a void (*)(char *) function pointer. Name one target the
attacker can still reach and one they cannot.
Answer
They can still reach any address-taken function whose type is void (char *)
(for example, if the program anywhere takes the address of a logging function with that
signature). They cannot reach system if its type does not match (int (const char *)),
nor the middle of any function, nor a function whose address is never taken. If an
address-taken void (char *) function does something dangerous with its argument,
the attack may still succeed — CFI limits targets; it does not judge their semantics.
6. Why must CFI be combined with a non-executable data policy (W⊕X)?
Answer
If data were executable, the attacker could inject code that contains no CFI checks (or forge a valid label in front of it) and jump there. If code were writable, the attacker could simply overwrite the checks. CFI’s guarantees assume code is immutable and data is not executable.
7. On a modern Ubuntu system you disassemble /bin/ls and see endbr64 at the
start of nearly every function. What is it, what does it cost on a CPU without CET,
and what attacks does it hinder on a CPU with IBT enabled?
Answer
It is Intel CET’s ENDBRANCH marker, emitted because Ubuntu’s GCC enables
-fcf-protection by default. On CPUs without CET it executes as a nop, costing
essentially nothing. With IBT enforced, an indirect call or jump that does not land
on an endbr raises a control-protection fault, so jump-oriented or call-oriented
gadgets in the middle of functions become unusable as indirect-branch targets.
Summary
- Control-flow hijacking abuses indirect transfers: forward edges (indirect calls/jumps through function pointers and vtables) and backward edges (returns).
- CFI computes a CFG ahead of time and instruments every indirect branch to check its runtime target against it, typically with labels on valid targets. It assumes W⊕X and tolerates an attacker who controls all of data memory.
- Shadow stacks give precise backward-edge protection by keeping a protected copy of each return address.
- CFI is only as strong as its precision. Coarse-grained CFI was bypassed with call-preceded and entry-point gadgets; even precise static CFI needs a shadow stack.
- CPI/CPS protect code pointers as data in an isolated safe region instead of checking every branch.
- Clang/LLVM CFI enforces type-based forward-edge checks via jump tables (needs
-flto -fvisibility=hidden); context-sensitive CFI uses path or origin history for more precision. - Hardware CFI — Intel CET (IBT + shadow stack) and ARM PAC/BTI — brings the cost close to zero and is now shipping, though IBT’s forward-edge policy is coarse.
Connection to the Labs
Lab 2 builds a return-to-libc attack and a short ROP chain. After
finishing it, think about which edge each step of your exploit violates: the
overwritten return address in bof() is a backward-edge violation that a shadow stack
would catch immediately, while jumping to the start of system() would satisfy a
coarse forward-edge policy such as IBT. As an optional exercise, recompile the lab’s
vulnerable program with -fcf-protection=full and inspect the result with
objdump -d and readelf -n; on a CET-capable machine with user shadow stacks
enabled, observe how the attack fails.
Further Reading
- Martín Abadi, Mihai Budiu, Úlfar Erlingsson, and Jay Ligatti. “Control-Flow Integrity.” ACM CCS, 2005. Extended version: “Control-Flow Integrity: Principles, Implementations, and Applications.” ACM TISSEC 13(1), 2009.
- Volodymyr Kuznetsov, László Szekeres, Mathias Payer, George Candea, R. Sekar, and Dawn Song. “Code-Pointer Integrity.” USENIX OSDI, 2014.
- Caroline Tice, Tom Roeder, Peter Collingbourne, Stephen Checkoway, Úlfar Erlingsson, Luis Lozano, and Geoff Pike. “Enforcing Forward-Edge Control-Flow Integrity in GCC & LLVM.” USENIX Security, 2014.
- Enes Göktaş, Elias Athanasopoulos, Herbert Bos, and Georgios Portokalidis. “Out of Control: Overcoming Control-Flow Integrity.” IEEE S&P, 2014.
- Nicholas Carlini, Antonio Barresi, Mathias Payer, David Wagner, and Thomas R. Gross. “Control-Flow Bending: On the Effectiveness of Control-Flow Integrity.” USENIX Security, 2015.
- Ren Ding et al. “Efficient Protection of Path-Sensitive Control Security.” USENIX Security, 2017.
- Mustakimur Rahman Khandaker et al. “Origin-sensitive Control Flow Integrity.” USENIX Security, 2019.
- Clang documentation, “Control Flow Integrity”: https://clang.llvm.org/docs/ControlFlowIntegrity.html
- Intel CET overview (Linux Plumbers Conference 2020): https://lpc.events/event/7/contributions/729/attachments/496/903/CET-LPC-2020.pdf