Inspecting PowerShell for Dangerous Paths and Oversized Extractions Before Expanding ZIP Files

PowerShellカテゴリを表すパンダのイラスト PowerShell

About This Article
This article was created using an automated generation workflow powered by generative AI. Based on official .NET ZipArchive and ZipArchiveEntry APIs, it is structured as a preflight check to inspect paths extending outside the destination and excessively large extraction sizes before actually expanding the ZIP file.

Verification Status: 📘 Microsoft Official Specification Confirmed, Execution Unverified

Simply listing the contents without expanding the ZIP file is useful, but proceeding to automated processing requires an extra step.

Determining whether it is safe to expand the ZIP file to a specified folder beforehandmakes it easier to prevent unexpected paths and oversized extractions.

First, Open the Target for Inspection

$zipPath = 'C:Tempsample.zip'
$extractRoot = 'C:Tempextract'

$archive = [IO.Compression.ZipFile]::OpenRead($zipPath)

No extraction takes place here yet.

1. Verify That Paths Do Not Extend Outside the Destination

If a ZIP entry name contains .., a simple path combination may point outside the intended destination directory.

For each entry, calculate what the absolute path would be if it were actually expanded.

$rootFull = [IO.Path]::GetFullPath($extractRoot)
$rootPrefix = $rootFull.TrimEnd(
    [IO.Path]::DirectorySeparatorChar,
    [IO.Path]::AltDirectorySeparatorChar
) + [IO.Path]::DirectorySeparatorChar

foreach ($entry in $archive.Entries) {

    $dest = [IO.Path]::GetFullPath(
        [IO.Path]::Combine($rootFull, $entry.FullName)
    )

    if (-not $dest.StartsWith(
        $rootPrefix,
        [StringComparison]::OrdinalIgnoreCase
    )) {
        "BLOCK: $($entry.FullName)"
    }
}

The goal is not merely to check whether .. exists as a string, but rather to verify whether the normalized absolute path remains within the extraction rootwhether the normalized absolute path remains within the extraction root.

2. Check the Total Post-Extraction Size

Even if the compressed file itself is small, it can become extremely large after extraction.

$totalUncompressed = (
    $archive.Entries |
    Measure-Object -Property Length -Sum
).Sum

"Total uncompressed: $totalUncompressed bytes"

For example, if business rules dictate a limit of 100 MB, automated extraction can be halted the moment that upper limit is exceeded.

3. Impose Limits on the Number of Files

$count = $archive.Entries.Count

if ($count -gt 1000) {
    "BLOCK: too many entries ($count)"
}

In addition to the total size, you can also check whether the archive contains an excessively large number of files.

4. Allow Only Expected Extensions

For CSV ingestion processing, you can establish rules to permit only CSV and README files, for example.

$allowed = '.csv', '.txt'

foreach ($entry in $archive.Entries) {

    if ([string]::IsNullOrEmpty($entry.Name)) {
        continue  # ディレクトリエントリ
    }

    $ext = [IO.Path]::GetExtension($entry.Name).ToLowerInvariant()

    if ($ext -notin $allowed) {
        "REVIEW: unexpected extension $ext : $($entry.FullName)"
    }
}

Preflight Check Workflow

flowchart TD
A[ZIPをOpenRead] --> B[パス正規化]
B --> C{展開先配下か}
C -- No --> X[BLOCK]
C -- Yes --> D[合計サイズ]
D --> E[ファイル数]
E --> F[拡張子/命名規則]
F --> G[人または後続処理が展開判断]

Practical Business Use Cases

  • Automated receipt of ZIP files from business partners

  • Input validation prior to batch processing

  • Extracting backups

  • Inspecting CI/CD artifacts

  • Pre-verifying user-uploaded ZIP files

Rather than simply expanding files because they are ZIPs, you canestablish rules for extraction conditions in advance.

Precautions

This example alone cannot completely detect malicious ZIP files.

In actual operations, you should also check factors such as:

  • Handling encrypted ZIP files

  • Special entries like symbolic links

  • Individual file size limits

  • Compression ratios

  • File name lengths

  • Malware inspection

  • Extraction destination permissions

depending on your specific use case.

Always Ensure Disposal

$archive.Dispose()

In actual code, use try/finally to ensure resources are closed properly even if an inspection error occurs midway.

Summary

  • Dangerous paths in ZIP files can be inspected before extraction.

  • Judgment is based on absolute path normalization rather than just string .. inspection.

  • Upper limits can be placed on the total post-extraction size and file count.

  • Defining allowed extensions makes ingestion processing safer.

  • Extraction decisions are made only after the preflight check.

Official and Primary Sources

Document information

Article title
Inspecting PowerShell for Dangerous Paths and Oversized Extractions Before Expanding ZIP Files
Published
Updated
Source
https://papanda925.com/?p=15395&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL