use super::SIGNATURE_HEADER_SIZE;
use super::header::BlockIndex;
use super::header::SevenZHeader;
use crate::ArchiveError;
use crate::EntryCompression;
use crate::Limit;
use crate::Malformation;
use crate::Result;
use crate::SecurityConfig;
use crate::SolidArchives;
use crate::SolidBlock;
use crate::SolidMemoryScope;
use crate::Violation;
use crate::error::QuotaResource;
use crate::formats::common;
use crate::inspection::report::Finding;
use crate::inspection::report::Heuristic;
use crate::inspection::report::IssueSeverity;
use crate::inspection::report::UnverifiedReason;
use crate::inspection::report::VerificationIssue;
use crate::security::Compressed;
use crate::security::Uncompressed;
use crate::security::zipbomb::DeclaredCompressedBudget;
use sevenz_rust2::BlockDecoder;
use sevenz_rust2::Password;
use std::io;
pub(super) fn packed_stream_count(block: &sevenz_rust2::Block) -> usize {
use sevenz_rust2::EncoderMethod;
let bcj2 = block
.coders
.iter()
.filter(|coder| coder.encoder_method_id() == EncoderMethod::ID_BCJ2)
.count();
1 + 3 * bcj2
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum BlockTotal {
Bytes(u64),
Overflow,
}
impl BlockTotal {
fn add(self, size: u64) -> Self {
match self {
Self::Bytes(total) => total.checked_add(size).map_or(Self::Overflow, Self::Bytes),
Self::Overflow => Self::Overflow,
}
}
}
struct BlockTally {
files: usize,
uncompressed: BlockTotal,
}
fn tally_blocks(header: &SevenZHeader) -> Vec<BlockTally> {
let mut tallies: Vec<BlockTally> = header
.block_indices()
.map(|_| BlockTally {
files: 0,
uncompressed: BlockTotal::Bytes(0),
})
.collect();
for (index, file) in header.files().iter().enumerate() {
if let Some(block) = header.file_block(index) {
let tally = &mut tallies[block.get()];
tally.files += 1;
tally.uncompressed = tally.uncompressed.add(file.size);
}
}
tallies
}
pub fn sevenz_entry_compression(
header: &SevenZHeader,
source_len: u64,
) -> Result<Vec<EntryCompression>> {
let archive = header.archive();
let data_region = source_len
.checked_sub(SIGNATURE_HEADER_SIZE)
.and_then(|len| len.checked_sub(archive.pack_pos()))
.ok_or_else(|| ArchiveError::from(Malformation::DeclaredCompressedExceedsArchive))?;
let mut budget = DeclaredCompressedBudget::new(data_region);
for &pack_size in archive.pack_sizes() {
budget.charge(pack_size)?;
}
let pack_sizes = archive.pack_sizes();
let block_compressed = |block: BlockIndex| -> Result<Compressed> {
let start = header.block_first_pack(block);
let end = header.next_block_first_pack(block).unwrap_or_else(|| {
start
.saturating_add(packed_stream_count(header.block(block)))
.min(pack_sizes.len())
});
pack_sizes[start..end]
.iter()
.try_fold(0u64, |acc, &size| acc.checked_add(size))
.map(Compressed)
.ok_or_else(|| ArchiveError::from(Malformation::PackSizesOverflow))
};
let tallies = tally_blocks(header);
let mut block_uncompressed = Vec::with_capacity(tallies.len());
let mut block_files = Vec::with_capacity(tallies.len());
for tally in &tallies {
let BlockTotal::Bytes(bytes) = tally.uncompressed else {
return Err(ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow,
});
};
block_uncompressed.push(bytes);
block_files.push(tally.files);
}
header
.files()
.iter()
.enumerate()
.map(|(index, file)| {
let Some(block) = header.file_block(index) else {
return Ok(EntryCompression::Unknown);
};
if !file.has_stream {
return Ok(EntryCompression::Unknown);
}
let compressed = block_compressed(block)?;
if block_files[block.get()] <= 1 {
return Ok(EntryCompression::Entry(compressed));
}
if header.block_first_file(block) == index {
Ok(EntryCompression::SolidBlockStart(SolidBlock::new(
compressed,
Uncompressed(block_uncompressed[block.get()]),
)))
} else {
Ok(EntryCompression::SolidBlockMember)
}
})
.collect()
}
#[derive(Debug)]
pub(super) struct Refused {
pub(super) reason: UnverifiedReason,
pub(super) error: ArchiveError,
}
impl Refused {
const fn new(reason: UnverifiedReason, error: ArchiveError) -> Self {
Self { reason, error }
}
}
pub(super) fn check_solid_policy(
is_solid: bool,
blocks: impl IntoIterator<Item = BlockTotal>,
config: &SecurityConfig,
) -> std::result::Result<(), Refused> {
if !is_solid {
return Ok(());
}
let SolidArchives::Allow(limits) = config.solid_archives else {
return Err(Refused::new(
UnverifiedReason::SolidPolicy,
Violation::SolidArchive.into(),
));
};
let max = limits.max_block_memory.get();
let resource_limit = |resource| {
Refused::new(
UnverifiedReason::ResourceLimit,
ArchiveError::QuotaExceeded { resource },
)
};
let mut archive_total = 0u64;
for block in blocks {
let BlockTotal::Bytes(current) = block else {
return Err(resource_limit(QuotaResource::IntegerOverflow));
};
if current > max {
return Err(resource_limit(QuotaResource::SolidBlockMemory {
scope: SolidMemoryScope::Block,
current,
max,
}));
}
archive_total = archive_total
.checked_add(current)
.ok_or_else(|| resource_limit(QuotaResource::IntegerOverflow))?;
}
if config.max_total_size == Limit::Unbounded && archive_total > max {
return Err(resource_limit(QuotaResource::SolidBlockMemory {
scope: SolidMemoryScope::Archive,
current: archive_total,
max,
}));
}
Ok(())
}
pub(super) const BZIP2_DECODER_MEMORY: u64 = 4 * 1024 * 1024;
pub(super) fn lzma2_dict_size(props: &[u8]) -> Option<u32> {
let bits = u32::from(*props.first()?);
match bits {
0..=39 => Some((2 | (bits & 1)) << (bits / 2 + 11)),
40 => Some(u32::MAX),
_ => None,
}
}
pub(super) fn coder_memory(coder: &sevenz_rust2::Coder, unpack_size: u64) -> Option<u64> {
use sevenz_rust2::EncoderMethod;
let props = coder.properties();
let window = |dict: u64| dict.min(unpack_size.saturating_mul(2));
match coder.encoder_method_id() {
EncoderMethod::ID_COPY
| EncoderMethod::ID_DELTA
| EncoderMethod::ID_BCJ_X86
| EncoderMethod::ID_BCJ_PPC
| EncoderMethod::ID_BCJ_IA64
| EncoderMethod::ID_BCJ_ARM
| EncoderMethod::ID_BCJ_ARM64
| EncoderMethod::ID_BCJ_ARM_THUMB
| EncoderMethod::ID_BCJ_SPARC
| EncoderMethod::ID_BCJ_RISCV
| EncoderMethod::ID_BCJ2
| EncoderMethod::ID_DEFLATE => Some(0),
EncoderMethod::ID_LZMA => {
let dict = props.get(1..)?.first_chunk::<4>()?;
Some(window(u64::from(u32::from_le_bytes(*dict))))
}
EncoderMethod::ID_LZMA2 => Some(window(u64::from(lzma2_dict_size(props)?))),
EncoderMethod::ID_PPMD => {
let mem = props.get(1..)?.first_chunk::<4>()?;
Some(u64::from(u32::from_le_bytes(*mem)))
}
EncoderMethod::ID_BZIP2 => Some(BZIP2_DECODER_MEMORY),
_ => None,
}
}
pub(super) fn block_span(header: &SevenZHeader, block: BlockIndex) -> std::ops::Range<usize> {
let password = Password::empty();
let mut no_source = io::Cursor::new(&[][..]);
let count = BlockDecoder::new(1, block.get(), header.archive(), &password, &mut no_source)
.entry_count();
let first = header.block_first_file(block);
first..first.saturating_add(count)
}
pub(super) fn declared_sizes(header: &SevenZHeader) -> Vec<Option<u64>> {
let mut sizes = vec![Some(0u64); header.block_count()];
for (index, file) in header.files().iter().enumerate() {
if let Some(block) = header.file_block(index) {
let size = &mut sizes[block.get()];
*size = size.and_then(|sum| sum.checked_add(file.size));
}
}
sizes
}
pub(super) fn block_charge(block: &sevenz_rust2::Block) -> u64 {
block
.coders
.iter()
.map(|coder| block.get_unpack_size_for_coder(coder))
.max()
.unwrap_or_default()
}
pub(super) fn admit_sevenz_block(
block: &sevenz_rust2::Block,
declared_size: Option<u64>,
config: &SecurityConfig,
) -> std::result::Result<(), Refused> {
let not_decodable = |error| Refused::new(UnverifiedReason::NotDecodable, error);
let output = block_charge(block).max(declared_size.unwrap_or_default());
let mut memory: u64 = 0;
for coder in &block.coders {
if coder.encoder_method_id() == sevenz_rust2::EncoderMethod::ID_AES256_SHA256 {
return Err(not_decodable(common::encrypted_archive_error()));
}
let needed = coder_memory(coder, output).ok_or_else(|| {
not_decodable(ArchiveError::from(Malformation::SevenZUnsupportedCoder))
})?;
memory = memory.saturating_add(needed);
}
if memory > config.max_decoder_memory.get() {
return Err(Refused::new(
UnverifiedReason::ResourceLimit,
ArchiveError::QuotaExceeded {
resource: QuotaResource::DecoderMemory {
max: config.max_decoder_memory.get(),
},
},
));
}
if declared_size != Some(block.get_unpack_size()) {
return Err(not_decodable(ArchiveError::from(
Malformation::BlockSizeUnaccounted,
)));
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefusalScope {
Archive,
Block(BlockIndex),
}
#[derive(Debug)]
pub struct SevenZRefusal {
pub(super) scope: RefusalScope,
unverified: UnverifiedReason,
pub(super) error: ArchiveError,
}
impl SevenZRefusal {
fn new(scope: RefusalScope, refused: Refused) -> Self {
Self {
scope,
unverified: refused.reason,
error: refused.error,
}
}
pub(super) const fn unverified(&self) -> UnverifiedReason {
self.unverified
}
pub(crate) fn into_error(self) -> ArchiveError {
self.error
}
}
pub fn iter_sevenz_refusals<'a>(
header: &'a SevenZHeader,
config: &'a SecurityConfig,
) -> impl Iterator<Item = SevenZRefusal> + 'a {
let solid = check_solid_policy(
header.is_solid(),
tally_blocks(header)
.into_iter()
.map(|tally| tally.uncompressed),
config,
)
.err()
.map(|refused| SevenZRefusal::new(RefusalScope::Archive, refused));
let blocks = header
.block_indices()
.zip(declared_sizes(header))
.filter_map(move |(index, declared)| {
admit_sevenz_block(header.block(index), declared, config)
.err()
.map(|refused| SevenZRefusal::new(RefusalScope::Block(index), refused))
});
solid.into_iter().chain(blocks)
}
pub fn sevenz_refusals(header: &SevenZHeader, config: &SecurityConfig) -> Vec<SevenZRefusal> {
iter_sevenz_refusals(header, config).collect()
}
pub(super) const MAX_REFUSAL_ISSUES: usize = 32;
pub fn refusal_issues(refusals: &[SevenZRefusal]) -> Vec<VerificationIssue> {
let mut issues: Vec<_> = refusals
.iter()
.take(MAX_REFUSAL_ISSUES)
.map(|r| VerificationIssue::from_error(&r.error, None))
.collect();
if let Some(omitted) = refusals.len().checked_sub(MAX_REFUSAL_ISSUES)
&& omitted > 0
{
issues.push(VerificationIssue::new(
IssueSeverity::Info,
Finding::Heuristic(Heuristic::OmittedRefusals { omitted }),
));
}
issues
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use crate::SolidLimits;
use std::assert_matches;
fn config(max_solid_memory: u64) -> SecurityConfig {
SecurityConfig::default().with_solid_archives(SolidArchives::Allow(
SolidLimits::DEFAULT
.with_max_block_memory(std::num::NonZeroU64::new(max_solid_memory).unwrap()),
))
}
fn bytes(sizes: &[u64]) -> Vec<BlockTotal> {
sizes.iter().copied().map(BlockTotal::Bytes).collect()
}
#[test]
fn solid_policy_refusal_carries_its_own_reason() {
let refused =
check_solid_policy(true, bytes(&[1]), &SecurityConfig::default()).unwrap_err();
assert_eq!(refused.reason, UnverifiedReason::SolidPolicy);
assert_matches!(refused.error, ArchiveError::SecurityViolation { .. });
}
#[test]
fn solid_size_overflow_is_an_integer_overflow() {
let refused = check_solid_policy(true, [BlockTotal::Overflow], &config(100)).unwrap_err();
assert_eq!(refused.reason, UnverifiedReason::ResourceLimit);
assert_matches!(
refused.error,
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow
}
);
}
#[test]
fn block_totals_that_overflow_together_are_an_integer_overflow() {
let unbounded = config(u64::MAX).with_max_total_size(Limit::Unbounded);
let refused = check_solid_policy(true, bytes(&[u64::MAX, 1]), &unbounded).unwrap_err();
assert_matches!(
refused.error,
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow
}
);
}
#[test]
fn a_block_over_the_limit_is_a_solid_block_memory_refusal() {
let refused = check_solid_policy(true, bytes(&[120]), &config(100)).unwrap_err();
assert_eq!(refused.reason, UnverifiedReason::ResourceLimit);
assert_matches!(
refused.error,
ArchiveError::QuotaExceeded {
resource: QuotaResource::SolidBlockMemory {
scope: SolidMemoryScope::Block,
current: 120,
max: 100
}
}
);
}
#[test]
fn every_block_is_checked_not_only_the_first() {
let refused = check_solid_policy(true, bytes(&[10, 1, 101]), &config(100)).unwrap_err();
assert_matches!(
refused.error,
ArchiveError::QuotaExceeded {
resource: QuotaResource::SolidBlockMemory { current: 101, .. }
}
);
}
#[test]
fn blocks_each_within_the_limit_pass_while_the_total_is_bounded() {
let bounded = config(100).with_max_total_size(crate::non_zero!(1000));
assert!(check_solid_policy(true, bytes(&[60, 60, 60]), &bounded).is_ok());
}
#[test]
fn an_unbounded_total_keeps_the_archive_wide_cap() {
let unbounded = config(100).with_max_total_size(Limit::Unbounded);
let refused = check_solid_policy(true, bytes(&[60, 60]), &unbounded).unwrap_err();
assert_eq!(refused.reason, UnverifiedReason::ResourceLimit);
assert_matches!(
refused.error,
ArchiveError::QuotaExceeded {
resource: QuotaResource::SolidBlockMemory {
scope: SolidMemoryScope::Archive,
current: 120,
max: 100
}
}
);
}
#[test]
fn non_solid_archive_passes_the_policy() {
assert!(
check_solid_policy(false, bytes(&[u64::MAX, 1]), &SecurityConfig::default()).is_ok()
);
}
}