exarch-core 0.11.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
//! The one 7z extraction loop, shared by every destination.
//!
//! A destination is an [`ExtractTarget`] that also answers the pre-pass: the
//! checks that can refuse an archive from its file table alone, before the
//! target sees an entry. Admission, the pre-pass, the empty-archive
//! short-circuit and the decode loop are the same for the host filesystem and
//! for an entry sink; only the [`SevenZTarget`] hooks differ.

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::path::Path;
use std::path::PathBuf;

use super::SevenZArchive;
use super::StoredLinkTarget;
use super::classify::SevenZClass;
use super::classify::SevenZKind;
use super::classify::abort_with;
use super::classify::reparse_point_refusal;
use super::decode::DecodeFailure;
use super::decode::decode_archive_entries;
use super::header::BlockIndex;
use super::iter_sevenz_refusals;
use super::links::read_sevenz_link_target;
use super::lzma2::DecodeKnobs;
use super::push_anti_item_warning;
use crate::ArchiveError;
use crate::EntryPosition;
use crate::EntryTotal;
use crate::ExtractionReport;
use crate::ProgressCallback;
use crate::RepeatedPaths;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::formats::common;
use crate::formats::common::EntryCompleteGuard;
use crate::formats::occupant::repeated_path_between;
use crate::formats::occupant::shape_type;
use crate::formats::source_fault::ReadFamily;
use crate::formats::source_fault::ReadFaults;
use crate::formats::source_fault::SourceRead;
use crate::formats::source_fault::SourceTap;
use crate::formats::target::Admission;
use crate::formats::target::ExtractTarget;
use crate::formats::target::FileRequest;
use crate::formats::target::Tally;
use crate::security::Uncompressed;
use crate::security::admitted::EntrySize;
use crate::security::validator::EntryPath;
use crate::security::validator::Gated;
use crate::security::zipbomb::validate_entry_compression;
use crate::selection::EntryShape;
use crate::types::SafePath;
use crate::types::safe_symlink::require_symlinks_allowed;

/// A 7z archive that passed [`SevenZArchive::admit`] under `config`: solid
/// policy, decoder memory, coders and block layout.
///
/// Extraction goes through [`Self::extract_with`], which builds the target
/// from the admission's `config`, so the pre-pass, the decode and the target
/// use the one configuration. The token owns the archive borrow, so it cannot
/// be redeemed against another archive.
pub(crate) struct AdmittedSevenZ<'a, R: Read + Seek> {
    archive: &'a mut SevenZArchive<R>,
    config: &'a SecurityConfig,
}

impl<'a, R: Read + Seek> AdmittedSevenZ<'a, R> {
    /// Extracts into the target `make_target` builds from the admission's
    /// config.
    ///
    /// # Errors
    ///
    /// Returns the target's construction error, or the first extraction
    /// refusal.
    pub(crate) fn extract_with<T: SevenZTarget>(
        self,
        make_target: impl FnOnce(&'a SecurityConfig) -> Result<T>,
        options: SinkOptions,
        progress: &mut dyn ProgressCallback,
    ) -> Result<ExtractionReport> {
        let mut target = make_target(self.config)?;
        self.archive
            .extract_admitted(self.config, &mut target, options, progress)
    }
}

/// What the pre-pass does with a file entry once its destination is known.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FilePlan {
    /// Reserve the file's quota.
    Reserve,
    /// Extraction will skip the entry as a duplicate, so it reserves nothing.
    Skip,
}

/// The destination-specific half of the pre-pass.
///
/// Each method is one place where the host filesystem and an entry sink
/// differ; the order of the checks around them is fixed by
/// [`SevenZArchive::run_pre_pass`].
pub(crate) trait PrePass {
    /// Validates an entry's path against the destination as it is now and
    /// applies the selection: the entry is skipped, or admitted at its
    /// landing.
    fn validate_path(
        &mut self,
        path: &Path,
        shape: EntryShape,
    ) -> Result<Gated<EntryPath<SafePath>>>;

    /// Checks a directory entry at its landing.
    fn directory(&mut self, landing: &SafePath) -> Result<()>;

    /// Checks a symlink entry, at its landing, whose target is still
    /// undecoded.
    fn symlink(&mut self, link: &SafePath, file: &sevenz_rust2::ArchiveEntry) -> Result<()>;

    /// Checks a file entry against what already occupies its destination.
    fn file(&mut self, safe_path: &SafePath) -> Result<FilePlan>;

    /// Charges an entry the extraction will skip to `max_file_count`.
    fn charge_skipped(&mut self) -> Result<()>;

    /// Reserves quota for a symlink.
    fn reserve_symlink(&mut self, size: u64) -> Result<()>;

    /// Reserves quota for a file.
    fn reserve_file(&mut self, size: u64) -> Result<()>;
}

/// The landings the entries of one archive claim, kept only while repeated
/// paths are refused so the pre-pass can refuse a repeat before any write.
struct RepeatClaims(Option<HashMap<PathBuf, EntryShape>>);

impl RepeatClaims {
    fn of(policy: RepeatedPaths) -> Self {
        Self((policy == RepeatedPaths::Refuse).then(HashMap::new))
    }

    /// Records the landing `rel` of an entry of kind `shape`.
    ///
    /// # Errors
    ///
    /// [`crate::Violation::RepeatedPath`] when an earlier entry claimed `rel`,
    /// except for a directory entry over a directory entry.
    fn claim(&mut self, rel: &Path, shape: EntryShape) -> Result<()> {
        let Some(claimed) = &mut self.0 else {
            return Ok(());
        };
        match claimed.entry(rel.to_path_buf()) {
            Entry::Vacant(slot) => {
                slot.insert(shape);
                Ok(())
            }
            Entry::Occupied(first)
                if shape == EntryShape::Directory && *first.get() == EntryShape::Directory =>
            {
                Ok(())
            }
            Entry::Occupied(first) => Err(repeated_path_between(
                rel,
                shape_type(*first.get()),
                shape_type(shape),
            )),
        }
    }
}

/// A destination the shared 7z loop can extract into.
pub(crate) trait SevenZTarget: ExtractTarget {
    /// Runs `run` against a fresh pre-pass over this destination.
    ///
    /// The pre-pass keeps its own quota, so the extraction that follows does
    /// not count an entry twice.
    fn with_pre_pass(
        &self,
        config: &SecurityConfig,
        options: SinkOptions,
        run: &mut dyn FnMut(&mut dyn PrePass) -> Result<()>,
    ) -> Result<()>;
}

impl<R: Read + Seek> SevenZArchive<R> {
    /// Admits the archive under `config`, or returns the first refusal.
    ///
    /// # Errors
    ///
    /// Returns the first admission refusal.
    pub(crate) fn admit<'a>(
        &'a mut self,
        config: &'a SecurityConfig,
    ) -> Result<AdmittedSevenZ<'a, R>> {
        if let Some(refusal) = iter_sevenz_refusals(&self.header, config).next() {
            return Err(refusal.into_error());
        }
        Ok(AdmittedSevenZ {
            archive: self,
            config,
        })
    }

    /// Extracts into `target`.
    ///
    /// Everything that can be refused from the file table alone (ratios,
    /// quotas, link policy, paths) is refused before the target sees an entry.
    fn extract_admitted<T: SevenZTarget>(
        &mut self,
        config: &SecurityConfig,
        target: &mut T,
        options: SinkOptions,
        progress: &mut dyn ProgressCallback,
    ) -> Result<ExtractionReport> {
        let options = options.under(config);
        target.with_pre_pass(config, options, &mut |pre| self.run_pre_pass(config, pre))?;

        let total = self
            .entries
            .iter()
            .filter(|entry| matches!(entry.class, SevenZClass::Present(_)))
            .count();
        let anti_items = self.anti_item_count();
        if total == 0 {
            let mut report = ExtractionReport::new();
            push_anti_item_warning(&mut report, anti_items);
            target.finish_scan()?;
            return Ok(report);
        }

        let report = self.decode_into(target, config, options, progress, total, anti_items)?;
        progress.on_complete();
        Ok(report)
    }

    /// The checks that need only the file table, in the order every
    /// destination applies them.
    fn run_pre_pass(&self, config: &SecurityConfig, pre: &mut dyn PrePass) -> Result<()> {
        let mut claims = RepeatClaims::of(config.repeated_paths);
        for (index, entry) in self.header.file_indices().zip(&self.entries) {
            let Some(kind) = entry.class.present(&entry.name)? else {
                continue;
            };
            let path = PathBuf::from(common::normalize_entry_name(&entry.name));
            let safe_path = match pre.validate_path(&path, kind.shape())? {
                Gated::Skip(_) | Gated::Admit(EntryPath::Root(_)) => continue,
                Gated::Admit(EntryPath::Child(safe_path)) => safe_path,
            };
            match kind {
                SevenZKind::Directory => pre.directory(&safe_path)?,
                SevenZKind::ReparsePoint => return Err(reparse_point_refusal(&entry.name)),
                SevenZKind::UnixSymlink => {
                    validate_entry_compression(
                        &entry.compression,
                        Uncompressed(entry.size),
                        config,
                    )?;
                    require_symlinks_allowed(config)?;
                    pre.symlink(&safe_path, self.header.file(index))?;
                    pre.reserve_symlink(entry.size)?;
                }
                SevenZKind::File => {
                    // The ratio is a property of the archive, not of the
                    // destination, so it is checked before the duplicate skip,
                    // matching what `verify` reports.
                    validate_entry_compression(
                        &entry.compression,
                        Uncompressed(entry.size),
                        config,
                    )?;
                    if !common::is_extension_allowed(safe_path.as_path(), config) {
                        pre.charge_skipped()?;
                        continue;
                    }
                    match pre.file(&safe_path)? {
                        FilePlan::Reserve => pre.reserve_file(entry.size)?,
                        FilePlan::Skip => pre.charge_skipped()?,
                    }
                }
            }
            // After the gates above, so a repeat is refused only once its
            // copy would have been admitted.
            claims.claim(safe_path.as_path(), kind.shape())?;
        }
        Ok(())
    }

    fn decode_into<T: SevenZTarget>(
        &mut self,
        target: &mut T,
        config: &SecurityConfig,
        options: SinkOptions,
        progress: &mut dyn ProgressCallback,
        total: usize,
        anti_items: u64,
    ) -> Result<ExtractionReport> {
        let mut report = ExtractionReport::new();
        let mut pending_error: Option<ArchiveError> = None;
        let mut index = 0_usize;
        let is_solid = self.header.is_solid();
        let tap = SourceTap::default();
        let plain = ReadFaults::new(ReadFamily::SevenZ, Some(&tap));
        let sealed = plain.decrypting(crate::EncryptionRefusal::WrongPasswordOrCorrupt);
        let header = &self.header;
        let faults_of = |block: Option<BlockIndex>| {
            if block.is_some_and(|block| header.is_block_encrypted(block)) {
                sealed
            } else {
                plain
            }
        };
        let mut file_position = 0_usize;

        let mut each = |entry: &sevenz_rust2::ArchiveEntry,
                        reader: &mut dyn Read|
         -> std::result::Result<bool, sevenz_rust2::Error> {
            let faults = faults_of(header.file_block(file_position));
            file_position = file_position.saturating_add(1);
            let kind = match SevenZClass::of(entry).present(&entry.name) {
                Ok(Some(kind)) => kind,
                Ok(None) => return Ok(true),
                Err(refusal) => return Err(abort_with(&mut pending_error, refusal)),
            };
            let path = PathBuf::from(common::normalize_entry_name(&entry.name));
            let position = EntryPosition::at_index(index, EntryTotal::Known(total));
            index = index.saturating_add(1);
            let mut guard = EntryCompleteGuard::try_start(&mut *progress, &path, position)
                .map_err(|error| abort_with(&mut pending_error, error))?;

            let outcome = {
                let mut tally = Tally {
                    report: &mut report,
                    options,
                    progress: guard.progress_mut(),
                };
                process_entry(target, entry, kind, &mut *reader, faults, &path, &mut tally)
            };
            // Entries of a solid block share one decoder stream: bytes a
            // skipped entry left unread would be served to the next entry.
            let outcome = outcome.and_then(|()| {
                if is_solid {
                    io::copy(&mut (&mut *reader).take(entry.size), &mut io::sink())
                        .map(drop)
                        .map_err(|error| faults.classify_read(error))
                } else {
                    Ok(())
                }
            });
            match outcome {
                Ok(()) => {
                    guard.complete();
                    Ok(true)
                }
                Err(error) => Err(abort_with(&mut pending_error, error)),
            }
        };

        let mut source = SourceRead::new(&mut self.source, tap.clone());
        let result = decode_archive_entries(
            &mut source,
            header,
            config.parallel_decode,
            DecodeKnobs::production(),
            &mut each,
        );
        push_anti_item_warning(&mut report, anti_items);
        match result {
            Ok(()) => match target.finish_scan() {
                Ok(()) => Ok(report),
                Err(error) => Err(ArchiveError::partial_or(report, error)),
            },
            Err(failure) => {
                let (block, error) = match failure {
                    DecodeFailure::Block { block, error } => (Some(block), error),
                    DecodeFailure::Handover(error) => (None, error),
                };
                Err(ArchiveError::partial_or(
                    report,
                    pending_error
                        .take()
                        .unwrap_or_else(|| outside_callback(error, faults_of(block))),
                ))
            }
        }
    }
}

/// The error `sevenz-rust2` raised outside the per-entry callback, such as
/// while draining an entry nobody asked for: a read error is a decoder verdict
/// unless the source faulted.
fn outside_callback(error: sevenz_rust2::Error, faults: ReadFaults<'_>) -> ArchiveError {
    match error {
        sevenz_rust2::Error::Io(io_error, _) => faults.classify_read(io_error),
        other => ArchiveError::from(other),
    }
}

pub(super) fn process_entry<T: ExtractTarget>(
    target: &mut T,
    entry: &sevenz_rust2::ArchiveEntry,
    kind: SevenZKind,
    reader: &mut dyn Read,
    faults: ReadFaults<'_>,
    path: &Path,
    tally: &mut Tally<'_>,
) -> Result<()> {
    let size = EntrySize::new(Uncompressed(entry.size), None);
    match kind {
        SevenZKind::ReparsePoint => Err(reparse_point_refusal(&entry.name)),
        SevenZKind::UnixSymlink => {
            let link_target = match read_sevenz_link_target(reader, entry.size)? {
                Ok(StoredLinkTarget::Read(link_target)) => link_target,
                Ok(StoredLinkTarget::Oversized { bytes }) => {
                    return Err(common::symlink_target_too_large(bytes));
                }
                Err(failure) => return Err(failure.into_extract_error(&entry.name)),
            };
            match target.validate_symlink(path, &link_target, size, tally)? {
                Admission::Admit(symlink) => target.symlink(&symlink, tally),
                Admission::Skipped(_) => Ok(()),
            }
        }
        SevenZKind::Directory => match target.validate_directory(path, size, tally)? {
            Admission::Admit(safe_path) => target.directory(&safe_path, tally),
            Admission::Skipped(_) => Ok(()),
        },
        SevenZKind::File => {
            let request = FileRequest {
                path,
                size,
                mode: None,
            };
            if let Admission::Admit(admitted) = target.validate_file(request, tally)? {
                let mut reader = reader;
                target.file(&mut reader, faults, admitted, tally)?;
            }
            Ok(())
        }
    }
}