exarch-core 0.9.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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Where the entries of a listed archive land under the destination.
//!
//! A front end that wants to know which host paths an extraction would write
//! (for a conflict pre-check, say) must not re-implement the entry-to-path
//! mapping: it differs in the details that matter (Windows drive prefixes,
//! `./` and leading separators, symlinked parents, non-file entries). This
//! module derives the landing from the same validation and projection that
//! `verify` and the sink use.

use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;

use crate::SecurityConfig;
use crate::formats::common::is_extension_allowed;
use crate::inspection::manifest::ArchiveEntry;
use crate::inspection::manifest::ArchiveManifest;
use crate::inspection::manifest::LinkTarget;
use crate::inspection::manifest::ManifestEntryKind;
use crate::security::fs_view::CollisionRecording;
use crate::security::fs_view::LandingLimits;
use crate::security::fs_view::Node;
use crate::security::fs_view::NodeBudget;
use crate::security::fs_view::PathModel;
use crate::security::fs_view::VirtualRoot;
use crate::security::fs_view::VirtualTree;
use crate::types::SafePath;
use crate::types::SafeSymlink;

/// The destination-relative path an entry lands at, derived lexically.
///
/// The path is relative and normalized (no root, drive prefix, `.` or `..`),
/// its name lengths fit the host, and every symlink among the earlier entries
/// it passes through has been resolved. It is a **lexical** answer: it says
/// nothing about what already exists on disk, so it does not claim that
/// writing there stays inside the destination. A caller that acts on the
/// filesystem must still use `symlink_metadata` and the extraction itself for
/// containment.
///
/// # Examples
///
/// ```
/// use exarch_core::ArchiveEntry;
/// use exarch_core::ArchiveManifest;
/// use exarch_core::ManifestEntryKind;
/// use exarch_core::SecurityConfig;
/// use exarch_core::formats::detect::ArchiveType;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
/// manifest.add_entry(ArchiveEntry::new(
///     "./a/b.txt".into(),
///     ManifestEntryKind::Directory,
/// ))?;
/// let config = SecurityConfig::default();
/// let landed: Vec<_> = manifest.landing_paths(&config).collect();
/// assert_eq!(landed[0].1.as_path(), std::path::Path::new("a/b.txt"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LandingPath(PathBuf);

impl LandingPath {
    /// The relative path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }

    /// Consumes the value and returns the relative path.
    #[must_use]
    pub fn into_path_buf(self) -> PathBuf {
        self.0
    }
}

impl AsRef<Path> for LandingPath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

/// What put a path in the landing set.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum LandingKind<'a> {
    /// An archive entry lands here.
    Entry(&'a ArchiveEntry),
    /// No entry names this path, but extraction creates it as a parent
    /// directory of one that lands below it.
    ImplicitParent,
}

/// A path extraction creates, with what put it there.
#[derive(Debug, Clone)]
pub struct Landing<'a> {
    path: LandingPath,
    kind: LandingKind<'a>,
}

impl<'a> Landing<'a> {
    /// Where the path lands.
    #[must_use]
    pub const fn path(&self) -> &LandingPath {
        &self.path
    }

    /// Whether an entry or an implied parent directory lands here.
    #[must_use]
    pub const fn kind(&self) -> LandingKind<'a> {
        self.kind
    }
}

impl ArchiveManifest {
    /// The entries extraction would create, each with where it lands.
    ///
    /// Entries are judged in archive order against a model of what earlier
    /// entries created, so a path through an earlier symlink is resolved the
    /// way extraction resolves it. An entry that extraction would not create
    /// is left out: one the validation refuses (traversal, a banned
    /// component, a symlink or hardlink the config disallows, a symlink whose
    /// target escapes), one that cannot be placed (a conflict with an earlier
    /// entry, a landing longer than the host allows) and a regular file the
    /// extension allowlist skips. Every other kind of entry is covered, not
    /// only regular files.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ArchiveManifest;
    /// use exarch_core::ManifestEntryKind;
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::formats::detect::ArchiveType;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
    /// manifest.add_entry(ArchiveEntry::new(
    ///     "../evil".into(),
    ///     ManifestEntryKind::Directory,
    /// ))?;
    /// let config = SecurityConfig::default();
    /// assert_eq!(manifest.landing_paths(&config).count(), 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn landing_paths<'a>(
        &'a self,
        config: &SecurityConfig,
    ) -> impl Iterator<Item = (&'a ArchiveEntry, LandingPath)> + use<'a> {
        let root = VirtualRoot::new();
        let mut tree = VirtualTree::new(
            &root,
            PathModel::Host,
            NodeBudget::from_config(config),
            CollisionRecording::Discard,
        );
        let landed: Vec<_> = self
            .entries()
            .iter()
            .filter_map(|entry| {
                land(entry, config, &root, &mut tree).map(|landing| (entry, landing))
            })
            .collect();
        landed.into_iter()
    }

    /// Everything extraction would create, entries and the directories it
    /// creates for them on its own, in the order they land.
    ///
    /// An archive can hold `a/b.txt` without an `a/` entry; extraction then
    /// creates `a`. Each such parent is reported once, as
    /// [`LandingKind::ImplicitParent`], before the first entry that needs it,
    /// outermost first. A front end that probes the destination for conflicts
    /// probes every landing, so a parent that is a file (or a symlink) in the
    /// destination is found at that parent and not below it.
    ///
    /// The parents are those of the resolved landing, so a path through an
    /// earlier symlink reports the directories it really lands in.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ArchiveManifest;
    /// use exarch_core::LandingKind;
    /// use exarch_core::ManifestEntryKind;
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::Uncompressed;
    /// use exarch_core::formats::detect::ArchiveType;
    /// use std::assert_matches;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
    /// let file = ManifestEntryKind::File {
    ///     size: Uncompressed(1),
    /// };
    /// manifest.add_entry(ArchiveEntry::new("a/b.txt".into(), file))?;
    /// let config = SecurityConfig::default();
    /// let landings: Vec<_> = manifest.landings(&config).collect();
    /// assert_eq!(landings.len(), 2);
    /// assert_matches!(landings[0].kind(), LandingKind::ImplicitParent);
    /// assert_eq!(landings[0].path().as_path(), std::path::Path::new("a"));
    /// assert_matches!(landings[1].kind(), LandingKind::Entry(_));
    /// # Ok(())
    /// # }
    /// ```
    pub fn landings<'a>(
        &'a self,
        config: &SecurityConfig,
    ) -> impl Iterator<Item = Landing<'a>> + use<'a> {
        let mut seen = HashSet::new();
        let mut out = Vec::new();
        for (entry, landing) in self.landing_paths(config) {
            let ancestors: Vec<_> = landing
                .as_path()
                .ancestors()
                .skip(1)
                .filter(|p| !p.as_os_str().is_empty())
                .map(Path::to_path_buf)
                .collect();
            for parent in ancestors.into_iter().rev() {
                if seen.insert(parent.clone()) {
                    out.push(Landing {
                        path: LandingPath(parent),
                        kind: LandingKind::ImplicitParent,
                    });
                }
            }
            seen.insert(landing.as_path().to_path_buf());
            out.push(Landing {
                path: landing,
                kind: LandingKind::Entry(entry),
            });
        }
        out.into_iter()
    }
}

fn land(
    entry: &ArchiveEntry,
    config: &SecurityConfig,
    root: &VirtualRoot,
    tree: &mut VirtualTree,
) -> Option<LandingPath> {
    let is_file = matches!(entry.kind, ManifestEntryKind::File { .. });
    if is_file && !is_extension_allowed(&entry.path, config) {
        return None;
    }
    let safe = SafePath::validate_in(&entry.path, root, config, tree).ok()?;
    let node = match &entry.kind {
        ManifestEntryKind::File { .. } => Node::File,
        ManifestEntryKind::Hardlink { .. } => {
            if !config.allowed.hardlinks.is_allowed() {
                return None;
            }
            Node::File
        }
        ManifestEntryKind::Directory => Node::Dir,
        ManifestEntryKind::Symlink { target } => {
            if !config.allowed.symlinks.is_allowed() {
                return None;
            }
            match target {
                LinkTarget::Recorded(t) => {
                    SafeSymlink::validate_in(&safe, t, root, config, tree).ok()?;
                    Node::Symlink(t.clone())
                }
                LinkTarget::Unread => Node::OpaqueSymlink,
                LinkTarget::Missing | LinkTarget::Unreadable | LinkTarget::Oversized { .. } => {
                    return None;
                }
            }
        }
    };
    let landed = tree
        .project_landing(&safe, node, LandingLimits::Enforced)
        .ok()?;
    Some(LandingPath(landed.into_path_buf()))
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use std::collections::BTreeSet;
    use std::io::Cursor;
    use std::io::Write as _;

    use exarch_testkit::raw_zip::RawEntry;
    use exarch_testkit::raw_zip::RawZip;

    use super::*;
    use crate::extract_archive;
    use crate::list_archive;

    fn config() -> SecurityConfig {
        SecurityConfig::default()
            .with_allow_absolute_paths(true)
            .with_allow_symlinks(true)
    }

    fn tar_entry(
        builder: &mut tar::Builder<Vec<u8>>,
        name: &[u8],
        kind: tar::EntryType,
        link: &str,
    ) {
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(kind);
        header.set_mode(0o644);
        header.set_size(u64::from(kind == tar::EntryType::Regular));
        header.as_old_mut().name[..name.len()].copy_from_slice(name);
        if !link.is_empty() {
            header.set_link_name(link).unwrap();
        }
        header.set_cksum();
        let data: &[u8] = if kind == tar::EntryType::Regular {
            b"x"
        } else {
            b""
        };
        builder.append(&header, data).unwrap();
    }

    fn non_directories(root: &Path) -> BTreeSet<PathBuf> {
        let mut found = BTreeSet::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            for item in std::fs::read_dir(&dir).unwrap() {
                let path = item.unwrap().path();
                if std::fs::symlink_metadata(&path).unwrap().is_dir() {
                    stack.push(path);
                } else {
                    found.insert(path.strip_prefix(root).unwrap().to_path_buf());
                }
            }
        }
        found
    }

    fn every_path(root: &Path) -> BTreeSet<PathBuf> {
        let mut found = BTreeSet::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            for item in std::fs::read_dir(&dir).unwrap() {
                let path = item.unwrap().path();
                if std::fs::symlink_metadata(&path).unwrap().is_dir() {
                    stack.push(path.clone());
                }
                found.insert(path.strip_prefix(root).unwrap().to_path_buf());
            }
        }
        found
    }

    /// The landing set of the non-directory entries must be the set of
    /// non-directories extraction really created.
    fn assert_landing_matches_extraction(file_name: &str, bytes: &[u8]) {
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join(file_name);
        std::fs::write(&archive, bytes).unwrap();
        let dest = dir.path().join("out");
        std::fs::create_dir(&dest).unwrap();
        let config = config();

        let manifest = list_archive(&archive, &config).unwrap();
        let landed: BTreeSet<PathBuf> = manifest
            .landing_paths(&config)
            .filter(|(entry, _)| !matches!(entry.kind, ManifestEntryKind::Directory))
            .map(|(_, landing)| landing.into_path_buf())
            .collect();
        extract_archive(&archive, &dest, &config).unwrap();

        assert_eq!(landed, non_directories(&dest), "{file_name}");
        let every: BTreeSet<PathBuf> = manifest
            .landings(&config)
            .map(|landing| landing.path().as_path().to_path_buf())
            .collect();
        assert_eq!(every, every_path(&dest), "{file_name}: implicit parents");
        let implicit = manifest
            .landings(&config)
            .filter(|l| matches!(l.kind(), LandingKind::ImplicitParent))
            .count();
        assert!(implicit > 0, "{file_name}: the fixture implies a parent");
        assert!(!landed.is_empty(), "{file_name}");
    }

    #[test]
    fn tar_landing_matches_extraction_for_dot_slash_absolute_and_linked_parents() {
        let mut builder = tar::Builder::new(Vec::new());
        tar_entry(&mut builder, b"./a.txt", tar::EntryType::Regular, "");
        tar_entry(&mut builder, b"/abs.txt", tar::EntryType::Regular, "");
        tar_entry(&mut builder, b"d/", tar::EntryType::Directory, "");
        tar_entry(&mut builder, b"d/sub.txt", tar::EntryType::Regular, "");
        // Windows extraction refuses symlinks, so the linked parent is
        // Unix-only.
        #[cfg(unix)]
        {
            tar_entry(&mut builder, b"link", tar::EntryType::Symlink, "d");
            tar_entry(
                &mut builder,
                b"link/through.txt",
                tar::EntryType::Regular,
                "",
            );
        }
        tar_entry(&mut builder, b"x/y/z.txt", tar::EntryType::Regular, "");
        assert_landing_matches_extraction("a.tar", &builder.into_inner().unwrap());
    }

    #[test]
    fn a_path_through_a_symlink_lands_at_the_resolved_path() {
        let mut builder = tar::Builder::new(Vec::new());
        tar_entry(&mut builder, b"d/", tar::EntryType::Directory, "");
        tar_entry(&mut builder, b"link", tar::EntryType::Symlink, "d");
        tar_entry(&mut builder, b"link/x.txt", tar::EntryType::Regular, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("a.tar");
        std::fs::write(&archive, builder.into_inner().unwrap()).unwrap();
        let config = config();

        let manifest = list_archive(&archive, &config).unwrap();
        let landed: Vec<_> = manifest
            .landing_paths(&config)
            .map(|(_, l)| l.into_path_buf())
            .collect();
        assert_eq!(
            landed,
            [
                PathBuf::from("d"),
                PathBuf::from("link"),
                PathBuf::from("d/x.txt")
            ]
        );
    }

    #[test]
    fn zip_landing_matches_extraction_for_backslashes_and_drive_prefixes() {
        let entries = [
            "a\\b.txt",
            "C:\\win.txt",
            "/abs.txt",
            "plain.txt",
            "dir/",
            "p/q/r.txt",
        ]
        .iter()
        .map(|name| RawEntry::stored(name, if name.ends_with('/') { b"" } else { b"x" }))
        .collect();
        let bytes = RawZip::new(entries).build().bytes;
        assert_landing_matches_extraction("a.zip", &bytes);
    }

    #[test]
    fn sevenz_landing_matches_extraction() {
        let mut writer = sevenz_rust2::ArchiveWriter::new(Cursor::new(Vec::new())).unwrap();
        for name in ["a.txt", "dir/b.txt", "dir/deeper/c.txt"] {
            writer
                .push_archive_entry(
                    sevenz_rust2::ArchiveEntry::new_file(name),
                    Some(Cursor::new(b"x".to_vec())),
                )
                .unwrap();
        }
        let bytes = writer.finish().unwrap().into_inner();
        assert_landing_matches_extraction("a.7z", &bytes);
    }

    #[test]
    fn refused_and_skipped_entries_do_not_land() {
        let mut builder = tar::Builder::new(Vec::new());
        tar_entry(&mut builder, b"ok.txt", tar::EntryType::Regular, "");
        tar_entry(&mut builder, b"skip.bin", tar::EntryType::Regular, "");
        tar_entry(
            &mut builder,
            b"esc",
            tar::EntryType::Symlink,
            "../../outside",
        );
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("a.tar");
        std::fs::write(&archive, builder.into_inner().unwrap()).unwrap();
        let config = config().try_add_allowed_extension("txt").unwrap();

        let manifest = list_archive(&archive, &config).unwrap();
        let landed: Vec<_> = manifest
            .landing_paths(&config)
            .map(|(_, l)| l.into_path_buf())
            .collect();
        assert_eq!(landed, [PathBuf::from("ok.txt")]);
    }

    #[test]
    fn disallowed_links_do_not_land() {
        let mut builder = tar::Builder::new(Vec::new());
        tar_entry(&mut builder, b"s", tar::EntryType::Symlink, "ok.txt");
        tar_entry(&mut builder, b"h", tar::EntryType::Link, "ok.txt");
        let _ = builder.get_mut().flush();
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("a.tar");
        std::fs::write(&archive, builder.into_inner().unwrap()).unwrap();
        let config = config();

        let manifest = list_archive(&archive, &config).unwrap();
        let strict = SecurityConfig::default();
        assert_eq!(manifest.landing_paths(&strict).count(), 0);
    }

    #[test]
    fn implicit_parents_are_reported_once_outermost_first() {
        let mut builder = tar::Builder::new(Vec::new());
        tar_entry(&mut builder, b"first.txt", tar::EntryType::Regular, "");
        tar_entry(&mut builder, b"a/b/c.txt", tar::EntryType::Regular, "");
        tar_entry(&mut builder, b"a/d.txt", tar::EntryType::Regular, "");
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("a.tar");
        std::fs::write(&archive, builder.into_inner().unwrap()).unwrap();
        let config = config();

        let manifest = list_archive(&archive, &config).unwrap();
        let shape: Vec<_> = manifest
            .landings(&config)
            .map(|l| {
                (
                    l.path().as_path().to_path_buf(),
                    matches!(l.kind(), LandingKind::ImplicitParent),
                )
            })
            .collect();
        assert_eq!(
            shape,
            [
                (PathBuf::from("first.txt"), false),
                (PathBuf::from("a"), true),
                (PathBuf::from("a/b"), true),
                (PathBuf::from("a/b/c.txt"), false),
                (PathBuf::from("a/d.txt"), false),
            ]
        );
    }
}