diff --git a/include/libssh/priv.h b/include/libssh/priv.h index 1e21d92b..57ab902f 100644 --- a/include/libssh/priv.h +++ b/include/libssh/priv.h @@ -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 diff --git a/src/misc.c b/src/misc.c index 9e8c381f..c2bb5484 100644 --- a/src/misc.c +++ b/src/misc.c @@ -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) {