Closed dima74 closed 5 months ago
DefaultIsZeroes
underlies the core zeroization behavior for integer types, which is performed using core::ptr::write_volatile
.
A Copy
bound is the simplest way we can avoid making DefaultIsZeroes
an unsafe trait
:
Zeroize
for [Z] where Z: DefaultIsZeroes
, which performs a memset
-like operation underneath which requires the source type is Copy
, since it makes a bunch of copies of it, which makes it possible to optimize zeroization of e.g. [u8]
(though we haven't yet implemented an optimized version, see #841). With a Copy
bound on DefaultIsZeros
, we can make such impls safe.!Drop
, which is necessary because write_volatile
will bypass the drop handler on the target value.What is recommended approach to implement Zeroize for non-copy-types?
For your example:
impl Zeroize for SecretKey {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
Though you'd likely be better zeroizing in a drop handler for such a use case, to avoid use-after-zeroize problems:
impl Drop for SecretKey {
fn drop(&mut self) {
self.0.zeroize();
}
}
impl ZeroizeOnDrop for SecretKey {}
Thanks for the detailed answer!
impl Zeroize for SecretKey { fn zeroize(&mut self) { self.0.zeroize(); } }
If this can't be used because SecretKey
is from (external) library which doesn't use zeroize
, and SecretKey
doesn't implement Copy
, are there any possibilities to use zeroize
on the wrapper (MyKey
), or the only solution would be to approach library author and suggest to use zeroize
?
There's no safe way to zeroize a foreign type.
zeroize_flat_type
function which could potentially apply to these cases, although it's a bit dangerous to use on a type you don't control as its internal structure could change.Thanks for the explanation 👍
https://github.com/RustCrypto/utils/blob/216d2b82f691487b80e8d94022a1aaf45b2f926f/zeroize/src/lib.rs#L283
What is recommended approach to implement
Zeroize
for non-copy-types? Consider some library has non-copy type:And in user code we have wrapper around that which we would like to zeroize on drop:
One approach would be to implement
Default
forMyKey
and addimpl DefaultIsZeroes for MyKey {}
soMyKey
will implementZeroize
, but it is not possible because ofCopy
constraint onDefaultIsZeroes