Skip to content
4 changes: 2 additions & 2 deletions src/Xamarin.Android.Tools.AndroidSdk/DownloadUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ static string ComputeHashString (HashAlgorithm hasher, Stream stream)
/// <summary>Extracts a ZIP archive with Zip Slip protection.</summary>
public static void ExtractZipSafe (string archivePath, string destinationPath, CancellationToken cancellationToken)
{
using var archive = ZipFile.OpenRead (archivePath);
var fullExtractRoot = Path.GetFullPath (destinationPath);

using var archive = ZipFile.OpenRead (archivePath);
foreach (var entry in archive.Entries) {
cancellationToken.ThrowIfCancellationRequested ();

Expand All @@ -131,7 +131,7 @@ public static void ExtractZipSafe (string archivePath, string destinationPath, C
if (!string.IsNullOrEmpty (entryDir))
Directory.CreateDirectory (entryDir);

entry.ExtractToFile (destinationFile, overwrite: true);
entry.ExtractToFile (destinationFile, overwrite: true); // CodeQL [SM02729] IsUnderDirectory canonicalizes both paths and enforces ordinal directory-boundary containment.
}
}

Expand Down
12 changes: 8 additions & 4 deletions src/Xamarin.Android.Tools.AndroidSdk/FileUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,18 @@ internal static bool IsTargetPathWritable (string targetPath, Action<TraceLevel,
}

/// <summary>Checks if a path is under a given directory.</summary>
internal static bool IsUnderDirectory (string path, string directory)
internal static bool IsUnderDirectory (string? path, string? directory)
{
if (string.IsNullOrEmpty (directory) || string.IsNullOrEmpty (path))
return false;
if (path.Equals (directory, StringComparison.OrdinalIgnoreCase))

var fullPath = Path.GetFullPath (path);
var fullDirectory = Path.GetFullPath (directory);
if (fullPath.Equals (fullDirectory, StringComparison.Ordinal))
return true;
return path.StartsWith (directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
if (!fullDirectory.EndsWith (Path.DirectorySeparatorChar.ToString (), StringComparison.Ordinal))
fullDirectory += Path.DirectorySeparatorChar;
return fullPath.StartsWith (fullDirectory, StringComparison.Ordinal);
}

// Returns .msi (Windows), .pkg (macOS), or null (Linux)
Expand Down Expand Up @@ -271,4 +276,3 @@ internal static async Task SetExecutablePermissionsAsync (string directory, Acti
#endif
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -163,16 +163,17 @@ public void ExtractZipSafe_ValidZip_ExtractsFiles ()
Assert.AreEqual ("hello world", File.ReadAllText (extractedFile));
}

[Test]
public void ExtractZipSafe_ZipSlip_Throws ()
[TestCase ("../relative.txt")]
[TestCase ("../extracted-other/prefix.txt")]
[TestCase ("../EXTRACTED/case.txt")]
public void ExtractZipSafe_UnsafeRelativePath_Throws (string entryName)
{
var zipPath = Path.Combine (tempDir, "evil.zip");
var zipPath = Path.Combine (tempDir, "test.zip");
var extractPath = Path.Combine (tempDir, "extracted");
Directory.CreateDirectory (extractPath);

using (var archive = ZipFile.Open (zipPath, ZipArchiveMode.Create)) {
// Create an entry with a path traversal
var entry = archive.CreateEntry ("../relative.txt");
var entry = archive.CreateEntry (entryName);
using var writer = new StreamWriter (entry.Open ());
writer.Write ("malicious");
}
Expand All @@ -182,6 +183,81 @@ public void ExtractZipSafe_ZipSlip_Throws ()
Assert.That (ex!.Message, Does.Contain ("outside target directory"));
Comment thread
jonathanpeppers marked this conversation as resolved.
Resolved
}

[Test]
public void ExtractZipSafe_PlatformSeparatorTraversal_Throws ()
{
var zipPath = Path.Combine (tempDir, "test.zip");
var extractPath = Path.Combine (tempDir, "extracted");
Directory.CreateDirectory (extractPath);

using (var archive = ZipFile.Open (zipPath, ZipArchiveMode.Create)) {
var entry = archive.CreateEntry ($"..{Path.DirectorySeparatorChar}relative.txt");
using var writer = new StreamWriter (entry.Open ());
writer.Write ("malicious");
}

Assert.Throws<InvalidOperationException> (() =>
DownloadUtils.ExtractZipSafe (zipPath, extractPath, CancellationToken.None));
}

[Test]
public void ExtractZipSafe_RootedPath_Throws ()
{
var zipPath = Path.Combine (tempDir, "test.zip");
var extractPath = Path.Combine (tempDir, "extracted");
Directory.CreateDirectory (extractPath);
var pathRoot = Path.GetPathRoot (extractPath);
Assert.IsNotNull (pathRoot);

using (var archive = ZipFile.Open (zipPath, ZipArchiveMode.Create)) {
var entry = archive.CreateEntry (Path.Combine (pathRoot, "rooted.txt"));
using var writer = new StreamWriter (entry.Open ());
writer.Write ("malicious");
}

Assert.Throws<InvalidOperationException> (() =>
DownloadUtils.ExtractZipSafe (zipPath, extractPath, CancellationToken.None));
}

[Test]
public void ExtractZipSafe_TrailingSeparator_ExtractsFiles ()
{
var zipPath = Path.Combine (tempDir, "test.zip");
var extractPath = Path.Combine (tempDir, "extracted") + Path.DirectorySeparatorChar;
Directory.CreateDirectory (extractPath);

using (var archive = ZipFile.Open (zipPath, ZipArchiveMode.Create)) {
var entry = archive.CreateEntry ("hello.txt");
using var writer = new StreamWriter (entry.Open ());
writer.Write ("hello world");
}

DownloadUtils.ExtractZipSafe (zipPath, extractPath, CancellationToken.None);

Assert.AreEqual ("hello world", File.ReadAllText (Path.Combine (extractPath, "hello.txt")));
}

[Test]
public void ExtractZipSafe_SymbolicLinkMetadata_ExtractsRegularFile ()
Comment thread
jonathanpeppers marked this conversation as resolved.
Resolved
{
var zipPath = Path.Combine (tempDir, "test.zip");
var extractPath = Path.Combine (tempDir, "extracted");
Directory.CreateDirectory (extractPath);

using (var archive = ZipFile.Open (zipPath, ZipArchiveMode.Create)) {
var entry = archive.CreateEntry ("link");
entry.ExternalAttributes = unchecked ((0xA000 | 0x1FF) << 16);
using var writer = new StreamWriter (entry.Open ());
writer.Write ("../outside.txt");
}

DownloadUtils.ExtractZipSafe (zipPath, extractPath, CancellationToken.None);

var extractedFile = Path.Combine (extractPath, "link");
Assert.IsTrue (File.Exists (extractedFile));
Assert.IsFalse ((File.GetAttributes (extractedFile) & FileAttributes.ReparsePoint) != 0);
}

[Test]
public void ExtractZipSafe_EmptyZip_NoFilesExtracted ()
{
Expand Down
42 changes: 25 additions & 17 deletions tests/Xamarin.Android.Tools.AndroidSdk-Tests/FileUtilTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,32 +93,40 @@ public void MoveWithRollback_SourceDoesNotExist_NoExistingTarget_Throws ()
[Test]
public void IsUnderDirectory_ChildPath_ReturnsTrue ()
{
var parent = Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs");
var parent = Path.Combine (tempDir, "programs");
var child = Path.Combine (parent, "java", "jdk-21");
Assert.IsTrue (FileUtil.IsUnderDirectory (child, parent));
}

[Test]
public void IsUnderDirectory_ExactMatch_ReturnsTrue ()
{
var dir = Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs");
Assert.IsTrue (FileUtil.IsUnderDirectory (dir, dir));
var directory = Path.Combine (tempDir, "programs");
Assert.IsTrue (FileUtil.IsUnderDirectory (directory, directory));
}

[Test]
public void IsUnderDirectory_SiblingPath_ReturnsFalse ()
{
Assert.IsFalse (FileUtil.IsUnderDirectory (
Path.Combine ($"{Path.DirectorySeparatorChar}opt", "data", "java"),
Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs")));
Path.Combine (tempDir, "data", "java"),
Path.Combine (tempDir, "programs")));
}

[Test]
public void IsUnderDirectory_DifferentRoot_ReturnsFalse ()
{
Assert.IsFalse (FileUtil.IsUnderDirectory (
Path.Combine ($"{Path.DirectorySeparatorChar}other", "java"),
Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs")));
Path.Combine (Path.GetPathRoot (tempDir), "other", "java"),
Path.Combine (tempDir, "programs")));
}

[Test]
public void IsUnderDirectory_PartialDirNameMatch_ReturnsFalse ()
{
var parent = Path.Combine (tempDir, "programs");
var sibling = Path.Combine (tempDir, "programs-extra", "java");
Assert.IsFalse (FileUtil.IsUnderDirectory (sibling, parent));
}

[TestCase (null, "/dir")]
Expand All @@ -128,24 +136,24 @@ public void IsUnderDirectory_DifferentRoot_ReturnsFalse ()
[TestCase (null, null)]
public void IsUnderDirectory_NullOrEmpty_ReturnsFalse (string path, string directory)
{
Assert.IsFalse (FileUtil.IsUnderDirectory (path!, directory!));
Assert.IsFalse (FileUtil.IsUnderDirectory (path, directory));
}

[Test]
public void IsUnderDirectory_CaseInsensitive ()
public void IsUnderDirectory_CaseSensitive ()
{
var parent = Path.Combine ($"{Path.DirectorySeparatorChar}opt", "Programs");
var child = Path.Combine ($"{Path.DirectorySeparatorChar}opt", "PROGRAMS", "java");
Assert.IsTrue (FileUtil.IsUnderDirectory (child, parent));
var parent = Path.Combine (tempDir, "Programs");
var child = Path.Combine (tempDir, "PROGRAMS", "java");
Assert.IsFalse (FileUtil.IsUnderDirectory (child, parent));
}

[Test]
public void IsUnderDirectory_PartialDirNameMatch_ReturnsFalse ()
public void IsUnderDirectory_CanonicalCaseMismatch_ReturnsFalse ()
{
var parent = Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs");
Assert.IsFalse (FileUtil.IsUnderDirectory (
Path.Combine ($"{Path.DirectorySeparatorChar}opt", "programs-extra", "java"),
parent));
var parent = Path.Combine (tempDir, "programs");
var sibling = Path.Combine (parent, "..", "PROGRAMS", "java");
Assert.IsFalse (FileUtil.IsUnderDirectory (sibling, parent));
}

}
}
Loading