Skip to content

🔒 Fix path traversal vulnerability in SaveVisualizationAsFile#203

Open
Dor-bl wants to merge 1 commit intomainfrom
fix-path-traversal-savevisualization-2834004444876715981
Open

🔒 Fix path traversal vulnerability in SaveVisualizationAsFile#203
Dor-bl wants to merge 1 commit intomainfrom
fix-path-traversal-savevisualization-2834004444876715981

Conversation

@Dor-bl
Copy link
Owner

@Dor-bl Dor-bl commented Mar 22, 2026

🎯 What: The SaveVisualizationAsFile method lacked validation on the user-supplied fileName, directly writing the Base64 visualization to the provided path.
⚠️ Risk: An attacker controlling the filename could provide an absolute path (C:\Windows\System32\malicious.dll) or use relative path traversal (../../etc/passwd) to overwrite arbitrary files on the local filesystem.
🛡️ Solution: The method now restricts the output file location to the application's current working directory. It uses Path.GetFullPath combined with StartsWith to ensure that no directory traversal sequences or absolute paths escape the allowed base directory. Invalid path characters are also sanitized.


PR created automatically by Jules for task 2834004444876715981 started by @Dor-bl

* Added path validation to SaveVisualizationAsFile
* Ensured file path stays within the allowed executing directory
* Prevented relative path traversal (..) and absolute path manipulation
@google-labs-jules
Copy link

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings March 22, 2026 21:44
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the image-comparison result API by preventing path traversal/absolute-path overwrites when saving the base64 visualization to disk.

Changes:

  • Added argument validation for fileName before writing the visualization.
  • Resolved the target path to a full path under the current working directory and blocked paths outside it.
  • Updated file writing to use the validated full path.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +35 to +42
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}

string fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), fileName));

if (!fullPath.StartsWith(allowedDirectory, StringComparison.OrdinalIgnoreCase))
Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fullPath.StartsWith(..., OrdinalIgnoreCase) can be bypassed on case-sensitive file systems (e.g., Linux/macOS) by traversing into a differently-cased sibling directory (e.g., ../App/... vs base .../app). Use an OS-appropriate comparison (Ordinal on non-Windows) or avoid string prefix checks altogether by using Path.GetRelativePath(baseDir, fullPath) and rejecting rooted/..-prefixed results.

Suggested change
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}
string fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), fileName));
if (!fullPath.StartsWith(allowedDirectory, StringComparison.OrdinalIgnoreCase))
string fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), fileName));
string relativePath = Path.GetRelativePath(allowedDirectory, fullPath);
if (Path.IsPathRooted(relativePath) ||
relativePath.Equals("..", StringComparison.Ordinal) ||
relativePath.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal))

Copilot uses AI. Check for mistakes.
Comment on lines +24 to +28
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}

Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method throws ArgumentNullException for an empty string because it uses IsNullOrEmpty. Consider throwing ArgumentException for "" and reserving ArgumentNullException for null to match common .NET exception semantics for public APIs.

Suggested change
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
if (fileName.Length == 0)
{
throw new ArgumentException("The file name must not be an empty string.", nameof(fileName));
}

Copilot uses AI. Check for mistakes.
Comment on lines +29 to +32
if (fileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
{
throw new ArgumentException("The file name contains invalid characters.", nameof(fileName));
}
Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description says invalid path characters are "sanitized", but the implementation rejects them by throwing. Either update the description to reflect the behavior or implement actual sanitization so callers get the promised behavior.

Copilot uses AI. Check for mistakes.
Comment on lines +34 to +40
string allowedDirectory = Path.GetFullPath(Directory.GetCurrentDirectory());
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}

string fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), fileName));
Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Directory.GetCurrentDirectory() is called twice (for allowedDirectory and again when building fullPath). Capture the current directory once and reuse it to avoid inconsistent results if the working directory changes between calls (and to simplify the logic).

Suggested change
string allowedDirectory = Path.GetFullPath(Directory.GetCurrentDirectory());
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}
string fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), fileName));
string currentDirectory = Directory.GetCurrentDirectory();
string allowedDirectory = Path.GetFullPath(currentDirectory);
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}
string fullPath = Path.GetFullPath(Path.Combine(currentDirectory, fileName));

Copilot uses AI. Check for mistakes.
Comment on lines +46 to 49

File.WriteAllBytes(fullPath, Convert.FromBase64String(Visualization));
}

Copy link

Copilot AI Mar 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restricting to a base directory via path-string checks does not prevent symlink traversal (e.g., saving to subdir/file.png where subdir is a symlink to an external location). If this API can be called with untrusted fileName and the base directory is writable by untrusted users, consider mitigating by detecting/rejecting symlinks along the path (where supported) or clearly documenting this limitation.

Suggested change
File.WriteAllBytes(fullPath, Convert.FromBase64String(Visualization));
}
if (ContainsSymlinkWithinBaseDirectory(allowedDirectory, fullPath))
{
throw new IOException("The path to the output file traverses a symbolic link or reparse point, which is not allowed.");
}
File.WriteAllBytes(fullPath, Convert.FromBase64String(Visualization));
}
private static bool ContainsSymlinkWithinBaseDirectory(string allowedDirectory, string fullPath)
{
if (string.IsNullOrEmpty(allowedDirectory))
{
throw new ArgumentNullException(nameof(allowedDirectory));
}
if (string.IsNullOrEmpty(fullPath))
{
throw new ArgumentNullException(nameof(fullPath));
}
// Ensure the allowed directory has a trailing directory separator for reliable prefix checks.
if (!allowedDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
!allowedDirectory.EndsWith(Path.AltDirectorySeparatorChar.ToString()))
{
allowedDirectory += Path.DirectorySeparatorChar;
}
// If the path is not under the allowed directory, treat it as unsafe.
if (!fullPath.StartsWith(allowedDirectory, StringComparison.OrdinalIgnoreCase))
{
return true;
}
string relativePath = fullPath.Substring(allowedDirectory.Length);
if (relativePath.Length == 0)
{
return false;
}
var separators = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
string[] parts = relativePath.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string currentPath = allowedDirectory.TrimEnd(separators);
foreach (string part in parts)
{
currentPath = Path.Combine(currentPath, part);
if (Directory.Exists(currentPath) || File.Exists(currentPath))
{
FileAttributes attributes;
try
{
attributes = File.GetAttributes(currentPath);
}
catch (IOException)
{
// If attributes cannot be read, treat the path as unsafe.
return true;
}
catch (UnauthorizedAccessException)
{
// If attributes cannot be read due to permissions, treat the path as unsafe.
return true;
}
if ((attributes & FileAttributes.ReparsePoint) != 0)
{
// A reparse point (including symlinks/junctions) is present along the path.
return true;
}
}
}
return false;
}

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants