HIGH path traversalaspnetbasic auth

Path Traversal in Aspnet with Basic Auth

Path Traversal in Aspnet with Basic Auth — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when an attacker manipulates file path inputs to access files outside the intended directory, often using sequences like ../. In ASP.NET applications protected with HTTP Basic Authentication, the presence of authentication can create a false sense of security while the underlying path handling remains unsafe. Basic Auth verifies identity per request but does not constrain how the application builds file system paths from user-controlled data.

Consider an endpoint that retrieves user documents from a directory derived from a query parameter. If the application concatenates the username (supplied via Basic Auth) into a path without validation, an authenticated user can supply a crafted username such as ../../../etc/passwd to traverse directories. Because the request includes valid credentials, the middleware allows the request to proceed to the file logic, where unsafe use of Path.Combine or string concatenation can resolve to a location outside the intended base directory.

In the context of middleBrick’s checks, this scenario maps to the BOLA/IDOR and Input Validation categories. An authenticated probe can reveal whether path normalization is applied after authentication and whether the framework’s built-in protections are sufficient. For example, ASP.NET Core’s Path.GetFullPath can be used to detect attempts to escape the base directory, but it must be applied before any file access occurs. Without this, an attacker can leverage legitimate credentials to read arbitrary files, demonstrating that authentication does not automatically prevent path traversal.

Real-world analogies include scenarios where an authenticated user requests /files/..%2F..%2Fweb.config and the server resolves the path to a sensitive configuration file. Even when routes are guarded, if parameter sanitization is inconsistent across endpoints, the authenticated session becomes a vector for unauthorized file access. This highlights the importance of validating and sanitizing all path inputs independently of authentication state.

Basic Auth-Specific Remediation in Aspnet — concrete code fixes

To mitigate Path Traversal in ASP.NET with Basic Auth, treat username-derived inputs as untrusted even when authentication succeeds. Always validate and sanitize path inputs, and use framework utilities that prevent directory escape.

Example: Unsafe implementation with Basic Auth

app.Use(async (context, next) =>
{
    var authHeader = context.Request.Headers["Authorization"].ToString();
    if (authHeader.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
    {
        var token = Convert.FromBase64String(authHeader.Substring("Basic ".Length).Trim());
        var credentials = Encoding.UTF8.GetString(token).Split(':');
        var username = credentials[0];
        // Unsafe: username used directly in path construction
        var filePath = Path.Combine(baseDirectory, username, "document.txt");
        if (File.Exists(filePath))
        {
            await context.Response.WriteAsync(await File.ReadAllTextAsync(filePath));
        }
    }
    await next();
});

In the example above, an authenticated user can supply a username like ..\..\..\windows to reach parent directories. The fix is to normalize and restrict the username segment to a safe subdirectory.

Secure implementation with path validation

app.Use(async (context, next) =>
{
    var authHeader = context.Request.Headers["Authorization"].ToString();
    if (authHeader.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
    {
        var token = Convert.FromBase64String(authHeader.Substring("Basic ".Length).Trim());
        var credentials = Encoding.UTF8.GetString(token).Split(':');
        var username = credentials[0];

        // Validate username to prevent path traversal
        if (string.IsNullOrWhiteSpace(username) || username.Contains("..") || username.Contains(Path.AltDirectorySeparatorChar) || username.Contains(Path.DirectorySeparatorChar))
        {
            context.Response.StatusCode = 400;
            return;
        }

        // Use Path.GetFullPath to detect attempts to escape the base directory
        var baseDirectory = Path.GetFullPath(AppContext.BaseDirectory);
        var userDirectory = Path.GetFullPath(Path.Combine(baseDirectory, "users", username));

        if (!userDirectory.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase))
        {
            context.Response.StatusCode = 403;
            return;
        }

        var filePath = Path.Combine(userDirectory, "document.txt");
        if (File.Exists(filePath))
        {
            await context.Response.WriteAsync(await File.ReadAllTextAsync(filePath));
        }
        else
        {
            context.Response.StatusCode = 404;
        }
    }
    await next();
});

This approach ensures that the username is checked for directory traversal sequences and that the resolved path remains within the intended base directory. Combining this with input length limits and allowed character sets further reduces risk. middleBrick’s scans can surface such logic flaws under the BOLA/IDOR and Input Validation checks, helping teams verify that authentication does not inadvertently widen the attack surface.

For teams using the middleBrick CLI, running middlebrick scan <url> can identify endpoints where path handling is inconsistent with authentication boundaries. Teams on the Pro plan gain continuous monitoring and CI/CD integration, which can flag regressions in path handling as part of automated pipelines.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does Basic Auth prevent path traversal attacks in ASP.NET?
No. Basic Auth provides identity but does not secure path construction. Unsafe use of user-derived values in file paths can still enable traversal, making input validation essential regardless of authentication.
How can I test if my ASP.NET endpoint is vulnerable to path traversal with Basic Auth?
Send authenticated requests with crafted path sequences (e.g., username set to ..%2F..%2Fetc%2Fpasswd) and inspect responses. You can also use middleBrick’s scans to detect missing path normalization and unsafe file access patterns.