Clearing sensitive data with memset

Clearing sensitive data with memset

Description

A compiler can optimize away an ordinary memset used only to erase sensitive data, leaving secret values in memory.

Potential impact

  • Secrets may be exposed through memory or core dumps, use-after-free or swap storage.

Remediation

Use a clearing API that the target platform guarantees will not be optimized away, such as memset_s, explicit_bzero or SecureZeroMemory. Check availability and usage requirements, and separately manage copies left elsewhere in memory.

Examples

Before

c
char password[64];
memset(password, 0, sizeof(password));

After

c
char password[64];
explicit_bzero(password, sizeof(password));

The compiler may remove the unused ordinary memset; the second excerpt uses a dedicated clearing API. Filling and using the password buffer are omitted. This excerpt requires an environment that provides explicit_bzero.

References