Why Destroying a Key Is Harder Than Making One
I made a 256-bit key, handed it to AES, zeroed my copy, then searched the process's memory. The whole key was still there. Making it took one read from a random number generator, but getting rid of it means finding every place those bytes ended up.
Some of those places are inside your process. Others belong to the kernel, the filesystem, the hypervisor or last Tuesday's backup job, none of which got your memo.
Zeroing your slice leaves the library's copy behind
The victim in this experiment reads a key from a file, builds a cipher, wipes the slice and waits.
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"io"
"log"
"os"
"runtime"
)
var block cipher.Block
func main() {
key, err := os.ReadFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
block, err = aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
clear(key)
fmt.Println("ready")
io.Copy(io.Discard, os.Stdin)
runtime.KeepAlive(block)
}
A separate script starts it and reads /proc/PID/mem. The scan has to come from outside, because a program searching itself has to hold the thing it is searching for, and then proudly finds it.
import os, subprocess
key = os.urandom(32) # throwaway test key
with open("k.bin", "wb") as f:
f.write(key)
p = subprocess.Popen(["./demo", "k.bin"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdout.readline() # wait for "ready"
full = half = 0
with open(f"/proc/{p.pid}/mem", "rb", 0) as mem, open(f"/proc/{p.pid}/maps") as maps:
for line in maps:
addr, perms = line.split()[:2]
start, end = (int(x, 16) for x in addr.split("-"))
if "r" not in perms or end - start > 1 << 30:
continue
try:
mem.seek(start)
data = mem.read(end - start)
except OSError:
continue
full += data.count(key)
half += data.count(key[:16])
print("full key:", full, "first half:", half)
p.stdin.close()
p.wait()
On Go 1.27.4, linux/amd64, it found one full copy of the key and two copies of its first 16 bytes. As a control, I removed the aes.NewCipher call and both counts dropped to zero.
The culprit is the key schedule. AES expands your key into a series of round keys, and for AES-256 the first two are simply the key itself. cipher.Block keeps that schedule and offers no method to wipe it.
Quick detour: why is half the key there twice?
Go builds the decryption schedule up front too, and it ends with the first encryption round key. The two hits were 464 bytes apart: 240 bytes of encryption schedule, then 224 bytes into the decryption one. I love it when a stray number turns out to be that tidy.
Setting block = nil and calling runtime.GC() did not change the counts. Garbage collection frees memory without promising to scrub it.
Go has an experimental fix
The runtime/secret package erases registers and stack used by a function, and erases its heap allocations once the collector finds them unreachable. In 1.27.4 you still need GOEXPERIMENT=runtimesecret.
I moved the file read, cipher construction and clear inside secret.Do, discarded the cipher and forced two collections. The scanner found nothing. There are conditions:
- Every reference to those allocations has to be gone.
- Globals written by the function are not protected.
- Only linux/amd64 and linux/arm64 get the erasure.
- It does nothing about copies made outside the process, including the key file.
Swap, hibernation and core dumps copy RAM for you
While a key is live, the system may write it to disk without your code doing anything. Each route needs its own control.
- Swap:
mlockkeeps chosen pages out of it. - Hibernation: RAM gets written to disk, and mlock does not stop it.
- Core dumps:
MADV_DONTDUMPexcludes chosen pages. Check/proc/sys/kernel/core_patternto see where dumps go; mine pipes to Apport. - VM snapshots: one that includes memory captures the key, whatever the guest asked for.
This allocates a page outside the Go heap with the first and third protections. mlock can fail if RLIMIT_MEMLOCK is too low, so do not ignore the error.
const madvDontDump = 16 // MADV_DONTDUMP, not exported by package syscall
// lockedPage returns a page that is kept out of swap and core dumps.
func lockedPage() ([]byte, error) {
b, err := syscall.Mmap(-1, 0, os.Getpagesize(),
syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_PRIVATE|syscall.MAP_ANON)
if err != nil {
return nil, fmt.Errorf("mmap: %w", err)
}
if err := syscall.Mlock(b); err != nil {
syscall.Munmap(b)
return nil, fmt.Errorf("mlock: %w", err)
}
if err := syscall.Madvise(b, madvDontDump); err != nil {
syscall.Munmap(b)
return nil, fmt.Errorf("madvise: %w", err)
}
return b, nil
}
It protects only what stays in that page. Pass the bytes to aes.NewCipher and you get a fresh schedule in ordinary Go memory.
Side path: Linux also has memfd_secret, memory removed from the kernel's own direct map. It is locked against swap, and hibernation is blocked while any such region exists. Clever, but you cannot pass pointers into it to system calls, and a library that copies the key elsewhere still wins.
For swap as a whole, encrypt it. If you never hibernate, crypttab can give it a new random key at each boot. Use a stable device path and check it twice, because the swap option formats whatever you point it at.
cswap /dev/disk/by-partuuid/YOUR-SWAP-PARTUUID /dev/urandom swap,cipher=aes-xts-plain64,size=512
Deleting the key file may leave its blocks intact
rm removes a name. shred tries to overwrite the contents, but its own manual warns that this relies on the filesystem overwriting data in place.
That assumption can fail with:
- copy-on-write or log-structured filesystems, and some journalling modes
- Btrfs, ZFS, LVM or hypervisor snapshots that still reference old blocks
- SSDs, whose controllers remap writes so the old flash page is out of your reach
- network or RAID storage keeping state you cannot inspect
So the best plaintext key file is one that never existed. Overwriting it later is an attempted repair, and you have no reliable way to check the result from userspace.
Backups keep the key you thought you had retired
Defeating deletion is a backup's job. Removing a key today does nothing to yesterday's archive, the off-site replica or the copy someone put in a password manager "just in case".
Take LUKS. The header backup documentation says that the backup plus a passphrase valid when it was taken can still decrypt the data, even after you change or remove that passphrase on the device. cryptsetup erase clears the keyslots on the disk and leaves the file in your cupboard alone.
The same problem undermines cryptographic erase, where you destroy a key instead of the data. NIST SP 800-88 Rev. 2 says it "should not be trusted" on storage media that have been backed up or escrowed, unless the organisation has high confidence about how and where the keys were stored and managed elsewhere.
Plan the destruction before generating the key
You cannot reliably reconstruct a key's travels afterwards, so decide them in advance.
- Write down every permitted copy, who controls it and how it expires.
- Store the key only in wrapped (encrypted) form, so backups pick up ciphertext.
- Keep the wrapping key somewhere that restricts export, such as a TPM or HSM, and check what its backup or recovery features copy.
- Limit plaintext lifetime. A short-lived helper process gives you a clearer boundary than a daemon that runs for months, though exiting is not a guaranteed wipe of physical RAM.
- Deal with swap, hibernation, dumps and memory snapshots on every host that unwraps it.
- To destroy it, destroy every instance of the wrapping key, or every copy of the wrapped key.
- Test with an old backup restored in isolation. If it can still decrypt, you are not finished.
Wrapping swaps many uncontrolled copies for a smaller thing you have a chance of controlling. Some of the problem remains, because the unwrapped key still visits RAM unless the hardware does the encryption itself.
Be precise about the claim you make afterwards. "We deleted the key" describes an action. "No copy we know of can decrypt the data, and here is the list we checked" is something another person can argue with, which is much more useful.