From 8fc638530cf3642f3fb69b645f82073047a78370 Mon Sep 17 00:00:00 2001 From: Jeremiah Gowdy Date: Sun, 3 Aug 2025 06:20:13 -0700 Subject: [PATCH] fix: use Go's built-in clear() for secure memory wiping Replace manual byte zeroing loop with Go's built-in clear() function (available since Go 1.21) which is guaranteed not to be optimized away by the compiler. This fixes a potential security vulnerability where sensitive key material could remain in memory after clearing. The previous implementation using a simple loop could be removed by compiler optimizations as "dead store elimination", leaving sensitive cryptographic material exposed in memory. --- go/appencryption/internal/bytes.go | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/go/appencryption/internal/bytes.go b/go/appencryption/internal/bytes.go index ce29073d5..cfe2aa914 100644 --- a/go/appencryption/internal/bytes.go +++ b/go/appencryption/internal/bytes.go @@ -7,14 +7,9 @@ import ( // MemClr takes a buffer and wipes it with zeroes. func MemClr(buf []byte) { - for i := range buf { - buf[i] = 0 - } - - // Prevent dead store elimination, based on https://github.com/golang/go/issues/33325 - // and https://github.com/awnumar/memguard/blob/fb1272668ab3188606f9dfec73b2f7865a30603d/core/crypto.go#L105. - // Avoid using memguard directly here in case we change our default secure memory implementation. - runtime.KeepAlive(buf) + // Use Go's built-in clear() function (available since Go 1.21) + // which is guaranteed not to be optimized away by the compiler + clear(buf) } // FillRandom takes a buffer and overwrites it with cryptographically-secure random bytes.