HIGH zip slipaspnetcockroachdb

Zip Slip in Aspnet with Cockroachdb

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

Zip Slip is a path traversal vulnerability that occurs when an application constructs file paths by directly concatenating user-supplied input with a base directory. In an ASP.NET application that uses CockroachDB as the backend database, the risk is not in the database engine itself but in how the application handles file operations before or after interacting with CockroachDB. If user input such as a filename or archive entry is used to build filesystem paths without proper validation, an attacker can traverse directories and overwrite arbitrary files, including those critical to the application or its database tooling.

When CockroachDB is involved, the exposure often arises in scenarios where the application exports or imports data using file-based operations, such as backups, CSV imports, or log handling. For example, an endpoint in ASP.NET might accept a fileName parameter to stream a database backup file to the client. If the endpoint does not sanitize the fileName and directly appends it to a backup directory path, an input like ../../../etc/passwd can escape the intended directory. This becomes particularly dangerous if the application process has filesystem permissions that allow reading sensitive system files or writing to directories used by CockroachDB tooling.

The vulnerability chain is as follows: an attacker sends a crafted request to the ASP.NET endpoint, the server-side code uses unsafe path joining (e.g., Path.Combine(basePath, userInput) without normalization and validation), the path traverses outside the intended directory, and the attacker can read or overwrite files. If the compromised files include configuration files or scripts that the CockroachDB client uses, it may lead to further compromise of database operations. MiddleBrick detects this pattern during its unauthenticated scan by analyzing the API surface for path traversal indicators and unsafe consumption practices, flagging the issue under Unsafe Consumption and Data Exposure checks.

Cockroachdb-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on strict input validation, path normalization, and avoiding direct concatenation of user input into filesystem paths. In ASP.NET, use the Path.GetFullPath method combined with a strict base directory check to ensure the resolved path remains within the allowed location. Additionally, prefer using unique identifiers for filenames stored on disk and maintain a mapping in CockroachDB to associate logical references with physical files.

Example: Secure file streaming with path validation

Below is a secure ASP.NET endpoint that streams backup files from a designated directory. It ensures the resolved path is within the allowed directory and uses a parameterized query to fetch file metadata from CockroachDB.

using System;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using Npgsql;
using System.IO;

[ApiController]
[Route("api/[controller]")]
public class BackupController : ControllerBase
{
    private readonly string _backupDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "backups"));
    private readonly string _connectionString = Environment.GetEnvironmentVariable("COCKROACHDB_CONNECTION_STRING");

    [HttpGet("{fileId}")]
    public IActionResult GetBackup(string fileId)
    {
        string filePath;
        using (var conn = new NpgsqlConnection(_connectionString))
        {
            conn.Open();
            using (var cmd = new NpgsqlCommand("SELECT path FROM backups WHERE id = @id AND user_id = @userId", conn))
            {
                cmd.Parameters.AddWithValue("@id", fileId);
                cmd.Parameters.AddWithValue("@userId", GetCurrentUserId());
                using (var reader = cmd.ExecuteReader())
                {
                    if (!reader.Read())
                    {
                        return NotFound();
                    }
                    var relativePath = reader.GetString(0);
                    filePath = Path.GetFullPath(Path.Combine(_backupDirectory, relativePath));
                }
            }
        }

        if (!filePath.StartsWith(_backupDirectory, StringComparison.Ordinal))
        {
            return BadRequest("Invalid file path.");
        }

        if (!System.IO.File.Exists(filePath))
        {
            return NotFound();
        }

        var memory = new System.IO.MemoryStream();
        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            stream.CopyTo(memory);
        }
        memory.Position = 0;
        return File(memory, "application/octet-stream", Path.GetFileName(filePath));
    }

    private string GetCurrentUserId()
    {
        // Implementation omitted
        return "user-123";
    }
}

In this example, the file identifier is not used directly as a filesystem path. Instead, it references a record in CockroachDB that stores a relative path. The resolved path is normalized and verified to be within the _backupDirectory. This prevents directory traversal regardless of the input provided by the user.

Additionally, ensure that the CockroachDB connection string is stored securely using ASP.NET Core configuration and that the application does not expose filesystem paths in API responses. Regularly audit file operations and apply the principle of least privilege to the process running the ASP.NET application to limit the impact of any potential traversal vulnerability.

Frequently Asked Questions

Can Zip Slip affect applications that only interact with CockroachDB and do not handle files?
Zip Slip specifically requires filesystem operations. If your ASP.NET application only uses CockroachDB for data storage and does not read, write, or serve files based on user input, the vulnerability does not apply. However, if your application ever handles file uploads, exports, or backups, those entry points must be validated.
How does middleBrick detect Zip Slip risks in an API?
MiddleBrick performs black-box testing of the unauthenticated attack surface, including unsafe consumption endpoints. It checks for improper path handling, missing validation on user-supplied path segments, and references to directory traversal patterns. Findings are mapped to the Unsafe Consumption and Data Exposure checks and include remediation guidance.