%% options
copyright owner = Dirk Krause
copyright year = 2015-xxxx
license = bsd
%% header
/** @file
Secure memory reset (reset byte buffer
to 0x00 bytes and read the buffer to prevent compilers
from optimizing the resetting out).
*/
#ifdef __cplusplus
extern "C" {
#endif
/** Secure memory reset.
This function does not just reset the bytes to 0,
it also reads each byte to check it.
Reading each byte should prevent the compiler from optimizing
out.
This function has significantly lower performance than
dk4mem_reset(), so use it to clear sensitive memory
(i.e. used for passwords, keys...) only.
CRT on Windows: Not used.
@param ptr Start address of memory range.
@param sz Size of memory range in bytes.
@param erp Error report, may be NULL.
@return 1 on success, 0 on error.
Error codes:
- DK4_E_INVALID_ARGUMENTS
if ptr is NULL or sz is 0,
- DK4_E_BUG
if one of the bytes in the buffer is not 0 during check.
*/
int
dk4mem_reset_secure(void *ptr, size_t sz, dk4_er_t *erp);
/** Secure memory release.
This function does not just reset the bytes to 0 before releasing
memory, it also reads each byte to check it.
Reading each byte should prevent the compiler from optimizing
out.
This function has significantly lower performance than
dk4mem_free(), so use it to clear sensitive memory
(i.e. used for passwords, keys...) only.
CRT on Windows: Not used.
@param ptr Start address of memory range.
@param sz Size of memory range in bytes.
@param erp Error report, may be NULL.
@return 1 on success, 0 on error.
Error codes:
- DK4_E_INVALID_ARGUMENTS
if ptr is NULL or sz is 0,
- DK4_E_BUG
if one of the bytes in the buffer is not 0 during check.
*/
int
dk4mem_free_secure(void *ptr, size_t sz, dk4_er_t *erp);
#ifdef __cplusplus
}
#endif
/** Release memory securely (sanitize memory before releasing it).
*/
#define dk4mem_release_secure(ptr,sz,erp) \
do { if (NULL != ptr) { (void)dk4mem_free_secure(ptr,sz,erp); } ptr = NULL; } while (0)
%% module
#include "dk4conf.h"
#ifndef STDIO_H_INCLUDED
#include
#define STDIO_H_INCLUDED 1
#endif
#ifndef STDLIB_H_INCLUDED
#include
#define STDLIB_H_INCLUDED 1
#endif
#if DK4_ON_WINDOWS
#ifndef WINDOWS_H_INCLUDED
#include
#define WINDOWS_H_INCLUDED 1
#endif
#endif
#include "dk4mem.h"
int
dk4mem_reset_secure(void *ptr, size_t sz, dk4_er_t *erp)
{
#if !DK4_ON_WINDOWS
unsigned char *p1;
#endif
int back = 0;
if ((NULL != ptr) && (0 < sz)) {
#if DK4_ON_WINDOWS
SecureZeroMemory(ptr, sz);
back = 1;
#else
DK4_MEMRES(ptr, sz);
p1 = (unsigned char *)ptr;
back = 1;
while(sz--) {
if ('\0' != *(p1++)) {
back = 0;
dk4error_set_simple_error_code(erp, DK4_E_BUG);
}
}
#endif
} else {
dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
}
return back;
}
int
dk4mem_free_secure(void *ptr, size_t sz, dk4_er_t *erp)
{
int back = 0;
if (NULL != ptr) {
if (0 < sz) {
back = dk4mem_reset_secure(ptr, sz, erp);
} else {
back = 1;
}
dk4mem_free(ptr);
} else {
dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
}
return back;
}