exarch-core 0.8.0

Memory-safe archive extraction library with security validation
Documentation
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
//! Where a TAR or ZIP handler's validated entries go.
//!
//! The handler loops own every per-format gate (metadata budget, entry-type
//! refusal, encrypted entries, declared sizes, extension filter, two-pass
//! hardlinks). Only validation and the final write go through an
//! [`ExtractTarget`], so the host filesystem ([`HostTarget`]) and an
//! `EntrySink` run the same gates.

use std::io::Read;
use std::path::Path;

use crate::ArchiveError;
use crate::ExtractionReport;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::config::Validated;
use crate::copy::CopyBuffer;
use crate::security::admitted::EntrySize;
use crate::security::admitted::ValidatedFile;
use crate::security::admitted::ValidatedHardlink;
use crate::security::fs_view::HostFs;
use crate::security::hardlink::hardlink_target_missing;
use crate::security::quota::EntryCount;
use crate::security::quota::QuotaPermit;
use crate::security::validator::EntryPath;
use crate::security::validator::NodeKind;
use crate::security::validator::ValidatorCore;
use crate::types::DestDir;
use crate::types::SafePath;
use crate::types::SafeSymlink;
use crate::types::safe_symlink::resolve_through_symlinks;

use super::common;
use super::dir_walker::DirWalker;

/// The per-run counters a target updates while it writes.
pub struct Tally<'a> {
    pub(crate) report: &'a mut ExtractionReport,
    pub(crate) options: SinkOptions,
    /// File and symlink entries skipped as pre-existing duplicates.
    pub(crate) duplicate_skips: &'a mut u64,
    pub(crate) progress: &'a mut dyn ProgressCallback,
}

impl Tally<'_> {
    /// Counts one entry skipped as a pre-existing duplicate.
    ///
    /// A target that skips a file at admission returns the token as
    /// [`FileAdmission::Skipped`]; other skip sites count through this method
    /// without one.
    ///
    /// # Errors
    ///
    /// Returns an error when the skipped-files counter would overflow.
    pub(crate) fn record_duplicate_skip(&mut self) -> Result<DuplicateSkipped> {
        common::checked_increment_files_skipped(self.report)?;
        *self.duplicate_skips = self.duplicate_skips.saturating_add(1);
        Ok(DuplicateSkipped(()))
    }
}

/// What [`Tally::record_duplicate_skip`] returns once a duplicate entry is
/// counted as skipped, so a target that skips in `validate_file` has to count
/// it.
#[derive(Debug)]
pub struct DuplicateSkipped(());

/// A file entry as a target is asked to admit it.
#[derive(Debug, Clone, Copy)]
pub struct FileRequest<'p> {
    pub(crate) path: &'p Path,
    pub(crate) size: EntrySize,
    pub(crate) mode: Option<u32>,
}

/// A target's decision on a requested file.
#[derive(Debug)]
pub enum FileAdmission<A> {
    /// The file is admitted and is to be written with `A`.
    Write(A),
    /// The file duplicates an existing path and was skipped.
    Skipped(DuplicateSkipped),
}

/// The validation and write half of an extraction.
pub trait ExtractTarget {
    /// What a target needs to write a file it admitted.
    type AdmittedFile;

    /// Validates a regular file and reserves its size against the quota, or
    /// skips it as a duplicate.
    fn validate_file(
        &mut self,
        request: FileRequest<'_>,
        tally: &mut Tally<'_>,
    ) -> Result<FileAdmission<Self::AdmittedFile>>;

    /// Validates a directory entry.
    fn validate_directory(&mut self, path: &Path, size: EntrySize) -> Result<SafePath>;

    /// Validates a symlink entry and its target.
    fn validate_symlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
    ) -> Result<SafeSymlink>;

    /// Validates a hardlink entry for the second pass.
    fn validate_hardlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
    ) -> Result<ValidatedHardlink>;

    /// Creates a validated directory.
    fn directory(&mut self, path: &SafePath, tally: &mut Tally<'_>) -> Result<()>;

    /// Streams an admitted file from `reader`, enforcing the declared `size`.
    fn file<R: Read>(
        &mut self,
        reader: &mut R,
        admitted: Self::AdmittedFile,
        size: u64,
        tally: &mut Tally<'_>,
    ) -> Result<()>;

    /// Creates a validated symlink.
    fn symlink(&mut self, symlink: &SafeSymlink, tally: &mut Tally<'_>) -> Result<()>;

    /// Materializes a hardlink in the second pass, once every target exists.
    fn hardlink(
        &mut self,
        link: &SafePath,
        target: &SafePath,
        counted: EntryCount,
        tally: &mut Tally<'_>,
        hardlink_duplicate_skips: &mut u64,
    ) -> Result<()>;
}

/// Extraction onto the real filesystem.
pub struct HostTarget<'a> {
    dest: DestDir,
    dirs: DirWalker,
    copy_buffer: CopyBuffer,
    core: ValidatorCore<'a>,
}

impl<'a> HostTarget<'a> {
    /// Creates `output_dir` if needed and a target writing into it.
    pub(crate) fn create(output_dir: &Path, config: &'a SecurityConfig<Validated>) -> Result<Self> {
        Ok(Self {
            dest: DestDir::new_or_create(output_dir.to_path_buf())?,
            dirs: DirWalker::new(config),
            copy_buffer: CopyBuffer::new(),
            core: ValidatorCore::new(config),
        })
    }

    pub(super) const fn dest(&self) -> &DestDir {
        &self.dest
    }

    pub(super) fn copy_buffer_mut(&mut self) -> &mut CopyBuffer {
        &mut self.copy_buffer
    }

    pub(super) const fn dirs(&self) -> DirWalker {
        self.dirs
    }

    /// Validates only the path of an entry, leaving quota to the caller.
    pub(super) fn validate_path(&self, path: &Path, kind: NodeKind) -> Result<EntryPath<SafePath>> {
        let ctx = self.core.context::<HostFs>();
        self.core
            .validate_entry_path_in(path, kind, &self.dest, &HostFs, &ctx)
    }

    /// Reserves `size` bytes of quota for a file.
    pub(super) fn reserve_file(&mut self, size: u64) -> Result<QuotaPermit> {
        self.core.reserve_file(size)
    }
}

impl ExtractTarget for HostTarget<'_> {
    type AdmittedFile = ValidatedFile;

    fn validate_file(
        &mut self,
        request: FileRequest<'_>,
        _tally: &mut Tally<'_>,
    ) -> Result<FileAdmission<ValidatedFile>> {
        let ctx = self.core.context::<HostFs>();
        self.core
            .validate_file_in(
                request.path,
                request.size,
                request.mode,
                &self.dest,
                &HostFs,
                &ctx,
            )
            .map(FileAdmission::Write)
    }

    fn validate_directory(&mut self, path: &Path, size: EntrySize) -> Result<SafePath> {
        let ctx = self.core.context::<HostFs>();
        self.core
            .validate_directory_in(path, size, &self.dest, &HostFs, &ctx)
    }

    fn validate_symlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
    ) -> Result<SafeSymlink> {
        let ctx = self.core.context::<HostFs>();
        self.core
            .validate_symlink_in(path, target, size, &self.dest, &HostFs, &ctx)
            .map(|validated| validated.symlink)
    }

    fn validate_hardlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
    ) -> Result<ValidatedHardlink> {
        let ctx = self.core.context::<HostFs>();
        self.core
            .validate_hardlink_in(path, target, size, &self.dest, &HostFs, &ctx)
    }

    fn directory(&mut self, path: &SafePath, tally: &mut Tally<'_>) -> Result<()> {
        common::create_directory(path, &self.dest, tally.report, self.dirs)
    }

    fn file<R: Read>(
        &mut self,
        reader: &mut R,
        admitted: ValidatedFile,
        size: u64,
        tally: &mut Tally<'_>,
    ) -> Result<()> {
        common::extract_file_with_permit(
            reader,
            &admitted.path,
            admitted.mode,
            admitted.permit,
            &self.dest,
            tally.report,
            Some(size),
            &mut self.copy_buffer,
            self.dirs,
            tally.options,
            tally.duplicate_skips,
            tally.progress,
        )
    }

    fn symlink(&mut self, symlink: &SafeSymlink, tally: &mut Tally<'_>) -> Result<()> {
        common::create_symlink(
            symlink,
            &self.dest,
            tally.report,
            self.dirs,
            tally.options,
            tally.duplicate_skips,
        )
    }

    /// Creates a hardlink in the second pass by copying content.
    ///
    /// Uses a content copy instead of `fs::hard_link` to avoid shared-inode
    /// corruption: a real OS hardlink would allow a subsequent write to
    /// `link_path` to silently overwrite `target_path` (GHSA-2367-c296-3mp2
    /// variant, issue #130).
    ///
    /// # Security - Symlink-at-Destination Rejection (issue #467)
    ///
    /// `Path::exists()` returns `false` for a dangling symlink, so a
    /// pre-planted symlink at `link_path` used to bypass the old
    /// existence-based duplicate check, and the subsequent `fs::copy`
    /// followed it, writing archive content outside the extraction root.
    /// The destination is now opened via `common::create_file_with_mode`
    /// (mode `None`, since permissions are copied from the target's bytes
    /// afterward, not set at creation) with `create_new = true`, which
    /// atomically fails with `ErrorKind::AlreadyExists` for any pre-existing
    /// path at `link_path` — symlink (dangling or not), regular file, or
    /// directory — folding the duplicate check into the `open()` call
    /// itself instead of a separate, bypassable `exists()` probe. This
    /// reuses the same `O_EXCL`+`O_NOFOLLOW` (Unix) discipline as the
    /// normal-file write path (issue #459) for consistency, though
    /// `create_new`'s `O_EXCL` alone already refuses any pre-existing path.
    ///
    /// # Security - Target Read TOCTOU and Quota TOCTOU (issue #467)
    ///
    /// Hardlinks are validated in two passes: `validate` (via
    /// `HardlinkTracker::validate_hardlink_in`) resolves `target` through
    /// any on-disk symlinks and checks containment in pass one, but this
    /// function — pass two — runs later, after every entry in the archive has
    /// been validated and every non-hardlink entry extracted. Nothing
    /// re-validates `target_path` in between. A plain path-based `File::open`
    /// (or `std::fs::metadata`, as this function used to do to size the quota
    /// reservation) would silently follow whatever is at `target_path` by the
    /// time pass two runs — which, given an attacker-writable destination
    /// directory, may not be what pass one validated at all (the target
    /// swapped for a symlink escaping `dest` in between the two passes).
    /// Separately, sizing the quota reservation from a path-based `stat` and
    /// then copying from a *different*, separately-opened handle left its own
    /// TOCTOU window: swapping `target_path` between the two operations could
    /// charge the quota for N bytes while actually copying an unbounded
    /// amount.
    ///
    /// Both are narrowed the same way: [`common::open_no_follow`] opens
    /// `target_path` once, refusing to follow a symlink (Unix, via
    /// `O_NOFOLLOW`) rather than a separate `stat`-then-`open`; the quota
    /// reservation is sized from that same open handle's `fstat`, and the
    /// copy reads from that same handle — never re-touching the path
    /// afterward. A symlink at `target_path` is not automatically rejected,
    /// though: it is a legitimate, common archive shape for a hardlink's
    /// target to itself be a symlink created earlier in the *same*
    /// extraction (already pass-one-validated). On `ErrorKind::FilesystemLoop`
    /// from `open_no_follow`, [`resolve_through_symlinks`] re-runs the exact
    /// containment check pass one already trusts, against the *current*
    /// on-disk state; if it still resolves inside `dest`, the resolved
    /// (symlink-free, since `canonicalize` dereferences fully) path is opened
    /// instead. This narrows the TOCTOU window from "the entire gap between
    /// pass one and pass two" down to "between this re-check and the open" —
    /// consistent with the check-then-act discipline the rest of the pipeline
    /// already accepts elsewhere (e.g. `DirWalker`'s documented TOCTOU). If the
    /// re-resolution instead lands outside `dest`, that is a genuine escape
    /// attempt and is reported as such, not as a raw OS errno.
    fn hardlink(
        &mut self,
        link: &SafePath,
        target: &SafePath,
        counted: EntryCount,
        tally: &mut Tally<'_>,
        hardlink_duplicate_skips: &mut u64,
    ) -> Result<()> {
        let link_path = self.dest.join(link);
        let target_path = self.dest.join(target);

        if !target_path.exists() {
            return Err(hardlink_target_missing(target.as_path()));
        }

        self.dirs.ensure_parent(&self.dest, link.as_path())?;

        let link_file = match common::create_file_with_mode(&link_path, None, true) {
            Ok(file) => file,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                if tally.options.skip_duplicates {
                    common::checked_increment_files_skipped(tally.report)?;
                    *hardlink_duplicate_skips = hardlink_duplicate_skips.saturating_add(1);
                    return Ok(());
                }
                return Err(ArchiveError::InvalidArchive(format!(
                    "duplicate entry: {}",
                    link.as_path().display()
                )));
            }
            Err(e) => return Err(ArchiveError::Io(e)),
        };
        let cleanup_guard = common::TempFileGuard::new(link_path);

        // Opened once, refusing to follow a symlink at `target_path`; the
        // quota reservation below and the copy further down both operate on
        // this same handle instead of re-touching the path (issue #467).
        let target_file = match common::open_no_follow(&target_path) {
            Ok(file) => file,
            Err(e) if common::is_filesystem_loop_error(&e) => {
                // `target_path`'s final component is a symlink. Re-run pass
                // one's own containment check against the current on-disk
                // state; a symlink created by an earlier entry in this same
                // extraction resolves safely inside `dest` and is opened at
                // its resolved (symlink-free) location, while a genuine
                // escape attempt is rejected as HardlinkEscape rather than
                // surfacing as a raw ELOOP.
                let resolved = resolve_through_symlinks(
                    self.dest.as_path(),
                    target.as_path(),
                    &self.dest,
                    link.as_path(),
                )
                .map_err(|_| ArchiveError::HardlinkEscape {
                    path: link.as_path().to_path_buf(),
                })?;
                common::open_no_follow(&resolved)?
            }
            Err(e) => return Err(ArchiveError::Io(e)),
        };

        // Every hardlink copies the target's real bytes to a new inode, so it
        // must be charged against the same quota tracker as regular files
        // (issue #426): otherwise N hardlinks to one small file extract N
        // full copies with no size enforcement. The entry itself was counted
        // in pass one (`counted`), so a skipped duplicate keeps its count
        // slot but is charged no bytes, and the pending list is bounded by
        // `max_file_count` before anything is copied. The permit is consumed
        // by value below, so this charge cannot be spent twice.
        let target_size = target_file.metadata()?.len();
        let permit = self.core.charge_hardlink(counted, target_size)?;

        // Copy content between the two handles opened above. Any subsequent
        // write to `link_path` cannot corrupt `target_path` because they are
        // separate files.
        let bytes_copied = common::copy_file_content_with_permit(target_file, link_file, permit)?;
        cleanup_guard.persist();

        tally.report.files_extracted = common::checked_add_count(tally.report.files_extracted, 1)?;
        tally.report.bytes_written =
            common::checked_add_bytes(tally.report.bytes_written, bytes_copied)?;
        tally.progress.on_bytes_written(bytes_copied);

        Ok(())
    }
}