Skip to main content
Be Bitwise

Binary Hardening & Secure Development

Defensive Exploitation & Red Team Techniques · Defense & Forensics track

9 min read

In this module

Making Exploitation Harder

Throughout this curriculum, you've learned how attackers exploit memory corruption. Hardening is the other side: configuring compilers, linkers, and operating systems to make exploitation as painful as possible, even when bugs inevitably exist.

No hardening eliminates bugs. But it raises the bar. A trivially exploitable bug in an unhardened binary might need a multi-stage exploit chain against a hardened one — or might not be exploitable at all.

Compiler Security Flags

Modern compilers (GCC and Clang) support numerous security-related options. Understanding what each one does is essential for building secure software.

Stack Canaries (-fstack-protector-strong): Inserts a random value (the canary) between local variables and the saved return address. Before the function returns, it checks whether the canary has been modified. If it has, the program aborts. This detects sequential stack buffer overflows that overwrite the return address.

text
Stack with canary:
[ local buffer ]
[ CANARY VALUE ] ← random, checked before return
[ saved RBP ]
[ return address]

The -fstack-protector-strong variant protects functions that have local arrays, take address of local variables, or use alloca. The older -fstack-protector-all protects every function but adds more overhead.

FORTIFY_SOURCE (-D_FORTIFY_SOURCE=2, or 3 with GCC 12+ or Clang 9+ and glibc 2.34+): Replaces common C library functions (memcpy, strcpy, sprintf, etc.) with bounds-checked versions. When the compiler can determine the size of the destination buffer at compile time, the checked version verifies that the copy will not overflow.

c
char buf[64];
memcpy(buf, src, n);
/* With FORTIFY_SOURCE=2, this becomes: */
__memcpy_chk(buf, src, n, 64); /* Aborts if n > 64 */

FORTIFY_SOURCE catches many simple buffer overflows with minimal performance overhead (typically less than 1%).

Position-Independent Executable (-fPIE -pie): Compiles the executable as position-independent code and links it as a PIE. This enables ASLR for the main executable (not just shared libraries), randomizing the base address of the program's code and data on each execution.

PIE (Position-Independent Executable)

A Position-Independent Executable is compiled so that it can be loaded at any address in memory. Combined with ASLR, this means the program's code, global data, and GOT/PLT are at unpredictable addresses. Without PIE, the main executable is always loaded at a fixed address, giving attackers known code locations for ROP gadgets.

RELRO (-Wl,-z,relro,-z,now): Full RELRO (Relocation Read-Only) resolves all dynamic symbol lookups at load time and then marks the GOT (Global Offset Table) as read-only. This prevents GOT overwrite attacks, where an attacker modifies a GOT entry to redirect a library function call to their own code.

text
Partial RELRO: GOT is writable → GOT overwrite possible
Full RELRO: GOT is read-only after startup → GOT overwrite blocked

Control Flow Integrity (-fsanitize=cfi): Clang's CFI implementation adds type checks to indirect calls and virtual function calls. Each call site verifies that the target function has the expected type signature. This blocks attacks that redirect indirect calls to unintended targets. It only covers this forward edge: returns aren't checked, so ROP needs a separate defence such as a shadow stack (Intel CET's shadow stack, or Clang's ShadowCallStack on AArch64).

Intel CET (-fcf-protection=full): GCC and Clang emit endbr64 landing pads at every legitimate indirect-branch target and mark the binary as CET-compatible. On a CPU with CET, the hardware keeps a second, write-protected copy of each return address (the shadow stack) and faults if ret pops a value that doesn't match. That's the backward edge CFI leaves open. The binary only gets it when the kernel and the C library turn it on as well (Linux's option is X86_USER_SHADOW_STACK, and glibc enables it at load time for binaries carrying the CET marking), so the flag is cheap insurance that switches on as the platform catches up.

Stack clash protection (-fstack-clash-protection): Probes each page as a large stack frame or alloca grows, so the stack can't jump over the guard page into the heap or another mapping.

Linker and OS-Level Hardening

Beyond compiler flags, the linker and operating system provide additional hardening:

NX/DEP: Marking the stack and heap as non-executable. This is enabled by default on modern systems and prevents classic shellcode injection.

ASLR: The operating system randomizes the base addresses of the stack, heap, shared libraries, and (with PIE) the main executable. Modern Linux provides full ASLR with reasonable entropy.

seccomp: Covered again in the kernel exploitation module, seccomp restricts which system calls a process can make. For programs that do not need extensive OS interaction (parsers, renderers, network protocol handlers), seccomp dramatically reduces the kernel attack surface.

Namespaces and cgroups: Linux namespaces isolate processes from each other and from the host system. Mount namespaces, PID namespaces, network namespaces, and user namespaces each limit what a process can see and do.

Checking Binary Hardening

You can check whether a binary has been compiled with proper hardening using tools like checksec:

text
$ checksec --file=/usr/bin/nginx
RELRO STACK CANARY NX PIE
Full RELRO Canary found NX enabled PIE enabled
FORTIFY Fortified Fortifiable
Yes 12 15

This shows that nginx has Full RELRO, stack canaries, NX, and PIE enabled, and 12 of 15 fortifiable functions are using checked versions. This is a well-hardened binary.

A poorly configured build might show:

text
RELRO STACK CANARY NX PIE
No RELRO No canary found NX enabled No PIE

This binary is missing critical hardening features and would be significantly easier to exploit.

Harden it: which flag turns each "bad" column above into the "good" one, and what does each fix cost?
  • No RELRO → Full RELRO: link with -Wl,-z,relro,-z,now. Every symbol is bound at start-up, so launch is a little slower for programs with many imports.
  • No canary found → Canary found: -fstack-protector-strong. A few instructions in each protected function's prologue and epilogue.
  • No PIE → PIE enabled: -fPIE -pie. On x86-64 the cost is small, since code addresses data RIP-relative anyway.
  • FORTIFY: -D_FORTIFY_SOURCE=2 (or 3 on newer GCC and glibc), which only does anything with optimisation on (-O1 or higher). That catches people out: a -O0 debug build shows no fortified functions however you set the macro.

Many distributions already turn most of these on by default, so run checksec on a plain gcc build before assuming you start from the bad row.

Secure Coding Practices

Hardening mitigates exploitation, but the best defence is not having vulnerabilities in the first place. Secure coding practices reduce the number of bugs:

Use safe functions: Replace strcpy with snprintf or strlcpy (in the BSDs and macOS, and in glibc only since 2.38). Be wary of strncpy: it doesn't add a NUL when the source fills the buffer, and it zero-pads the rest. Replace sprintf with snprintf. Replace gets (never use gets) with fgets. Replace memcpy of untrusted sizes with bounds-checked versions.

Validate all input: Check sizes, bounds, and types of all input before using it. Validate not just at the entry point but at every function that processes external data.

Integer overflow checks: Use safe arithmetic functions that detect overflow before it happens. The compiler builtins __builtin_add_overflow, __builtin_mul_overflow, etc., perform the operation and return whether it overflowed.

c
size_t total;
if (__builtin_mul_overflow(count, element_size, &total)) {
return ERROR_OVERFLOW;
}
void *buf = malloc(total);

The runner puts three of those habits side by side: a strncpy that silently leaves a string unterminated, the snprintf version that truncates safely and tells you so, and __builtin_mul_overflow catching a size that would have wrapped. Predict what the first line prints before you run it.

Try itPredict the strncpy line first, then shorten the name to fit in 8 bytes and see all three behave.
C (GCC 9.2.0)

Minimise pointer lifetime: Free resources as soon as they are no longer needed. Null out pointers after freeing to prevent use-after-free (though this is not foolproof with copies of the pointer).

Use memory-safe languages: For new code, using Rust, Go, or other memory-safe languages eliminates entire classes of vulnerabilities. For existing C/C++ codebases, gradually rewriting critical components in memory-safe languages reduces risk.

The Defence Stack

The most secure software combines multiple hardening layers:

text
Layer 1: Memory-safe language (eliminates most bugs)
↓ If C/C++ is required:
Layer 2: Secure coding practices (reduces bugs)
Layer 3: Static analysis (finds bugs at compile time)
Layer 4: Fuzzing + sanitizers (finds bugs through testing)
Layer 5: Compiler hardening (stack canaries, FORTIFY, CFI)
Layer 6: Linker hardening (RELRO, PIE)
Layer 7: OS hardening (ASLR, NX, seccomp, sandboxing)
Layer 8: Runtime monitoring (crash reporting, anomaly detection)

Each layer catches bugs that earlier layers missed. The combination makes exploitation dramatically harder. An attacker facing a well-hardened binary in a sandboxed, ASLR-enabled environment with seccomp restrictions must chain multiple sophisticated techniques - or find a different target.

This is defence in depth as engineering practice. No single layer holds on its own, but stacked together they push the cost of exploitation beyond what most attackers are willing to invest — and that's the actual goal.