Chris Low-level systems developer
← Back to all posts

The Most Honest Lie in C

ISA

matters at ISA because the verified properties are the concrete RISC-V instruction sequences gcc emits for memset at -O2: eight sb zero stores inline for the 8-byte call, a tail call to memset for the 16-byte call, a 32-iteration sb loop for the volatile-pointer wipe, and four sd zero stores surviving the compiler barrier, each read off the object disassembly firsthand this run.

MICROARCH

not at Microarch because the verified properties are the compiler's compile-time instruction choices, not the behavior of the machine executing them: nothing was timed, no buffer or line was measured, and the same objects would carry the same argument on any RV64 implementation.

FIRMWARE

not at Firmware because no firmware contract is involved: the objects were compiled and read with objdump, never linked into a boot image and never booted, so trap delegation and the machine-mode handoff never enter the argument.

KERNEL

matters at Kernel because the second half makes explicit kernel claims: the kernel may page the secret's anonymous page to the swap device at any time, and the mlock, munlock, and RLIMIT_MEMLOCK sequence is a system-call contract with the kernel's memory manager. Those claims rest on the cited manual and documentation pages; the firsthand bench work here remains compile-and-read, nothing was executed.

ALGORITHM

matters at Algorithm because the verified properties are the portable optimizer contract every language with an as-if rule shares: stores to provably dead memory may be deleted, and a compiler barrier declaring memory observable elsewhere restores the wipe, which is the explicit_bzero bargain and the memset_s contract.

I compiled two one-line functions this morning, gcc 13.2.0 at -O2 for rv64g, and read the disassembly. memset(p, 0, 8) becomes eight sb zero stores, one per byte, and no call instruction anywhere. memset(p, 0, 16) does the opposite: load 16 into a2, jump to memset, a real tail call. The border between inline the bytes and call the library sits between 8 and 16 bytes on this target. The compiler is not running your function. It is choosing the implementation from the size.

A chalkboard wiped clean
You wrote the wipe. The binary never did.

The decision that matters lives in a dumber function. I wrote one that declares a 32-byte stack key, wipes it with memset, and returns. Its compiled body, the whole of it:

0000000000000044 <secret>:
  44:   00008067    ret

One instruction: ret. The wipe is gone. The hand-rolled byte loop I wrote as the obvious fix compiles to the same single ret. The compiler proved the memory could never be read again, and under the as-if rule that made every store dead. You can see the wipe in the source. It is not in the binary.

The as-if rule is the contract behind the deletion. The compiler may do anything that does not change what the program can observe, and a store to memory that is provably never read again changes nothing observable. So it deletes the stores, the call and the loop alike. A secret key sitting in stack memory after the function returns is exactly what an attacker reads. The wipe you wrote for safety is the store the compiler can prove is useless, which is why it is the first to go.

Two spellings survived my objects. The volatile-pointer loop, cast through volatile unsigned char*, compiled to a real 32-iteration sb loop: every store through a volatile pointer is a side effect the compiler must honor, the read side of the same bargain covered in an earlier note. The barrier spelling, memset followed by __asm__ volatile("" ::: "memory"), kept all four sd stores: the memory clobber tells the optimizer that memory can be observed by something it cannot see. glibc ships exactly this bargain as explicit_bzero, memset plus a compiler barrier, with the promise that the call will not be deleted even when the buffer is dead afterward [2]. C11 tried to standardize the answer with memset_s, evaluated strictly per the abstract machine, but Annex K is optional and glibc never implemented it, so the barrier remains the working answer.

This is not a theoretical hazard. Yang, Johannesmeyer, Olesen, Lerner, and Levchenko examined eleven open-source security projects in a 2017 USENIX Security paper [6] and found four with flawed memory scrubbing, plus four more that owned a scrubber and used it inconsistently. Eight of eleven, wrong in two different ways. The compiler was never working against you. It applied the as-if rule, and the rule said those stores could go. One sentence to keep: memset is a request the compiler is allowed to deny, so wiping a secret takes not just a function call but a barrier that stops the optimizer from deleting the stores.


Update, , prompted by a reader

The wipe can survive and still lose. There is a second deletion that no compiler barrier stops: the kernel paging the secret to swap. Watch the shape where this applies clearly.

char *key = malloc(32);
read_key(key);
serve_clients(key);
explicit_bzero(key, 32);
free(key);

The wipe ran. The 32 bytes in RAM are zero. But the kernel was free to page that anonymous page out to the swap device at any point while the secret sat there, and page it back in when the process touched it next. The copy on disk was written before the wipe and is never touched by the wipe. It outlives the process. Anyone with read access to the swap device or a disk image of it, a forensics capture, or the disk of a stolen unencrypted laptop, reads the key in the clear. Encrypted swap closes this particular window; disabling swap closes it more completely [3]. Your program cannot observe the kernel doing this: paging is transparent to the running process, so nothing in your code can tell you whether that disk copy exists.

The fix is to tell the kernel the pages are not pageable, and to do it before the secret arrives:

char *key = malloc(32);
if (mlock(key, 32) != 0)
    exit(1);              /* no lock, no secret */
read_key(key);
serve_clients(key);
explicit_bzero(key, 32);  /* locked */
munlock(key, 32);
free(key);

Three details carry the whole fix. First, the lock comes before the secret, because a page already written to swap is already lost. Second, the mlock return value is checked: the call can fail, the per-process lock limit RLIMIT_MEMLOCK is the usual reason, and an unchecked failure is the same as no lock. Third, the wipe happens while the pages are still locked: munlock marks the pages swappable again, so wiping after the unlock reopens the window. libsodium gets this ordering right, zeroing the memory in sodium_munlock before the pages become swappable again [3].

When does this not apply? Two conditions have to hold for the risk to be real: the secret sits in ordinary pageable memory, and the process lives long enough under enough memory pressure for the kernel to page it out. A TLS server holding its private key for weeks on a machine with swap: applies. A password checked and dropped in the same second on a box with no swap: does not.

What the six sources say, each in one line. OpenSSL documents the wipe half: OPENSSL_cleanse fills ptr with zeros, and its clear_realloc and clear_free "should be used when the buffer at addr holds sensitive information", zeroizing the old buffer before freeing it [1]. The OpenBSD manual states the wipe half as the reason explicit_bzero exists: it "will not be removed by a compiler's dead store optimization pass, making it useful for clearing sensitive memory such as a password"; the swap control lives one man page over, in mlock(2) [2]. libsodium is the one source that names swap directly and hands you the mechanism: sodium_mlock "can help avoid swapping sensitive data to disk", its guarded allocator locks memory by default, and it recommends disabling swap or using encrypted swap [3]. The book states the general law: wipe a secret's storage location as soon as it is no longer needed, because a page the kernel copied to swap is a storage location you can no longer wipe [4]. The secure-coding standards state the wipe as curriculum: inspect the optimized release assembly, because if the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data [5]. The USENIX paper measured the compiler half against eleven open-source security projects: four with flawed scrubbing, four more with a scrubber used inconsistently [6].

One more sentence to keep: a wipe that survives the compiler cleans only RAM, because the kernel may already have copied the secret to swap, so lock the pages before the secret arrives. The working review habit checks the pair in that order: lock first, then a wipe the optimizer cannot delete. Lock without a wipe leaves the live copy; a wipe without a lock leaves the swapped copy.

Sources

  1. 01
    OpenSSL documentation: OPENSSL_cleanseOpenSSL Project

    The manual's wipe half, stated plainly: OPENSSL_cleanse() fills ptr of size len with a string of 0's, and OPENSSL_clear_realloc() and OPENSSL_clear_free() 'should be used when the buffer at addr holds sensitive information', zeroizing the old buffer via OPENSSL_cleanse before freeing it.

  2. 02
    explicit_bzero(3), OpenBSD manual pagesOpenBSD

    The manual states the wipe half as the reason the function exists: explicit_bzero 'will not be removed by a compiler's dead store optimization pass, making it useful for clearing sensitive memory such as a password'. The swap control lives one man page over, in mlock(2).

  3. 03
    Memory management, libsodium documentationlibsodium

    The one source that names swap directly: sodium_mlock 'locks at least len bytes of memory starting at addr. This can help avoid swapping sensitive data to disk.' Locking can fail because operating systems limit locked memory, so sodium_mlock returns -1 on failure; sodium_munlock zeroes the memory before making the pages swappable again; the guarded allocator locks by default and may use MAP_NOCORE or MADV_DONTDUMP. The docs recommend disabling swap on machines handling sensitive data, with encrypted swap as second choice, and disabling core dumps.

  4. 04
    Cryptography Engineering: Design Principles and Practical ApplicationsWiley, 2010. Ferguson, Schneier, Kohno

    Chapter 21, 'Storing Secrets', section 21.10, 'Wiping Secrets': states the general law that a secret's storage location should be wiped as soon as the secret is no longer needed. A page the kernel copied to swap is a storage location you can no longer wipe, which is the gap this section warns about.

  5. 05
    SEI CERT C Coding Standard, MSC06-CCarnegie Mellon SEI

    The standard's canonical instance: a memset meant to clear a password can be removed by compiler optimization when the buffer is never read afterward, so the optimized release assembly must be inspected to confirm the clearing survived. Risk assessment: 'If the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data.'

  6. 06
    Dead Store Elimination (Still) Considered HarmfulUSENIX Security 2017. Yang, Johannesmeyer, Olesen, Lerner, Levchenko

    Examined eleven open-source security projects: four used flawed scrubbing techniques that may fail to scrub sensitive data, and four more owned a scrubbing function but used it inconsistently. The paper the post's compiler half is measured against.

Related work: C audit from $350, fixed price. .

Choose how to get in touch

The project brief is filled in for you.

Compose in Gmail Use my email app