mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 19:58:11 +00:00
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.
This commit is contained in:
parent
d158f2ed89
commit
3bf6902790
3 changed files with 81 additions and 0 deletions
42
Userland/Libraries/LibCore/SecretString.cpp
Normal file
42
Userland/Libraries/LibCore/SecretString.cpp
Normal file
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue