exarch-core 0.12.0

Memory-safe archive extraction library with security validation
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! The link walk reads only the targets it was asked for, from admitted
//! blocks, and degrades decode problems into per-link failures.

use super::admit::sevenz_entry_compression;
use super::header::FileIndex;
use super::header::HeaderLimit;
use super::links::LinkOutcome;
use super::links::LinkReadFailure;
use super::links::LinkTable;
use super::links::StoredLinkTarget;
use super::links::walk_sevenz_links;
use std::assert_matches;
use std::io::Cursor;
use std::path::PathBuf;

use sevenz_rust2::ArchiveEntry;
use sevenz_rust2::ArchiveWriter;
use sevenz_rust2::EncoderConfiguration;
use sevenz_rust2::EncoderMethod;
use sevenz_rust2::SourceReader;

use super::*;
use crate::test_utils::flip_first;

const SIGNATURE_LEN: usize = 32;

fn writer(stored: bool) -> ArchiveWriter<Cursor<Vec<u8>>> {
    let mut writer = ArchiveWriter::new(Cursor::new(Vec::new())).unwrap();
    if stored {
        writer.set_content_methods(vec![EncoderConfiguration::new(EncoderMethod::COPY)]);
    }
    writer
}

fn entry(name: &str, data: &[u8]) -> ArchiveEntry {
    let mut entry = ArchiveEntry::new_file(name);
    entry.has_stream = !data.is_empty();
    entry.size = data.len() as u64;
    entry
}

fn solid(files: &[(&str, &[u8])], stored: bool) -> Vec<u8> {
    let mut writer = writer(stored);
    let entries = files.iter().map(|(name, data)| entry(name, data)).collect();
    let readers = files
        .iter()
        .map(|(_, data)| SourceReader::from(Cursor::new(data.to_vec())))
        .collect();
    writer.push_archive_entries(entries, readers).unwrap();
    writer.finish().unwrap().into_inner()
}

fn one_block_each(files: &[(&str, &[u8])]) -> Vec<u8> {
    let mut writer = writer(true);
    for (name, data) in files {
        let reader = (!data.is_empty()).then(|| Cursor::new(data.to_vec()));
        writer
            .push_archive_entry(entry(name, data), reader)
            .unwrap();
    }
    writer.finish().unwrap().into_inner()
}

struct Parsed {
    header: SevenZHeader,
    compression: Vec<EntryCompression>,
}

fn parse(bytes: &[u8]) -> Parsed {
    let header = read_sevenz_header(&mut Cursor::new(bytes), HeaderLimit::UNLIMITED).unwrap();
    let compression = sevenz_entry_compression(&header, bytes.len() as u64).unwrap();
    Parsed {
        header,
        compression,
    }
}

fn config(solid: bool) -> SecurityConfig {
    let solid_archives = if solid {
        crate::SolidArchives::Allow(
            crate::SolidLimits::DEFAULT.with_max_block_memory(crate::non_zero!(100 * 1024 * 1024)),
        )
    } else {
        crate::SolidArchives::Refuse
    };
    SecurityConfig::default().with_solid_archives(solid_archives)
}

fn table(indices: &[usize]) -> LinkTable<()> {
    let mut table = LinkTable::default();
    for &index in indices {
        table.push(FileIndex::at(index), ()).unwrap();
    }
    table
}

fn walk(
    parsed: &Parsed,
    source: Vec<u8>,
    config: &SecurityConfig,
    links: &[usize],
) -> Vec<(usize, LinkOutcome)> {
    let mut seen = Vec::new();
    walk_sevenz_links(
        &parsed.header,
        &mut Cursor::new(source),
        &parsed.compression,
        config,
        &table(links),
        &mut |index, outcome| {
            seen.push((index.get(), outcome));
            Ok(())
        },
    )
    .unwrap();
    seen
}

fn target(path: &str) -> StoredLinkTarget {
    StoredLinkTarget::Read(PathBuf::from(path))
}

#[test]
fn a_link_table_accepts_only_ascending_indices() {
    let mut table = LinkTable::default();
    table.push(FileIndex::at(2), "a").unwrap();
    table.push(FileIndex::at(5), "b").unwrap();

    assert_matches!(
        table.push(FileIndex::at(5), "c"),
        Err(ArchiveError::InvalidArchive(_))
    );
    assert_matches!(
        table.push(FileIndex::at(3), "c"),
        Err(ArchiveError::InvalidArchive(_))
    );
    assert_eq!(table.get(FileIndex::at(5)), Some(&"b"));
    assert_eq!(table.get(FileIndex::at(3)), None);
    assert_eq!(
        table.indices().map(FileIndex::get).collect::<Vec<_>>(),
        [2, 5]
    );
}

#[test]
fn reads_links_of_separate_blocks_in_order() {
    let bytes = one_block_each(&[("a", b"first"), ("x", b"data"), ("b", b"second")]);
    let parsed = parse(&bytes);

    let seen = walk(&parsed, bytes, &config(false), &[0, 2]);

    assert_eq!(seen, [(0, Ok(target("first"))), (2, Ok(target("second")))]);
}

#[test]
fn a_corrupt_checksum_on_a_drained_file_does_not_hide_the_link() {
    let filler = b"FILLERFILLERFILLER";
    let mut bytes = solid(&[("filler", filler), ("link", b"target")], true);
    flip_first(&mut bytes, filler);
    let parsed = parse(&bytes);

    let seen = walk(&parsed, bytes, &config(true), &[1]);

    assert_eq!(seen, [(1, Ok(target("target")))]);
}

#[test]
fn a_decoder_failure_gives_the_remaining_links_a_decode_failure() {
    let filler = vec![b'f'; 1000];
    let bytes = solid(
        &[("one", b"first"), ("filler", &filler), ("two", b"second")],
        true,
    );
    let parsed = parse(&bytes);
    let truncated = bytes[..SIGNATURE_LEN + 100].to_vec();

    let seen = walk(&parsed, truncated, &config(true), &[0, 2]);

    assert_eq!(seen.len(), 2);
    assert_eq!(seen[0], (0, Ok(target("first"))));
    assert_matches!(
        &seen[1],
        (
            2,
            Err(LinkReadFailure::Truncated | LinkReadFailure::Decode(_))
        )
    );
}

#[test]
fn a_checksum_failure_on_a_link_keeps_the_block_aligned() {
    let mut bytes = solid(&[("one", b"FIRSTFIRST"), ("two", b"second")], true);
    flip_first(&mut bytes, b"FIRSTFIRST");
    let parsed = parse(&bytes);

    let seen = walk(&parsed, bytes, &config(true), &[0, 1]);

    assert_eq!(seen[0], (0, Err(LinkReadFailure::Checksum)));
    assert_eq!(seen[1], (1, Ok(target("second"))));
}

#[test]
fn a_refused_block_is_not_decoded() {
    let bytes = solid(&[("a", b"hi"), ("link", b"a")], true);
    let parsed = parse(&bytes);

    let seen = walk(&parsed, Vec::new(), &config(false), &[1]);

    assert_eq!(seen, [(1, Err(LinkReadFailure::BlockRefused))]);
}

#[test]
fn a_block_over_the_ratio_limit_is_not_decoded() {
    let zeros = vec![0u8; 64 * 1024];
    let bytes = solid(&[("zeros", &zeros), ("link", b"a")], false);
    let parsed = parse(&bytes);
    let strict = SecurityConfig::default().with_solid_archives(crate::SolidArchives::Allow(
        crate::SolidLimits::DEFAULT
            .with_max_block_memory(crate::non_zero!(100 * 1024 * 1024))
            .with_max_ratio(crate::ratio_limit!(10.0)),
    ));

    let seen = walk(&parsed, Vec::new(), &strict, &[1]);

    assert_eq!(seen, [(1, Err(LinkReadFailure::BlockRefused))]);
}

#[test]
fn an_oversized_target_is_not_read() {
    let oversized = vec![b'a'; 70_000];
    let bytes = one_block_each(&[("link", &oversized)]);
    let parsed = parse(&bytes);

    let seen = walk(&parsed, Vec::new(), &config(false), &[0]);

    assert_eq!(
        seen,
        [(0, Ok(StoredLinkTarget::Oversized { bytes: 70_000 }))]
    );
}

#[test]
fn a_link_without_data_has_an_empty_target() {
    let bytes = one_block_each(&[("link", b"")]);
    let parsed = parse(&bytes);

    let seen = walk(&parsed, Vec::new(), &config(false), &[0]);

    assert_eq!(seen, [(0, Ok(target("")))]);
}

#[cfg(feature = "encryption")]
#[test]
fn a_link_walk_derives_each_key_once_and_only_for_the_blocks_it_reads() {
    use super::header::open_sevenz_header;
    use crate::Password;
    use crate::encryption::Credentials;
    use sevenz_rust2::encoder_options::AesEncoderOptions;
    use std::sync::Arc;

    let mut archive = ArchiveWriter::new(Cursor::new(Vec::new())).unwrap();
    archive.set_encrypt_header(false);
    for (salt, name, data) in [
        (1u8, "a", &b"first"[..]),
        (1, "b", &b"second"[..]),
        (2, "c", &b"third"[..]),
    ] {
        let mut options = AesEncoderOptions::new(sevenz_rust2::Password::new("pw"));
        options.salt = [salt; 16];
        options.num_cycles_power = 4;
        archive.set_content_methods(vec![
            options.into(),
            EncoderConfiguration::new(EncoderMethod::COPY),
        ]);
        archive
            .push_archive_entry(entry(name, data), Some(Cursor::new(data.to_vec())))
            .unwrap();
    }
    let bytes = archive.finish().unwrap().into_inner();
    let config = SecurityConfig::default();
    let credentials = Credentials::new(Some(Arc::new(Password::new(b"pw".to_vec()).unwrap())));
    let header = open_sevenz_header(
        &mut Cursor::new(&bytes),
        HeaderLimit::from_config(&config),
        &credentials,
    )
    .unwrap();
    let compression = sevenz_entry_compression(&header, bytes.len() as u64).unwrap();
    let derived = || crate::encryption::kdf::DERIVATIONS.with(std::cell::Cell::get);
    let before = derived();

    let mut targets = 0;
    walk_sevenz_links(
        &header,
        &mut Cursor::new(bytes),
        &compression,
        &config,
        &table(&[0, 1]),
        &mut |_, _| {
            targets += 1;
            Ok(())
        },
    )
    .unwrap();

    assert_eq!(targets, 2);
    assert_eq!(
        derived(),
        before + 1,
        "the third block's key is never derived"
    );
}

#[test]
fn an_error_from_the_receiver_ends_the_walk() {
    let bytes = one_block_each(&[("a", b"first"), ("b", b"second")]);
    let parsed = parse(&bytes);
    let mut calls = 0;

    let result = walk_sevenz_links(
        &parsed.header,
        &mut Cursor::new(bytes),
        &parsed.compression,
        &config(false),
        &table(&[0, 1]),
        &mut |_, _| {
            calls += 1;
            Err(ArchiveError::unclassified("stop"))
        },
    );

    assert_matches!(result, Err(ArchiveError::InvalidArchive(_)));
    assert_eq!(calls, 1);
}

#[test]
fn a_target_that_is_not_utf8_is_a_hard_error() {
    let bytes = one_block_each(&[("link", &[0xFF, 0xFE])]);
    let parsed = parse(&bytes);

    let result = walk_sevenz_links(
        &parsed.header,
        &mut Cursor::new(bytes),
        &parsed.compression,
        &config(false),
        &table(&[0]),
        &mut |_, _| Ok(()),
    );

    assert_matches!(result, Err(ArchiveError::InvalidArchive(reason)) if reason.to_string().contains("UTF-8"));
}

mod bytes_read {
    use std::cell::Cell;
    use std::io::Read;
    use std::io::Seek;
    use std::io::SeekFrom;
    use std::rc::Rc;

    use super::*;
    use crate::StoredTargets;
    use crate::inspection::list::ListPass;
    use crate::inspection::list::list_sevenz_reader;

    const FILLER_LEN: usize = 300_000;
    const UNIX_SYMLINK_ATTRIBUTES: u32 = 0x8000 | (0o120_777 << 16);

    struct Counting<R> {
        inner: R,
        read: Rc<Cell<u64>>,
    }

    impl<R: Read> Read for Counting<R> {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = self.inner.read(buf)?;
            self.read.set(self.read.get() + n as u64);
            Ok(n)
        }
    }

    impl<R: Seek> Seek for Counting<R> {
        fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
            self.inner.seek(pos)
        }
    }

    /// A stored solid block of a large file followed by one symlink.
    fn solid_block_with_trailing_link() -> Vec<u8> {
        let filler = vec![b'f'; FILLER_LEN];
        let mut link = entry("link", b"filler");
        link.has_windows_attributes = true;
        link.windows_attributes = UNIX_SYMLINK_ATTRIBUTES;
        let mut writer = writer(true);
        writer
            .push_archive_entries(
                vec![entry("filler", &filler), link],
                vec![
                    SourceReader::from(Cursor::new(filler.clone())),
                    SourceReader::from(Cursor::new(b"filler".to_vec())),
                ],
            )
            .unwrap();
        writer.finish().unwrap().into_inner()
    }

    fn counting(bytes: Vec<u8>) -> (Counting<Cursor<Vec<u8>>>, Rc<Cell<u64>>) {
        let read = Rc::new(Cell::new(0));
        let source = Counting {
            inner: Cursor::new(bytes),
            read: Rc::clone(&read),
        };
        (source, read)
    }

    #[test]
    fn listing_decodes_the_link_block_only_when_asked_to_read_targets() {
        let bytes = solid_block_with_trailing_link();
        let config = config(true);

        let (source, skipped) = counting(bytes.clone());
        list_sevenz_reader(source, &config, &mut ListPass::strict()).unwrap();
        let (source, read) = counting(bytes);
        list_sevenz_reader(
            source,
            &config,
            &mut ListPass::strict_with(StoredTargets::Read),
        )
        .unwrap();

        assert!(skipped.get() < 1_000, "{} bytes read", skipped.get());
        assert!(read.get() >= FILLER_LEN as u64, "{} bytes read", read.get());
    }

    #[cfg(unix)]
    #[test]
    fn extraction_reads_each_pack_stream_once() {
        let bytes = solid_block_with_trailing_link();
        let archive_len = bytes.len() as u64;
        let (source, read) = counting(bytes);
        let config = SecurityConfig::default()
            .with_allow_symlinks(true)
            .with_solid_archives(crate::SolidArchives::Allow(
                crate::SolidLimits::DEFAULT
                    .with_max_block_memory(crate::non_zero!(100 * 1024 * 1024)),
            ));
        let out = tempfile::TempDir::new().unwrap();

        let report = SevenZArchive::new(source, &config)
            .unwrap()
            .extract(
                out.path(),
                &ExtractionOptions::default(),
                &mut crate::NoopProgress,
            )
            .unwrap();

        assert_eq!(report.symlinks_created, 1);
        assert!(
            read.get() < archive_len + archive_len / 4,
            "{} bytes read of {archive_len}",
            read.get()
        );
    }
}