Skip to content

Commit

Permalink
mem: Added mem_secclean function.
Browse files Browse the repository at this point in the history
The function can be used to securely clear a block of memory without
compiler optimizing away this call.
  • Loading branch information
Lastique committed Jul 27, 2022
1 parent eeeba71 commit 1f03390
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
3 changes: 2 additions & 1 deletion include/re_mem.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ void *mem_zalloc(size_t size, mem_destroy_h *dh);
void *mem_realloc(void *data, size_t size);
void *mem_reallocarray(void *ptr, size_t nmemb,
size_t membsize, mem_destroy_h *dh);
void mem_destructor(void *data, mem_destroy_h *dh);
void mem_destructor(void *data, mem_destroy_h *dh);
void *mem_ref(void *data);
void *mem_deref(void *data);
uint32_t mem_nrefs(const void *data);
Expand All @@ -40,3 +40,4 @@ int mem_get_stat(struct memstat *mstat);

/* Secure memory functions */
int mem_seccmp(const uint8_t *s1, const uint8_t *s2, size_t n);
void mem_secclean(void *data, size_t size);
44 changes: 43 additions & 1 deletion src/mem/secure.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,19 @@
* Copyright (C) 2010 Creytiv.com
*/

#include <string.h>
#include <re_types.h>
#include <re_mem.h>

#if !defined(__GNUC__)
#if defined(USE_OPENSSL)
#include <openssl/crypto.h>
#elif defined(WIN32)
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#endif /* !defined(__GNUC__) */

/**
* Compare two byte strings in constant time. This function can be used
Expand Down Expand Up @@ -35,3 +45,35 @@ int mem_seccmp(const uint8_t *s1, const uint8_t *s2, size_t n)

return val;
}


#if !defined(__GNUC__) && !defined(USE_OPENSSL) && !defined(WIN32)
/* Use a volatile pointer to memset to force the compiler always
* call it and not optimize away. */
typedef void *(memset_t)(void *, int, size_t);
static memset_t *const volatile memset_ptr = &memset;
#endif

/**
* Securely clean memory. This function is guaranteed not to get optimized
* away by compiler.
*
* @param data Pointer to data buffer
* @param size Size of the buffer
*/
void mem_secclean(void *data, size_t size)
{
#if defined(__GNUC__)
memset(data, 0, size);
/* Insert an asm statement that may potentially depend
* on the memory contents that were affected by memset.
* This prevents optimizing away the memset. */
__asm__ __volatile__("" : : "r" (data), "r" (size) : "memory");
#elif defined(USE_OPENSSL)
OPENSSL_cleanse(data, size);
#elif defined(WIN32)
SecureZeroMemory(data, size);
#else
(*memset_ptr)(data, 0, size);
#endif
}

0 comments on commit 1f03390

Please sign in to comment.