Explicit_bzero and bzero
As stated in the manpage:
The
bzero
() function writes len zero bytes to the string b. If len is zero,bzero
() does nothing. Theexplicit_bzero
() variant behaves the same, but will not be removed by a compiler’s dead store optimization pass, making it useful for clearing sensitive memory such as a password.
This is how it’s implemented:
/* $OpenBSD: explicit_bzero.c,v 1.4 2015/08/31 02:53:57 guenther Exp $ */
/*
* Public domain.
* Written by Matthew Dempsky.
*/
#include <string.h>
__attribute__((weak)) void
__explicit_bzero_hook(void *buf, size_t len)
{
}
void
explicit_bzero(void *buf, size_t len)
{
memset(buf, 0, len);
__explicit_bzero_hook(buf, len);
}
DEF_WEAK(explicit_bzero);
Unfortunately, it might get optimized away when using static linking with LTO.
A better implementation would be:
void *
explicit_memset(void *buf, size_t len)
{
memset(buf, 0, len);
__asm__ __volatile__("" :: "r"(buf) : "memory");
return s;
}
But it’s sill a neat way of improving forward secrecy, by trying to remove cryptographic materials from memory as soon as possible.