Description
Before writing a ZIP entry, use Path.GetFullPath to normalize the target and verify it is inside the extraction directory.
Potential impact
Extraction can overwrite configuration or create unwanted files in a web root if the process has write access.
Remediation
Use a new, empty directory under a service-only location. If the randomly named directory already exists, choose another. Compare against the full base path with a trailing separator, reject targets outside it, and prevent other users from replacing files or links during extraction.
Examples
Before
csharp
using System.IO;
using System.IO.Compression;
sealed class ZipExtractor
{
public static void ExtractEntry(
ZipArchiveEntry entry,
string targetDirectory)
{
var path = Path.GetFullPath(Path.Combine(targetDirectory, entry.FullName));
entry.ExtractToFile(path, overwrite: true);
}
}
After
csharp
using System;
using System.IO;
using System.IO.Compression;
static string ExtractToNewDirectory(ZipArchive archive, string serviceOwnedRoot)
{
// Other users or processes must not be able to write to serviceOwnedRoot.
var targetRoot = Directory.CreateDirectory(
Path.Combine(serviceOwnedRoot, Path.GetRandomFileName())).FullName;
var targetPrefix = Path.GetFullPath(targetRoot) + Path.DirectorySeparatorChar;
foreach (var entry in archive.Entries)
{
var path = Path.GetFullPath(Path.Combine(targetRoot, entry.FullName));
if (!path.StartsWith(targetPrefix, StringComparison.Ordinal))
{
throw new InvalidDataException("Archive entry escapes the target directory");
}
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(path);
continue;
}
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
entry.ExtractToFile(path, overwrite: false);
}
return targetRoot;
}
StringComparison.Ordinal compares path characters case-sensitively. overwrite: false prevents replacement of an existing file.