HIGH zip slipaspnetbearer tokens

Zip Slip in Aspnet with Bearer Tokens

Zip Slip in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Zip Slip is a path traversal vulnerability that occurs when an archive (ZIP, TAR, JAR, etc.) is extracted without validating or sanitizing file paths inside the archive. In an ASP.NET application that accepts uploaded archives and extracts them, an attacker can craft entries with malicious paths such as ../../../etc/passwd or use absolute paths to escape the intended extraction directory. When the application also relies on Bearer Tokens for authorization, a subtle risk emerges: the API may expose endpoints that handle extraction or file operations under the assumption that a valid Bearer Token proves the request is authorized and safe. Because the scan category BOLA/IDOR and BFLA/Privilege Escalation test for these issues, middleBrick can detect cases where token-based access does not prevent path traversal or over-privileged operations.

Consider an endpoint /api/import that expects a Bearer Token in the Authorization header. The token may identify a tenant or user, and the developer assumes that verifying the token is sufficient to ensure the uploaded archive belongs to and should be extracted for that tenant. However, if the server uses the token only for authentication/authorization but does not validate and sanitize filenames during extraction, an archive containing ../../tenant2/config.json can write files outside the tenant’s directory. The presence of a Bearer Token creates a false sense of security: the request is authenticated and authorized, yet the file operation is unsafe. This combination is especially dangerous when the endpoint also exposes functionality to list or retrieve extracted files, because the attacker can leverage path traversal to read arbitrary files on the server, a finding mapped to Data Exposure and Input Validation in the scan output.

Moreover, if the ASP.NET application uses claims or roles from the Bearer Token to implement property-level authorization, incomplete checks can intersect with archive handling to create privilege escalation paths. For example, a token with a role claim like role: user might be allowed to upload archives, but extraction logic that does not enforce tenant isolation can let the attacker traverse paths and access data belonging to other users or system files. The Property Authorization and Inventory Management checks in middleBrick evaluate whether authorization is consistently applied across file operations and API inventory, highlighting gaps where token-based checks do not align with file system operations. Real-world attack patterns like CVE-2020-4075 (the original Zip Slip vulnerability) illustrate how improper path normalization enables arbitrary file writes; when such endpoints are protected only by Bearer Tokens without strict path validation, the risk is elevated.

To illustrate, here is a minimal example of an unsafe extraction in ASP.NET Core that uses Bearer Token authentication but does not secure path handling:

// UNSAFE: Bearer Token validated, but archive paths are not sanitized
[Authorize] // Assumes token is sufficient
[HttpPost("import")]
public async Task<IActionResult> Import(IFormFile archive)
{
    using var stream = new FileStream(Path.GetTempFileName(), FileMode.Create);
    await archive.CopyToAsync(stream);
    using var archiveReader = new ZipArchive(stream, ZipArchiveMode.Read);
    foreach (var entry in archiveReader.Entries)
    {
        var destinationPath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", entry.FullName);
        entry.ExtractToFile(destinationPath, overwrite: true); // Unsafe: entry.FullName can be ../../outside
    }
    return Ok();
}

In this snippet, the [Authorize] attribute validates the Bearer Token, but entry.FullName is used directly to build the destination path. An attacker can include malicious paths in the archive, leading to path traversal and potential data exposure or overwrite. middleBrick’s scans include checks that correlate authentication/authorization mechanisms like Bearer Tokens with file operation safety, surfacing such mismatches between identity checks and input validation.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on strict path sanitization and ensuring that authorization tied to Bearer Tokens is complemented by secure file handling. Do not rely on token ownership alone to prevent path traversal; always validate and normalize paths independently of authentication.

1. Validate and sanitize archive entries before extracting. Use Path.GetFileName or custom logic to reject paths containing .. or absolute segments. Prefer using the entry’s Name instead of FullName, and construct paths with Path.Combine while ensuring the base directory is an absolute, canonical path.

2. Enforce tenant or user isolation at the filesystem level. Compute a safe destination directory per token subject or claim, and ensure extracted files cannot escape that directory.

3. Use a whitelist of allowed file extensions and reject entries with executable or unexpected types to reduce impact of any successful traversal.

Here is a secure version of the previous endpoint:

// SECURE: Bearer Token validated and archive paths sanitized
[Authorize]
[HttpPost("import")]
public async Task<IActionResult> Import(IFormFile archive)
{
    var baseDirectory = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "uploads"));
    using var stream = new FileStream(Path.GetTempFileName(), FileMode.Create);
    await archive.CopyToAsync(stream);
    using var archiveReader = new ZipArchive(stream, ZipArchiveMode.Read);
    foreach (var entry in archiveReader.Entries)
    {
        // Use the entry name to avoid directory traversal, and reject dangerous names
        var fileName = Path.GetFileName(entry.FullName);
        if (string.IsNullOrEmpty(fileName) || entry.FullName.StartsWith("../", StringComparison.Ordinal) || entry.FullName.Contains("..")) 
        {
            continue; // or log and reject the archive
        }
        // Optionally enforce tenant isolation via claims
        var user = User;
        var tenantSafePath = Path.Combine(baseDirectory, user.FindFirst("tenant_id")?.Value ?? "unknown", fileName);
        var destinationPath = Path.GetFullPath(tenantSafePath);
        if (!destinationPath.StartsWith(baseDirectory, StringComparison.Ordinal))
        {
            // Reject paths that escape the base directory
            continue;
        }
        entry.ExtractToFile(destinationPath, overwrite: true);
    }
    return Ok();
}

In this secure example, Path.GetFullPath canonicalizes paths, and we explicitly check for .. patterns and ensure the final path remains within baseDirectory. The tenant context from the Bearer Token claims is used to construct a subdirectory, reinforcing isolation. These steps align with the scanner’s checks for Input Validation, BOLA/IDOR, and Property Authorization, reducing the likelihood of traversal and privilege escalation.

Additionally, consider using libraries designed for safe extraction (e.g., SharpCompress with strict path handling) and avoid relying on default framework behavior that may not normalize paths consistently. Regularly run middleBrick scans to verify that remediation aligns with detected findings; the BFLA/Privilege Escalation and Data Exposure checks will help confirm that file operations remain constrained.

Frequently Asked Questions

Can middleBrick detect Zip Slip vulnerabilities when Bearer Tokens are used for authorization?
Yes. middleBrick runs checks such as BOLA/IDOR, BFLA/Privilege Escalation, Input Validation, and Data Exposure. It correlates authentication mechanisms like Bearer Tokens with file operation safety to identify cases where token-based authorization does not prevent path traversal or over-privileged extraction.
Does using a Bearer Token eliminate the need to sanitize archive file paths in ASP.NET?
No. Bearer Tokens provide identity and authorization but do not protect against path traversal. Always validate and sanitize filenames and enforce tenant isolation independently of token checks to prevent Zip Slip and related file system attacks.