Binary Hardening Techniques
Binary hardening is the practice of switching on compiler and linker features that make exploitation expensive even when bugs slip into the source. These are defence-in-depth moves — they don't fix bugs, but they raise the cost of turning a bug into a working exploit substantially. Every production binary should ship with the full set of hardening flags on.
This lesson walks through each major hardening technique, explains what it does at the assembly level, and shows the concrete diffs between hardened and unhardened output.
For the theoretical foundation on compiler defenses, see Compiler and Linker Hardening.
The Complete Hardening Flag Set
The recommended hardening set for GCC on Linux looks like this:
gcc -fstack-protector-strong \ -D_FORTIFY_SOURCE=2 \ -fPIE -pie \ -Wl,-z,relro,-z,now \ -fcf-protection \ -fno-delete-null-pointer-checks \ -O2 \ -o hardened program.cTime to crack each flag open.
1. Stack Canaries: -fstack-protector-strong
Stack canaries park a random value — the "canary" — between local buffers and the saved frame pointer. Before the function returns, it re-checks the canary. If an overflow trampled it, the program aborts before the corrupted return address gets a chance to run.
Without stack protection:
vulnerable: push rbp mov rbp, rsp sub rsp, 80 ; ... function body ... leave ret ; no canary checkWith -fstack-protector-strong:
vulnerable: push rbp mov rbp, rsp sub rsp, 96 ; extra space for canary
; === CANARY INSERTION === mov rax, qword fs:[0x28] ; load canary from TLS mov qword [rbp-8], rax ; place it on stack above saved rbp xor eax, eax ; clear rax (prevent leaking canary value)
; ... function body (buffer is below the canary) ...
; === CANARY VERIFICATION === mov rax, qword [rbp-8] ; reload canary from stack xor rax, qword fs:[0x28] ; compare with original jne .stack_smash_detected ; mismatch = corruption!
leave ret
.stack_smash_detected: call __stack_chk_fail ; prints error and calls abort()Set the protected and unprotected output side by side in the diff viewer:
Unhardened vs Hardened (-fstack-protector-strong)
x86-64Hover over code lines or mapping badges to see correspondences
Variants:
| Flag | What Gets Protected |
|---|---|
-fstack-protector | Functions with char arrays > 8 bytes |
-fstack-protector-strong | Functions with any arrays, address-taken locals, or calls to alloca |
-fstack-protector-all | Every function (maximum coverage, some performance cost) |
-fstack-protector-strong is the sensible default — it protects the functions most likely to bite without paying the overhead of guarding every function in the binary.
No single hardening technique is enough on its own. Canaries fall to info leaks (read the canary, splice it back into the overflow). ASLR falls to address leaks. DEP falls to ROP. Each defence addresses one slice of the attack chain; stacking them forces an attacker to defeat every layer at once. That principle — defence in depth — is the bedrock of modern binary security.
2. FORTIFY_SOURCE: -D_FORTIFY_SOURCE=2
FORTIFY_SOURCE swaps the dangerous libc functions for checked versions that know the destination buffer size:
Without FORTIFY_SOURCE:
; strcpy with no size checklea rdi, [rbp-64] ; destination buffermov rsi, rdx ; source stringcall strcpy ; copies until \0, no length checkWith -D_FORTIFY_SOURCE=2:
; __strcpy_chk with size verificationlea rdi, [rbp-64] ; destination buffermov rsi, rdx ; source stringmov rdx, 64 ; BUFFER SIZE passed as third argumentcall __strcpy_chk ; checks length before copying__strcpy_chk aborts via __chk_fail the moment the source outgrows the destination. At the assembly level, the giveaway is the extra mov rdx, SIZE argument before the call.
Functions that FORTIFY_SOURCE protects:
strcpy -> __strcpy_chkstrncpy -> __strncpy_chkstrcat -> __strcat_chksprintf -> __sprintf_chksnprintf -> __snprintf_chkmemcpy -> __memcpy_chkmemset -> __memset_chkLevels:
-D_FORTIFY_SOURCE=1: Checks that can't change the behaviour of a conforming program, at compile time where the size is known and at run time otherwise-D_FORTIFY_SOURCE=2: Adds stricter checks (sub-object bounds,%nin writable format strings) that can break some conforming programs-D_FORTIFY_SOURCE=3: Uses__builtin_dynamic_object_sizeso sizes known only at run time are checked too (GCC 12+, glibc 2.34+)
Every level needs optimisation switched on (-O1 or higher). At -O0 the macro does nothing and recent glibc warns about it.
3. PIE: -fPIE -pie
Position-Independent Executable (PIE) compiles the main binary as position-independent code, which lets ASLR randomise its base address. Without PIE, the main binary loads at a fixed address (usually 0x400000), and ROP gadgets in the binary become trivially addressable.
Without PIE (fixed addressing):
; Absolute addressing -- address hardcoded by linkermov rax, qword [0x404028] ; fixed GOT entry addresslea rdi, [0x402010] ; fixed string addresscall 0x401030 ; fixed PLT addressWith PIE (RIP-relative addressing):
; Position-independent -- all addresses relative to ripmov rax, qword [rip + 0x2f8a] ; GOT entry, rip-relativelea rdi, [rip + 0x1234] ; string address, rip-relativecall [rip + 0x2f90] ; PLT call, rip-relativeUnder PIE, every address reference in the binary encodes as an offset from rip. Because rip shifts with ASLR, the actual addresses move on every run. An attacker without the PIE base can't aim gadgets from the main binary.
4. RELRO: -Wl,-z,relro,-z,now
RELRO (Relocation Read-Only) protects the GOT (Global Offset Table) from getting overwritten. The GOT holds pointers to library functions, and that makes it prime real estate for exploitation.
Without RELRO:
GOT section: rw- (readable and writable)Attacker can overwrite a GOT entry to redirect a function callPartial RELRO (-Wl,-z,relro):
.got: r-- (read-only after relocation).got.plt: rw- (still writable -- lazy binding)Full RELRO (-Wl,-z,relro,-z,now):
.got: r-- (read-only).got.plt: r-- (read-only -- all symbols resolved at load time)The assembly-level difference shows up in how function calls actually resolve:
; Lazy binding (no full RELRO): first call resolves through PLT stubputs@plt: jmp qword [rip + puts@GOTPLT] ; initially points to resolver push 0x0 ; resolver index jmp .PLT0 ; call the dynamic linker
; Full RELRO: all GOT entries resolved at load time; GOT is then made read-only (mprotect); Attempting to overwrite a GOT entry triggers SIGSEGVWith full RELRO, the attacker can't redirect function calls by overwriting GOT entries — and that removes a sizeable category of exploit techniques from the table.
5. Control-Flow Integrity: -fcf-protection
Intel CET (Control-flow Enforcement Technology) bolts on hardware-assisted protection for both forward and backward edges:
-fcf-protection=branch (forward edge - indirect calls):
; With CET, indirect call targets must start with ENDBR64; If the target does not have ENDBR64, the CPU raises #CP
target_function: endbr64 ; marks this as a valid indirect call target push rbp mov rbp, rsp ; ...
; An indirect call: call qword [rax] ; CPU checks that [rax] starts with endbr64-fcf-protection=return (backward edge - shadow stack):
The CPU keeps a hardware shadow stack of return addresses. When ret runs, it compares the return address on the regular stack with the matching entry on the shadow stack. Any mismatch — i.e. a corruption — raises a fault.
; With shadow stack:; CALL pushes return address to BOTH the regular stack and shadow stack; RET checks that both values match; An attacker who overwrites the regular stack's return address; cannot modify the shadow stack (it is hardware-protected)-fcf-protection always emits the endbr64 markers and the ELF notes, but whether the CPU enforces anything depends on the whole stack. The Linux kernel supports shadow stacks for user space (kernel 6.6+ built with X86_USER_SHADOW_STACK) and glibc 2.39+ can turn them on, though it's off by default and every loaded library must be marked compatible. Indirect branch tracking is used inside the kernel only; user-space IBT isn't supported, so endbr64 in your program is a no-op today. On most current desktops and servers, treat CET as a mechanism you're preparing for rather than one that's protecting you.
6. Other Important Flags
-fno-delete-null-pointer-checks (optional): stops the compiler from optimising away null-pointer checks that it can prove redundant under the C rules. The Linux kernel builds with it because address 0 can be valid memory in kernel context. It isn't in the usual distro hardening set for applications, so treat it as an extra you can leave out of the list above.
-Wl,-z,noexecstack: explicitly marks the stack non-executable. Should be the default, but worth confirming.
-fstack-clash-protection: inserts probe instructions to detect and prevent stack-clash attacks where the stack grows down into other mappings.
Verifying Hardening with checksec
The checksec tool reports which protections are actually enabled on a compiled binary:
checksec --file=./target
# Output:# RELRO: Full RELRO# Stack: Canary found# NX: NX enabled# PIE: PIE enabled# FORTIFY: EnabledEach "enabled" is one more wall the attacker has to climb. A fully hardened binary with every protection on makes exploitation a much taller order — usually requiring multiple info leaks and a multi-stage attack just to land code execution.
Hardened vs Unhardened Comparison
Same function compiled both ways, hardening on and off:
# Unhardenedgcc -fno-stack-protector -no-pie -z execstack -z norelro -O0 -o vuln_soft vuln.c
# Hardenedgcc -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie -Wl,-z,relro,-z,now -fcf-protection -O2 -o vuln_hard vuln.cThe hardened binary lands slightly larger and a touch slower, but the security gain is dramatic. In the hardened version:
- Buffer overflows trip the canary before the corrupted return address ever runs
strcpyis swapped for__strcpy_chk, which actually checks the buffer size- Addresses all randomise (PIE + ASLR)
- The GOT is read-only (full RELRO)
- Indirect branch targets carry
endbr64markers, ready for CET where the kernel and CPU enforce it
Full hardening typically costs 1–5 % of performance for most applications. Stack canaries add a handful of instructions per function. PIE pays a small tax for RIP-relative addressing. Full RELRO costs startup time (every symbol resolves upfront) but takes the lazy resolver out of the first call to each function. FORTIFY_SOURCE adds one comparison per protected call. The cumulative overhead is dust compared to the security upside, which is exactly why every major Linux distro now compiles its system packages with full hardening switched on by default.
What is Next
The closing lesson of this module — and of the entire security track — is a capstone where you dissect a deliberately vulnerable binary, catalogue every vulnerability class on display, work out which mitigations are missing, and prescribe the hardening flags that lock it down. It pulls together everything from all four security modules.