Project 13: FORTIFY_SOURCE Implementation

Your own implementation of FORTIFY_SOURCE-style compile-time and runtime bounds checking for string functions.

Quick Reference

Attribute Value
Primary Language C
Alternative Languages N/A
Difficulty Level 4: Expert
Time Estimate 2-3 weeks
Knowledge Area Secure Coding / Compiler Defenses
Tooling GCC, glibc headers
Prerequisites Projects 1, 7, macro programming

What You Will Build

Your own implementation of FORTIFY_SOURCE-style compile-time and runtime bounds checking for string functions.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Compile-time size detection → maps to __builtin_object_size
  • Function wrappers → maps to replacing libc functions
  • Runtime checks → maps to abort on overflow
  • Performance balance → maps to when to check

Key Concepts

  • Object Size Builtin: GCC documentation
  • Macro Replacement: glibc bits/string_fortified.h
  • Compile-Time vs Runtime: FORTIFY_SOURCE levels

Real-World Outcome

$ cat test.c
char buf[10];
strcpy(buf, argv[1]);  // Potentially dangerous!

$ gcc -D_FORTIFY_SOURCE=2 test.c -o test
(Our fortified headers intercept strcpy)

$ ./test "short"
OK

$ ./test "this is a very long string"
*** buffer overflow detected ***: terminated
Aborted

$ gcc -DFORTIFY_EXPLAIN -D_FORTIFY_SOURCE=2 test.c -o test
$ ./test "this is a very long string"
FORTIFY: strcpy overflow detected
  Destination size: 10 bytes (known at compile time)
  Source size: 28 bytes
  Call site: test.c:3
*** buffer overflow detected ***: terminated

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: LEARN_SECURE_C_AND_EXPLOIT_AWARENESS.md
  • “Effective C, 2nd Edition” by Robert C. Seacord