Skip to content

Commit

Permalink
Sanitize archive entry file name
Browse files Browse the repository at this point in the history
  • Loading branch information
alerickson committed Oct 24, 2023
1 parent b6aaf36 commit 5bd8930
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/code/InstallHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1175,13 +1175,19 @@ private bool TryExtractToDirectory(string zipPath, string extractPath, out Error
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
// Sanitize the filename to remove any potentially harmful characters
string sanitizedFileName = Path.GetFileName(entry.FullName);

// Create a new entry in the archive
ZipArchiveEntry sanitizedEntry = archive.CreateEntry(sanitizedFileName);

// If a file has one or more parent directories.
if (entry.FullName.Contains(Path.DirectorySeparatorChar) || entry.FullName.Contains(Path.AltDirectorySeparatorChar))
if (sanitizedEntry.FullName.Contains(Path.DirectorySeparatorChar) || sanitizedEntry.FullName.Contains(Path.AltDirectorySeparatorChar))
{
// Create the parent directories if they do not already exist
var lastPathSeparatorIdx = entry.FullName.Contains(Path.DirectorySeparatorChar) ?
entry.FullName.LastIndexOf(Path.DirectorySeparatorChar) : entry.FullName.LastIndexOf(Path.AltDirectorySeparatorChar);
var parentDirs = entry.FullName.Substring(0, lastPathSeparatorIdx);
sanitizedEntry.FullName.LastIndexOf(Path.DirectorySeparatorChar) : sanitizedEntry.FullName.LastIndexOf(Path.AltDirectorySeparatorChar);
var parentDirs = sanitizedEntry.FullName.Substring(0, lastPathSeparatorIdx);
var destinationDirectory = Path.Combine(extractPath, parentDirs);
if (!Directory.Exists(destinationDirectory))
{
Expand All @@ -1190,9 +1196,9 @@ private bool TryExtractToDirectory(string zipPath, string extractPath, out Error
}

// Gets the full path to ensure that relative segments are removed.
string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));
string destinationPath = Path.GetFullPath(Path.Combine(extractPath, sanitizedEntry.FullName));

Check failure

Code scanning / CodeQL

Arbitrary file access during archive extraction ("Zip Slip") High

Unsanitized archive entry, which may contain '..', is used in a
file system operation
.

entry.ExtractToFile(destinationPath, overwrite:true);
sanitizedEntry.ExtractToFile(destinationPath, overwrite:true);
}
}
}
Expand Down

0 comments on commit 5bd8930

Please sign in to comment.