Consider a scenario, where std::string
is used to store a secret. Once it is consumed and is no longer needed, it would be good to cleanse it, i.e overwrite the memory that contained it, thus hiding the secret.
std::string
provides a function const char* data()
returning a pointer to (since C++11) continous memory.
Now, since the memory is continous and the variable will be destroyed right after the cleanse due to scope end, would it be safe to:
char* modifiable = const_cast<char*>(secretString.data());
OpenSSL_cleanse(modifiable, secretString.size());
According to standard quoted here:
$5.2.11/7 - Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a
const_cast
that casts away aconst-qualifier
68 may produce undefined behavior (7.1.5.1).
That would advise otherwise, but do the conditions above (continuous, to-be-just-removed) make it safe?
OpenSSL_cleanse
and possible UB why not iterate through the string and assign it random values from a PRNG? – NathanOliver 2 days agodata
is overloaded to return a non const pointer so you can use it then. – NathanOliver 2 days agorand()
(or similiar) calls as possible, while guaranteeing acceptable safety. Imagine a case whererand()
is called on hardware, and could be costly. Besides, reinventing the wheel... And another thing - as @ilotXXI stated in comment below - naive clear may be optimized away (usually is). – hauron 2 days agostd::string
, but an actual securestring-type to ensure all buffers get scrubbed. Take a look at codereview.stackexchange.com/questions/107991/… for a way to hackstd::basic_string
to fill the need. – Deduplicator yesterday