exarch-core 0.2.9

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
//! Hardlink security validation and tracking.

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

use crate::ExtractionError;
use crate::Result;
use crate::SecurityConfig;
use crate::types::DestDir;
use crate::types::SafePath;
use crate::types::safe_symlink::resolve_through_symlinks;

/// Tracks hardlink targets during extraction.
///
/// Hardlinks in archives can be used for attacks:
/// 1. Link to files outside the extraction directory
/// 2. Create multiple hardlinks to the same file (resource exhaustion)
/// 3. Link to sensitive files (if absolute paths allowed)
///
/// This tracker ensures:
/// - Hardlinks are allowed in the security configuration
/// - Targets are relative paths
/// - Targets resolve within the destination directory
/// - Duplicate hardlinks are detected
///
/// # Two-Pass Validation
///
/// Hardlinks require two-pass validation:
/// 1. **First pass (during validation):** Track target paths, verify they're
///    within bounds
/// 2. **Second pass (after extraction):** Verify targets actually exist
///
/// This is necessary because hardlink targets may appear later in the archive.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::security::HardlinkTracker;
/// use exarch_core::types::DestDir;
/// use exarch_core::types::SafePath;
/// use std::path::Path;
/// use std::path::PathBuf;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let dest = DestDir::new(PathBuf::from("/tmp"))?;
/// let mut config = SecurityConfig::default();
/// config.allowed.hardlinks = true;
///
/// let mut tracker = HardlinkTracker::new();
/// let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)?;
/// let target = Path::new("target.txt");
///
/// tracker.validate_hardlink(&link, target, &dest, &config)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
pub struct HardlinkTracker {
    /// Maps target path to the first link path that referenced it
    seen_targets: HashMap<PathBuf, PathBuf>,
}

impl HardlinkTracker {
    /// Creates a new hardlink tracker.
    #[must_use]
    pub fn new() -> Self {
        Self {
            seen_targets: HashMap::new(),
        }
    }

    /// Validates that a hardlink target is safe and tracks it.
    ///
    /// # Performance
    ///
    /// Typical execution time: ~1-5 μs (`HashMap` insert + path validation)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Hardlinks are not allowed in configuration
    /// - Target is an absolute path
    /// - Target would escape the destination directory
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use exarch_core::SecurityConfig;
    /// use exarch_core::security::HardlinkTracker;
    /// use exarch_core::types::DestDir;
    /// use exarch_core::types::SafePath;
    /// use std::path::Path;
    /// use std::path::PathBuf;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dest = DestDir::new(PathBuf::from("/tmp"))?;
    /// let mut config = SecurityConfig::default();
    /// config.allowed.hardlinks = true;
    ///
    /// let mut tracker = HardlinkTracker::new();
    /// let link = SafePath::validate(&PathBuf::from("link"), &dest, &config)?;
    /// let target = Path::new("target.txt");
    ///
    /// tracker.validate_hardlink(&link, target, &dest, &config)?;
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::items_after_statements)]
    pub fn validate_hardlink(
        &mut self,
        link_path: &SafePath,
        target: &Path,
        dest: &DestDir,
        config: &SecurityConfig,
    ) -> Result<()> {
        // Check if hardlinks are allowed
        if !config.allowed.hardlinks {
            return Err(ExtractionError::SecurityViolation {
                reason: "hardlinks not allowed".into(),
            });
        }

        use std::path::Component;

        // H-SEC-2: Reject Windows-specific absolute path components in target (before
        // resolution) This prevents bypasses on Windows like C:\ or
        // \\server\share
        for component in target.components() {
            if matches!(component, Component::Prefix(_) | Component::RootDir) {
                return Err(ExtractionError::HardlinkEscape {
                    path: link_path.as_path().to_path_buf(),
                });
            }
        }

        // Also reject absolute targets (redundant with above, but keeps existing check)
        if target.is_absolute() {
            return Err(ExtractionError::HardlinkEscape {
                path: link_path.as_path().to_path_buf(),
            });
        }

        // Resolve target against destination, following any on-disk symlinks
        // encountered during traversal.
        //
        // String-based normalization is insufficient: if a previously extracted
        // symlink lies on the target path, a hardlink target can escape the
        // extraction root via on-disk resolution even though string normalization
        // would pass (two-hop chain bypass, GHSA-83g3-92jg-28cx variant — #116).
        let resolved =
            resolve_through_symlinks(dest.as_path(), target, dest.as_path(), link_path.as_path())
                .map_err(|_| ExtractionError::HardlinkEscape {
                path: link_path.as_path().to_path_buf(),
            })?;

        // Track this hardlink target (H-PERF-6: use entry API)
        self.seen_targets
            .entry(resolved)
            .or_insert_with(|| link_path.as_path().to_path_buf());

        Ok(())
    }

    /// Returns the number of tracked hardlinks.
    #[inline]
    #[must_use]
    pub fn count(&self) -> usize {
        self.seen_targets.len()
    }

    /// Checks if a target path has been seen before.
    #[must_use]
    pub fn has_target(&self, target: &Path) -> bool {
        self.seen_targets.contains_key(target)
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_dest() -> (TempDir, DestDir) {
        let temp = TempDir::new().expect("failed to create temp dir");
        let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
        (temp, dest)
    }

    #[test]
    fn test_hardlink_tracker_new() {
        let tracker = HardlinkTracker::new();
        assert_eq!(tracker.count(), 0);
    }

    #[test]
    fn test_validate_hardlink_allowed() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
        let target = PathBuf::from("target.txt");

        assert!(
            tracker
                .validate_hardlink(&link, &target, &dest, &config)
                .is_ok()
        );
        assert_eq!(tracker.count(), 1);
    }

    #[test]
    fn test_validate_hardlink_disabled() {
        let (_temp, dest) = create_test_dest();
        let config = SecurityConfig::default(); // hardlinks disabled by default

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
        let target = PathBuf::from("target.txt");

        assert!(
            tracker
                .validate_hardlink(&link, &target, &dest, &config)
                .is_err()
        );
    }

    #[test]
    fn test_validate_hardlink_absolute_target() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
        let target = PathBuf::from("/etc/passwd");

        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
        assert!(matches!(
            result,
            Err(ExtractionError::HardlinkEscape { .. })
        ));
    }

    #[test]
    fn test_validate_hardlink_escape() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
        let target = PathBuf::from("../../etc/passwd");

        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
        assert!(matches!(
            result,
            Err(ExtractionError::HardlinkEscape { .. })
        ));
    }

    #[test]
    fn test_hardlink_tracker_multiple() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();

        let link1 = SafePath::validate(&PathBuf::from("link1"), &dest, &config).unwrap();
        let link2 = SafePath::validate(&PathBuf::from("link2"), &dest, &config).unwrap();

        tracker
            .validate_hardlink(&link1, &PathBuf::from("target1.txt"), &dest, &config)
            .unwrap();
        tracker
            .validate_hardlink(&link2, &PathBuf::from("target2.txt"), &dest, &config)
            .unwrap();

        assert_eq!(tracker.count(), 2);
    }

    #[test]
    fn test_hardlink_tracker_has_target() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("link"), &dest, &config).unwrap();
        let target = PathBuf::from("target.txt");

        tracker
            .validate_hardlink(&link, &target, &dest, &config)
            .unwrap();

        let resolved_target = dest.as_path().join(&target);
        assert!(tracker.has_target(&resolved_target));
    }

    #[test]
    fn test_hardlink_tracker_relative_safe() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("foo/link"), &dest, &config).unwrap();
        // Safe relative path within destination
        let target = PathBuf::from("target.txt");

        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
        assert!(result.is_ok());
    }

    // H-TEST-2: Duplicate hardlink to same target test
    #[test]
    fn test_duplicate_hardlink_to_same_target() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();
        let target = PathBuf::from("target.txt");

        // Create multiple hardlinks to the same target
        for i in 0..3 {
            let link =
                SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config).unwrap();

            let result = tracker.validate_hardlink(&link, &target, &dest, &config);
            assert!(
                result.is_ok(),
                "multiple hardlinks to same target should be allowed"
            );
        }

        // All three links point to the same target, so only 1 unique target tracked
        assert_eq!(
            tracker.count(),
            1,
            "should track unique targets, not individual links"
        );
    }

    #[test]
    fn test_hardlink_different_targets() {
        let (_temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        let mut tracker = HardlinkTracker::new();

        // Create hardlinks to different targets
        for i in 0..3 {
            let link =
                SafePath::validate(&PathBuf::from(format!("link{i}")), &dest, &config).unwrap();
            let target = PathBuf::from(format!("target{i}.txt"));

            tracker
                .validate_hardlink(&link, &target, &dest, &config)
                .unwrap();
        }

        // Three different targets
        assert_eq!(tracker.count(), 3, "should track each unique target");
    }

    /// Hardlink target that traverses through an already-extracted symlink must
    /// be rejected (two-hop chain, GHSA-83g3-92jg-28cx variant — issue #116).
    ///
    /// Entry 2 (symlink a/b/c/up -> ../..) is on disk when hardlink is
    /// validated. Target a/b/escape/../../etc/passwd: string normalization
    /// → dest/a/etc/passwd (looks safe), but if a/b/escape is an on-disk
    /// symlink resolving outside dest, the hardlink must be rejected.
    #[test]
    #[cfg(unix)]
    #[allow(clippy::unwrap_used)]
    fn test_hardlink_two_hop_chain_rejected() {
        use std::fs;
        use std::os::unix;

        let (temp, dest) = create_test_dest();
        let mut config = SecurityConfig::default();
        config.allowed.hardlinks = true;

        // Simulate on-disk state after extracting the two symlink entries.
        let a = temp.path().join("a");
        let b = a.join("b");
        let c = b.join("c");
        fs::create_dir_all(&c).unwrap();
        // a/b/c/up -> ../..  (first hop: resolves to a/)
        unix::fs::symlink("../..", c.join("up")).unwrap();
        // a/b/escape -> c/up/../..  (second hop: resolves outside dest on disk)
        unix::fs::symlink("c/up/../..", b.join("escape")).unwrap();

        let mut tracker = HardlinkTracker::new();
        let link = SafePath::validate(&PathBuf::from("exfil"), &dest, &config).unwrap();
        // Target traverses through the escape symlink
        let target = PathBuf::from("a/b/escape/../../etc/passwd");

        let result = tracker.validate_hardlink(&link, &target, &dest, &config);
        assert!(
            matches!(result, Err(ExtractionError::HardlinkEscape { .. })),
            "hardlink through two-hop symlink chain must be rejected"
        );
    }
}