Path Traversal in Aspnet with Firestore
Path Traversal in Aspnet with Firestore — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when user-controlled input is used to construct file or resource paths without proper validation, allowing an attacker to access files outside the intended directory. In an ASP.NET application that integrates with Google Cloud Firestore, this risk can manifest in two primary ways: through insecure handling of Firestore document IDs or paths and through unsafe use of file-system operations that mirror Firestore data locally.
First, if an ASP.NET endpoint accepts a document ID or a subcollection path from the client and passes it directly to Firestore without validation, an attacker can supply sequences like ../../../sensitive-collection/document. Although Firestore does not allow escaping its own namespace with .. in document IDs, a vulnerable handler might concatenate user input into a path used for logging, backups, or hybrid file-based workflows, inadvertently exposing references that map to sensitive logical groupings or metadata.
Second, if the application maintains a local file cache or export of Firestore data (for example, writing documents to disk under a user-supplied key), an attacker can traverse directory boundaries using encoded slashes or null bytes (depending on the runtime environment) to read or overwrite arbitrary files. Common patterns include using Path.Combine with unsanitized IDs or query parameters to build file paths such as Path.Combine(baseDir, userSuppliedId). Without canonicalization and strict allowlisting, this enables reads outside the intended directory, potentially reaching configuration files or other application artifacts.
Even when Firestore rules restrict access, the ASP.NET layer remains a critical boundary. An attacker probing for IDOR or BOLA issues may use traversal-inspired payloads to enumerate document hierarchies or infer naming patterns. Since middleBrick tests unauthenticated attack surfaces and includes checks for BOLA/IDOR and Input Validation, it can surface risky endpoint behaviors that combine path-style inputs with Firestore references, highlighting where canonicalization or over-permissive regexes enable unsafe routing.
Firestore-Specific Remediation in Aspnet — concrete code fixes
Remediation centers on strict input validation, canonicalization, and avoiding filesystem interactions with user-controlled values. When working with Firestore in ASP.NET, treat all IDs and paths as untrusted and enforce allowlists.
1. Validate and sanitize document IDs
Do not concatenate user input directly into document references. Use a strict regex to allow only safe characters and reject paths containing . segments or slashes.
using System.Text.RegularExpressions;
using Google.Cloud.Firestore;
public bool IsValidDocumentId(string id)
{
// Allow alphanumeric, underscore, dash, and dot, but not path separators or sequences like '..'
var pattern = @"^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*$";
return !string.IsNullOrEmpty(id) && Regex.IsMatch(id, pattern) && !id.Contains("..");
}
[ApiController]
[Route("api/documents")]
public class DocumentsController : ControllerBase
{
private readonly FirestoreDb _db;
public DocumentsController(FirestoreDb db) => _db = db;
[HttpGet("{docId}")]
public async Task<IActionResult>Get(string docId)
{
if (!IsValidDocumentId(docId))
return BadRequest("Invalid document identifier");
DocumentReference docRef = _db.Collection("public-data").Document(docId);
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (!snapshot.Exists)
return NotFound();
return Ok(snapshot.ToDictionary());
}
}
2. Avoid filesystem operations with user input
If you must write Firestore data to disk, derive filenames from server-side hashes or IDs, never from raw user input. If you must use user input as part of a path, canonicalize and restrict it to a single directory.
using System.IO;
using System.Security.Cryptography;
public string GetSafeFilePath(string userInput, string baseDir)
{
// Derive a hash rather than using raw input
using var sha = SHA256.Create();
byte[] hash = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(userInput));
string safeName = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
return Path.GetFullPath(Path.Combine(baseDir, safeName));
}
// Usage: ensure baseDir is an absolute, application-controlled path
string baseDir = Path.GetFullPath("./export-cache");
string filePath = GetSafeFilePath(userSuppliedId, baseDir);
// Proceed to write/read only within baseDir
3. Enforce Firestore rules and audit mappings
Ensure your Firestore security rules align with the identity context used by your ASP.NET service account. Do not rely on client-side constraints. Combine rules that limit read/write scope with server-side validation to reduce the impact of misconfigured endpoints.
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 |