ladybird/Userland/Libraries/LibCore/SecretString.cpp
Brian Gianforcaro 3bf6902790 LibCore: Add SecretString, a buffer that is zero'd on destruction
We have a few places where we read secrets into memory, and then
do some computation on them. In these cases we should always make
sure we zero the allocations before they are free'd.

The SecureString wrapper provides this abstraction by wrapping a
ByteBuffer and calling explicit_bzero on destruction of the object.
2021-09-12 16:36:52 +02:00

42 lines
976 B
C++

/*
* Copyright (c) 2021, Brian Gianforcaro <bgianf@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibCore/SecretString.h>
#include <string.h>
namespace Core {
SecretString SecretString::take_ownership(char*& cstring, size_t length)
{
auto buffer = ByteBuffer::copy(cstring, length);
VERIFY(buffer.has_value());
explicit_bzero(cstring, length);
free(cstring);
return SecretString(buffer.release_value());
}
SecretString SecretString::take_ownership(ByteBuffer&& buffer)
{
return SecretString(move(buffer));
}
SecretString::SecretString(ByteBuffer&& buffer)
: m_secure_buffer(move(buffer))
{
}
SecretString::~SecretString()
{
if (!m_secure_buffer.is_empty()) {
// Note: We use explicit_bzero to avoid the zeroing from being optimized out by the compiler,
// which is possible if memset was to be used here.
explicit_bzero(m_secure_buffer.data(), m_secure_buffer.capacity());
}
}
}