← Back to section · Tutorials & Labs

Catching Bugs in Cryptographic Code with AddressSanitizer and UBSan

Turn on -fsanitize=address,undefined for test builds: what each sanitizer catches, what it cannot catch, and exactly how to wire a sanitizer build into CI.

Published 22 November 2026 · 5 min read · PQ Frontier

Catching Bugs in Cryptographic Code with AddressSanitizer and UBSan
AI-generated site artwork
Video explainer · C/C++ cryptography: libraries and implementation

Why Cryptographic Code Needs Sanitizers Especially

Cryptographic implementations are a breeding ground for memory errors: lots of hand-managed fixed-size buffers, dense pointer arithmetic, and sizes that vary by algorithm — ML-KEM public keys run from 800 to 1568 bytes across the three parameter sets — so one miscopied size or off-by-one can write straight through a buffer. Worse, such errors are usually silent in functional tests: the overflow corrupts a neighboring padding byte, the program still produces correct output, and one day the same bug becomes an exploitable vulnerability in production. Human review is poor at spotting these, static analysis catches some, and runtime sanitizers are the most cost-effective layer: the program runs under supervision during tests and reports the exact location at the first illegal access. This article covers the two built into both GCC and Clang: AddressSanitizer (ASan) for memory errors and UndefinedBehaviorSanitizer (UBSan) for undefined behavior.

How to Enable Them, and Who Catches What

Integration is one set of flags for the test build, and it must be present at both compile and link time — forgetting the link step is the most common wiring mistake:

CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -g"
clang -fsanitize=address,undefined -fno-omit-frame-pointer -g \
      -o pq_demo_asan src/main.c -lcrypto -loqs

Be clear about the division of labor. ASan surrounds every allocation with poisoned redzones and intercepts out-of-bounds reads and writes, use-after-free and double free, and reports memory leaks at exit through its built-in LeakSanitizer (on by default on Linux). For cryptographic code, ASan’s greatest value is catching “buffer operated on with the wrong size”: using an ML-KEM-512 length against a 1024 key, or undercounting a signature length during serialization. UBSan does not watch memory layout; it catches language-level undefined behavior — signed integer overflow, out-of-range shifts, misaligned access, null dereference, out-of-range enum values. These are just as deadly in crypto code: an overflowing intermediate in polynomial coefficient arithmetic “looks fine” in local tests, then yields wrong results — or is optimized into entirely different logic — under another compiler setting. Both sanitizers have acceptable overhead (ASan roughly doubles memory with a clear slowdown; UBSan is lighter), so test builds should enable both by default.

How They Interact with the Earlier Articles — and Their Limits

Sanitizers complement the earlier articles in this column, and their boundaries should be explicit. First, ASan catches buffer overflows but not “the wipe was optimized away”: wipe code can be eliminated in a sanitizer build just as well, and ASan does not verify wipe semantics — that remains the job of functions like OPENSSL_cleanse. Second, sanitizers are powerless against timing side channels: comparing secrets with memcmp runs perfectly cleanly under ASan and still leaks; constant time is the previous article’s library functions and dedicated timing tests. Third, performance numbers measured under a sanitizer build are meaningless — benchmarks must run on a separate release build. One practical detail: third-party libraries linked into the test binary generally work without being rebuilt with sanitizer flags (ASan only requires the main program to link its runtime), but cross-boundary memory errors get fuzzier reports; when possible, rebuild the dependencies you control, such as a self-built liboqs, with the same flags for precise reports. And when ASan reports something inside a library, first check whether you passed it the wrong size — in practice, most reports trace back to the caller.

Wiring It into CI

Sanitizers only keep working if they live in continuous integration, and three points matter. First, give the sanitizer build its own row in the build matrix: with the previous article’s CMake setup, inject the flags (via -DCMAKE_C_FLAGS, or an option switch in CMakeLists) and keep its output directory strictly separate from the release build — never mix artifacts. Second, set the runtime options correctly: ASAN_OPTIONS=detect_leaks=1 enables leak detection explicitly, and UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 makes UBSan print a stack trace and fail at the first error — by default some UBSan checks “report and continue”, and without halt_on_error CI can go green over a pile of undefined behavior. Third, treat every report as a real defect: no sanitizer finding may be waved away as a test-environment quirk; historically, reports dismissed that way have a habit of returning as production vulnerabilities. Make the sanitizer build a merge gate: functional tests all pass and the sanitizer report is empty, or nothing merges.

Reading Your First Report

A first ASan report looks intimidating in length, but its structure is fixed, and four blocks pin down the problem. The first is the error line — for example “heap-buffer-overflow on address … WRITE of size 1088” — telling you whether the out-of-bounds access was a read or a write and how many bytes it touched; 1088 happens to be exactly ML-KEM-768’s ciphertext length, and a familiar algorithm size in that line often names the parameter-set mix-up immediately. The second block is the access stack trace, which, with -g and frame pointers enabled, points to the exact source line — the reason sanitizer builds must carry debug information. The third block is the allocation stack for that memory: where the buffer was allocated and at what size; set against the access stack, inconsistencies like “allocated with the 512 length, written with the 1024 length” expose themselves on the spot. The fourth block is the redzone diagram showing which side of the allocation the address fell on. UBSan reports are far shorter: one line giving the file, line and kind of undefined behavior — a signed integer overflow, say — with the values involved. Build the habit: read the type and size first, then the allocation and access stacks, and only then change code. Do not guess first and fix later — the sanitizer’s whole value is that it hands you an evidence chain, and following the evidence gives the highest chance of fixing it in one pass.

Summary

ASan owns spatial errors, UBSan owns semantic ones, and enabling both is the default configuration for C/C++ cryptographic test builds. Together with constant-time functions and secure wiping, each covers its own stretch: sanitizers clean out memory and undefined-behavior errors during testing, while side channels and wipe semantics belong to the dedicated library functions. The next article zooms out from individual libraries and compares two C++-native cryptography libraries, Botan and Crypto++, side by side.

Tags: CC++TestingDebugging