Skip to content
systemcoding.dev
Security

The Complete Guide to Compiler and Linker Hardening Flags

Every GCC and Clang hardening flag that matters, with its minimum version, cost and effect on the binary, plus Make, CMake and Meson recipes and checks.

23 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, LLVM and C++ logos.

Hardening flags are the cheapest security work in a C or C++ project. Each one is a switch on the compiler or the linker that makes a class of bugs harder to exploit, easier to detect or impossible to build. They need no changes to the source, they cost little at run time and most of them are decades old. They are also easy to get wrong. A flag spelled differently in GCC and Clang, a flag that needs optimization to do anything, a flag that conflicts with another, a flag that a build system silently overrides: any of these leaves a binary unprotected while the build script looks perfect. This guide is the reference. It lists every flag that matters for security, grouped by the problem it addresses, with the minimum compiler version, what changes in the output, what it costs and how to confirm it took effect. It then gives recipes for Make, CMake and Meson, explains the all-in-one -fhardened option of GCC 14, and ends with the flags that sound protective and are not. Examples target GCC 15, Clang 20, binutils 2.45 and glibc 2.41 on x86-64 Linux 6.12.

How to think about flags

A flag does one of four jobs, and keeping the jobs apart makes the list easy to remember.

  1. Detect the bug at compile time. Warnings such as -Wformat-security and -Wstringop-overflow find bugs without running the program.

  2. Detect the bug at run time and stop. The stack protector, _FORTIFY_SOURCE, bounds trapping and sanitizers abort on a violation.

  3. Make the bug harder to exploit. PIE, RELRO, a non-executable stack and control-flow markers take away the attacker's next step.

  4. Remove undefined behavior that hides bugs. Zero-initializing locals and defining signed overflow make the program behave predictably.

Three rules apply to all of them.

  • Optimization changes what flags do. _FORTIFY_SOURCE does nothing at -O0, and many overflow warnings only appear at -O2, so harden the build you ship and not only the debug build.

  • Flags must reach every object. One object built without -fPIE, a CET marker or a stack note can weaken the final link. Static libraries and vendored code are the usual gaps.

  • The binary is the evidence. The only proof a flag worked is a property of the output, which the last section shows how to read.

This is the baseline for Linux user-space code, in the form it takes for GCC and Clang. It follows the guidance published by the OpenSSF for C and C++ and the defaults of the major distributions, and the sections below justify each line.

PurposeFlagGCCClangNeeds
warn about bad formats-Wformat=2 -Werror=format-securityallall
implicit declarations are errors-Werror=implicit-function-declarationallall
bad pointer and integer conversions are errors-Werror=incompatible-pointer-types -Werror=int-conversionallall
stack canary-fstack-protector-strong4.93.7
fortified libc-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=31217-O1 or higher, glibc 2.33 or later
stack clash probes-fstack-clash-protection811
position-independent code-fPIE for executables, -fPIC for librariesallall
position-independent link-pieallall
full RELRO-Wl,-z,relro,-z,nowallall
non-executable stack-Wl,-z,noexecstackallall
CET on x86-fcf-protection=full87
BTI and PAC on AArch64-mbranch-protection=standard99
zero locals-ftrivial-auto-var-init=zero128 (16 without a long extra flag)
hardened C++ library-D_GLIBCXX_ASSERTIONS or the libc++ hardening macroalllibc++ 18
defined wraparound where you rely on it-fno-strict-overflow or -fwrapvallall

The versions are the releases that introduced or stabilized each flag as far as we can state them from the compilers' documentation. If your toolchain is older than the column says, the flag is rejected or ignored, and a configure-time test, as the CMake post in this series shows, is how you avoid breaking the build.

Warnings that catch security bugs

Warnings are free, and a few of them are worth turning into errors.

The format family

-Wformat checks calls to printf-style functions against their format strings and comes with -Wall. -Wformat-security warns about calls where the format is not a string literal and there are no arguments, the shape of a format-string vulnerability. -Wformat=2 enables both and adds -Wformat-nonliteral, which warns about any non-literal format that is not forwarded by an annotated wrapper, and -Wformat-y2k. Promote the security case with -Werror=format-security. Wrappers need __attribute__((format(printf, N, M))) so the checks reach their callers.

Bounds and sizes

-Wstringop-overflow (on by default in GCC), -Warray-bounds (with -Wall at -O2), -Wformat-overflow=2 and -Wformat-truncation=2 report copies and formatted writes that provably exceed a destination. They depend on the optimizer's knowledge of sizes, so they need -O2 to be useful. -Walloc-size-larger-than= and -Wvla-larger-than= catch absurd allocation and stack sizes. -Wframe-larger-than= flags functions whose stack frame is large, a hint for stack-clash risk.

Conversions and signs

-Wconversion and -Wsign-conversion flag implicit narrowing and sign changes, the source of many size bugs, and are noisy enough that projects enable them for parsers and size-handling code only. -Wsign-compare is in -Wextra for C and finds the comparison between signed and unsigned values that turns -1 into a huge number.

Declarations and types

-Werror=implicit-function-declaration turns calls to undeclared functions into errors, which matters because the implicit return type is int and truncates pointers. -Werror=incompatible-pointer-types and -Werror=int-conversion stop the assignments that silently reinterpret pointers. GCC 14 and Clang 16 made these errors by default for C, so the explicit flags document intent and protect older compilers.

Control and flow

-Wimplicit-fallthrough finds switch cases that run into the next one. -Wnull-dereference reports paths where a null pointer is used. -Wshadow finds locals that hide others. -Wundef flags #if on an undefined macro. -Wtrampolines reports nested functions that require an executable stack. -Wvla and -Walloca flag the stack allocation that the attacker can size. GCC 12 added -Wbidi-chars, which detects bidirectional text control characters in source that can make code read differently than it compiles, a supply-chain defense.

The earlier post on turning on warnings gives a rollout order for a project with many existing warnings.

Compile-time and run-time checks on memory

Stack protector

-fstack-protector-strong places a canary in every function with a local array or an address-taken local and checks it before returning. -fstack-protector is narrower, -fstack-protector-all is wider, -fstack-protector-explicit is manual. The strong level is the default choice. It protects against linear stack overflows and fails with *** stack smashing detected ***. It costs a few instructions in protected functions and nothing elsewhere. Disable it for early-boot or kernel-like code with __attribute__((no_stack_protector)) (GCC 11).

Fortify source

-O2 -D_FORTIFY_SOURCE=3 swaps memcpy, strcpy, sprintf, read and a few dozen other functions for checked versions when the compiler can find the destination size, and at level 3 when it can compute it at run time. Add -U_FORTIFY_SOURCE before the define to avoid redefinition warnings from distribution compilers. It needs optimization, covers library calls and not your own loops and shows as __*_chk imports in the binary. Level 2 is the choice for glibc older than 2.33 or compilers that lack level 3.

Bounds trapping

For code that cannot afford the full sanitizer, both compilers can compile array-bound checks into the program and trap on a violation. With Clang, -fsanitize=bounds -fsanitize-trap=bounds inserts a compare and an ud2 instruction for each checked array access, with no runtime library. GCC has -fsanitize=bounds with -fsanitize-undefined-trap-on-error. The checks apply to arrays with known bounds, and they do not cover pointer arithmetic. Combine with -fstrict-flex-arrays=3 (GCC 13, Clang 16), which tells the compiler that only a real flexible array member, declared [], may be indexed past its declared size, and so that trailing arrays of one or zero elements are checked like any other.

Stack clash protection

-fstack-clash-protection probes each page of a large stack frame or variable-length allocation so the guard region faults and the stack cannot jump over it. It adds nothing to small frames. Use it everywhere.

Zeroing locals

-ftrivial-auto-var-init=zero initializes automatic variables that have no initializer, which removes a class of information leaks and uninitialized-value bugs. =pattern makes the bug loud in testing. It costs a store for each variable, and large stack arrays are the expensive case. The post on uninitialized memory covers the trade-offs, and __attribute__((uninitialized)) exempts a deliberate case.

Zeroing registers on return

-fzero-call-used-regs=used-gpr (GCC 11, Clang 15) clears the call-used registers that a function touched before it returns. It reduces the number of useful gadgets ending in a return and stops stale register contents from leaking to the caller. The cost is a few xor instructions per function.

Making exploitation harder in the binary

Position-independent executables

-fPIE at compile time and -pie at link time produce an executable that loads at a random address, so ASLR covers its code. Libraries use -fPIC -shared. Missing either half of the pair gives no ASLR or a link error. For a static executable, use -static-pie. The cost is negligible on x86-64 and arm64 and real on 32-bit x86.

Relro and bind now

-Wl,-z,relro makes the relocation-fixed sections read-only after loading, and adding -z now binds every symbol at startup so the whole global offset table can be read-only. Full RELRO is -Wl,-z,relro,-z,now. The price is resolving all imports before main, which matters mostly for short-lived programs with many imports.

Non-executable stack and no RWX segments

-Wl,-z,noexecstack forces the stack header to non-executable regardless of what objects ask for, and every assembly file should declare .section .note.GNU-stack,"",%progbits so the linker has no reason to disagree. GNU ld 2.39 and later warns about missing notes and about LOAD segments that are readable, writable and executable.

Control-flow markers

-fcf-protection=full on x86 inserts endbr64 at indirect-branch targets and marks the object as shadow-stack compatible. -mbranch-protection=standard on AArch64 enables return-address signing and branch target identification, with pac-ret+leaf available to sign leaf functions too. Neither costs anything on hardware that lacks the feature, and both give the loader and kernel the information they need to enable enforcement. Check the notes with readelf -n.

Clang control-flow integrity

-fsanitize=cfi with -flto -fvisibility=hidden checks indirect calls by function type and virtual calls by class hierarchy, and traps on a violation, with -fsanitize-cfi-cross-dso for shared libraries. It is available in Clang and not in GCC, and it needs whole-program builds. The post on control-flow integrity compares it with kCFI and the hardware features.

-Wl,-z,nodlopen marks an object as not loadable with dlopen, which shrinks the surface for libraries that are only ever linked. -Wl,--as-needed drops unused libraries from DT_NEEDED, -Wl,-z,separate-code puts code on its own pages (the default in recent binutils) and -Wl,--fatal-warnings turns linker warnings, such as missing stack notes, into errors. -Wl,-z,noexecheap is not a standard GNU option, and the heap is non-executable anyway.

Speculative execution flags

Some mitigations address the speculative execution side channels rather than memory corruption. They apply to specific threat models, mostly kernels, hypervisors and code that handles secrets in a shared environment.

FlagAddresses
-mindirect-branch=thunk -mfunction-return=thunk (GCC)Spectre variant 2, with retpoline thunks for indirect branches and returns
-mretpoline (Clang)Spectre variant 2
-mharden-sls=all (GCC on AArch64, Clang)straight-line speculation after unconditional branches
-mlfence-before-indirect-branch, -mlvi-hardening (Clang)load value injection

These carry real costs, since retpolines slow indirect calls, and the right choice depends on whether you run in an environment where the attack is in scope. Linux enables its own versions in the kernel configuration, and user-space programs seldom need them unless they host a sandbox.

Flags that define behavior you may rely on

Several flags change the language rules and belong with the hardening set because they remove undefined behavior that compilers exploit.

  • **-fno-strict-overflow and -fwrapv** give signed integer overflow defined two's-complement wrapping, so overflow checks written the natural way are not deleted. The Linux kernel builds with -fno-strict-overflow. They do not make the code correct, since a wrapped size is still wrong, and they stop the optimizer from removing your check.

  • **-fno-delete-null-pointer-checks** keeps the compiler from assuming a dereferenced pointer is non-null and deleting the later test, which the kernel also uses.

  • **-fno-strict-aliasing** disables type-based alias analysis for code that violates the aliasing rules and cannot be fixed immediately.

  • **-fno-common** puts tentative definitions of globals in .bss, so duplicate definitions fail at link time and do not silently merge. It is the default since GCC 10.

  • **-fexceptions** keeps unwind tables in C code, so exceptions from C++ callbacks propagate and stack unwinding in crash reports works.

  • **-fno-plt** makes calls to shared-library functions go through the global offset table directly. It helps with full RELRO and avoids a writable PLT target, at the cost of an indirect call.

Use each only when you can name the reason. -fno-strict-aliasing in particular is a performance cost that you should pay only for code you cannot fix.

GCC 14: -fhardened

GCC 14 added a single flag that enables a set of the options above, with a rule that explicit flags override it. -fhardened turns on, where the target supports them:

Enabled by -fhardenedEquivalent
fortification-D_FORTIFY_SOURCE=3 (or 2 on older glibc)
C++ assertions-D_GLIBCXX_ASSERTIONS
zeroed locals-ftrivial-auto-var-init=zero
position independence-fPIE and -pie, with -fPIC if -shared is given
relro and bind now-Wl,-z,relro,-z,now
stack protector-fstack-protector-strong
stack clash probes-fstack-clash-protection
control-flow markers-fcf-protection=full where available

It does not turn on warnings, and it does not turn on -fno-strict-overflow and similar behavior flags. If you pass a flag that conflicts with part of the set, for example -fno-stack-protector or -O0 with fortification, GCC warns with -Whardened, so the option does not silently weaken. The full list is in the GCC manual under Instrumentation Options for your version, and it can differ between releases, so read it for the compiler you ship. Clang has no equivalent single switch. The practical use of -fhardened is to get the baseline in one flag for new code on a recent GCC, and to keep the explicit list in the build for the flags it does not cover and for portability to other compilers.

C++ additions

C++ code needs the same flags and a few more.

  • Hardened standard library. -D_GLIBCXX_ASSERTIONS for libstdc++, and -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST for libc++ 18 and later, make operator[], front, back and std::optional access check their preconditions. The post on hardening C++ containers shows the failure output.

  • RTTI-based checks. -fsanitize=vptr in tests and Clang's cfi-derived-cast in production catch bad downcasts.

  • **-Wnon-virtual-dtor and -Woverloaded-virtual** find destructor and override mistakes that lead to type confusion.

  • **-Wdangling-pointer and -Wdangling-reference** (GCC 13 and 13) report some references to temporaries.

  • **-fvisibility=hidden and -fvisibility-inlines-hidden** reduce exported symbols, which helps CFI and shrinks the dynamic symbol table.

Recipes for build systems

The details depend on the build system. The principle is the same: put the flags in one place, test them against the compiler, apply them per target and verify the output.

Make

Makefilemake
CC ?= gcc
HARDEN_CFLAGS  = -fstack-protector-strong -fstack-clash-protection \
                 -fcf-protection=full -fPIE -ftrivial-auto-var-init=zero \
                 -Wformat=2 -Werror=format-security \
                 -Werror=implicit-function-declaration
HARDEN_CPPFLAGS = -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3
HARDEN_LDFLAGS = -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack

CFLAGS   ?= -O2
CFLAGS   += $(HARDEN_CFLAGS)
CPPFLAGS += $(HARDEN_CPPFLAGS)
LDFLAGS  += $(HARDEN_LDFLAGS)

app: main.o util.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

Using += appends to the user's values and does not replace them, so a packager's CFLAGS from the command line, which overrides the file's assignment, still keeps the hardening if the Makefile uses override CFLAGS += .... Without override, a command-line make CFLAGS=-O2 replaces the whole variable, and the hardening vanishes, which is the most common way flags get lost. Put the hardening in a separate variable that the compile rule always adds.

CMake

Use check_compiler_flag and check_linker_flag, apply flags with target_compile_options and target_link_options, set POSITION_INDEPENDENT_CODE ON and guard the fortify definitions with a configuration check, as shown in the post on hardening a CMake project. Per-target options travel with the target and are not erased by a user's CMAKE_C_FLAGS.

Meson

Meson has built-in options that cover part of the set, and b_pie=true gives PIE. Add the rest with add_project_arguments and add_project_link_arguments, filtered through the compiler's own check:

meson.buildmeson
project('demo', 'c', default_options: ['c_std=c17', 'b_pie=true', 'warning_level=2'])

cc = meson.get_compiler('c')
harden_c = cc.get_supported_arguments(
  '-fstack-protector-strong',
  '-fstack-clash-protection',
  '-fcf-protection=full',
  '-ftrivial-auto-var-init=zero',
  '-Werror=format-security',
)
harden_ld = cc.get_supported_link_arguments(
  '-Wl,-z,relro,-z,now',
  '-Wl,-z,noexecstack',
)
add_project_arguments(harden_c, language: 'c')
add_project_link_arguments(harden_ld, language: 'c')

if get_option('optimization') != '0'
  add_project_arguments('-U_FORTIFY_SOURCE', '-D_FORTIFY_SOURCE=3', language: 'c')
endif

executable('demo', 'main.c', install: true)

get_supported_arguments returns only the flags that the compiler accepts, which is the same job as the CMake feature checks. The optimization option is 0 for a debug build type, and the condition avoids the fortify-needs-optimization warning there.

Autotools and packaging systems

For Autotools, pass hardening through CFLAGS, CPPFLAGS and LDFLAGS at configure time, and run config.log through a check to see that the final compile lines include them. Debian-style packaging gets the set from dpkg-buildflags with DEB_BUILD_MAINT_OPTIONS=hardening=+all, and RPM-based systems get it from the macros %{optflags} and %{build_ldflags}. Use those when you package, and your own list when you build a standalone binary.

Compatibility problems and how to resolve them

Hardening exposes bugs and incompatibilities. The common ones, with fixes:

SymptomCauseFix
relocation R_X86_64_32 ... can not be used when making a PIE objectan object or static library built without -fPIE or -fPICrebuild it with the flag
warning: ... missing .note.GNU-stack section implies executable stackan assembly file lacks the noteadd .section .note.GNU-stack,"",%progbits
"_FORTIFY_SOURCE" redefinedthe distribution compiler defines itadd -U_FORTIFY_SOURCE first
warning: _FORTIFY_SOURCE requires compiling with optimization-O0 buildskip fortification in debug configurations
program aborts with *** buffer overflow detected ***a real overflow, or a trailing array used as a flexible arrayfix the copy, or declare [] or use counted_by
program aborts with *** stack smashing detected ***a real overflowfind with AddressSanitizer
SIGILL under CFIan indirect call through a pointer of the wrong typefix the cast or add no_sanitize("cfi")
slow startup after adding -z nowmany imports resolved before mainmeasure, and consider keeping partial RELRO for short-lived tools
plugin fails to loadit requires an executable stack, or lacks CET notes where enforcement is onrebuild the plugin with the same flags
LTO and hardening conflictper-object flags lost at link timepass the same codegen flags at the link step with -flto

With link-time optimization, the flags at the link step decide some code generation, so repeat the compile flags there. A mismatch such as a different stack protector level between compile and link can produce a binary that is less protected than any single object.

The linker flags one by one

The -z options of the GNU linker are the least familiar part of the set, and each one maps to a single visible property in the output. Pass them through the compiler driver as -Wl,-z,<keyword>.

KeywordEffectVisible in
relroemit a PT_GNU_RELRO header covering the sections that are read-only after relocationreadelf -lW, GNU_RELRO
nowset DF_BIND_NOW, so the loader resolves every symbol at startupreadelf -d, BIND_NOW and FLAGS_1 NOW
noexecstackset PT_GNU_STACK flags to RWreadelf -lW, GNU_STACK
execstackthe opposite, forces RWEthe same line
separate-codeplace executable code in its own page-aligned segment, apart from read-only dataa LOAD segment with R E that contains only code
nodlopenmark the object so dlopen refuses itDF_1_NOOPEN in FLAGS_1
noexecheap-style optionsnot provided by GNU ld, and not needed since heaps are non-executable by defaultn/a
textfail the link if relocations against read-only text would be neededthe link fails instead of producing TEXTREL
defsfail the link on undefined symbols in a shared librarythe link fails
originallow $ORIGIN in RPATH, which you should use with careFLAGS with ORIGIN
pack-relative-relocsemit compact relative relocations (DT_RELR)RELR section in readelf -S

Three of these deserve a few more sentences. separate-code means the executable segment no longer shares pages with read-only data such as constants and tables, so a data table cannot be used as a source of gadgets and the permissions of each page match its content. Recent binutils enables it by default on Linux x86, and an old linker may produce a layout where the first page mixes ELF headers and code. text and defs do not harden the binary itself. They make the link fail on mistakes, text relocations that would force the loader to modify code pages and undefined references in a library, so a regression becomes a build error and not a runtime surprise. pack-relative-relocs is a size and startup optimization for PIE: it compresses the table of relative relocations that position-independent code needs, which matters for large C++ programs and is available with glibc 2.36 or later and binutils 2.38 or later.

Two options to leave alone unless you know why you need them are -Wl,--no-as-needed, which keeps unused libraries in the dependency list and enlarges the attack surface, and -rpath pointing to build or user-writable directories, which lets a planted library take precedence. If you need an rpath, use $ORIGIN-relative paths into directories that only the installer can write, and check the RUNPATH line in readelf -d for anything that points at /tmp or a home directory.

Executables and shared libraries differ

The recommended set is written for executables, and libraries need adjustments.

ConcernExecutableShared library
code generation-fPIE-fPIC
link mode-pie-shared
relro and nowyesyes
noexecstackyesyes, a library requesting an executable stack can force it on the whole process
symbol exportsonly main neededexport a defined API, -fvisibility=hidden plus explicit __attribute__((visibility("default")))
interpositionn/a-fno-semantic-interposition for performance, with the loss of interposition
CET and BTI notesyesyes, one unmarked library disables enforcement for the process

Libraries have a further rule: they run inside programs you do not control, so the hardening you apply is the floor for every program that loads them. A library built without CET notes stops shadow stacks from being enabled in each program that loads it, and a library that needs an executable stack can be refused by the loader. Treat library flags as part of your public interface.

Static libraries are linked into the final program and carry no flags of their own. The objects inside must be compiled with -fPIE or -fPIC for a PIE link, the CET notes must be present and the stack-protector level should match the executable. Check them with readelf -S on the members, or rebuild them as part of the same build.

Which compiler release gives you what

Hardening features arrive over time, and your compiler version decides what you can use. A short timeline of the options in this guide, as far as the compilers' documentation and release notes state:

FeatureFirst in GCCFirst in Clang
-fstack-protector-strong4.93.7
-fstack-clash-protection811
-fcf-protection87
-mbranch-protection (AArch64)99
-ftrivial-auto-var-init128
-fzero-call-used-regs1115
__attribute__((no_stack_protector))11available in recent releases
_FORTIFY_SOURCE=3 (with glibc 2.33 or later)1217
-fstrict-flex-arrays1316
-fhardened14none
<stdckdint.h>1418
libc++ hardening modesn/a18

Use the table as a guide and not as a promise, and let a configure-time check decide for each flag, because a distribution may backport a feature and a vendor compiler may lag. When a flag is missing on an older toolchain, write down the gap in the build file so that the next upgrade picks it up.

A worked example: hardening a small legacy project

Consider a small C project built by a Makefile with a single line, CFLAGS = -O2 -g, that produces a network tool from four source files. This is the sequence that takes it from nothing to the full set, with the check after each step.

Step 1, measure the starting point. Build and run the script from the verification post. The weak build shows FAIL for PIE on a distribution whose compiler does not default to it, PASS for noexecstack, PASS for partial RELRO, FAIL for bind-now and warnings for the canary and fortification:

Text
FAIL  pie (type is not DYN)
PASS  noexecstack
PASS  relro
FAIL  bind-now (lazy binding left on)
PASS  no-rwx
PASS  no-textrel
WARN  stack-canary (no __stack_chk_fail import; fine if no function has arrays)
WARN  fortify (no _chk imports; fine if there are no fortifiable calls)
FAIL  cet (x86 feature note lacks IBT or SHSTK)

The exact lines depend on the distribution's compiler defaults, and on a system whose compiler already enables some of these you will see more passes.

Step 2, add the compile flags. Add the stack protector, clash protection, CET markers, zero-init and the format warnings to CFLAGS, plus the fortify defines in CPPFLAGS. Rebuild everything, since objects are not rebuilt on a flag change unless the Makefile tracks flags, and run make clean first. The build prints new warnings from -Wformat=2. Fix them: two are calls to a logging helper that needed the format attribute and one is a real printf(buf) in an error path.

Step 3, add the link flags. Add -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack to LDFLAGS. The link fails with relocation R_X86_64_32S against ... can not be used when making a PIE object, because a static helper library in the repository was built without -fPIE. Rebuild it with the flag, and the link passes.

Step 4, run the tests under sanitizers. A second configuration builds with -fsanitize=address,undefined -O1 -g. The test suite reports a heap overflow in a packet parser, which has been there since the first commit: malloc(n * 4) with n from the packet. Fix it with calloc, and add a regression test.

Step 5, verify and lock in. Run the script again:

Text
PASS  pie
PASS  noexecstack
PASS  relro
PASS  bind-now
PASS  no-rwx
PASS  no-textrel
PASS  stack-canary
PASS  fortify
PASS  cet (IBT and SHSTK)

Add the script to the make check target so a flag lost in a later change fails the build. The four defects found along the way, the logging helper, the printf(buf), the PIE-incompatible helper library and the multiplication overflow, were all real, and none of them needed a deep audit to find, only the flags and one sanitizer run.

Reproducible and debuggable hardened builds

Hardening interacts with two practices that teams care about, reproducible builds and debuggability.

For reproducibility, hardening flags are deterministic, and so are the builds they produce when the paths and timestamps are controlled. PIE and ASLR do not affect the file contents, since randomization happens at load time. -fcf-protection and -mbranch-protection change the output deterministically. The one hazard is -ftrivial-auto-var-init=pattern, which is deterministic too but is a test-time flag. Use -ffile-prefix-map=$PWD=. and -Wl,--build-id so that paths and identifiers do not leak build locations, and so crash reports can be matched to symbols.

For debugging, keep symbols separate with objcopy --only-keep-debug and strip, or -g with a split debug file, and keep the build ID. Hardening makes some debugging steps different: addresses are randomized, stack-smashing aborts show a short message, and -O2 reorders code, so stepping through a hardened binary is less pleasant than through a debug build. Maintain a debug configuration with the same warnings and sanitizers, and treat the hardened release configuration as the one you ship and analyze crash reports from, using the build ID to find the exact symbols.

Where hardening flags stop

They do not fix logic errors, authentication mistakes or injection bugs, and they do not defend against a bug in a dependency that you built without them. They do not help when the attacker is inside the trust boundary, as with a malicious plugin that you load into your own process. They reduce the damage of memory errors in code you compile, with the flags you pass. For everything else, the rest of the security cluster, sandboxing, privilege reduction, fuzzing and defensive reverse engineering, applies.

Verifying the result

Run the checks on the final executable, as the earlier posts show:

Text
readelf -h app | grep Type
readelf -lW app | grep -E 'GNU_STACK|GNU_RELRO'
readelf -d app | grep -E 'BIND_NOW|FLAGS_1|TEXTREL|RPATH|RUNPATH'
readelf -n app | grep -A1 Properties
nm -D app | grep -E '__stack_chk_fail|_chk'

A hardened x86-64 executable shows DYN, GNU_STACK ... RW, GNU_RELRO, BIND_NOW, no TEXTREL, no RPATH pointing at a build directory, x86 feature: IBT, SHSTK and the canary and _chk imports. The checksec tool puts them in one table, and the script in the verification post fails a build when one is missing. For a record that survives compiler upgrades, store the output for each release and diff it against the previous one.

What each flag costs

We do not quote percentages, because measurements depend on the program, the compiler and the CPU. The mechanisms point to where costs appear:

  • The stack protector adds a load, store, load and compare to protected functions.

  • Fortification adds a size comparison to covered library calls, usually folded away.

  • Clash protection adds probes only to large frames.

  • CET markers add four bytes per indirect-branch target and are no-ops without hardware.

  • PIE adds negligible cost on x86-64 and arm64 and a base register on 32-bit x86.

  • Full RELRO moves symbol resolution to startup.

  • Zero-initialization adds stores for locals, notably large arrays.

  • Bounds trapping adds a compare and branch per checked access.

  • CFI adds a table check per indirect call and requires LTO.

  • Retpolines slow indirect calls and returns noticeably, which is why they are reserved for the places that need them.

The post on measuring the cost of hardening flags gives a method that controls noise and separates the flags. Measure the ones you doubt and keep the others.

Flags that sound like hardening and are not

  • **-fno-stack-protector, -U_FORTIFY_SOURCE without a replacement and -z norelro** are the opposite, and show up in copied build lines. Search your build for them.

  • **-fomit-frame-pointer** is an optimization and not a hardening flag, though frame pointers help crash analysis. Ubuntu and Fedora have enabled frame pointers in their packages for profiling and debugging reasons.

  • **-s and strip** remove symbols, which makes reverse engineering mildly harder and debugging much harder. They are not a security mechanism.

  • **-fvisibility=hidden** is design hygiene and helps CFI, and it does not stop an attacker.

  • **-D_FORTIFY_SOURCE=2 on a recent glibc** is weaker than level 3 for dynamic sizes.

  • **-Wl,-z,execstack** is a pessimization that gives you an executable stack on purpose. Remove it.

  • **-fPIE alone** without -pie does not randomize the executable.

  • Obfuscation flags and packers are not mitigations and add no protection against memory corruption.

  • **-ftrapv** aims to abort on signed overflow, and it is unreliable across compiler versions, so prefer -fsanitize=signed-integer-overflow in tests and checked arithmetic in code.

A checklist to keep

  1. The compile line includes -fstack-protector-strong, -fstack-clash-protection, -fcf-protection=full or -mbranch-protection=standard, -ftrivial-auto-var-init=zero and the format warnings.

  2. Optimized builds define _FORTIFY_SOURCE=3.

  3. Executables use -fPIE and -pie, libraries use -fPIC.

  4. The link line includes -Wl,-z,relro,-z,now and -Wl,-z,noexecstack.

  5. C++ builds define the hardened-library macro.

  6. A verification script runs on the shipped artifacts and fails on a missing property.

  7. A weak fixture binary must fail the script.

  8. Test builds use AddressSanitizer and UndefinedBehaviorSanitizer, and release builds use the hardening set, as two separate configurations.

  9. The flags are written down in one place per build system, with a comment for each decision to leave one out.

  10. Someone re-reads the compiler's release notes when upgrading, because defaults and flag names change.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.