Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions age/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ const V1_MAGIC: &[u8] = b"v1";
const MAC_TAG: &[u8] = b"---";
const ENCODED_MAC_LENGTH: usize = 43;

/// Maximum header size to prevent unbounded memory allocation.
///
/// This matches the limit used by the reference Go implementation.
const MAX_HEADER_SIZE: usize = 64 * 1024; // 64 KiB

#[derive(Debug, PartialEq)]
pub(crate) struct HeaderV1 {
pub(crate) recipients: Vec<Stanza>,
Expand Down Expand Up @@ -118,6 +123,12 @@ impl Header {
// remainder of the input will be truncated.
let m = data.len();
let new_len = m + n.get();

// Prevent unbounded memory allocation.
if new_len > MAX_HEADER_SIZE {
break Err(DecryptError::InvalidHeader);
}

data.resize(new_len, 0);
input.read_exact(&mut data[m..new_len])?;
}
Expand Down Expand Up @@ -148,6 +159,11 @@ impl Header {
"Incomplete header",
)));
}

// Prevent unbounded memory allocation.
if data.len() > MAX_HEADER_SIZE {
break Err(DecryptError::InvalidHeader);
}
}
Err(_) => {
break Err(DecryptError::InvalidHeader);
Expand Down Expand Up @@ -176,6 +192,12 @@ impl Header {
// remainder of the input will be truncated.
let m = data.len();
let new_len = m + n.get();

// Prevent unbounded memory allocation.
if new_len > MAX_HEADER_SIZE {
break Err(DecryptError::InvalidHeader);
}

data.resize(new_len, 0);
input.read_exact(&mut data[m..new_len]).await?;
}
Expand Down Expand Up @@ -210,6 +232,11 @@ impl Header {
"Incomplete header",
)));
}

// Prevent unbounded memory allocation.
if data.len() > MAX_HEADER_SIZE {
break Err(DecryptError::InvalidHeader);
}
}
Err(_) => {
break Err(DecryptError::InvalidHeader);
Expand Down