Skip to main content

onelf_format/
reader.rs

1//! Bounds checking for the regions a package footer describes.
2//!
3//! A packed file is untrusted input: the runtime parses one on an end user's
4//! machine, and the packer's inspection commands parse whatever they are
5//! handed. Every offset and size in the footer, and in the blocks the
6//! manifest carries, is an attacker-controlled `u64`.
7//!
8//! These checks used to live only in the runtime, so `onelf info` on a
9//! truncated download tried to allocate whatever the footer claimed and
10//! aborted. Both sides now validate here, before allocating or seeking.
11
12use std::io;
13
14use crate::entry::Block;
15use crate::footer::Footer;
16
17fn invalid(msg: &'static str) -> io::Error {
18    io::Error::new(io::ErrorKind::InvalidData, msg)
19}
20
21/// True when `off + len` stays within `file_size` without overflowing.
22fn in_bounds(off: u64, len: u64, file_size: u64) -> bool {
23    off.checked_add(len).is_some_and(|end| end <= file_size)
24}
25
26/// Check every region `footer` points at against the real file size.
27///
28/// Callers MUST run this before acting on any footer field. It is what makes
29/// a later `vec![0; size]` safe to perform.
30pub fn validate_footer(footer: &Footer, file_size: u64) -> io::Result<()> {
31    if !in_bounds(
32        footer.manifest_offset,
33        footer.manifest_compressed,
34        file_size,
35    ) {
36        return Err(invalid("manifest region out of bounds"));
37    }
38    if !in_bounds(footer.payload_offset, footer.payload_size, file_size) {
39        return Err(invalid("payload region out of bounds"));
40    }
41    // The manifest decompresses into a buffer sized by this field, so it has
42    // to be backed by something even though it describes no file region.
43    if footer.manifest_original > file_size.saturating_mul(MAX_MANIFEST_EXPANSION) {
44        return Err(invalid("manifest expands implausibly"));
45    }
46    if footer.dict_size > 0 && !in_bounds(footer.dict_offset, footer.dict_size as u64, file_size) {
47        return Err(invalid("dictionary region out of bounds"));
48    }
49    Ok(())
50}
51
52/// Ceiling on how far the manifest may claim to decompress, relative to the
53/// whole file. Compressed manifests are small and text-like; anything beyond
54/// this is a crafted header rather than a real package.
55const MAX_MANIFEST_EXPANSION: u64 = 1024;
56
57/// Absolute file offset of `block`'s compressed bytes, checked against the
58/// payload region `footer` declares.
59///
60/// Returns the offset and the compressed length, so the caller can allocate
61/// knowing the file can back it.
62pub fn block_extent(footer: &Footer, block: &Block) -> io::Result<(u64, usize)> {
63    let abs = footer
64        .payload_offset
65        .checked_add(block.payload_offset)
66        .ok_or_else(|| invalid("payload offset overflow"))?;
67    let payload_end = footer
68        .payload_offset
69        .checked_add(footer.payload_size)
70        .ok_or_else(|| invalid("payload region overflow"))?;
71    if !in_bounds(abs, block.compressed_size, payload_end) {
72        return Err(invalid("block extends past the payload region"));
73    }
74    let len = usize::try_from(block.compressed_size)
75        .map_err(|_| invalid("block larger than this address space"))?;
76    Ok((abs, len))
77}
78
79/// Decompressed size of `block`, rejected when it exceeds any plausible
80/// block size.
81///
82/// Both zstd and the dictionary path size their output buffer from this, so
83/// an unchecked value is an allocation an attacker chooses. The bound is
84/// deliberately absolute rather than a compression ratio: real content
85/// reaches extreme ratios, a run of zeroes compressing by four orders of
86/// magnitude, and a ratio test rejects those legitimate packages.
87pub fn block_original_size(block: &Block) -> io::Result<usize> {
88    if block.original_size > MAX_BLOCK_ORIGINAL {
89        return Err(invalid("block decompresses to an implausible size"));
90    }
91    usize::try_from(block.original_size)
92        .map_err(|_| invalid("block larger than this address space"))
93}
94
95/// Ceiling on one block's decompressed size. The packer emits 256 KiB
96/// blocks, so this sits three orders of magnitude above anything real; it
97/// exists only to bound the allocation. zstd then rejects any block whose
98/// actual output does not match what the header claimed.
99const MAX_BLOCK_ORIGINAL: u64 = 256 * 1024 * 1024;
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::footer::Flags;
105
106    fn footer() -> Footer {
107        Footer {
108            format_version: 1,
109            flags: Flags::empty(),
110            manifest_offset: 100,
111            manifest_compressed: 50,
112            manifest_original: 200,
113            payload_offset: 200,
114            payload_size: 300,
115            dict_offset: 0,
116            dict_size: 0,
117            manifest_checksum: [0; 4],
118        }
119    }
120
121    fn block(offset: u64, compressed: u64, original: u64) -> Block {
122        Block {
123            payload_offset: offset,
124            compressed_size: compressed,
125            original_size: original,
126            content_hash: [0u8; 32],
127        }
128    }
129
130    #[test]
131    fn well_formed_footer_passes() {
132        assert!(validate_footer(&footer(), 1000).is_ok());
133    }
134
135    #[test]
136    fn regions_past_the_file_are_rejected() {
137        let mut f = footer();
138        f.manifest_compressed = u64::MAX;
139        assert!(validate_footer(&f, 1000).is_err());
140
141        let mut f = footer();
142        f.payload_size = 10_000;
143        assert!(validate_footer(&f, 1000).is_err());
144
145        let mut f = footer();
146        f.dict_size = 900;
147        f.dict_offset = 500;
148        assert!(validate_footer(&f, 1000).is_err());
149    }
150
151    #[test]
152    fn overflowing_offsets_are_rejected() {
153        let mut f = footer();
154        f.manifest_offset = u64::MAX;
155        f.manifest_compressed = 1;
156        assert!(validate_footer(&f, 1000).is_err());
157    }
158
159    #[test]
160    fn absurd_manifest_expansion_is_rejected() {
161        let mut f = footer();
162        f.manifest_original = u64::MAX;
163        assert!(validate_footer(&f, 1000).is_err());
164    }
165
166    #[test]
167    fn block_within_payload_resolves() {
168        let f = footer();
169        let (abs, len) = block_extent(&f, &block(10, 20, 40)).unwrap();
170        assert_eq!((abs, len), (210, 20));
171    }
172
173    #[test]
174    fn block_past_the_payload_is_rejected() {
175        let f = footer();
176        assert!(block_extent(&f, &block(290, 20, 40)).is_err());
177        assert!(block_extent(&f, &block(u64::MAX, 1, 1)).is_err());
178        assert!(block_extent(&f, &block(0, u64::MAX, 1)).is_err());
179    }
180
181    #[test]
182    fn absurd_block_size_is_rejected() {
183        assert!(block_original_size(&block(0, 10, 40)).is_ok());
184        assert!(block_original_size(&block(0, 1, u64::MAX)).is_err());
185        // A stored block reports equal sizes and must stay acceptable.
186        assert!(block_original_size(&block(0, 4096, 4096)).is_ok());
187    }
188
189    /// Real content reaches extreme compression ratios: a 256 KiB run of
190    /// zeroes lands near 30 bytes, roughly 9000:1. A ratio-based bound
191    /// rejected exactly such a package, so the shape is pinned here.
192    #[test]
193    fn extreme_but_real_compression_ratios_are_accepted() {
194        let compressed = 30u64;
195        let original = 256 * 1024u64;
196        assert!(original / compressed > 4096, "fixture must be extreme");
197        assert!(block_original_size(&block(0, compressed, original)).is_ok());
198    }
199}