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
//! 7z extraction onto the host filesystem.
//!
//! [`SevenZHostTarget`] is a [`HostTarget`] that writes a file over an
//! existing regular file through a temp file and a rename, so a decode failure
//! cannot leave a truncated file where the original stood.

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

use super::extract::FilePlan;
use super::extract::PrePass;
use super::extract::SevenZTarget;
use super::write::FileWrite;
use super::write::lstat_dest;
use super::write::refuse_undecoded_target_in;
use super::write::write_file_direct;
use super::write::write_file_with_permit;
use crate::OccupiedBy;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::formats::common;
use crate::formats::dir_walker::DirWalker;
use crate::formats::occupant::KeptOccupant;
use crate::formats::occupant::OccupantAction;
use crate::formats::occupant::OccupantPolicy;
use crate::formats::occupant::OccupiedSite;
use crate::formats::occupant::ReplacePermit;
use crate::formats::occupant::replaces_symlink;
use crate::formats::output_root::OutputRoot;
use crate::formats::pinned_dir::Leaf;
use crate::formats::pinned_dir::PinnedRoot;
use crate::formats::pinned_dir::VettedDir;
use crate::formats::run_record::Maker;
use crate::formats::source_fault::ReadFaults;
use crate::formats::target::Admission;
use crate::formats::target::ExtractTarget;
use crate::formats::target::FileRequest;
use crate::formats::target::HostParent;
use crate::formats::target::HostTarget;
use crate::formats::target::Tally;
use crate::security::admitted::EntrySize;
use crate::security::admitted::ValidatedFile;
use crate::security::admitted::ValidatedHardlink;
use crate::security::context::ValidationContext;
use crate::security::fs_view::HostFs;
use crate::security::fs_view::Occupant;
use crate::security::hardlink::HardlinkTarget;
use crate::security::validator::EntryPath;
use crate::security::validator::Gated;
use crate::security::validator::ValidatorCore;
use crate::selection::EntryShape;
use crate::types::SafePath;
use crate::types::SafeSymlink;

/// What one lstat finds at a file's destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DestOccupancy {
    Vacant,
    RegularFile,
    Symlink,
    Directory,
}

impl DestOccupancy {
    fn of(occupant: Option<Occupant>) -> Self {
        match occupant {
            None => Self::Vacant,
            Some(Occupant::File) => Self::RegularFile,
            Some(Occupant::Symlink) => Self::Symlink,
            Some(Occupant::Directory) => Self::Directory,
        }
    }

    /// Looks at `leaf` in `parent` without following a symlink, so a dangling
    /// link counts as occupied.
    fn probe(parent: &VettedDir, leaf: Leaf<'_>) -> std::io::Result<Self> {
        parent.probe(leaf).map(Self::of)
    }

    /// Path-based variant for the pre-pass, whose result only decides whether
    /// to skip or refuse an entry before anything is written; the write
    /// re-probes relative to its pinned parent.
    fn probe_path(dest_path: &Path) -> std::io::Result<Self> {
        Ok(Self::of(
            lstat_dest(dest_path)?.map(|meta| meta.file_type().into()),
        ))
    }

    const fn occupant(self) -> Option<Occupant> {
        match self {
            Self::Vacant => None,
            Self::RegularFile => Some(Occupant::File),
            Self::Symlink => Some(Occupant::Symlink),
            Self::Directory => Some(Occupant::Directory),
        }
    }

    const fn is_occupied(self) -> bool {
        !matches!(self, Self::Vacant)
    }

    /// A pre-existing symlink that is refused rather than unlinked and written
    /// under its name, as TAR and ZIP refuse it on every host.
    fn kept_symlink(self) -> Option<KeptOccupant> {
        (self == Self::Symlink).then_some(KeptOccupant::Symlink)
    }

    /// How to write over this occupant with the policy's `permit`, or the
    /// occupant that cannot be replaced.
    fn replace_mode(self, permit: ReplacePermit) -> std::result::Result<WriteMode, KeptOccupant> {
        if let Some(kept) = self.kept_symlink() {
            return Err(kept);
        }
        match self {
            Self::Vacant => Ok(WriteMode::CreateNew),
            Self::Directory => Err(KeptOccupant::Directory),
            Self::RegularFile | Self::Symlink => Ok(WriteMode::ReplaceRegular(permit)),
        }
    }
}

/// How an admitted file reaches its destination.
#[derive(Debug)]
enum WriteMode {
    /// Nothing is there: open the destination itself with `O_EXCL`.
    CreateNew,
    /// A regular file is there: replace it through a temp file and a rename,
    /// as the permit allows.
    ReplaceRegular(ReplacePermit),
}

/// A file the 7z host admitted, with the way to write it.
#[derive(Debug)]
pub(super) struct SevenZAdmittedFile {
    file: ValidatedFile<HostParent>,
    write_mode: WriteMode,
    parent: VettedDir,
}

/// A host destination for 7z extraction.
pub(super) struct SevenZHostTarget<'a> {
    inner: HostTarget<'a>,
}

impl<'a> SevenZHostTarget<'a> {
    /// Creates the output directory if needed and a target writing into it.
    pub(super) fn create<'o>(
        output: impl Into<OutputRoot<'o>>,
        config: &'a SecurityConfig,
    ) -> Result<Self> {
        Ok(Self {
            inner: HostTarget::create(output, config)?,
        })
    }
}

impl ExtractTarget for SevenZHostTarget<'_> {
    type AdmittedFile = SevenZAdmittedFile;
    type Parent = HostParent;

    fn validate_file(
        &mut self,
        request: FileRequest<'_>,
        tally: &mut Tally<'_>,
    ) -> Result<Admission<SevenZAdmittedFile>> {
        let pending = match tally.admission(self.inner.screen_file(request)?, request.path)? {
            Admission::Admit(pending) => pending,
            Admission::Skipped(skipped) => return Ok(Admission::Skipped(skipped)),
        };
        let safe_path = pending.path().clone();
        let (parent, leaf) = self
            .inner
            .dirs()
            .ensure_parent(self.inner.root(), &safe_path)?;
        // Owned because `admit_file` borrows the extractor mutably.
        let parent = parent.into_owned()?;

        let occupancy = DestOccupancy::probe(&parent, leaf)?;
        let write_mode = if occupancy.is_occupied() {
            let root = self.inner.root();
            let action = OccupantPolicy::of(tally.options).on_occupant(
                EntryShape::File,
                safe_path.as_path(),
                || Ok(occupancy.occupant()),
                || root.created().maker(&parent, leaf, safe_path.as_path()),
                OccupiedSite::Host(root),
            )?;
            match action {
                OccupantAction::Skip => {
                    self.inner.charge_skipped()?;
                    return tally
                        .record_duplicate_skip(safe_path.as_path())
                        .map(Admission::Skipped);
                }
                OccupantAction::Replace(permit) => {
                    occupancy.replace_mode(permit).map_err(|kept| {
                        common::kept_refusal_at(kept, &parent, leaf, safe_path.as_path(), root)
                    })?
                }
            }
        } else {
            WriteMode::CreateNew
        };

        // Quota is reserved before anything is removed, so a refusal never
        // destroys a destination it could not replace.
        let file = self.inner.admit_file(pending)?;
        Ok(Admission::Admit(SevenZAdmittedFile {
            file,
            write_mode,
            parent,
        }))
    }

    fn validate_directory(
        &mut self,
        path: &Path,
        size: EntrySize,
        tally: &mut Tally<'_>,
    ) -> Result<Admission<SafePath<HostParent>>> {
        self.inner.validate_directory(path, size, tally)
    }

    fn validate_symlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
        tally: &mut Tally<'_>,
    ) -> Result<Admission<SafeSymlink<HostParent>>> {
        self.inner.validate_symlink(path, target, size, tally)
    }

    fn validate_hardlink(
        &mut self,
        path: &Path,
        target: &Path,
        size: EntrySize,
        tally: &mut Tally<'_>,
    ) -> Result<Admission<ValidatedHardlink<HostParent>>> {
        self.inner.validate_hardlink(path, target, size, tally)
    }

    fn finish_scan(&mut self) -> Result<()> {
        self.inner.finish_scan()
    }

    fn directory(&mut self, path: &SafePath<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
        self.inner.directory(path, tally)
    }

    fn file<R: Read>(
        &mut self,
        reader: &mut R,
        faults: ReadFaults<'_>,
        admitted: SevenZAdmittedFile,
        tally: &mut Tally<'_>,
    ) -> Result<()> {
        let SevenZAdmittedFile {
            file,
            write_mode,
            parent,
        } = admitted;
        let (path, permit, _mode) = file.into_parts();
        let (_, leaf) = Leaf::split(path.as_path())?;
        let (copy_buffer, marking) = self.inner.copy_buffer_and_marking();
        let written = match write_mode {
            WriteMode::CreateNew => write_file_direct(
                reader,
                faults,
                &parent,
                leaf,
                FileWrite {
                    copy_buffer,
                    permit,
                    marking,
                    progress: &mut *tally.progress,
                },
            )?,
            WriteMode::ReplaceRegular(replace) => write_file_with_permit(
                reader,
                faults,
                &parent,
                leaf,
                replace,
                FileWrite {
                    copy_buffer,
                    permit,
                    marking,
                    progress: &mut *tally.progress,
                },
            )?,
        };
        self.inner
            .root()
            .created()
            .note(&parent, leaf, path.as_path());
        tally.record_file(written)
    }

    fn symlink(&mut self, symlink: &SafeSymlink<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
        self.inner.symlink(symlink, tally)
    }

    fn hardlink(
        &mut self,
        link: &SafePath<HostParent>,
        target: &HardlinkTarget,
        counted: crate::security::quota::EntryCount,
        tally: &mut Tally<'_>,
    ) -> Result<()> {
        self.inner.hardlink(link, target, counted, tally)
    }
}

/// The host's pre-pass: paths against the disk as it is now.
struct HostPrePass<'a> {
    core: ValidatorCore<'a>,
    root: &'a PinnedRoot,
    config: &'a SecurityConfig,
    options: SinkOptions,
}

impl PrePass for HostPrePass<'_> {
    fn validate_path(
        &mut self,
        path: &Path,
        shape: EntryShape,
    ) -> Result<Gated<EntryPath<SafePath>>> {
        let ctx: ValidationContext<HostFs> = self.core.context().deferring_leaf_symlink();
        self.core
            .route_entry_in(path, shape, self.root.dest(), &HostFs, &ctx)
    }

    fn directory(&mut self, landing: &SafePath) -> Result<()> {
        let rel = landing.as_path();
        if common::landing_is_free_or_directory(self.root, rel) {
            return Ok(());
        }
        let dirs = DirWalker::new(self.config);
        let held_by_symlink = dirs
            .open_parent(self.root, rel)
            .is_ok_and(|(parent, leaf)| matches!(parent.probe(leaf), Ok(Some(Occupant::Symlink))));
        if held_by_symlink {
            common::refuse_unadmitted_symlink_landing(self.root, dirs, rel, || {
                OccupiedBy::Existing
            })?;
        }
        Ok(())
    }

    fn symlink(&mut self, link: &SafePath, file: &sevenz_rust2::ArchiveEntry) -> Result<()> {
        common::require_symlink_creation()?;
        refuse_undecoded_target_in(link, file, self.root.dest(), self.config, &HostFs)
    }

    fn file(&mut self, safe_path: &SafePath) -> Result<FilePlan> {
        let dest_path = self.root.dest().join(safe_path);
        let occupancy = DestOccupancy::probe_path(&dest_path)?;
        if occupancy.is_occupied() {
            let action = OccupantPolicy::of(self.options).on_occupant(
                EntryShape::File,
                safe_path.as_path(),
                || Ok(occupancy.occupant()),
                || Maker::Foreign,
                OccupiedSite::Host(self.root),
            )?;
            if matches!(action, OccupantAction::Skip) {
                return Ok(FilePlan::Skip);
            }
        }
        // Fail here too, before any entry is written, so the pre-pass keeps
        // its no-partial-extraction guarantee for this refusal.
        if occupancy.kept_symlink().is_some() {
            return Err(replaces_symlink(safe_path.as_path(), OccupiedBy::Existing));
        }
        Ok(FilePlan::Reserve)
    }

    fn charge_skipped(&mut self) -> Result<()> {
        self.core.charge_skipped()
    }

    fn reserve_symlink(&mut self, size: u64) -> Result<()> {
        self.core.reserve_symlink(size)
    }

    fn reserve_file(&mut self, size: u64) -> Result<()> {
        self.core.reserve_file(size).map(drop)
    }
}

impl SevenZTarget for SevenZHostTarget<'_> {
    fn with_pre_pass(
        &self,
        config: &SecurityConfig,
        options: SinkOptions,
        run: &mut dyn FnMut(&mut dyn PrePass) -> Result<()>,
    ) -> Result<()> {
        let mut pre = HostPrePass {
            core: ValidatorCore::new(config),
            root: self.inner.root(),
            config,
            options,
        };
        run(&mut pre)
    }
}