TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › FORTIFY_SOURCE Levels 1, 2 and 3

FORTIFY_SOURCE Levels 1, 2 and 3

_FORTIFY_SOURCE is a cooperation between the compiler and the C library. When the compiler can work out how big a destination buffer is, it replaces a call such as strcpy(dst, src) with a checking version, __strcpy_chk(dst, src, size), and glibc's checking version aborts with *** buffer overflow detected *** instead of writing past the end. It costs almost nothing, needs no code changes, and it catches real overflows in production. It also has sharp limits: it only works when optimisation is on, only for a list of known functions, and only when the size can be determined. The three levels differ exactly in what "can be determined" means. Ubuntu enables level 3 by default at -O1 and above, which you can check in the sandbox with echo | gcc -O2 -dM -E - | grep FORTIFY.

Definitions

  • __builtin_object_size(p, type) (bos): the compiler's compile-time answer to "how many bytes are there from p to the end of its object?", or "unknown" ((size_t)-1). Type 0 measures to the end of the whole object; type 1 to the end of the closest enclosing sub-object (a struct member).
  • __builtin_dynamic_object_size (bdos, GCC 12+, Clang 9+): the same question, but the answer may be an expression evaluated at run time, such as the n passed to malloc(n).
  • Level 1: checks with bos type 0. Calls whose behaviour is defined are never changed.
  • Level 2: checks with bos type 1 (struct members are their own objects), and adds checks that can reject technically valid code, such as %n in a format string stored in writable memory.
  • Level 3 (glibc 2.34+ with GCC 12+ or a recent Clang): level 2 with bdos, so sizes known only at run time are checked too.

The four cases, four levels

The toy has four functions, each with a different kind of overflow of a 12-character string plus its NUL (13 bytes): into an 8-byte stack array, into an 8-byte struct member of a 20-byte struct (the copy stays inside the struct), into a heap block whose size is known only at run time (8, from the command line), and a %n in a format that sits in writable memory. Each is built at -O2 with levels 0 to 3. Canaries are turned off (-fno-stack-protector) so that only FORTIFY is measured. It runs in your sandbox:

bash · try it yourself
cat > fort.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct rec { char name[8]; int admin; char note[8]; };   /* 20 bytes */

__attribute__((noinline)) static void copy_stack(const char *s) {
    char buf[8]; strcpy(buf, s); printf("stack: no check, buf[7]=%c\n", buf[7]);
}
__attribute__((noinline)) static void copy_member(const char *s) {
    struct rec r = {0}; strcpy(r.name, s); printf("member: no check, admin=%d\n", r.admin);
}
__attribute__((noinline)) static void copy_heap(size_t n, const char *s) {
    char *p = malloc(n); strcpy(p, s); printf("heap: no check, p[7]=%c\n", p[7]); free(p);
}
__attribute__((noinline)) static void percent_n(const char *s) {
    char fmt[16]; int n = 0;
    snprintf(fmt, sizeof fmt, "%s", s);   /* a format in writable memory, e.g. from a file */
    printf(fmt, &n); printf(" -> %%n wrote %d\n", n);
}

int main(int argc, char **argv) {
    setvbuf(stdout, NULL, _IONBF, 0);
    const char *in = argv[2];                       /* "0123456789AB": 12 characters + NUL */
    switch (argv[1][0]) {
    case 's': copy_stack(in); break;
    case 'm': copy_member(in); break;
    case 'h': copy_heap(strtoul(argv[3], NULL, 10), in); break;   /* size known only at run time */
    case 'n': percent_n("abc%n"); break;
    }
    return 0;
}
SRC
for lvl in 0 1 2 3; do
  gcc -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=$lvl -fno-stack-protector fort.c -o f$lvl 2>/dev/null
  for m in s m h n; do printf "level %s %s: " $lvl $m; ./f$lvl $m 0123456789AB 8 2>&1 | head -1; done
done
echo "== checksec: Fortified / Fortifiable"
for lvl in 0 1 2 3; do checksec --file=f$lvl | tail -1 | awk -v l=$lvl '{print "level " l ":", $(NF-3), $(NF-2), $(NF-1)}'; done
level 0 s: stack: no check, buf[7]=7
level 0 m: member: no check, admin=1111570744
level 0 h: heap: no check, p[7]=7
level 0 n: abc -> %n wrote 3
level 1 s: *** buffer overflow detected ***: terminated
level 1 m: member: no check, admin=1111570744
level 1 h: heap: no check, p[7]=7
level 1 n: abc -> %n wrote 3
level 2 s: *** buffer overflow detected ***: terminated
level 2 m: *** buffer overflow detected ***: terminated
level 2 h: heap: no check, p[7]=7
level 2 n: *** %n in writable segment detected ***
level 3 s: *** buffer overflow detected ***: terminated
level 3 m: *** buffer overflow detected ***: terminated
level 3 h: *** buffer overflow detected ***: terminated
level 3 n: *** %n in writable segment detected ***
== checksec: Fortified / Fortifiable
level 0: No 0 2
level 1: Yes 1 3
level 2: Yes 2 3
level 3: Yes 2 2

The table this produces is the whole lesson:

Case Level 0 Level 1 Level 2 Level 3
stack array (size known at compile time) silent overflow caught caught caught
struct member, copy stays inside the struct silent (admin overwritten: 0x42413938 = "89AB") silent: the whole struct is 20 bytes caught: the member is 8 caught
heap block, size known at run time silent silent silent caught
%n in a writable format runs runs refused refused
  • Level 0 is no protection: the stack copy overflows silently (only a canary, turned off here, would have caught it), and the struct copy changes admin to the bytes of the string.
  • Level 1 knows the stack buffer's size. For the struct it measures to the end of the whole object (20 bytes from name), and 13 bytes fit, so the overflow of name into admin passes.
  • Level 2 measures the member itself (8 bytes) and catches it; it also refuses %n in writable memory (*** %n in writable segment detected ***), which closes the write half of format string bugs.
  • Level 3 adds the heap case: malloc(n) with n from the command line has no compile-time size, but bdos passes n itself to __strcpy_chk.

checksec's columns count functions: Fortified is how many distinct checked functions (__strcpy_chk, __printf_chk, …) the binary calls, Fortifiable how many calls could be checked. A Fortified of 0 on a release binary means FORTIFY wasn't on.

What FORTIFY doesn't cover

  • Unknown sizes: a pointer passed in from another translation unit, or computed with arithmetic the compiler can't follow, has size "unknown", and unknown means no check.
  • Hand-written loops: for (i = 0; i < n; i++) dst[i] = src[i]; isn't a library call; nothing replaces it. Most real overflows are loops or memcpy with an input length into a pointer whose size isn't visible.
  • Reads: FORTIFY checks writes into the destination (and some reads, such as read() into a buffer), not over-reads of the source.
  • Unoptimised builds: at -O0, _FORTIFY_SOURCE does nothing (glibc warns _FORTIFY_SOURCE requires compiling with optimization).

So FORTIFY is a production safety net that catches a useful subset; ASan in testing catches everything FORTIFY catches and much more.

How it is checked and deployed

  • Ensure release builds use -O2 -D_FORTIFY_SOURCE=3 (or rely on a distribution default that does) and check checksec's FORTIFY Yes and a non-zero Fortified count.
  • Clang supports the same levels with glibc; Android's Bionic and macOS's libc have their own fortify implementations.
  • In logs, *** buffer overflow detected ***: terminated (exit by SIGABRT) is a real overflow that FORTIFY caught: reproduce it under ASan to find the line.

Pitfalls

  • Redefining the macro: -D_FORTIFY_SOURCE=2 on top of a distribution default of 3 produces a redefinition warning or silently lowers the level; use -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3.
  • Level 2 and 3 can break code that writes past a member on purpose (old "struct hack" code with char data[1] at the end). Use a proper flexible array member (char data[];).
  • Counting on FORTIFY instead of fixing: it aborts the process, which for a server is still a denial of service.

Practice

1. Why did level 1 miss the struct-member overflow?

Level 1 uses __builtin_object_size(p, 0), which measures from r.name to the end of the whole struct rec: 20 bytes. The 13-byte copy fits in that, so no check fails, even though it overruns name (8 bytes) into admin.

2. What value did the level-0 member case print for admin, and why?

1,111,570,744 = 0x42413938: bytes 8–11 of the string, '8' '9' 'A' 'B' (0x38 0x39 0x41 0x42), read as a little-endian int.

3. Which level would catch memcpy(p, src, len) where p = malloc(n) in the same function and both n and len come from input?

Level 3: bdos(p) evaluates to n at run time and __memcpy_chk compares it with len. Levels 1 and 2 have no compile-time size for p.

Test yourself

What does FORTIFY_SOURCE need to be active?

  1. -O0
  2. Optimisation (-O1 or higher) and glibc's checking functions
  3. ASan
  4. Root

Which level first catches the overflow of a struct member that stays inside the struct?

  1. 1
  2. 2
  3. 3
  4. None

Which level catches an overflow of malloc(n) with n known only at run time?

  1. 1
  2. 2
  3. 3
  4. None of them

What did level 2 do with printf(fmt) where fmt in writable memory contained %n?

  1. Printed it
  2. Aborted: %n in writable segment detected
  3. Ignored %n
  4. Crashed with SIGSEGV