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
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
544
545
546
547
548
549
550
//! Archive verification implementation.

use std::path::Path;
use std::path::PathBuf;

use crate::ExtractionError;
use crate::Result;
use crate::SecurityConfig;
use crate::inspection::list::list_archive;
use crate::inspection::manifest::ArchiveEntry;
use crate::inspection::manifest::ManifestEntryType;
use crate::inspection::report::CheckStatus;
use crate::inspection::report::IssueCategory;
use crate::inspection::report::IssueSeverity;
use crate::inspection::report::VerificationIssue;
use crate::inspection::report::VerificationReport;
use crate::inspection::report::VerificationStatus;
use crate::security::path::validate_path;
use crate::security::permissions::sanitize_permissions;
use crate::security::quota::QuotaTracker;
use crate::security::symlink::validate_symlink;
use crate::security::zipbomb::validate_compression_ratio;
use crate::types::DestDir;
use crate::types::EntryType;

/// Verifies archive integrity and security without extracting.
///
/// Performs comprehensive validation:
/// - Integrity checks (structure, checksums)
/// - Security checks (path traversal, zip bombs, CVEs)
/// - Policy checks (file types, permissions)
///
/// # Arguments
///
/// * `archive_path` - Path to archive file
/// * `config` - Security configuration for validation
///
/// # Errors
///
/// Returns error if:
/// - Archive file cannot be opened
/// - Archive is severely corrupted (cannot read structure)
///
/// Security violations are reported in `VerificationReport.issues`,
/// not as errors.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::VerificationStatus;
/// use exarch_core::verify_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let report = verify_archive("archive.tar.gz", &config)?;
///
/// if report.status == VerificationStatus::Pass {
///     println!("Archive is safe to extract");
/// } else {
///     eprintln!("Security issues found:");
///     for issue in report.issues {
///         eprintln!("  [{}] {}", issue.severity, issue.message);
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub fn verify_archive<P: AsRef<Path>>(
    archive_path: P,
    config: &SecurityConfig,
) -> Result<VerificationReport> {
    let archive_path = archive_path.as_ref();

    // List archive to get all entries
    let manifest = list_archive(archive_path, config)?;

    // Collect security issues
    let mut issues = Vec::new();
    let mut suspicious_entries = 0;

    // Use temporary destination for validation
    let temp_dir = std::env::temp_dir().join("exarch-verify");
    std::fs::create_dir_all(&temp_dir)?;
    let temp_dest = DestDir::new(temp_dir)?;

    // Track quota during verification
    let mut quota_tracker = QuotaTracker::new();

    for entry in &manifest.entries {
        // Validate entry and collect issues
        let entry_issues = verify_entry(entry, config, &temp_dest, &mut quota_tracker);

        if !entry_issues.is_empty() {
            suspicious_entries += 1;
            issues.extend(entry_issues);
        }

        // Add heuristic checks
        let heuristic_issues = check_heuristics(entry);
        issues.extend(heuristic_issues);
    }

    // Sort issues by severity (critical first)
    issues.sort_by(|a, b| a.severity.cmp(&b.severity).reverse());

    // Determine overall status
    let status = determine_status(&issues);
    let security_status = determine_security_status(&issues);

    Ok(VerificationReport {
        status,
        integrity_status: CheckStatus::Pass,
        security_status,
        issues,
        total_entries: manifest.total_entries,
        suspicious_entries,
        total_size: manifest.total_size,
        format: manifest.format,
    })
}

fn verify_entry(
    entry: &ArchiveEntry,
    config: &SecurityConfig,
    dest: &DestDir,
    quota_tracker: &mut QuotaTracker,
) -> Vec<VerificationIssue> {
    let mut issues = Vec::new();

    // Convert ManifestEntryType to EntryType
    let entry_type = match entry.entry_type {
        ManifestEntryType::File => EntryType::File,
        ManifestEntryType::Directory => EntryType::Directory,
        ManifestEntryType::Symlink => EntryType::Symlink {
            target: entry.symlink_target.clone().unwrap_or_default(),
        },
        ManifestEntryType::Hardlink => EntryType::Hardlink {
            target: entry.hardlink_target.clone().unwrap_or_default(),
        },
    };

    // Path validation
    if let Err(e) = validate_path(&entry.path, dest, config) {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    // Quota validation using record_file (combines all checks)
    if let Err(e) = quota_tracker.record_file(entry.size, config) {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    // Compression ratio validation (zip bomb detection)
    if let Some(compressed_size) = entry.compressed_size
        && let Err(e) = validate_compression_ratio(compressed_size, entry.size, config)
    {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    // Symlink validation
    if let EntryType::Symlink { ref target } = entry_type {
        // Safe path for link
        if let Ok(safe_link_path) = validate_path(&entry.path, dest, config)
            && let Err(e) = validate_symlink(&safe_link_path, target, dest, config)
        {
            issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
        }
    }

    // Hardlink validation (similar to symlink)
    if let EntryType::Hardlink { ref target } = entry_type
        && let Ok(safe_link_path) = validate_path(&entry.path, dest, config)
        && let Err(e) = validate_path(target, dest, config)
    {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Critical,
            category: IssueCategory::HardlinkEscape,
            entry_path: Some(entry.path.clone()),
            message: format!(
                "Hardlink target escapes destination: {} -> {}",
                safe_link_path.as_path().display(),
                target.display()
            ),
            context: Some(e.to_string()),
        });
    }

    // Permission validation
    if let Some(mode) = entry.mode
        && let Err(e) = check_permissions(mode, config)
    {
        issues.push(VerificationIssue::from_error(&e, Some(entry.path.clone())));
    }

    issues
}

fn check_permissions(mode: u32, config: &SecurityConfig) -> Result<()> {
    // Use a dummy path for permission validation
    let dummy_path = Path::new("");
    let sanitized = sanitize_permissions(dummy_path, mode, config)?;
    if sanitized == mode {
        Ok(())
    } else {
        Err(ExtractionError::InvalidPermissions {
            path: PathBuf::new(),
            mode,
        })
    }
}

fn check_heuristics(entry: &ArchiveEntry) -> Vec<VerificationIssue> {
    let mut issues = Vec::new();

    // Executable file detection
    if let Some(mode) = entry.mode
        && mode & 0o111 != 0
        && entry.entry_type == ManifestEntryType::File
    {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Low,
            category: IssueCategory::ExecutableFile,
            entry_path: Some(entry.path.clone()),
            message: format!("Executable file: {}", entry.path.display()),
            context: Some(format!("mode: {mode:#o}")),
        });
    }

    // Suspicious extension detection
    if is_suspicious_extension(&entry.path) {
        issues.push(VerificationIssue {
            severity: IssueSeverity::Info,
            category: IssueCategory::SuspiciousPath,
            entry_path: Some(entry.path.clone()),
            message: format!("Suspicious extension: {}", entry.path.display()),
            context: None,
        });
    }

    issues
}

fn is_suspicious_extension(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|s| s.to_str()),
        Some("exe" | "dll" | "sh" | "bat" | "cmd")
    )
}

fn determine_status(issues: &[VerificationIssue]) -> VerificationStatus {
    let has_critical = issues.iter().any(|i| i.severity == IssueSeverity::Critical);
    let has_high = issues.iter().any(|i| i.severity == IssueSeverity::High);
    let has_medium = issues.iter().any(|i| i.severity == IssueSeverity::Medium);

    if has_critical || has_high {
        VerificationStatus::Fail
    } else if has_medium {
        VerificationStatus::Warning
    } else {
        VerificationStatus::Pass
    }
}

fn determine_security_status(issues: &[VerificationIssue]) -> CheckStatus {
    let security_issues: Vec<_> = issues
        .iter()
        .filter(|i| {
            matches!(
                i.category,
                IssueCategory::PathTraversal
                    | IssueCategory::SymlinkEscape
                    | IssueCategory::HardlinkEscape
                    | IssueCategory::ZipBomb
                    | IssueCategory::InvalidPermissions
                    | IssueCategory::QuotaExceeded
            )
        })
        .collect();

    if security_issues.is_empty() {
        CheckStatus::Pass
    } else {
        let has_critical = security_issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Critical || i.severity == IssueSeverity::High);

        if has_critical {
            CheckStatus::Fail
        } else {
            CheckStatus::Warning
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_determine_status_pass() {
        let issues = vec![];
        assert_eq!(determine_status(&issues), VerificationStatus::Pass);
    }

    #[test]
    fn test_determine_status_fail_critical() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::Critical,
            category: IssueCategory::PathTraversal,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Fail);
    }

    #[test]
    fn test_determine_status_fail_high() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::High,
            category: IssueCategory::QuotaExceeded,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Fail);
    }

    #[test]
    fn test_determine_status_warning() {
        let issues = vec![VerificationIssue {
            severity: IssueSeverity::Medium,
            category: IssueCategory::InvalidPermissions,
            entry_path: None,
            message: "Test".to_string(),
            context: None,
        }];
        assert_eq!(determine_status(&issues), VerificationStatus::Warning);
    }

    #[test]
    fn test_is_suspicious_extension() {
        assert!(is_suspicious_extension(Path::new("file.exe")));
        assert!(is_suspicious_extension(Path::new("file.dll")));
        assert!(is_suspicious_extension(Path::new("file.sh")));
        assert!(is_suspicious_extension(Path::new("file.bat")));
        assert!(!is_suspicious_extension(Path::new("file.txt")));
        assert!(!is_suspicious_extension(Path::new("file.rs")));
    }

    #[test]
    fn test_check_heuristics_executable() {
        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from("test.sh"),
            entry_type: ManifestEntryType::File,
            size: 100,
            compressed_size: None,
            mode: Some(0o755),
            modified: None,
            symlink_target: None,
            hardlink_target: None,
        };

        let issues = check_heuristics(&entry);
        assert!(!issues.is_empty());
        assert!(
            issues
                .iter()
                .any(|i| i.category == IssueCategory::ExecutableFile)
        );
    }

    #[test]
    fn test_check_heuristics_suspicious_extension() {
        let entry = crate::inspection::manifest::ArchiveEntry {
            path: PathBuf::from("malware.exe"),
            entry_type: ManifestEntryType::File,
            size: 100,
            compressed_size: None,
            mode: Some(0o644),
            modified: None,
            symlink_target: None,
            hardlink_target: None,
        };

        let issues = check_heuristics(&entry);
        assert!(!issues.is_empty());
        assert!(
            issues
                .iter()
                .any(|i| i.category == IssueCategory::SuspiciousPath)
        );
    }

    #[test]
    fn test_verify_archive_safe() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = b"safe file content";
        let mut header = tar::Header::new_gnu();
        header.set_path("safe/file.txt").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o644);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert_eq!(
            report.status,
            VerificationStatus::Pass,
            "Safe archive should pass verification"
        );
        assert_eq!(report.total_entries, 1);
        assert_eq!(report.suspicious_entries, 0);
        assert!(
            report.issues.is_empty(),
            "Safe archive should have no issues"
        );
    }

    // Note: Full CVE regression tests for path traversal require real malicious
    // archives that cannot be created using the tar crate (it validates paths).
    // Those tests should be added in tests/cve/ directory with pre-built malicious
    // fixtures. This test verifies the workflow works with archives that tar
    // crate accepts.

    #[test]
    fn test_verify_archive_symlink_escape() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let mut header = tar::Header::new_gnu();
        header.set_path("evil_link").unwrap();
        header.set_size(0);
        header.set_mode(0o777);
        header.set_entry_type(tar::EntryType::Symlink);
        header.set_link_name("/etc/passwd").unwrap();
        header.set_cksum();
        builder.append(&header, &[][..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        // Default config blocks ALL symlinks, so check that the issue is detected
        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert_eq!(
            report.status,
            VerificationStatus::Fail,
            "Symlink should fail verification with default config"
        );
        assert_eq!(report.total_entries, 1);
        assert_eq!(report.suspicious_entries, 1);
        assert!(!report.issues.is_empty(), "Should detect symlink");

        // Symlink is blocked by default config (SecurityViolation -> SuspiciousPath
        // category)
        let has_symlink_issue = report.issues.iter().any(|i| {
            matches!(i.category, IssueCategory::SuspiciousPath) && i.message.contains("symlink")
        });

        assert!(
            has_symlink_issue,
            "Should have symlink-related issue, got: {:?}",
            report.issues
        );
    }

    #[test]
    fn test_verify_archive_setuid_binary() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = b"fake binary";
        let mut header = tar::Header::new_gnu();
        header.set_path("bin/setuid_prog").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o4755);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert!(
            !report.issues.is_empty(),
            "Should detect setuid permission issue"
        );
        assert!(
            report
                .issues
                .iter()
                .any(|i| i.category == IssueCategory::InvalidPermissions),
            "Should have InvalidPermissions issue for setuid"
        );
    }

    #[test]
    fn test_verify_archive_executable_file() {
        let mut temp_file = NamedTempFile::with_suffix(".tar").unwrap();
        let mut builder = tar::Builder::new(Vec::new());

        let data = b"#!/bin/bash\necho 'hello'";
        let mut header = tar::Header::new_gnu();
        header.set_path("script.sh").unwrap();
        header.set_size(data.len() as u64);
        header.set_mode(0o755);
        header.set_cksum();
        builder.append(&header, &data[..]).unwrap();

        let archive_data = builder.into_inner().unwrap();
        temp_file.write_all(&archive_data).unwrap();
        temp_file.flush().unwrap();

        let config = SecurityConfig::default();
        let report = verify_archive(temp_file.path(), &config).unwrap();

        assert!(!report.issues.is_empty(), "Should detect executable file");
        assert!(
            report
                .issues
                .iter()
                .any(|i| i.category == IssueCategory::ExecutableFile),
            "Should have ExecutableFile issue"
        );
        assert!(
            report
                .issues
                .iter()
                .any(|i| i.category == IssueCategory::SuspiciousPath),
            "Should have SuspiciousPath issue for .sh extension"
        );
    }
}