safe_unzip 0.1.6

Secure zip extraction. Prevents Zip Slip and Zip Bombs.
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
//! safe_unzip CLI - Secure archive extraction
//!
//! # Examples
//!
//! ```bash
//! # Simple extraction
//! safe_unzip archive.zip -d /tmp/out
//!
//! # With limits
//! safe_unzip archive.zip -d /tmp/out --max-size 100M --max-files 1000
//!
//! # Filter by pattern
//! safe_unzip archive.zip -d /tmp/out --include "**/*.py" --exclude "**/test_*"
//!
//! # Extract specific files
//! safe_unzip archive.zip -d /tmp/out --only README.md --only LICENSE
//!
//! # List contents without extracting
//! safe_unzip archive.zip --list
//!
//! # Generate shell completions
//! safe_unzip --completions bash > ~/.bash_completion.d/safe_unzip
//! safe_unzip --completions zsh > ~/.zfunc/_safe_unzip
//! safe_unzip --completions fish > ~/.config/fish/completions/safe_unzip.fish
//! ```

use clap::{CommandFactory, Parser, ValueEnum};
use clap_complete::{generate, Shell};
use safe_unzip::{
    Driver, Error, ExtractionMode, Extractor, Limits, OverwritePolicy, SymlinkPolicy,
};
use std::io;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[derive(Parser)]
#[command(
    name = "safe_unzip",
    about = "Secure archive extraction - prevents Zip Slip and Zip Bombs",
    version,
    after_help = "EXAMPLES:
    safe_unzip archive.zip -d /tmp/out
    safe_unzip archive.tar.gz -d /tmp/out --max-size 100M
    safe_unzip archive.zip -d /tmp/out --include '**/*.py'
    safe_unzip archive.zip --list"
)]
struct Cli {
    /// Archive file to extract (ZIP, TAR, TAR.GZ)
    #[arg(required_unless_present = "completions")]
    archive: Option<PathBuf>,

    /// Destination directory (created if missing)
    #[arg(short, long, default_value = ".")]
    dest: PathBuf,

    /// List contents without extracting
    #[arg(short, long)]
    list: bool,

    /// Verify archive integrity (CRC32 check) without extracting
    #[arg(long)]
    verify: bool,

    /// Generate shell completions for the specified shell
    #[arg(long, value_enum)]
    completions: Option<Shell>,

    /// Maximum total size to extract (e.g., 100M, 1G)
    #[arg(long, value_parser = parse_size)]
    max_size: Option<u64>,

    /// Maximum number of files to extract
    #[arg(long)]
    max_files: Option<usize>,

    /// Maximum size of a single file (e.g., 50M)
    #[arg(long, value_parser = parse_size)]
    max_single_file: Option<u64>,

    /// Maximum directory depth
    #[arg(long)]
    max_depth: Option<usize>,

    /// Extract only files matching glob patterns (can be repeated)
    #[arg(long = "include", value_name = "PATTERN")]
    include_patterns: Vec<String>,

    /// Exclude files matching glob patterns (can be repeated)
    #[arg(long = "exclude", value_name = "PATTERN")]
    exclude_patterns: Vec<String>,

    /// Extract only specific files by name (can be repeated)
    #[arg(long = "only", value_name = "FILE")]
    only_files: Vec<String>,

    /// What to do if file already exists
    #[arg(long, value_enum, default_value_t = OverwriteMode::Error)]
    overwrite: OverwriteMode,

    /// What to do with symlinks
    #[arg(long, value_enum, default_value_t = SymlinkMode::Skip)]
    symlinks: SymlinkMode,

    /// Validate all entries before extracting
    #[arg(long)]
    validate_first: bool,

    /// Quiet mode - only show errors
    #[arg(short, long)]
    quiet: bool,

    /// Verbose mode - show each file extracted
    #[arg(short, long)]
    verbose: bool,
}

#[derive(Clone, Copy, ValueEnum)]
enum OverwriteMode {
    /// Error if file exists
    Error,
    /// Skip existing files
    Skip,
    /// Overwrite existing files
    Overwrite,
}

#[derive(Clone, Copy, ValueEnum)]
enum SymlinkMode {
    /// Skip symlinks silently
    Skip,
    /// Error if archive contains symlinks
    Error,
}

fn parse_size(s: &str) -> Result<u64, String> {
    let s = s.trim().to_uppercase();
    let (num, multiplier) = if s.ends_with("G") || s.ends_with("GB") {
        let num_str = s.trim_end_matches("GB").trim_end_matches('G');
        (num_str, 1024 * 1024 * 1024)
    } else if s.ends_with("M") || s.ends_with("MB") {
        let num_str = s.trim_end_matches("MB").trim_end_matches('M');
        (num_str, 1024 * 1024)
    } else if s.ends_with("K") || s.ends_with("KB") {
        let num_str = s.trim_end_matches("KB").trim_end_matches('K');
        (num_str, 1024)
    } else {
        (s.as_str(), 1)
    };

    num.parse::<u64>()
        .map(|n| n * multiplier)
        .map_err(|_| format!("Invalid size: {}", s))
}

fn detect_format(path: &Path) -> ArchiveFormat {
    let name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("")
        .to_lowercase();

    if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
        ArchiveFormat::TarGz
    } else if name.ends_with(".tar") {
        ArchiveFormat::Tar
    } else if name.ends_with(".7z") {
        ArchiveFormat::SevenZ
    } else {
        ArchiveFormat::Zip
    }
}

enum ArchiveFormat {
    Zip,
    Tar,
    TarGz,
    SevenZ,
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    // Handle completions generation
    if let Some(shell) = cli.completions {
        generate(shell, &mut Cli::command(), "safe_unzip", &mut io::stdout());
        return ExitCode::SUCCESS;
    }

    if let Err(e) = run(cli) {
        eprintln!("Error: {}", format_error(&e));
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

fn run(cli: Cli) -> Result<(), Error> {
    let archive = cli.archive.as_ref().expect("archive is required");
    let format = detect_format(archive);

    // List mode
    if cli.list {
        return list_archive(archive, format, cli.quiet);
    }

    // Verify mode
    if cli.verify {
        return verify_archive(archive, format, cli.quiet);
    }

    // Extract mode
    let limits = Limits {
        max_total_bytes: cli.max_size.unwrap_or(Limits::default().max_total_bytes),
        max_file_count: cli.max_files.unwrap_or(Limits::default().max_file_count),
        max_single_file: cli
            .max_single_file
            .unwrap_or(Limits::default().max_single_file),
        max_path_depth: cli.max_depth.unwrap_or(Limits::default().max_path_depth),
    };

    let overwrite = match cli.overwrite {
        OverwriteMode::Error => OverwritePolicy::Error,
        OverwriteMode::Skip => OverwritePolicy::Skip,
        OverwriteMode::Overwrite => OverwritePolicy::Overwrite,
    };

    let symlinks = match cli.symlinks {
        SymlinkMode::Skip => SymlinkPolicy::Skip,
        SymlinkMode::Error => SymlinkPolicy::Error,
    };

    let mode = if cli.validate_first {
        ExtractionMode::ValidateFirst
    } else {
        ExtractionMode::Streaming
    };

    // Build extractor based on format
    match format {
        ArchiveFormat::Zip => extract_zip(&cli, archive, limits, overwrite, symlinks, mode),
        ArchiveFormat::Tar | ArchiveFormat::TarGz => {
            extract_tar(&cli, archive, format, limits, overwrite, symlinks, mode)
        }
        ArchiveFormat::SevenZ => {
            eprintln!("Error: 7z support requires --features sevenz");
            Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "7z not supported in this build",
            )))
        }
    }
}

fn extract_zip(
    cli: &Cli,
    archive: &Path,
    limits: Limits,
    overwrite: OverwritePolicy,
    symlinks: SymlinkPolicy,
    mode: ExtractionMode,
) -> Result<(), Error> {
    let mut extractor = Extractor::new_or_create(&cli.dest)?
        .limits(limits)
        .overwrite(overwrite)
        .symlinks(symlinks)
        .mode(mode);

    // Apply filters
    if !cli.only_files.is_empty() {
        extractor = extractor.only(&cli.only_files);
    }
    if !cli.include_patterns.is_empty() {
        extractor = extractor.include_glob(&cli.include_patterns);
    }
    if !cli.exclude_patterns.is_empty() {
        extractor = extractor.exclude_glob(&cli.exclude_patterns);
    }

    // Add progress callback if verbose
    if cli.verbose {
        extractor = extractor.on_progress(|p| {
            println!(
                "[{}/{}] {}",
                p.entry_index + 1,
                p.total_entries,
                p.entry_name
            );
        });
    }

    let report = extractor.extract_file(archive)?;

    if !cli.quiet {
        println!(
            "Extracted {} files ({} bytes) to {}",
            report.files_extracted,
            format_bytes(report.bytes_written),
            cli.dest.display()
        );
        if report.entries_skipped > 0 {
            println!("Skipped {} entries", report.entries_skipped);
        }
    }

    Ok(())
}

fn extract_tar(
    cli: &Cli,
    archive: &Path,
    format: ArchiveFormat,
    limits: Limits,
    overwrite: OverwritePolicy,
    symlinks: SymlinkPolicy,
    mode: ExtractionMode,
) -> Result<(), Error> {
    let overwrite_mode = match overwrite {
        OverwritePolicy::Error => safe_unzip::OverwriteMode::Error,
        OverwritePolicy::Skip => safe_unzip::OverwriteMode::Skip,
        OverwritePolicy::Overwrite => safe_unzip::OverwriteMode::Overwrite,
    };

    let symlink_behavior = match symlinks {
        SymlinkPolicy::Skip => safe_unzip::SymlinkBehavior::Skip,
        SymlinkPolicy::Error => safe_unzip::SymlinkBehavior::Error,
    };

    let validation = match mode {
        ExtractionMode::Streaming => safe_unzip::ValidationMode::Streaming,
        ExtractionMode::ValidateFirst => safe_unzip::ValidationMode::ValidateFirst,
    };

    let mut driver = Driver::new_or_create(&cli.dest)?
        .limits(limits)
        .overwrite(overwrite_mode)
        .symlinks(symlink_behavior)
        .validation(validation);

    // Apply filters
    if !cli.only_files.is_empty() {
        driver = driver.only(&cli.only_files);
    }
    if !cli.include_patterns.is_empty() {
        driver = driver.include_glob(&cli.include_patterns);
    }
    if !cli.exclude_patterns.is_empty() {
        driver = driver.exclude_glob(&cli.exclude_patterns);
    }

    let report = match format {
        ArchiveFormat::Tar => driver.extract_tar_file(archive)?,
        ArchiveFormat::TarGz => driver.extract_tar_gz_file(archive)?,
        _ => unreachable!(),
    };

    if !cli.quiet {
        println!(
            "Extracted {} files ({} bytes) to {}",
            report.files_extracted,
            format_bytes(report.bytes_written),
            cli.dest.display()
        );
        if report.entries_skipped > 0 {
            println!("Skipped {} entries", report.entries_skipped);
        }
    }

    Ok(())
}

fn list_archive(path: &Path, format: ArchiveFormat, quiet: bool) -> Result<(), Error> {
    match format {
        ArchiveFormat::Zip => {
            let entries = safe_unzip::list_zip_entries(path)?;

            if !quiet {
                println!("{} entries in {}:", entries.len(), path.display());
                println!();
            }

            let mut total_size = 0u64;
            for entry in &entries {
                let kind = match entry.kind {
                    safe_unzip::EntryKind::File => "",
                    safe_unzip::EntryKind::Directory => "/",
                    safe_unzip::EntryKind::Symlink { .. } => " -> [symlink]",
                };
                println!("{:>10}  {}{}", format_bytes(entry.size), entry.name, kind);
                total_size += entry.size;
            }

            if !quiet {
                println!();
                println!(
                    "Total: {} files, {}",
                    entries.len(),
                    format_bytes(total_size)
                );
            }
        }
        ArchiveFormat::Tar | ArchiveFormat::TarGz => {
            let entries = if matches!(format, ArchiveFormat::TarGz) {
                safe_unzip::list_tar_gz_entries(path)?
            } else {
                safe_unzip::list_tar_entries(path)?
            };

            if !quiet {
                println!("{} entries in {}:", entries.len(), path.display());
                println!();
            }

            let mut total_size = 0u64;
            for entry in &entries {
                let kind = match entry.kind {
                    safe_unzip::EntryKind::File => "",
                    safe_unzip::EntryKind::Directory => "/",
                    safe_unzip::EntryKind::Symlink { .. } => " -> [symlink]",
                };
                println!("{:>10}  {}{}", format_bytes(entry.size), entry.name, kind);
                total_size += entry.size;
            }

            if !quiet {
                println!();
                println!(
                    "Total: {} files, {}",
                    entries.len(),
                    format_bytes(total_size)
                );
            }
        }
        ArchiveFormat::SevenZ => {
            eprintln!("Error: 7z listing requires --features sevenz");
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "7z not supported in this build",
            )));
        }
    }

    Ok(())
}

fn verify_archive(path: &Path, format: ArchiveFormat, quiet: bool) -> Result<(), Error> {
    if !quiet {
        println!("Verifying {}...", path.display());
    }

    match format {
        ArchiveFormat::Zip => {
            let report = safe_unzip::verify_file(path)?;

            if !quiet {
                println!(
                    "✓ Verified {} entries ({})",
                    report.entries_verified,
                    format_bytes(report.bytes_verified)
                );
            }
        }
        ArchiveFormat::Tar | ArchiveFormat::TarGz => {
            // For TAR, we can list entries (which reads them) as a basic integrity check
            let entries = if matches!(format, ArchiveFormat::TarGz) {
                safe_unzip::list_tar_gz_entries(path)?
            } else {
                safe_unzip::list_tar_entries(path)?
            };

            let total_size: u64 = entries.iter().map(|e| e.size).sum();

            if !quiet {
                println!(
                    "✓ Verified {} entries ({})",
                    entries.len(),
                    format_bytes(total_size)
                );
            }
        }
        ArchiveFormat::SevenZ => {
            eprintln!("Error: 7z verification requires --features sevenz");
            return Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "7z not supported in this build",
            )));
        }
    }

    Ok(())
}

fn format_bytes(bytes: u64) -> String {
    if bytes >= 1024 * 1024 * 1024 {
        format!("{:.1}G", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    } else if bytes >= 1024 * 1024 {
        format!("{:.1}M", bytes as f64 / (1024.0 * 1024.0))
    } else if bytes >= 1024 {
        format!("{:.1}K", bytes as f64 / 1024.0)
    } else {
        format!("{}B", bytes)
    }
}

fn format_error(e: &Error) -> String {
    match e {
        Error::PathEscape { entry, detail } => {
            format!("Path traversal blocked in '{}': {}", entry, detail)
        }
        Error::TotalSizeExceeded { limit, would_be } => {
            format!(
                "Archive too large: {} (limit: {})",
                format_bytes(*would_be),
                format_bytes(*limit)
            )
        }
        Error::FileTooLarge { entry, size, limit } => {
            format!(
                "File '{}' too large: {} (limit: {})",
                entry,
                format_bytes(*size),
                format_bytes(*limit)
            )
        }
        Error::FileCountExceeded { limit, .. } => {
            format!("Too many files (limit: {})", limit)
        }
        Error::AlreadyExists { entry } => {
            format!("File already exists: {}", entry)
        }
        Error::EncryptedEntry { entry } => {
            format!("Encrypted entry not supported: {}", entry)
        }
        _ => e.to_string(),
    }
}