Path Traversal in Aspnet with Bearer Tokens
Path Traversal in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an attacker manipulates a file path to access or write files outside the intended directory. In ASP.NET applications, this typically arises when user-controlled input is concatenated directly into file system operations without proper validation or sanitization. The presence of Bearer Tokens in the request does not mitigate this class of vulnerability; instead, it can inadvertently expand the attack surface when APIs accept tokens as parameters or headers and use them to construct file paths or locate resources.
Consider an endpoint that retrieves user documents and uses a header value to personalize file system access. If the application extracts a Bearer Token from the Authorization header and uses it to build a path, such as combining a tenant identifier extracted from the token payload with a user-provided filename, an attacker can supply path sequences like ../../../etc/passwd to traverse directories. Because the token is trusted implicitly, the application may bypass intended access controls, assuming the token’s embedded claims guarantee authorization. This trust, combined with unchecked user input, results in insecure direct object references and path traversal opportunities.
In the context of OpenAPI/Swagger analysis, middleBrick correlates such patterns by cross-referencing spec definitions with runtime behavior. For example, if an operation defines a security scheme using bearerAuth and also accepts a user-supplied path parameter, middleBrick tests whether inputs are properly constrained and whether path construction is isolated from token-derived values. Real-world attack patterns like CVE-2021-44228-style logic, adapted to file system operations, demonstrate how traversal can occur when validation is incomplete. ASP.NET applications that use minimal APIs or controller actions without canonicalizing paths are especially at risk, as relative segments can resolve outside the application’s intended directory tree.
Moreover, when Bearer Tokens are passed as query parameters or in custom headers for debugging or logging, developers might inadvertently use these values in file system interactions, creating indirect traversal vectors. The risk is not limited to reading files; improper handling can enable overwriting critical configuration or application files. middleBrick’s 12 parallel security checks include Input Validation and Property Authorization specifically to detect such weaknesses, ensuring that path construction logic is verified against both spec definitions and runtime behavior.
Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes
Remediation focuses on strict input validation, path canonicalization, and avoiding the use of token-derived values in file system paths. Always treat user input as untrusted, even when it is derived from a Bearer Token. Use framework-provided utilities to safely combine paths and enforce strict allowlists for file access.
Example 1: Safe file access using Path.Combine and Path.GetFullPath to prevent directory traversal. This approach ensures that resolved paths remain within a designated base directory.
using System.IO;
var baseDirectory = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "uploads"));
var userFileName = "document.pdf"; // Assume this is validated/sanitized
var combinedPath = Path.Combine(baseDirectory, userFileName);
var fullPath = Path.GetFullPath(combinedPath);
if (!fullPath.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase))
{
throw new UnauthorizedAccessException("Invalid path.");
}
// Proceed with file operations using fullPath
using var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
Example 2: Using middleware to validate Bearer Token usage without incorporating it into file paths. Instead of using token claims for path construction, map claims to an internal access control list that references safe resources.
app.Use(async (context, next)
{
var authHeader = context.Request.Headers["Authorization"].ToString();
if (authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Bearer ".Length).Trim();
// Validate token and extract claims without using claims for file paths
var claims = ValidateToken(token);
context.Items["AllowedBasePath"] = GetBasePathForUser(claims);
}
await next.Invoke();
});
// Later in a controller or minimal API handler
var basePath = context.Items["AllowedBasePath"] as string ?? string.Empty;
var safeFilePath = Path.GetFullPath(Path.Combine(basePath, userProvidedName));
if (!safeFilePath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
{
Results.Forbid();
return;
}
Example 3: Enforcing strict filename patterns and rejecting paths containing traversal sequences at the API gateway or within model binders.
public static bool IsValidFileName(string filename)
{
if (string.IsNullOrWhiteSpace(filename))
return false;
var trimmed = filename.Trim();
if (trimmed.Contains("..") || trimmed.Contains("/") || trimmed.Contains("\\"))
return false;
// Allow only alphanumeric, underscore, dash, and dot within the filename
return System.Text.RegularExpressions.Regex.IsMatch(trimmed, @"^[a-zA-Z0-9._-]+$");
}
// Usage in a minimal API
app.MapGet("/files/{name}", (string name) =>
{
if (!IsValidFileName(name))
{
return Results.BadRequest("Invalid file name.");
}
var safeName = name; // Further path resolution as shown in previous examples
// ...
});
These practices ensure that Bearer Tokens do not inadvertently influence file system operations and that path traversal risks are mitigated through canonicalization and strict allowlisting.
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 |