Skip to content

Instantly share code, notes, and snippets.

@yesmar
Created December 8, 2017 22:27
Show Gist options
  • Save yesmar/266a76af42b7176c1bea6efdd37a8f08 to your computer and use it in GitHub Desktop.
Save yesmar/266a76af42b7176c1bea6efdd37a8f08 to your computer and use it in GitHub Desktop.
Secure in-memory string erasure
/*
* burn.c
* Secure in-memory string erasure
*
* This is a modified version of the code originally posted to the
* Cryptograhy ML by Werner Koch:
* https://www.mail-archive.com/cryptography@metzdowd.com/msg08428.html
*
* By default, modern C compilers will pick up and use the static inline
* function. However, if you prefer your C to be pre-C99, compile with
* -DFORCE_MACRO to force the C Preprocessor macro to be used instead.
* Compile with -DTEST to create a test driver so you can try it out:
*
* clang -DTEST -std=c11 -O3 -Wall -Wextra -Werror burn.c
*/
#include <stddef.h>
#if defined FORCE_MACRO || __STDC_VERSION__ < 199901L
/* burn as a C Preprocessor macro. */
#define burn(p, size) do { \
volatile char *vp = (volatile char *)(p); \
size_t vsize = (size); \
while(vsize) { *vp = 0; vp++; vsize--; } \
} while(0)
#else
// burn as a static inline function.
static inline void burn(void *p, size_t size) {
volatile char *vp = (volatile char *)p;
while(size) { *vp = 0; vp++; size--; }
}
#endif
#ifdef TEST
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#if defined FORCE_MACRO || __STDC_VERSION__ < 199901L
/* No frills hexdump as a C Preprocessor macro. */
#define hexdump(b, size) { \
for (size_t i = 0; i < (size); ++i) { (void)printf("%02x ", (b)[i]); } \
(void)putchar('\n'); \
} while(0)
#else
// No frills hexdump as a static inline function.
static inline void hexdump(void *b, size_t size) {
char *p = (char *)b;
for (size_t i = 0; i < size; ++i) { (void)printf("%02x ", (p)[i]); }
(void)putchar('\n');
}
#endif
int main(int __unused ac, char ** __unused av) {
char buffer[] = "sensitive content";
size_t blen = strlen(buffer);
hexdump(buffer, blen);
burn(buffer, blen);
hexdump(buffer, blen);
exit(EXIT_SUCCESS);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment