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 5bd8930 commit f2d52d0
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/code/InstallHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1175,19 +1175,25 @@ 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);
// Sanitize the filename to remove any potentially harmful characters (ie '..').
if (entry.Name.Equals(".."))
{
error = new ErrorRecord(
new Exception($"Error occured while extracting .nupkg. File contains a potentially malicious file path."),
"FileNameErrorWhenExtractingNupkg",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);

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

// If a file has one or more parent directories.
if (sanitizedEntry.FullName.Contains(Path.DirectorySeparatorChar) || sanitizedEntry.FullName.Contains(Path.AltDirectorySeparatorChar))
if (entry.FullName.Contains(Path.DirectorySeparatorChar) || entry.FullName.Contains(Path.AltDirectorySeparatorChar))
{
// Create the parent directories if they do not already exist
var lastPathSeparatorIdx = entry.FullName.Contains(Path.DirectorySeparatorChar) ?
sanitizedEntry.FullName.LastIndexOf(Path.DirectorySeparatorChar) : sanitizedEntry.FullName.LastIndexOf(Path.AltDirectorySeparatorChar);
var parentDirs = sanitizedEntry.FullName.Substring(0, lastPathSeparatorIdx);
entry.FullName.LastIndexOf(Path.DirectorySeparatorChar) : entry.FullName.LastIndexOf(Path.AltDirectorySeparatorChar);
var parentDirs = entry.FullName.Substring(0, lastPathSeparatorIdx);
var destinationDirectory = Path.Combine(extractPath, parentDirs);
if (!Directory.Exists(destinationDirectory))
{
Expand All @@ -1196,9 +1202,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, sanitizedEntry.FullName));
string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.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
.

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

0 comments on commit f2d52d0

Please sign in to comment.