Skip to main content

exarch_core/security/
zipbomb.rs

1//! Zip bomb detection.
2
3use crate::ArchiveError;
4use crate::CompressionRatio;
5use crate::Malformation;
6use crate::Result;
7use crate::SecurityConfig;
8use crate::SolidLimits;
9use crate::ZipBombDetails;
10use crate::ZipBombScope;
11use crate::inspection::EntryCompression;
12use crate::inspection::SolidBlock;
13
14/// A byte count as stored in the archive.
15///
16/// Distinct from [`Uncompressed`] so the two sides of the compression ratio
17/// cannot be swapped at a call site.
18///
19/// # Examples
20///
21/// ```
22/// use exarch_core::Compressed;
23///
24/// assert_eq!(Compressed(512).0, 512);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct Compressed(pub u64);
28
29/// A byte count after decoding.
30///
31/// # Examples
32///
33/// ```
34/// use exarch_core::Uncompressed;
35///
36/// assert_eq!(Uncompressed(1024).0, 1024);
37/// ```
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct Uncompressed(pub u64);
40
41/// Validates compression ratio to detect potential zip bombs.
42///
43/// # Errors
44///
45/// Returns an error if the compression ratio exceeds the configured maximum.
46pub fn validate_compression_ratio(
47    compressed: Compressed,
48    uncompressed: Uncompressed,
49    config: &SecurityConfig,
50) -> Result<()> {
51    check_ratio(
52        ZipBombScope::Entry,
53        compressed,
54        uncompressed,
55        config.max_compression_ratio.get(),
56    )
57}
58
59/// Validates the compression ratio of a whole solid block against
60/// [`SolidLimits::max_ratio`](crate::SolidLimits::max_ratio).
61///
62/// Under [`SolidArchives::Refuse`](crate::SolidArchives::Refuse), which
63/// refuses solid archives before any data is read, the default limit applies
64/// to the block sizes a listing reports.
65///
66/// A block without data (`uncompressed == 0`) is accepted.
67///
68/// # Errors
69///
70/// Returns [`ArchiveError::ZipBomb`] when the block claims data but no
71/// compressed bytes, or when the ratio exceeds the configured maximum.
72pub fn validate_solid_block_ratio(block: &SolidBlock, config: &SecurityConfig) -> Result<()> {
73    check_ratio(
74        ZipBombScope::SolidBlock,
75        block.compressed,
76        block.uncompressed,
77        config
78            .solid_archives
79            .limits()
80            .unwrap_or(SolidLimits::DEFAULT)
81            .max_ratio
82            .get(),
83    )
84}
85
86/// Applies the ratio check that fits how `compression` attributes data to an
87/// entry of `uncompressed_size` bytes: per file for
88/// [`EntryCompression::Entry`], per block for a solid block start, none
89/// otherwise.
90///
91/// # Errors
92///
93/// Returns the error of [`validate_compression_ratio`] or
94/// [`validate_solid_block_ratio`].
95pub fn validate_entry_compression(
96    compression: &EntryCompression,
97    uncompressed_size: Uncompressed,
98    config: &SecurityConfig,
99) -> Result<()> {
100    match compression {
101        EntryCompression::Entry(compressed) => {
102            validate_compression_ratio(*compressed, uncompressed_size, config)
103        }
104        EntryCompression::SolidBlockStart(block) => validate_solid_block_ratio(block, config),
105        EntryCompression::Unknown | EntryCompression::SolidBlockMember => Ok(()),
106    }
107}
108
109/// Whether an entry of `uncompressed_size` bytes from `compressed_size` bytes
110/// is within `max_ratio`, by the same rule as [`validate_compression_ratio`].
111pub fn ratio_admitted(compressed: Compressed, uncompressed: Uncompressed, max_ratio: f64) -> bool {
112    check_ratio(ZipBombScope::Entry, compressed, uncompressed, max_ratio).is_ok()
113}
114
115fn check_ratio(
116    scope: ZipBombScope,
117    compressed: Compressed,
118    uncompressed: Uncompressed,
119    max_ratio: f64,
120) -> Result<()> {
121    let details = ZipBombDetails::new(scope, compressed, uncompressed);
122    match details.ratio() {
123        // HIGH-001: data claimed from zero compressed bytes bypasses any finite
124        // limit
125        CompressionRatio::Unbounded => Err(ArchiveError::ZipBomb(details)),
126        CompressionRatio::Finite(ratio) if ratio > max_ratio => Err(ArchiveError::ZipBomb(details)),
127        CompressionRatio::Finite(_) => Ok(()),
128    }
129}
130
131/// Bounds the sum of declared compressed sizes by the archive's data region.
132///
133/// Each entry's declared compressed size is charged against the budget, so
134/// the sizes of all entries together never exceed the space the archive can
135/// actually hold. Entries that declare more data than remains are rejected,
136/// which keeps per-entry compression-ratio checks anchored to real archive
137/// bytes.
138#[derive(Debug)]
139pub struct DeclaredCompressedBudget {
140    remaining: u64,
141}
142
143impl DeclaredCompressedBudget {
144    /// Creates a budget of `data_region` bytes, the archive space that can
145    /// hold compressed entry data.
146    pub const fn new(data_region: u64) -> Self {
147        Self {
148            remaining: data_region,
149        }
150    }
151
152    /// Charges one declared compressed size against the budget.
153    ///
154    /// # Errors
155    ///
156    /// Returns [`ArchiveError::InvalidArchive`] when `declared` exceeds what
157    /// is left of the budget.
158    pub fn charge(&mut self, declared: u64) -> Result<()> {
159        self.remaining = self
160            .remaining
161            .checked_sub(declared)
162            .ok_or_else(|| ArchiveError::from(Malformation::DeclaredCompressedExceedsArchive))?;
163        Ok(())
164    }
165}
166
167#[cfg(test)]
168#[allow(clippy::expect_used)]
169mod tests {
170    use super::*;
171    use std::assert_matches;
172
173    #[test]
174    fn test_validate_compression_ratio_safe() {
175        let config = SecurityConfig::default();
176        let result = validate_compression_ratio(Compressed(1000), Uncompressed(10_000), &config);
177        assert!(result.is_ok());
178    }
179
180    #[test]
181    fn test_validate_compression_ratio_bomb() {
182        let config = SecurityConfig::default();
183        let result = validate_compression_ratio(Compressed(1000), Uncompressed(1_000_000), &config);
184        assert_matches!(result, Err(ArchiveError::ZipBomb(_)));
185    }
186
187    #[test]
188    fn test_validate_compression_ratio_zero_compressed() {
189        let config = SecurityConfig::default();
190
191        // HIGH-001: Zero compressed with non-zero uncompressed is an unbounded
192        // ratio
193        let result = validate_compression_ratio(Compressed(0), Uncompressed(1000), &config);
194        assert_matches!(
195            result,
196            Err(ArchiveError::ZipBomb(details))
197                if details.ratio() == CompressionRatio::Unbounded
198                    && details.scope() == ZipBombScope::Entry,
199            "zero compressed with non-zero uncompressed should be rejected"
200        );
201    }
202
203    #[test]
204    fn test_solid_block_ratio_uses_solid_limit() {
205        let config = SecurityConfig::default();
206        // 138x passes the solid limit (1000) though it exceeds the per-file one
207        // (100).
208        assert!(
209            validate_solid_block_ratio(
210                &SolidBlock::new(Compressed(1000), Uncompressed(138_000)),
211                &config
212            )
213            .is_ok()
214        );
215        assert_matches!(
216            validate_solid_block_ratio(
217                &SolidBlock::new(Compressed(1000), Uncompressed(1_500_000)),
218                &config
219            ),
220            Err(ArchiveError::ZipBomb(_))
221        );
222    }
223
224    #[test]
225    fn test_ratio_equal_to_limit_is_accepted_and_just_above_is_rejected() {
226        let config = SecurityConfig::default();
227        assert!(
228            validate_solid_block_ratio(
229                &SolidBlock::new(Compressed(10), Uncompressed(10_000)),
230                &config
231            )
232            .is_ok()
233        );
234        assert_matches!(
235            validate_solid_block_ratio(
236                &SolidBlock::new(Compressed(10), Uncompressed(10_001)),
237                &config
238            ),
239            Err(ArchiveError::ZipBomb(_))
240        );
241        assert!(validate_compression_ratio(Compressed(10), Uncompressed(1000), &config).is_ok());
242        assert_matches!(
243            validate_compression_ratio(Compressed(10), Uncompressed(1001), &config),
244            Err(ArchiveError::ZipBomb(_))
245        );
246    }
247
248    #[test]
249    fn test_solid_block_ratio_empty_and_zero_compressed() {
250        let config = SecurityConfig::default();
251        assert!(
252            validate_solid_block_ratio(&SolidBlock::new(Compressed(0), Uncompressed(0)), &config)
253                .is_ok()
254        );
255        assert_matches!(
256            validate_solid_block_ratio(&SolidBlock::new(Compressed(0), Uncompressed(10)), &config),
257            Err(ArchiveError::ZipBomb(details))
258                if details.ratio() == CompressionRatio::Unbounded
259                    && details.scope() == ZipBombScope::SolidBlock
260        );
261    }
262
263    #[test]
264    fn test_entry_compression_dispatch() {
265        let config = SecurityConfig::default();
266        let block = EntryCompression::SolidBlockStart(SolidBlock::new(
267            Compressed(1000),
268            Uncompressed(138_000),
269        ));
270        assert!(validate_entry_compression(&block, Uncompressed(1), &config).is_ok());
271        assert!(
272            validate_entry_compression(
273                &EntryCompression::SolidBlockMember,
274                Uncompressed(u64::MAX),
275                &config
276            )
277            .is_ok()
278        );
279        assert!(
280            validate_entry_compression(&EntryCompression::Unknown, Uncompressed(u64::MAX), &config)
281                .is_ok()
282        );
283        assert_matches!(
284            validate_entry_compression(
285                &EntryCompression::Entry(Compressed(1000)),
286                Uncompressed(138_000),
287                &config
288            ),
289            Err(ArchiveError::ZipBomb(_))
290        );
291    }
292
293    #[test]
294    fn test_declared_budget_accepts_sizes_within_region() {
295        let mut budget = DeclaredCompressedBudget::new(100);
296        budget.charge(60).expect("fits");
297        budget.charge(40).expect("fits exactly");
298        budget.charge(0).expect("zero is free");
299    }
300
301    #[test]
302    fn test_declared_budget_rejects_cumulative_overrun() {
303        let mut budget = DeclaredCompressedBudget::new(100);
304        budget.charge(60).expect("fits");
305        assert_matches!(budget.charge(41), Err(ArchiveError::InvalidArchive(_)));
306    }
307
308    #[test]
309    fn test_declared_budget_rejects_u64_max() {
310        let mut budget = DeclaredCompressedBudget::new(u64::MAX - 1);
311        assert_matches!(
312            budget.charge(u64::MAX),
313            Err(ArchiveError::InvalidArchive(_))
314        );
315    }
316
317    // H-TEST-3: Division by zero edge cases test
318    #[test]
319    fn test_compressed_size_zero_with_uncompressed_zero() {
320        let config = SecurityConfig::default();
321
322        // Both zero - should be OK (empty file)
323        let result = validate_compression_ratio(Compressed(0), Uncompressed(0), &config);
324        assert!(result.is_ok(), "0/0 should be handled gracefully");
325    }
326
327    #[test]
328    fn test_compressed_size_zero_with_large_uncompressed() {
329        let config = SecurityConfig::default();
330
331        // HIGH-001: Compressed size zero with uncompressed > 0 is INVALID
332        // This prevents zip bomb bypass for stored compression
333        let result = validate_compression_ratio(Compressed(0), Uncompressed(1_000_000), &config);
334        assert_matches!(
335            result,
336            Err(ArchiveError::ZipBomb(details))
337                if details.ratio() == CompressionRatio::Unbounded,
338            "compressed_size == 0 but uncompressed_size > 0 should be rejected (HIGH-001 fix)"
339        );
340    }
341
342    #[test]
343    fn test_very_small_compressed_large_uncompressed() {
344        let config = SecurityConfig::default();
345
346        // Very small compressed size (1 byte) with large uncompressed
347        // This should trigger zip bomb detection
348        let result = validate_compression_ratio(Compressed(1), Uncompressed(1_000_000), &config);
349        assert_matches!(
350            result,
351            Err(ArchiveError::ZipBomb(_)),
352            "extremely high compression ratio should be detected as zip bomb"
353        );
354    }
355
356    #[test]
357    fn test_equal_sizes() {
358        let config = SecurityConfig::default();
359
360        // No compression (ratio = 1.0)
361        let result = validate_compression_ratio(Compressed(1000), Uncompressed(1000), &config);
362        assert!(result.is_ok(), "ratio of 1.0 should be safe");
363    }
364
365    #[test]
366    fn test_negative_compression() {
367        let config = SecurityConfig::default();
368
369        // Compressed larger than uncompressed (poor compression)
370        let result = validate_compression_ratio(Compressed(2000), Uncompressed(1000), &config);
371        assert!(
372            result.is_ok(),
373            "ratio < 1.0 should be safe (negative compression)"
374        );
375    }
376}