1//! Define a wrapper for `Vec<u8>` that will act as Writer, but zeroize its
2//! contents on drop or reallocation.
34use crate::Writer;
5use zeroize::{Zeroize, ZeroizeOnDrop};
67/// A [`Writer`] used for accumulating secret data, which gets cleared on drop.
8///
9/// Unlike `Zeroizing<Vec<u8>>`, this type makes sure that we always zeroize the
10/// contents of the buffer, even if the buffer has to be reallocated in order to
11/// grow.
12///
13/// We use this for cases when we're building the input to a key derivation
14/// function (KDF), and want to ensure that we don't expose the values we feed
15/// to it.
16///
17/// This struct is expected to have additional overhead beyond `Vec<u8>` only
18/// when it has to grow its capacity.
19#[derive(Zeroize, ZeroizeOnDrop, Debug, Clone, Eq, PartialEq)]
20pub struct SecretBuf(Vec<u8>);
2122/// The default size of our buffer.
23///
24/// This is based on the size of a typical secret input in `tor-proto`.
25const DEFAULT_CAPACITY: usize = 384;
2627impl SecretBuf {
28/// Construct a new empty [`SecretBuf`]
29pub fn new() -> Self {
30Self::with_capacity(DEFAULT_CAPACITY)
31 }
3233/// Construct a new empty [`SecretBuf`] with a specified capacity.
34 ///
35 /// This buffer will not have to be reallocated until it uses `capacity`
36 /// bytes.
37pub fn with_capacity(capacity: usize) -> Self {
38Self(Vec::with_capacity(capacity))
39 }
4041/// Truncate this buffer to a given length.
42pub fn truncate(&mut self, new_len: usize) {
43self.0.truncate(new_len);
44 }
4546/// Add all the bytes from `slice` to the end of this vector.
47pub fn extend_from_slice(&mut self, slice: &[u8]) {
48let new_len = self.0.len() + slice.len();
49if new_len >= self.0.capacity() {
50// We will need to reallocate. But in doing so we might reallocate,
51 // which neglects to zero the previous contents. So instead,
52 // explicitly make a new vector and zeroize the old one.
5354 // Make sure we always at least double our capacity.
55let new_capacity = std::cmp::max(self.0.capacity() * 2, new_len);
56let mut new_vec = Vec::with_capacity(new_capacity);
57 new_vec.extend_from_slice(&self.0[..]);
5859let mut old_vec = std::mem::replace(&mut self.0, new_vec);
60 old_vec.zeroize();
61 }
62self.0.extend_from_slice(slice);
63debug_assert_eq!(self.0.len(), new_len);
64 }
65}
6667impl From<Vec<u8>> for SecretBuf {
68fn from(v: Vec<u8>) -> Self {
69Self(v)
70 }
71}
7273impl Default for SecretBuf {
74fn default() -> Self {
75Self::new()
76 }
77}
7879impl AsMut<[u8]> for SecretBuf {
80fn as_mut(&mut self) -> &mut [u8] {
81&mut self.0[..]
82 }
83}
8485// It's okay to implement `Deref` since all operations taking an _immutable_
86// reference are still right here.
87impl std::ops::Deref for SecretBuf {
88type Target = Vec<u8>;
8990fn deref(&self) -> &Self::Target {
91&self.0
92}
93}
9495impl Writer for SecretBuf {
96fn write_all(&mut self, b: &[u8]) {
97self.extend_from_slice(b);
98 }
99}
100101#[cfg(test)]
102mod test {
103// @@ begin test lint list maintained by maint/add_warning @@
104#![allow(clippy::bool_assert_comparison)]
105 #![allow(clippy::clone_on_copy)]
106 #![allow(clippy::dbg_macro)]
107 #![allow(clippy::mixed_attributes_style)]
108 #![allow(clippy::print_stderr)]
109 #![allow(clippy::print_stdout)]
110 #![allow(clippy::single_char_pattern)]
111 #![allow(clippy::unwrap_used)]
112 #![allow(clippy::unchecked_duration_subtraction)]
113 #![allow(clippy::useless_vec)]
114 #![allow(clippy::needless_pass_by_value)]
115//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
116use super::*;
117118#[test]
119fn simple_case() -> crate::EncodeResult<()> {
120// Sadly, there is no way in safe rust to test that the zeroization
121 // actually happened. All we can test is that the data is correct.
122123let mut buf1 = SecretBuf::default();
124let mut buf2 = Vec::new();
125let xyz = b"Nine hundred pounds of sifted flax";
126127// This is enough to be sure that we'll reallocate.
128for _ in 0..200 {
129 buf1.write(xyz)?;
130 buf2.write(xyz)?;
131 }
132assert_eq!(&buf1[..], &buf2[..]);
133134Ok(())
135 }
136}