From 81573890225522e55f8b2983405723f0f16e7f28 Mon Sep 17 00:00:00 2001 From: Justus Winter Date: Fri, 9 Oct 2020 12:41:25 +0200 Subject: openpgp: Avoid possible reallocations in From::>. --- openpgp/src/crypto/mem.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/openpgp/src/crypto/mem.rs b/openpgp/src/crypto/mem.rs index f62244fe..2c9f7fca 100644 --- a/openpgp/src/crypto/mem.rs +++ b/openpgp/src/crypto/mem.rs @@ -98,11 +98,23 @@ impl DerefMut for Protected { } impl From> for Protected { - fn from(v: Vec) -> Self { - // FIXME(xanewok): This can potentially realloc and leave a lingering - // copy of the secret somewhere. It'd be great to explicitly move the - // source data by copying it and zeroing it explicitly afterwards. - Protected(v.into_boxed_slice()) + fn from(mut v: Vec) -> Self { + // Make a vector with the correct size to avoid potential + // reallocations when turning it into a `Protected`. + let mut p = Vec::with_capacity(v.len()); + p.extend_from_slice(&v); + + // Now clear the previous allocation. Just to be safe, we + // clear the whole allocation. + let capacity = v.capacity(); + unsafe { + // Safety: New size is equal to the capacity, and we + // initialize all elements. + v.set_len(capacity); + memsec::memzero(v.as_mut_ptr(), capacity); + } + + p.into_boxed_slice().into() } } -- cgit v1.2.3 ers Contrib clone of configmatthias
summaryrefslogtreecommitdiffstats
blob: 47f48002bdbd4a1474a343dca3566653b1984c65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use crate::element::AsConfigElement;

use super::SourceError;

pub trait FormatParser: std::fmt::Debug {
    type Output: AsConfigElement + std::fmt::Debug + Sized;

    fn parse(buffer: &str) -> Result<Self::Output, SourceError>;
}

#[cfg(feature = "json")]
#[derive(Debug)]
pub struct JsonFormatParser;

#[cfg(feature = "json")]
impl FormatParser for JsonFormatParser {
    type Output = serde_json::Value;

    fn parse(buffer: &str) -> Result<Self::Output, SourceError> {
        serde_json::from_str(buffer).map_err(SourceError::JsonParserError)
    }
}


#[cfg(feature = "toml")]
#[derive(Debug)]
pub struct TomlFormatParser;

#[cfg(feature = "toml")]
impl FormatParser for TomlFormatParser {
    type Output = toml::Value;

    fn parse(buffer: &str) -> Result<Self::Output, SourceError> {
        toml::from_str(buffer).map_err(SourceError::TomlParserError)
    }
}