Skip to main content

exarch_core/security/
hardlink.rs

1//! Hardlink security validation and tracking.
2
3use std::collections::HashMap;
4use std::path::Path;
5use std::path::PathBuf;
6
7use crate::ArchiveError;
8use crate::Malformation;
9use crate::Result;
10use crate::SecurityConfig;
11use crate::Violation;
12use crate::security::fs_view::FsView;
13#[cfg(any(test, feature = "testing"))]
14use crate::security::fs_view::HostFs;
15use crate::security::fs_view::LinkBase;
16use crate::security::fs_view::LinkKind;
17#[cfg(any(test, feature = "testing"))]
18use crate::types::DestDir;
19use crate::types::SafePath;
20use crate::types::dest_dir::ProbePath;
21use crate::types::safe_path::ParentCheck;
22use crate::types::safe_path::check_component_for;
23use crate::types::safe_symlink::has_root_or_prefix;
24
25/// Error for a hardlink whose target is absent when the link is created.
26pub fn hardlink_target_missing(target: &Path) -> ArchiveError {
27    ArchiveError::from(Malformation::HardlinkTargetAbsent {
28        target: target.to_path_buf(),
29    })
30}
31
32/// Fails with the hardlink-policy refusal unless `config` allows hardlinks.
33///
34/// # Errors
35///
36/// Returns `SecurityViolation` ("hardlinks not allowed") when hardlinks are
37/// disabled.
38pub fn require_hardlinks_allowed(config: &SecurityConfig) -> Result<()> {
39    config
40        .allowed
41        .hardlinks
42        .is_allowed()
43        .ok_or_else(|| Violation::LinksNotAllowed(LinkKind::Hardlink).into())
44}
45
46/// A hardlink target that passed `HardlinkTracker` validation.
47///
48/// The path is relative, non-empty and free of NUL bytes, root and prefix
49/// components; every normal component passed the component checks, and the
50/// target resolved inside the extraction root when it was validated. It may
51/// contain `..` components that stay inside the root, and it is re-resolved
52/// when opened in the second extraction pass, so it names a lexical location,
53/// not a proof about what is on disk at that time.
54///
55/// There is no public constructor: the only producer is
56/// `HardlinkTracker`'s validation, so a hardlink target cannot be assembled
57/// from an unchecked path.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct HardlinkTarget(PathBuf);
60
61impl HardlinkTarget {
62    /// Returns the validated target, relative to the destination directory.
63    #[inline]
64    #[must_use]
65    pub fn as_path(&self) -> &Path {
66        &self.0
67    }
68
69    /// Whether the target steps out of a directory it entered (`d/../f`).
70    #[must_use]
71    pub fn has_parent_dir(&self) -> bool {
72        self.0
73            .components()
74            .any(|c| matches!(c, std::path::Component::ParentDir))
75    }
76
77    /// Names the target below `dest` for a read-only probe.
78    #[must_use]
79    pub(crate) fn probe_under(&self, dest: &crate::types::DestDir) -> ProbePath {
80        dest.probe(&self.0)
81    }
82
83    /// Read-only probes of the target's parent directories below `dest`,
84    /// outermost first.
85    pub(crate) fn parent_probes<'a>(
86        &'a self,
87        dest: &'a crate::types::DestDir,
88    ) -> impl Iterator<Item = ProbePath> + 'a {
89        let mut prefix = PathBuf::new();
90        self.0
91            .parent()
92            .into_iter()
93            .flat_map(Path::components)
94            .map(move |component| {
95                prefix.push(component);
96                dest.probe(&prefix)
97            })
98    }
99}
100
101/// Tracks hardlink targets during extraction.
102///
103/// Hardlinks in archives can be used for attacks:
104/// 1. Link to files outside the extraction directory
105/// 2. Create multiple hardlinks to the same file (resource exhaustion)
106/// 3. Link to sensitive files (if absolute paths allowed)
107///
108/// This tracker ensures:
109/// - Hardlinks are allowed in the security configuration
110/// - Targets are relative paths
111/// - Targets resolve within the destination directory
112/// - Duplicate hardlinks are detected
113///
114/// # Two-Pass Validation
115///
116/// Hardlinks require two-pass validation:
117/// 1. **First pass (during validation):** Track target paths, verify they're
118///    within bounds
119/// 2. **Second pass (after extraction):** Verify targets actually exist
120///
121/// This is necessary because hardlink targets may appear later in the archive.
122///
123/// # Examples
124///
125/// ```ignore
126/// use exarch_core::SecurityConfig;
127/// use exarch_core::security::HardlinkTracker;
128/// use exarch_core::types::DestDir;
129/// use exarch_core::types::SafePath;
130/// use std::path::Path;
131/// use std::path::PathBuf;
132///
133/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
134/// let dest = DestDir::new(PathBuf::from("/tmp"))?;
135/// let mut config = SecurityConfig::default();
136/// config.allowed.hardlinks = exarch_core::Admit::Allow;
137///
138/// let mut tracker = HardlinkTracker::new();
139/// let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)?;
140/// let target = Path::new("target.txt");
141///
142/// tracker.validate_hardlink(&link, target, &dest, &config)?;
143/// # Ok(())
144/// # }
145/// ```
146#[derive(Debug, Default)]
147pub struct HardlinkTracker {
148    /// Maps target path to the first link path that referenced it
149    seen_targets: HashMap<PathBuf, PathBuf>,
150}
151
152impl HardlinkTracker {
153    /// Creates a new hardlink tracker.
154    #[must_use]
155    pub fn new() -> Self {
156        Self {
157            seen_targets: HashMap::new(),
158        }
159    }
160
161    /// Validates that a hardlink target is safe and tracks it.
162    ///
163    /// # Performance
164    ///
165    /// Typical execution time: ~1-5 μs (`HashMap` insert + path validation)
166    ///
167    /// # Errors
168    ///
169    /// Returns an error if:
170    /// - Hardlinks are not allowed in configuration
171    /// - Target is empty or contains NUL bytes
172    /// - Target is an absolute path (including Windows drive/UNC prefixes)
173    /// - Target would escape the destination directory
174    ///
175    /// # Examples
176    ///
177    /// ```ignore
178    /// use exarch_core::SecurityConfig;
179    /// use exarch_core::security::HardlinkTracker;
180    /// use exarch_core::types::DestDir;
181    /// use exarch_core::types::SafePath;
182    /// use std::path::Path;
183    /// use std::path::PathBuf;
184    ///
185    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
186    /// let dest = DestDir::new(PathBuf::from("/tmp"))?;
187    /// let mut config = SecurityConfig::default();
188    /// config.allowed.hardlinks = exarch_core::Admit::Allow;
189    ///
190    /// let mut tracker = HardlinkTracker::new();
191    /// let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)?;
192    /// let target = Path::new("target.txt");
193    ///
194    /// tracker.validate_hardlink(&link, target, &dest, &config)?;
195    /// # Ok(())
196    /// # }
197    /// ```
198    #[cfg(any(test, feature = "testing"))]
199    pub fn validate_hardlink(
200        &mut self,
201        link_path: &SafePath,
202        target: &Path,
203        dest: &DestDir,
204        config: &SecurityConfig,
205    ) -> Result<HardlinkTarget> {
206        self.validate_hardlink_in(link_path, target, dest, config, &HostFs)
207    }
208
209    /// Validates against `view` instead of the real filesystem.
210    #[expect(
211        clippy::items_after_statements,
212        reason = "the import is placed next to its only use"
213    )]
214    pub(crate) fn validate_hardlink_in<V: FsView, P: ParentCheck>(
215        &mut self,
216        link_path: &SafePath<P>,
217        target: &Path,
218        root: &V::Root,
219        config: &SecurityConfig,
220        view: &V,
221    ) -> Result<HardlinkTarget> {
222        require_hardlinks_allowed(config)?;
223
224        // Reject empty targets: they do not point anywhere.
225        if target.is_empty() {
226            return Err(Violation::LinkTargetEmpty(LinkKind::Hardlink).into());
227        }
228
229        // Reject null bytes in the target before any error message can be
230        // built from it. Without this check, a NUL byte either falls
231        // through to the OS as a raw `io::Error`, or gets embedded verbatim
232        // into a formatted `InvalidArchive` message further downstream (e.g.
233        // "hardlink target does not exist: {target}"). The message here
234        // intentionally omits the raw target bytes.
235        if crate::types::safe_path::has_null_bytes(target) {
236            return Err(Violation::LinkTargetNul(LinkKind::Hardlink).into());
237        }
238
239        use std::path::Component;
240
241        // H-SEC-2: Reject Windows-specific absolute path components in target
242        // (before resolution) This prevents bypasses on Windows like
243        // C:\ or \\server\share
244        if has_root_or_prefix(target) {
245            return Err(ArchiveError::HardlinkEscape {
246                path: link_path.as_path().to_path_buf(),
247            });
248        }
249
250        for component in target.components() {
251            if let Component::Normal(comp) = component {
252                check_component_for(view.path_model(), comp, config)?;
253            }
254        }
255
256        // Also reject absolute targets (redundant with above, but keeps
257        // existing check)
258        if target.is_absolute() {
259            return Err(ArchiveError::HardlinkEscape {
260                path: link_path.as_path().to_path_buf(),
261            });
262        }
263
264        // Resolve target against destination, following any on-disk symlinks
265        // encountered during traversal.
266        //
267        // String-based normalization is insufficient: if a previously extracted
268        // symlink lies on the target path, a hardlink target can escape the
269        // extraction root via on-disk resolution even though string
270        // normalization would pass (two-hop chain bypass,
271        // GHSA-83g3-92jg-28cx variant — #116).
272        let resolved = view
273            .resolve_link_target(link_path.as_path(), target, LinkBase::Destination, root)
274            .map_err(|_| ArchiveError::HardlinkEscape {
275                path: link_path.as_path().to_path_buf(),
276            })?;
277
278        // Track this hardlink target (H-PERF-6: use entry API)
279        self.seen_targets
280            .entry(resolved)
281            .or_insert_with(|| link_path.as_path().to_path_buf());
282
283        Ok(HardlinkTarget(target.to_path_buf()))
284    }
285
286    /// Returns the number of tracked hardlinks.
287    #[cfg(any(test, feature = "testing"))]
288    #[must_use]
289    pub fn count(&self) -> usize {
290        self.seen_targets.len()
291    }
292}
293
294#[cfg(test)]
295impl HardlinkTracker {
296    pub(crate) fn has_target(&self, target: &Path) -> bool {
297        self.seen_targets.contains_key(target)
298    }
299}
300
301#[cfg(test)]
302#[allow(
303    clippy::unwrap_used,
304    clippy::expect_used,
305    clippy::field_reassign_with_default
306)]
307mod tests {
308    use super::*;
309    use std::assert_matches;
310    use tempfile::TempDir;
311
312    fn create_test_dest() -> (TempDir, DestDir) {
313        let temp = TempDir::new().expect("failed to create temp dir");
314        let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
315        (temp, dest)
316    }
317
318    #[test]
319    fn test_hardlink_tracker_new() {
320        let tracker = HardlinkTracker::new();
321        assert_eq!(tracker.count(), 0);
322    }
323
324    #[test]
325    fn test_validate_hardlink_allowed() {
326        let (_temp, dest) = create_test_dest();
327        let mut config = SecurityConfig::default();
328        config.allowed.hardlinks = crate::Admit::Allow;
329
330        let mut tracker = HardlinkTracker::new();
331        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
332        let target = PathBuf::from("target.txt");
333
334        assert!(
335            tracker
336                .validate_hardlink(&link, &target, &dest, &config)
337                .is_ok()
338        );
339        assert_eq!(tracker.count(), 1);
340    }
341
342    #[test]
343    fn test_validate_hardlink_disabled() {
344        let (_temp, dest) = create_test_dest();
345        let config = SecurityConfig::default(); // hardlinks disabled by default
346
347        let mut tracker = HardlinkTracker::new();
348        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
349        let target = PathBuf::from("target.txt");
350
351        assert!(
352            tracker
353                .validate_hardlink(&link, &target, &dest, &config)
354                .is_err()
355        );
356    }
357
358    #[test]
359    fn test_validate_hardlink_absolute_target() {
360        let (_temp, dest) = create_test_dest();
361        let mut config = SecurityConfig::default();
362        config.allowed.hardlinks = crate::Admit::Allow;
363
364        let mut tracker = HardlinkTracker::new();
365        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
366        let target = PathBuf::from("/etc/passwd");
367
368        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
369        assert_matches!(result, Err(ArchiveError::HardlinkEscape { .. }));
370    }
371
372    #[test]
373    fn test_validate_hardlink_escape() {
374        let (_temp, dest) = create_test_dest();
375        let mut config = SecurityConfig::default();
376        config.allowed.hardlinks = crate::Admit::Allow;
377
378        let mut tracker = HardlinkTracker::new();
379        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
380        let target = PathBuf::from("../../etc/passwd");
381
382        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
383        assert_matches!(result, Err(ArchiveError::HardlinkEscape { .. }));
384    }
385
386    #[test]
387    fn test_hardlink_tracker_multiple() {
388        let (_temp, dest) = create_test_dest();
389        let mut config = SecurityConfig::default();
390        config.allowed.hardlinks = crate::Admit::Allow;
391
392        let mut tracker = HardlinkTracker::new();
393
394        let link1 = SafePath::validate(&PathBuf::from("link1"), &dest, &config).unwrap();
395        let link2 = SafePath::validate(&PathBuf::from("link2"), &dest, &config).unwrap();
396
397        tracker
398            .validate_hardlink(&link1, &PathBuf::from("target1.txt"), &dest, &config)
399            .unwrap();
400        tracker
401            .validate_hardlink(&link2, &PathBuf::from("target2.txt"), &dest, &config)
402            .unwrap();
403
404        assert_eq!(tracker.count(), 2);
405    }
406
407    #[test]
408    fn test_hardlink_tracker_has_target() {
409        let (_temp, dest) = create_test_dest();
410        let mut config = SecurityConfig::default();
411        config.allowed.hardlinks = crate::Admit::Allow;
412
413        let mut tracker = HardlinkTracker::new();
414        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
415        let target = PathBuf::from("target.txt");
416
417        tracker
418            .validate_hardlink(&link, &target, &dest, &config)
419            .unwrap();
420
421        let resolved_target = dest.as_path().join(&target);
422        assert!(tracker.has_target(&resolved_target));
423    }
424
425    #[test]
426    fn test_hardlink_tracker_relative_safe() {
427        let (_temp, dest) = create_test_dest();
428        let mut config = SecurityConfig::default();
429        config.allowed.hardlinks = crate::Admit::Allow;
430
431        let mut tracker = HardlinkTracker::new();
432        let link = SafePath::validate(&PathBuf::from("foo/link"), &dest, &config).unwrap();
433        // Safe relative path within destination
434        let target = PathBuf::from("target.txt");
435
436        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
437        assert!(result.is_ok());
438    }
439
440    #[test]
441    fn test_validated_target_keeps_the_validated_path_and_reports_parent_dir() {
442        let (_temp, dest) = create_test_dest();
443        let mut config = SecurityConfig::default();
444        config.allowed.hardlinks = crate::Admit::Allow;
445        std::fs::create_dir(dest.as_path().join("d")).unwrap();
446
447        let mut tracker = HardlinkTracker::new();
448        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
449
450        let plain = tracker
451            .validate_hardlink(&link, Path::new("d/f"), &dest, &config)
452            .unwrap();
453        assert_eq!(plain.as_path(), Path::new("d/f"));
454        assert!(!plain.has_parent_dir());
455
456        let stepping = tracker
457            .validate_hardlink(&link, Path::new("d/../f"), &dest, &config)
458            .unwrap();
459        assert_eq!(stepping.as_path(), Path::new("d/../f"));
460        assert!(stepping.has_parent_dir());
461    }
462
463    // H-TEST-2: Duplicate hardlink to same target test
464    #[test]
465    fn test_duplicate_hardlink_to_same_target() {
466        let (_temp, dest) = create_test_dest();
467        let mut config = SecurityConfig::default();
468        config.allowed.hardlinks = crate::Admit::Allow;
469
470        let mut tracker = HardlinkTracker::new();
471        let target = PathBuf::from("target.txt");
472
473        // Create multiple hardlinks to the same target
474        for i in 0..3 {
475            let link =
476                SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config).unwrap();
477
478            let result = tracker.validate_hardlink(&link, &target, &dest, &config);
479            assert!(
480                result.is_ok(),
481                "multiple hardlinks to same target should be allowed"
482            );
483        }
484
485        // All three links point to the same target, so only 1 unique target
486        // tracked
487        assert_eq!(
488            tracker.count(),
489            1,
490            "should track unique targets, not individual links"
491        );
492    }
493
494    #[test]
495    fn test_hardlink_different_targets() {
496        let (_temp, dest) = create_test_dest();
497        let mut config = SecurityConfig::default();
498        config.allowed.hardlinks = crate::Admit::Allow;
499
500        let mut tracker = HardlinkTracker::new();
501
502        // Create hardlinks to different targets
503        for i in 0..3 {
504            let link =
505                SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config).unwrap();
506            let target = PathBuf::from(format!("target{i}.txt"));
507
508            tracker
509                .validate_hardlink(&link, &target, &dest, &config)
510                .unwrap();
511        }
512
513        // Three different targets
514        assert_eq!(tracker.count(), 3, "should track each unique target");
515    }
516
517    /// Hardlink target that traverses through an already-extracted symlink must
518    /// be rejected (two-hop chain, GHSA-83g3-92jg-28cx variant — issue #116).
519    ///
520    /// Entry 2 (symlink a/b/c/up -> ../..) is on disk when hardlink is
521    /// validated. Target a/b/escape/../../etc/passwd: string normalization
522    /// → dest/a/etc/passwd (looks safe), but if a/b/escape is an on-disk
523    /// symlink resolving outside dest, the hardlink must be rejected.
524    #[test]
525    #[cfg(unix)]
526    #[allow(clippy::unwrap_used)]
527    fn test_hardlink_two_hop_chain_rejected() {
528        use std::fs;
529        use std::os::unix;
530
531        let (temp, dest) = create_test_dest();
532        let mut config = SecurityConfig::default();
533        config.allowed.hardlinks = crate::Admit::Allow;
534
535        // Simulate on-disk state after extracting the two symlink entries.
536        let a = temp.path().join("a");
537        let b = a.join("b");
538        let c = b.join("c");
539        fs::create_dir_all(&c).unwrap();
540        // a/b/c/up -> ../..  (first hop: resolves to a/)
541        unix::fs::symlink("../..", c.join("up")).unwrap();
542        // a/b/escape -> c/up/../..  (second hop: resolves outside dest on disk)
543        unix::fs::symlink("c/up/../..", b.join("escape")).unwrap();
544
545        let mut tracker = HardlinkTracker::new();
546        let link = SafePath::validate(&PathBuf::from("exfil"), &dest, &config).unwrap();
547        // Target traverses through the escape symlink
548        let target = PathBuf::from("a/b/escape/../../etc/passwd");
549
550        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
551        assert_matches!(
552            result,
553            Err(ArchiveError::HardlinkEscape { .. }),
554            "hardlink through two-hop symlink chain must be rejected"
555        );
556    }
557
558    #[test]
559    #[cfg(windows)]
560    fn test_hardlink_rejects_windows_hazards_in_target() {
561        let (_temp, dest) = create_test_dest();
562        let mut config = SecurityConfig::default();
563        config.allowed.hardlinks = crate::Admit::Allow;
564        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
565
566        for target in ["dir/foo.", "dir/foo ", "dir/a:b", "sub/NUL"] {
567            let mut tracker = HardlinkTracker::new();
568            assert_matches!(
569                tracker.validate_hardlink(&link, &PathBuf::from(target), &dest, &config),
570                Err(ArchiveError::SecurityViolation { .. }),
571                "{target}"
572            );
573        }
574    }
575
576    #[test]
577    fn test_hardlink_rejects_slash_unc_target() {
578        let (_temp, dest) = create_test_dest();
579        let mut config = SecurityConfig::default();
580        config.allowed.hardlinks = crate::Admit::Allow;
581        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
582
583        assert_matches!(
584            HardlinkTracker::new().validate_hardlink(
585                &link,
586                Path::new("//host/share/x"),
587                &dest,
588                &config
589            ),
590            Err(ArchiveError::HardlinkEscape { .. })
591        );
592    }
593
594    /// Regression for GHSA-5qh5-c9fp-66jm: UNC and device-namespace targets
595    /// must be rejected as escapes before any filesystem probe. Unverified
596    /// locally; runs only in the Windows CI job.
597    #[test]
598    #[cfg(windows)]
599    fn test_hardlink_rejects_unc_and_device_targets_windows() {
600        let (_temp, dest) = create_test_dest();
601        let mut config = SecurityConfig::default();
602        config.allowed.hardlinks = crate::Admit::Allow;
603        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
604
605        for target in [
606            r"\\host\share\x",
607            "//host/share/x",
608            r"\\?\UNC\host\share\x",
609            r"\\.\UNC\host\share\x",
610            r"\??\UNC\host\share\x",
611        ] {
612            assert_matches!(
613                HardlinkTracker::new().validate_hardlink(
614                    &link,
615                    &PathBuf::from(target),
616                    &dest,
617                    &config
618                ),
619                Err(ArchiveError::HardlinkEscape { .. }),
620                "{target}"
621            );
622        }
623    }
624}