strict-path 0.2.1

Secure path handling for untrusted input. Prevents directory traversal, symlink escapes, and 19+ real-world CVE attack patterns.
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
//! Proof test replicating CVE-2025-11001 (7-Zip symlink path traversal)
//!
//! ## Vulnerability Background
//!
//! CVE-2025-11001 and CVE-2025-11002 are critical vulnerabilities in 7-Zip (versions 21.02-24.09)
//! that allow path traversal via malicious symlinks in ZIP archives. The vulnerability exploits
//! flawed absolute path detection and symlink handling in 7-Zip's extraction logic.
//!
//! **Attack Vector:**
//! 1. Attacker creates a ZIP archive containing a Linux-style symlink pointing to a Windows
//!    absolute path like `C:\Users\[Username]\Desktop`
//! 2. 7-Zip misclassifies this as a relative path due to flawed path checking
//! 3. During extraction, 7-Zip creates the symlink and then follows it
//! 4. Subsequent files in the archive are written to the symlink target location
//! 5. This allows arbitrary file writes outside the extraction directory
//!
//! **Exploitation Requirements:**
//! - Windows OS (not exploitable on Linux/macOS)
//! - Elevated privileges, Developer Mode, or elevated service context (for symlink creation)
//! - Vulnerable 7-Zip version (21.02 through 24.09)
//!
//! **References:**
//! - https://github.com/pacbypass/CVE-2025-11001
//! - https://github.com/DK26/CVE-2025-11001 (forK)
//! - https://cybersecuritynews.com/poc-exploit-7-zip-vulnerabilities/
//! - https://pacbypass.github.io/2025/10/16/diffing-7zip-for-cve-2025-11001.html (detailed analysis)
//! - ZDI disclosure: October 7, 2025
//! - CVSS v3.0 Score: 7.0
//!
//! ## The Three 7-Zip Bugs (from pacbypass article)
//!
//! 1. **Issue #1 - Path Type Misclassification**: Linux symlink containing Windows absolute
//!    path `C:\Users\Desktop` is incorrectly labeled as "relative" because 7-Zip uses
//!    Linux-style path checking (`IS_PATH_SEPAR(path[0])` instead of `NName::IsAbsolutePath`)
//!
//! 2. **Issue #2 - Prepended Directory Bypass**: When symlink is in a subdirectory,
//!    7-Zip prepends the directory path before validation:
//!    `isSafePath("data/subdir/" + "C:\Users\Desktop")` incorrectly passes
//!
//! 3. **Issue #3 - Directory Check Bypass**: Final safety check has condition
//!    `if (_item.IsDir)` that only validates directory symlinks, allowing file
//!    symlinks to bypass validation entirely
//!
//! ## How strict-path Prevents This Attack
//!
//! This test demonstrates that `strict-path` prevents CVE-2025-11001 through:
//!
//! 1. **Path Boundary Validation**: All paths must be validated through `strict_join()`
//!    before any filesystem operations, rejecting escape attempts immediately
//!
//! 2. **Symlink Target Validation**: When creating symlinks via `strict_symlink()`,
//!    both the link path AND the target path are validated against the boundary
//!
//! 3. **Canonical Resolution**: Built on `soft-canonicalize`, which resolves symlinks
//!    and detects escape attempts before filesystem operations occur
//!
//! 4. **Fail-Fast Design**: Returns `Err(PathEscapesBoundary)` on escape attempts
//!    rather than silently allowing traversal
//!
//! The key insight: **If you can't create a StrictPath, you can't perform I/O**.
//! This makes the attack impossible at the API level.

// CVE-2025-11001/CVE-2025-11002 are Windows-specific vulnerabilities
// All tests in this module are Windows-only
#![cfg(windows)]

use crate::{PathBoundary, StrictPathError};
use std::path::Path;
/// Test structure mimicking the CVE-2025-11001 exploit
struct MaliciousZipStructure {
    /// Top-level directory in the archive
    top_dir: String,
    /// Symlink entry name that points outside the extraction dir
    link_name: String,
    /// Target path the symlink attempts to point to (absolute Windows path)
    symlink_target: String,
    /// File that would be written via the symlink
    payload_file: String,
}

impl MaliciousZipStructure {
    fn new_desktop_attack(username: &str) -> Self {
        Self {
            top_dir: "data".to_string(),
            link_name: "link_in".to_string(),
            symlink_target: format!("C:\\Users\\{username}\\Desktop"),
            payload_file: "malicious.exe".to_string(),
        }
    }

    fn new_system32_attack() -> Self {
        Self {
            top_dir: "data".to_string(),
            link_name: "link_in".to_string(),
            symlink_target: "C:\\Windows\\System32".to_string(),
            payload_file: "malicious.dll".to_string(),
        }
    }

    fn new_relative_traversal_attack() -> Self {
        Self {
            top_dir: "data".to_string(),
            link_name: "link_in".to_string(),
            // Attempts to traverse up and out of extraction directory
            symlink_target: "..\\..\\..\\sensitive".to_string(),
            payload_file: "payload.txt".to_string(),
        }
    }
}

/// Test replicating the exact attack pattern from pacbypass's article:
/// https://pacbypass.github.io/2025/10/16/diffing-7zip-for-cve-2025-11001.html
///
/// The vulnerability exploits three 7-Zip bugs:
/// 1. Linux symlink with Windows path `C:\` is mislabeled as "relative"
/// 2. Prepending zip directory allows bypass: `data/` + `C:\Users\Desktop` passes check
/// 3. Directory check (`_item.IsDir`) incorrectly skips validation for file symlinks
///
/// Attack structure in ZIP:
/// - data/link_in → symlink to C:\Users\TestUser\Desktop
/// - data/link_in/malicious.exe → file written through symlink
///
/// Result: malicious.exe ends up on Desktop instead of in extraction directory
#[test]
fn test_cve_2025_11001_desktop_symlink_attack_blocked() {
    let attack = MaliciousZipStructure::new_desktop_attack("TestUser");

    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    // Step 1: Attacker attempts to create top-level directory (this succeeds)
    let top_dir_path = extraction_sandbox.strict_join(&attack.top_dir).unwrap();
    top_dir_path.create_dir().unwrap();

    // Step 2: Attacker attempts to create symlink pointing to absolute Windows path
    // In the vulnerable 7-Zip, this would create a symlink to C:\Users\TestUser\Desktop
    //
    // 7-Zip BUG #1: Linux symlink with Windows path is mislabeled as "relative"
    // 7-Zip BUG #2: Prepending "data/" makes check pass: isSafePath("data/C:\Users\Desktop")
    // 7-Zip BUG #3: File symlink bypasses _item.IsDir check

    let top_dir = &attack.top_dir;
    let link_name = &attack.link_name;
    let link_path = extraction_sandbox
        .strict_join(format!("{top_dir}/{link_name}"))
        .unwrap();

    // Attempt to validate the symlink target - THIS IS WHERE strict-path BLOCKS THE ATTACK
    // strict-path does NOT mislabel absolute paths as relative
    let symlink_target_result = extraction_sandbox.strict_join(&attack.symlink_target);

    // SECURITY GUARANTEE: Absolute path to Desktop is rejected
    assert!(
        symlink_target_result.is_err(),
        "strict-path MUST reject absolute path to Desktop"
    );

    match symlink_target_result {
        Err(StrictPathError::PathEscapesBoundary { attempted_path, .. }) => {
            // Verify the error correctly identifies the escape attempt
            let path_str = attempted_path.to_string_lossy();

            // On Windows, the attempted path should reference the Desktop path
            assert!(
                path_str.contains("Users") || path_str.contains("Desktop"),
                "Error should reference the attempted Desktop path, got: {path_str}"
            );
        }
        Err(StrictPathError::PathResolutionError { .. }) => {
            // Also acceptable - path doesn't exist so resolution fails
            // This is what happens on CI where C:\Users\TestUser doesn't exist
        }
        Ok(_) => panic!("strict_join MUST NOT accept absolute path to C:\\Users"),
        Err(other) => panic!("Unexpected error variant: {other:?}"),
    }

    // Even if attacker had a StrictPath to the target (impossible via strict_join),
    // strict_symlink would validate both paths are within the same boundary
    // Demonstrate this with a safe target first - use a directory for junction compatibility
    let safe_target_dir = extraction_sandbox
        .strict_join(format!("{}/safe_target_dir", attack.top_dir))
        .unwrap();
    safe_target_dir.create_dir_all().unwrap();

    // Try creating symlink to safe target directory
    // On Windows: tries symlink first, falls back to junction if privileges unavailable
    // The key security property is that we can't create symlinks to outside paths
    match safe_target_dir.strict_symlink(link_path.interop_path()) {
        Ok(_) => {
            // Symlink created successfully - verify it exists
            assert!(link_path.exists(), "Link should exist after creation");
        }
        Err(e) if e.raw_os_error() == Some(1314) => {
            // Windows: Insufficient privileges for symlink
            // Prefer built-in junction helper (dir-only) when the feature is enabled; otherwise fall back to third-party for the test.
            link_path.create_parent_dir_all().ok();

            // Tests run with all features; fall back to built-in junction helper.
            #[cfg(feature = "junctions")]
            {
                match safe_target_dir.strict_junction(link_path.interop_path()) {
                    Ok(_) => {
                        // Best-effort verification: ensure junction is readable as a directory
                        if let Err(err) = link_path.read_dir() {
                            eprintln!("Warning: Junction created but not readable as dir: {err:?}");
                        }
                    }
                    Err(err) => {
                        eprintln!(
                            "Note: Could not create junction via built-in helper after symlink privilege error: {err:?}"
                        );
                    }
                }
            }

            #[cfg(not(feature = "junctions"))]
            {
                panic!(
                    "This test verifies the junction fallback path but the 'junctions' feature is disabled.\n\
                     Enable it with: cargo test -p strict-path --features junctions (CI/dev runs use --all-features)."
                );
            }
        }
        Err(e) => panic!("Unexpected error creating symlink: {e}"),
    }

    // Step 3: Attacker attempts to write payload through the symlink
    // In vulnerable 7-Zip, this would write to Desktop
    // With strict-path, we CANNOT create a StrictPath through a link that escapes boundary

    let top_dir = &attack.top_dir;
    let link_name = &attack.link_name;
    let payload_file = &attack.payload_file;
    let payload_through_link =
        extraction_sandbox.strict_join(format!("{top_dir}/{link_name}/{payload_file}"));

    // SECURITY GUARANTEE: Path traversal through symlink/junction is blocked
    // strict-path will either:
    // 1. Reject the path join entirely (most likely when link points outside), OR
    // 2. Allow it only if canonicalization keeps us within boundary
    match payload_through_link {
        Ok(payload_path) => {
            // If join succeeded, verify we're still within boundary
            assert!(
                payload_path.strictpath_starts_with(extraction_sandbox.interop_path()),
                "Payload path must remain within extraction boundary"
            );

            // If we got here, write is safe - we're still inside boundary
            // However, on Windows with junctions, the write itself might fail
            // due to OS-level restrictions (which is also a defense!)
            match payload_path.write(b"fake malware") {
                Ok(_) => {
                    // Write succeeded - verify Desktop wasn't touched
                    let desktop_path = Path::new(&attack.symlink_target).join(&attack.payload_file);
                    assert!(
                        !desktop_path.exists(),
                        "Desktop must remain untouched even after successful write"
                    );
                }
                Err(e) => {
                    // Write failed - this is also acceptable defense
                    eprintln!("Write blocked by OS: {e}");
                }
            }
        }
        Err(e) => {
            // Path join was rejected - this is the expected defense!
            // The link might point outside, so strict-path blocks traversal through it
            eprintln!("Attack blocked: strict_join rejected path through symlink: {e}");

            // Verify Desktop was not modified
            let desktop_path = Path::new(&attack.symlink_target).join(&attack.payload_file);
            assert!(
                !desktop_path.exists(),
                "Desktop must remain untouched - attack successfully blocked"
            );
        }
    }
}

/// Test demonstrating protection against Issue #2 from the pacbypass article:
/// 7-Zip vulnerability where prepending directory path bypasses safety check
///
/// Vulnerable 7-Zip logic:
/// ```
/// if (linkInfo.isRelative) // TRUE due to Bug #1
///     relatPath = GetDirPrefixOf(_item.Path); // "data/"
/// relatPath += linkInfo.linkPath; // "data/" + "C:\Users\Desktop"
/// if (!IsSafePath(relatPath)) // BUG: This passes!
/// ```
///
/// strict-path defense: Absolute paths are NEVER treated as relative,
/// regardless of what directory they're joined to
#[test]
fn test_cve_2025_11001_issue2_prepended_directory_bypass_blocked() {
    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    // Create nested directory structure like in the exploit
    let nested_dir = extraction_sandbox
        .strict_join("data/subdir/nested")
        .unwrap();
    nested_dir.create_dir_all().unwrap();

    // Simulate 7-Zip's vulnerable pattern: prepending directory to absolute path
    // In 7-Zip, this would become: "data/subdir/" + "C:\Users\Desktop"
    let absolute_targets = &[
        "C:\\Users\\Public\\Desktop",
        "C:\\Windows\\System32",
        "C:\\ProgramData\\sensitive.txt",
    ];

    for &target in absolute_targets {
        // Try to join from nested directory context
        let result = extraction_sandbox.strict_join(format!("data/subdir/{target}"));

        // SECURITY GUARANTEE: Prepending directory does NOT bypass validation
        // strict-path recognizes absolute paths regardless of prefix
        assert!(
            result.is_err(),
            "strict-path MUST reject absolute path even with prepended directory: {target}"
        );

        match result {
            Err(StrictPathError::PathEscapesBoundary { .. })
            | Err(StrictPathError::PathResolutionError { .. }) => {
                // Expected - absolute path detected and rejected
            }
            Ok(_) => {
                panic!("Prepended directory MUST NOT bypass absolute path detection: {target}")
            }
            Err(other) => panic!("Unexpected error for '{target}': {other:?}"),
        }
    }

    // Also test that the symlink target itself is validated independently
    // of what directory the symlink is created in
    for &target in absolute_targets {
        let target_result = extraction_sandbox.strict_join(target);

        assert!(
            target_result.is_err(),
            "Symlink target validation MUST reject absolute paths: {target}"
        );
    }
}

#[test]
fn test_cve_2025_11001_system32_attack_blocked() {
    let attack = MaliciousZipStructure::new_system32_attack();

    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    // Attempt to validate symlink target pointing to System32
    let symlink_target_result = extraction_sandbox.strict_join(&attack.symlink_target);

    // SECURITY GUARANTEE: Absolute path to System32 is rejected
    assert!(
        symlink_target_result.is_err(),
        "strict-path MUST reject absolute path to System32"
    );

    match symlink_target_result {
        Err(StrictPathError::PathEscapesBoundary { .. })
        | Err(StrictPathError::PathResolutionError { .. }) => {
            // Expected - absolute paths or non-existent paths are rejected
        }
        Ok(_) => panic!("strict_join MUST NOT accept absolute path to C:\\Windows\\System32"),
        Err(other) => panic!("Unexpected error variant: {other:?}"),
    }
}

/// Mirrors 7-Zip's forward-slash absolute path misclassification on Windows.
///
/// Some vulnerable 7-Zip versions treated `C:/...` style paths as relative on Windows
/// due to forward slash handling. Our validator must treat these as absolute and reject
/// them when they escape the boundary.
#[test]
fn test_cve_2025_11001_forward_slash_absolute_windows_paths_blocked() {
    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    // Representative absolute Windows paths using forward slashes
    let absolute_targets = vec!["C:/Windows/System32", "C:/Users/Public/Desktop"];

    for target in absolute_targets {
        let result = extraction_sandbox.strict_join(target);
        assert!(
            result.is_err(),
            "strict-path MUST reject forward-slash absolute path: {target}"
        );

        match result {
            Err(StrictPathError::PathEscapesBoundary { .. })
            | Err(StrictPathError::PathResolutionError { .. }) => {
                // Expected: treated as absolute/escaping and rejected.
            }
            Ok(p) => panic!("strict_join MUST NOT accept forward-slash absolute path: {p:?}"),
            Err(other) => panic!("Unexpected error variant: {other:?}"),
        }
    }
}

#[test]
fn test_cve_2025_11001_relative_traversal_blocked() {
    let attack = MaliciousZipStructure::new_relative_traversal_attack();

    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    // Create top-level directory
    let top_dir_path = extraction_sandbox.strict_join(&attack.top_dir).unwrap();
    top_dir_path.create_dir().unwrap();

    // Attempt to validate symlink target with relative traversal
    let symlink_target_result = extraction_sandbox.strict_join(&attack.symlink_target);

    // SECURITY GUARANTEE: Relative traversal is rejected
    assert!(
        symlink_target_result.is_err(),
        "strict-path MUST reject relative path traversal"
    );

    match symlink_target_result {
        Err(StrictPathError::PathEscapesBoundary { attempted_path, .. }) => {
            // Verify the error identifies the traversal attempt
            let path_str = attempted_path.to_string_lossy();
            assert!(
                path_str.contains("..") || path_str.contains("sensitive"),
                "Error should reference the attempted traversal: {path_str}"
            );
        }
        Err(StrictPathError::PathResolutionError { .. }) => {
            // Also acceptable - non-existent path
        }
        Ok(_) => panic!("strict_join MUST NOT accept path with parent directory components"),
        Err(other) => panic!("Unexpected error variant: {other:?}"),
    }
}

#[test]
fn test_cve_2025_11001_unc_path_attack_blocked() {
    // CVE-2025-11002 involves UNC path symlinks for network targets
    let unc_targets = vec![
        "\\\\malicious-server\\share\\payload.exe",
        "\\\\192.168.1.100\\c$\\Windows\\System32",
        "//network-share/sensitive/data.db",
    ];

    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    for unc_path in unc_targets {
        let result = extraction_sandbox.strict_join(unc_path);

        // SECURITY GUARANTEE: UNC paths are rejected
        assert!(
            result.is_err(),
            "strict-path MUST reject UNC path: {unc_path}"
        );

        match result {
            Err(StrictPathError::PathEscapesBoundary { .. })
            | Err(StrictPathError::PathResolutionError { .. }) => {
                // Expected - UNC paths are absolute and/or escape the boundary
            }
            Ok(_) => panic!("strict_join MUST NOT accept UNC path: {unc_path}"),
            Err(other) => panic!("Unexpected error for UNC path '{unc_path}': {other:?}"),
        }
    }
}

#[test]
fn test_cve_2025_11001_mixed_encoding_attack_blocked() {
    // Test URL-encoded traversal attempts (mentioned in the article)
    let encoded_attacks = vec![
        "..%2F..%2F..%2FUsers%2FPublic",
        "..%5C..%5C..%5CWindows%5CSystem32",
        "%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd", // Unix-style for completeness
    ];

    let extraction_dir = tempfile::tempdir().unwrap();
    let extraction_sandbox: PathBoundary =
        PathBoundary::try_new_create(extraction_dir.path()).unwrap();

    for encoded_path in encoded_attacks {
        let result = extraction_sandbox.strict_join(encoded_path);

        // Note: URL decoding is typically done at a higher layer (ZIP library)
        // strict-path handles the decoded path. This test verifies that even
        // if URL-encoded paths slip through, the literal strings are contained
        match result {
            Ok(validated_path) => {
                // If accepted (literal percent signs), verify containment
                assert!(
                    validated_path.strictpath_starts_with(extraction_sandbox.interop_path()),
                    "Even literal encoded string must stay within boundary"
                );
            }
            Err(StrictPathError::PathEscapesBoundary { .. })
            | Err(StrictPathError::PathResolutionError { .. }) => {
                // Also acceptable - rejected as traversal
            }
            Err(other) => panic!("Unexpected error for encoded path '{encoded_path}': {other:?}"),
        }
    }
}