Skip to main content
Be Bitwise
CSecurity-Focused C

Hardening C Programs

Even well-written C code benefits from compiler-level and OS-level hardening. These defenses raise the cost of exploitation when bugs slip through code review, which they will.

Compiler Security Flags

Modern compilers offer several flags that add runtime protections:

Stack Protector

bash
gcc -fstack-protector-strong program.c -o program

This wedges a stack canary between local variables and the saved return address: a random value the function checks just before returning. If an overflow trampled it, the program aborts rather than handing control to whatever the attacker wrote next.

Variants:

  • -fstack-protector: Protects functions with buffers larger than 8 bytes
  • -fstack-protector-strong: Protects functions with any local arrays or address-taken locals
  • -fstack-protector-all: Protects every function (slower, but maximum coverage)

FORTIFY_SOURCE

bash
gcc -D_FORTIFY_SOURCE=2 -O2 program.c -o program

This swaps strcpy, memcpy, sprintf and friends for bounds-checked versions whenever the compiler can pin down the destination size. Detected overflow means abort.

It needs optimisation (-O1 or higher) to do anything. Level 2 adds stricter checks on top of level 1. Level 3 (GCC 12 or Clang with glibc 2.34 or later) also covers buffers whose size is only known at run time, such as malloc(n), and several distributions now build their packages with it, so use -D_FORTIFY_SOURCE=3 when your toolchain supports it.

Position-Independent Executable (PIE)

bash
gcc -pie -fPIE program.c -o program

PIE lets Address Space Layout Randomisation (ASLR) scramble where the executable's code and data land in memory. ROP gets harder when the attacker can't predict where their gadgets will be.

Key Concept

ASLR randomizes the base addresses of the executable, shared libraries, stack, heap, and mmap regions each time a program runs. Without PIE, the executable itself is loaded at a fixed address, giving attackers a stable target.

Read-Only Relocations

bash
gcc -Wl,-z,relro,-z,now program.c -o program
  • -z relro (partial RELRO): Makes the GOT (Global Offset Table) header read-only after loading.
  • -z now (full RELRO): Resolves all symbols at load time and makes the entire GOT read-only. This prevents GOT overwrite attacks.

Non-Executable Stack, CET and Initialised Locals

bash
gcc -Wl,-z,noexecstack -fcf-protection=full -ftrivial-auto-var-init=zero program.c -o program
  • -z noexecstack marks the stack non-executable (NX, also called DEP). Modern toolchains do this by default, but one stray assembly file without a .note.GNU-stack section can quietly turn it off for the whole binary.
  • -fcf-protection=full (x86 only) emits Intel CET markers: endbr64 landing pads for indirect branches and shadow-stack compatibility, so ROP and JOP chains fail on CPUs and kernels that enforce it.
  • -ftrivial-auto-var-init=zero (GCC 12+, Clang) zeroes uninitialised locals, so a forgotten initialisation can't leak old stack contents.

Check the result with checksec --file=./program, which reports RELRO, the stack canary, NX, PIE and FORTIFY status in one line.

The Complete Hardening Recipe

bash
gcc -Wall -Wextra -Werror \
-fstack-protector-strong \
-D_FORTIFY_SOURCE=3 \
-O2 \
-pie -fPIE \
-Wl,-z,relro,-z,now,-z,noexecstack \
-fcf-protection=full \
-Wformat -Wformat-security \
program.c -o program

Static Analysis

Static analysis tools examine source code without running it, finding potential bugs:

cppcheck

bash
cppcheck --enable=all --error-exitcode=1 src/

cppcheck finds:

  • Buffer overflows
  • Null pointer dereferences
  • Memory leaks
  • Unused functions and variables
  • Style issues

Compiler Warnings as Static Analysis

GCC and Clang have extensive warning flags that catch common bugs:

bash
gcc -Wall -Wextra -Wpedantic \
-Wformat=2 \
-Wconversion \
-Wshadow \
-Wstrict-prototypes \
-Wmissing-prototypes \
-Wdouble-promotion \
-Wnull-dereference \
-Wcast-align \
-Wcast-qual \
program.c

Key warnings:

  • -Wformat=2: Extended format string checks
  • -Wconversion: Implicit type conversions that may lose data
  • -Wshadow: Variable shadowing (a local hides an outer variable)
  • -Wnull-dereference: Potential null pointer dereferences

Fuzzing Your Own Code

Fuzzing throws random or semi-random inputs at your code until something breaks. It's brutally effective at finding edge cases humans skip right past.

AFL (American Fuzzy Lop)

bash
# Compile with AFL++'s instrumented compiler (afl-gcc is the legacy wrapper)
afl-cc -o fuzz_target program.c
# Create seed inputs
mkdir input output
echo "sample input" > input/seed.txt
# Run the fuzzer
afl-fuzz -i input -o output ./fuzz_target

libFuzzer (built into Clang)

Write a fuzz target function:

c
// fuzz_target.c
#include <stdint.h>
#include <stddef.h>
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
// Call the function you want to fuzz
// with the random data
if (size < 4) return 0;
parse_message((const char *)data, size);
return 0;
}
bash
clang -fsanitize=fuzzer,address -g fuzz_target.c parser.c -o fuzzer
./fuzzer # Runs indefinitely, finding crashes

Fuzzing plus AddressSanitizer is the combination you want — the fuzzer generates inputs, and ASan catches memory errors that wouldn't otherwise crash visibly.

Hardening Checklist

For every C program you ship:

Compilation:

  • -Wall -Wextra -Werror
  • -fstack-protector-strong
  • -D_FORTIFY_SOURCE=3 (or =2 on older toolchains)
  • -pie -fPIE
  • -Wl,-z,relro,-z,now,-z,noexecstack
  • -fcf-protection=full on x86
  • Confirm with checksec

Static Analysis:

  • Run cppcheck (or similar tool)
  • Address all compiler warnings
  • Review all uses of dangerous functions

Dynamic Analysis:

  • Run test suite with AddressSanitizer
  • Run test suite with UndefinedBehaviorSanitizer
  • Fuzz critical input parsing code
  • Run Valgrind for leak checking

Code Review:

  • Verify all buffers have bounds checks
  • Verify all allocations are checked for NULL
  • Verify all format strings are literal
  • Verify integer arithmetic cannot overflow at trust boundaries

Real-World Impact

None of this is theoretical. The track record is on paper:

  • Stack protectors have killed thousands of stack overflow exploits before they landed
  • ASLR with PIE forces return-to-libc and ROP exploits to find an information leak first, which turns many one-shot bugs into two-bug chains
  • FORTIFY_SOURCE has caught buffer overflows in deployed software you've used today
  • Fuzzing has unearthed thousands of bugs in browsers, image parsers, and network protocols

Every flag and tool here traces back to a real vulnerability that hit real users. Use them all.