Recipe 10.4 · C#
Zip and Unzip Without Surprises
Problem
Zip files arrive from partners and users, and go out as bundles of reports. Creating them is easy. Extracting them is where the risk is. An entry named ../../web.config writes outside the target folder; this is the "Zip Slip" bug. A small archive that expands to tens of gigabytes, a zip bomb, fills the disk. And old code loads entire entries into memory to copy them.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
using (var archive = ZipFile.OpenRead(zipPath))
{
foreach (var entry in archive.Entries)
{
entry.ExtractToFile(Path.Combine(target, entry.FullName),
true);
}
}
Path.Combine with an entry name of ..\..\app.config points outside target, and nothing limits how much is written.
The improved recipe
Creation streams each file into its entry. Extraction resolves every entry through SafePath.Combine from Recipe 10.1, enforces limits on entry count, total size and compression ratio, and counts the bytes actually written rather than trusting the sizes in the archive's headers.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Files;
public sealed record ZipLimits(
int MaxEntries = 10_000,
long MaxTotalBytes = 1L * 1024 * 1024 * 1024,
int MaxCompressionRatio = 100);
public static class ZipTools
{
public static async Task CreateAsync(
Stream destination,
IEnumerable<(string EntryName, string FilePath)> files,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(files);
using var archive = new ZipArchive(
destination, ZipArchiveMode.Create, leaveOpen: true);
foreach (var (entryName, filePath) in files)
{
var entry = archive.CreateEntry(
entryName.Replace('\\', '/'), CompressionLevel.Optimal);
await using var input = File.OpenRead(filePath);
await using var output = entry.Open();
await input.CopyToAsync(output, ct);
}
}
public static IReadOnlyList<string> ExtractSafely(
string zipPath, string destinationFolder, ZipLimits? limits = null)
{
limits ??= new ZipLimits();
using var archive = ZipFile.OpenRead(zipPath);
if (archive.Entries.Count > limits.MaxEntries)
{
throw new InvalidDataException("Too many entries in archive.");
}
Directory.CreateDirectory(destinationFolder);
var written = new List<string>();
long remaining = limits.MaxTotalBytes;
foreach (var entry in archive.Entries)
{
string target =
SafePath.Combine(destinationFolder, entry.FullName);
if (entry.FullName.EndsWith('/'))
{
Directory.CreateDirectory(target);
continue;
}
if (entry.CompressedLength > 0 && entry.Length
/ entry.CompressedLength > limits.MaxCompressionRatio)
{
throw new InvalidDataException(
$"Suspicious compression ratio: {entry.FullName}");
}
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
using var input = entry.Open();
using var output = new FileStream(target, FileMode.CreateNew);
remaining -= CopyWithLimit(input, output, remaining);
written.Add(target);
}
return written;
}
private static long CopyWithLimit(
Stream input, Stream output, long limit)
{
byte[] buffer = new byte[81920];
long total = 0;
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
total += read;
if (total > limit)
{
throw new InvalidDataException(
"Archive expands beyond the allowed size.");
}
output.Write(buffer, 0, read);
}
return total;
}
}
How it works
CreateAsync writes to any stream: a file, a MemoryStream for an e-mail attachment, or an HTTP response body. Each entry is opened, the source file is copied into it, and the entry is closed before the next one starts, so memory use stays flat however many files you add. Entry names use forward slashes, which is what the zip format specifies; backslashes produce archives that look broken on macOS and Linux.
ExtractSafely checks three things before writing. Every entry path goes through SafePath.Combine, which throws for .., absolute paths and invalid names, so Zip Slip is impossible. The entry count is capped, because a million empty entries is a denial-of-service attack of its own. And entries whose declared compression ratio exceeds 100 to 1 are refused; ordinary documents compress 2 to 10 times, text logs perhaps 20.
Declared sizes come from the archive and can lie, so CopyWithLimit counts the bytes really written and stops when the total for the whole archive passes the limit. FileMode.CreateNew refuses to overwrite files, which also catches archives that contain the same name twice.
Variations and pitfalls
ZipFile.ExtractToDirectoryin modern .NET rejects entries that would land outside the destination, but it has no size limits. It is fine for archives you created yourself. Use the limited version for anything from outside.- Partial extraction. If extraction throws halfway, some files exist. Extract into a fresh temp folder (Recipe 10.7) and move it into place only after success.