feat(misc): add burn_free function and BURN_FREE macro for secure memory deallocation

Signed-off-by: Praneeth Sarode <praneethsarode@gmail.com>
Reviewed-by: Jakub Jelen <jjelen@redhat.com>
This commit is contained in:
Praneeth Sarode
2025-07-09 22:07:54 +05:30
committed by Jakub Jelen
parent 0f0ac314d2
commit ed52c88a03
2 changed files with 32 additions and 0 deletions

View File

@@ -369,6 +369,17 @@ int ssh_connector_remove_event(ssh_connector connector);
void explicit_bzero(void *s, size_t n);
#endif /* !HAVE_EXPLICIT_BZERO */
void burn_free(void *ptr, size_t len);
/** Free memory space after zeroing it */
#define BURN_FREE(x, len) \
do { \
if ((x) != NULL) { \
burn_free((x), (len)); \
(x) = NULL; \
} \
} while (0)
/**
* This is a hack to fix warnings. The idea is to use this everywhere that we
* get the "discarding const" warning by the compiler. That doesn't actually

View File

@@ -1619,6 +1619,27 @@ void explicit_bzero(void *s, size_t n)
}
#endif /* !HAVE_EXPLICIT_BZERO */
/**
* @brief Securely free memory by overwriting it before deallocation
*
* Overwrites the memory region with zeros before calling free() to prevent
* sensitive data from remaining in memory after deallocation.
*
* @param[in] ptr Pointer to the memory region to securely free.
* Can be NULL (no operation performed).
* @param[in] len Length of the memory region in bytes.
*
*/
void burn_free(void *ptr, size_t len)
{
if (ptr == NULL || len == 0) {
return;
}
explicit_bzero(ptr, len);
free(ptr);
}
#if !defined(HAVE_STRNDUP)
char *strndup(const char *s, size_t n)
{