Path Traversal in Aspnet (Csharp)
Path Traversal in Aspnet with Csharp — how this specific combination creates or exposes the vulnerability
Path Traversal in ASP.NET with C# occurs when user-controlled input is used to construct file system paths without proper validation, allowing an attacker to escape the intended directory. In ASP.NET, this commonly manifests in endpoints that serve static files or process uploaded resources. For example, an endpoint that builds a path using string concatenation or Path.Combine without canonicalizing the result can be tricked into accessing files outside the intended directory.
Consider an ASP.NET Core controller that serves user profiles from a subdirectory:
// Vulnerable example: user input directly influences the file path
[HttpGet("profile/photo")]
public IActionResult GetPhoto(string name)
{
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/profiles");
var filePath = Path.Combine(basePath, name);
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}
return PhysicalFile(filePath, "image/*");
}
An attacker can provide a name such as ../../../appsettings.json, causing filePath to resolve outside wwwroot/profiles. Because the scan category “Input Validation” tests for path traversal techniques, middleBrick would flag this as a finding. The “Property Authorization” check also helps surface cases where access to sensitive files is possible based on unvalidated input.
In the context of the 12 security checks run in parallel by middleBrick, Path Traversal intersects with several categories: Input Validation, BFLA/Privilege Escalation (if directory traversal enables unauthorized access), and Data Exposure (sensitive files may be read). Because ASP.NET often hosts sensitive configuration and runtime files, traversal to files such as appsettings.json, which may contain connection strings, represents a realistic risk. The scanner does not fix or block these issues; it reports them with severity and remediation guidance, enabling developers to address the root cause.
Csharp-Specific Remediation in Aspnet — concrete code fixes
To remediate Path Traversal in ASP.NET with C#, ensure that any user input used in file paths is validated, restricted to a known set of values, and combined with a canonical base directory. Always resolve the full path and confirm it remains within the intended directory.
One robust approach is to use Path.GetFullPath and verify the resulting path starts with the expected base directory:
// Secure example: validate resolved path is within allowed directory
[HttpGet("profile/photo")]
public IActionResult GetPhoto(string name)
{
var basePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/profiles"));
var requestedPath = Path.GetFullPath(Path.Combine(basePath, name));
if (!requestedPath.StartsWith(basePath, StringComparison.Ordinal))
{
return BadRequest("Invalid file path.");
}
if (!System.IO.File.Exists(requestedPath))
If you need to map a filename to a known resource rather than directly concatenating user input, use a dictionary or allowlist:
private static readonly Dictionary<string, string> AllowedPhotos = new()
{
{ "alice", "alice.jpg" },
{ "bob", "bob.png" }
};
[HttpGet("profile/photo")]
public IActionResult GetPhoto(string userId)
{
if (!AllowedPhotos.TryGetValue(userId, out var fileName))
Additionally, consider using PhysicalFileResult with a carefully controlled path and avoid exposing raw file system paths to the client. Content-Disposition headers can further reduce risks when serving downloadable content.
For ongoing assurance, the middleBrick CLI tool can be integrated into scripts and the GitHub Action can be added to CI/CD pipelines to fail builds if security scores drop below a chosen threshold. This helps catch regressions that reintroduce path traversal or other vulnerabilities before deployment.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |