Rules / C#
SHIELD-CSHARP-013
Path traversal from request input into file API
What it detects
A file read or stream is opened using a path derived directly from HTTP request input.
How to fix
Canonicalize and validate the path against an allowlisted base directory before opening the file.
Vulnerable — Shield flags thisReportDownload.cs
using System.IO;
using Microsoft.AspNetCore.Mvc;
public class ReportDownload : Controller
{
public IActionResult Get()
{
var bytes = System.IO.File.ReadAllBytes("/var/reports/" + Request.Query["name"]);
return File(bytes, "application/pdf");
}
}
Fixed — scans cleanReportDownload.cs
using System.IO;
using Microsoft.AspNetCore.Mvc;
public class ReportDownload : Controller
{
private const string BaseDir = "/var/reports/";
public IActionResult Get()
{
var fileName = Path.GetFileName(Request.Query["name"].ToString());
var fullPath = Path.GetFullPath(Path.Combine(BaseDir, fileName));
if (!fullPath.StartsWith(BaseDir)) return NotFound();
return File(System.IO.File.ReadAllBytes(fullPath), "application/pdf");
}
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CSHARP-013, the fixed one does not.