Path Traversal in Aspnet with Mongodb
Path Traversal in Aspnet with Mongodb — how this specific combination creates or exposes the vulnerability
Path Traversal in an ASP.NET context with MongoDB as the backend typically arises when user-controlled input is used to construct file-system paths or to dynamically build database queries without proper validation or encoding. Although MongoDB uses a structured query language, traversal-like issues can occur when input influences document field paths, collection names, or when file-system operations are combined with user input in an ASP.NET application.
Consider an endpoint in ASP.NET that builds a MongoDB query using string concatenation or interpolation based on request parameters. If a parameter such as collectionName is taken directly from the query string and used in Database.GetCollection<BsonDocument>(collectionName), an attacker can attempt to traverse collections or inject operators by supplying values like users; DROP DATABASE or by including dot notation intended for field traversal (e.g., profile.address.city) to manipulate nested document access unintentionally.
In a different scenario, an ASP.NET application might use user input to locate files (for example, serving reports stored on disk) and then store or retrieve metadata in MongoDB. If the file path is built by concatenating a user-supplied identifier to a base directory, an attacker can use sequences like ../../../etc/passwd to escape the intended directory. Even when metadata is stored in MongoDB, referencing files by a user-controlled key without canonicalizing and validating the path can lead to unauthorized file access or injection of malicious patterns into queries.
Another subtle risk emerges when field names in MongoDB documents are influenced by user input. If an ASP.NET controller dynamically accesses nested fields using dot notation derived from query parameters, an attacker may supply crafted input like user.$where or profile.$** to probe or manipulate document structures in ways that bypass intended access controls. This mirrors injection-like behaviors even though MongoDB does not use a traditional SQL parser. The combination of ASP.NET’s flexible routing and model binding with MongoDB’s expressive document model amplifies the impact of insufficient input validation and improper encoding.
These patterns align with common web security risks such as Injection and Broken Access Control from the OWASP API Top 10. Because middleBrick scans the unauthenticated attack surface and checks properties such as Input Validation and Property Authorization across 12 parallel security checks, it can surface these traversal-related misconfigurations in the API’s runtime behavior. The scanner also cross-references findings with the OpenAPI specification, so if your spec defines parameters that influence database or file-system paths, deviations between declared and observed behavior are highlighted with severity and remediation guidance.
Mongodb-Specific Remediation in Aspnet — concrete code fixes
To mitigate path traversal and injection-like issues when using MongoDB in ASP.NET, enforce strict allow-listing, avoid string interpolation for database and collection identifiers, and treat user input as untrusted at every layer. The following examples demonstrate secure patterns for collection selection, field access, and file-path handling.
1. Safe collection selection with allow-listing
Instead of directly using a request parameter to obtain a collection, map allowed values to known collection names.
// Good: Allow-list approach in ASP.NET with MongoDB C# driver
public IActionResult GetUserData(string requestedCollection)
{
var allowedCollections = new HashSet<string> { "users", "customers", "orders" };
if (!allowedCollections.Contains(requestedCollection))
{
return BadRequest("Invalid collection");
}
var collection = _database.GetCollection<BsonDocument>(requestedCollection);
var filter = Builders<BsonDocument>.Filter.Empty;
var documents = await collection.Find(filter).ToListAsync();
return Ok(documents);
}
2. Parameterized field access without dynamic dot notation
Avoid building field paths from raw user input. Use explicit DTOs or predefined field constants.
// Good: Strongly-typed access prevents traversal-like field manipulation
public class UserProfile
{
public ObjectId Id { get; set; }
public string Username { get; set; }
public Address ProfileAddress { get; set; }
}
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}
// Controller usage
[HttpGet("profile/city")]
public async Task<IActionResult> GetCityByUsername([FromQuery] string username)
{
var filter = Builders<UserProfile>.Filter.Eq(u => u.Username, username);
var projection = Builders<UserProfile>.Projection.Include(u => u.ProfileAddress.City);
var result = await _userProfiles.Find(filter).Project(projection).FirstOrDefaultAsync();
if (result == null) return NotFound();
return Ok(new { City = result["ProfileAddress.City"] });
}
3. Canonicalizing and validating file paths when combining with filesystem
If your ASP.NET app stores files and references them in MongoDB, resolve paths against a base directory and reject traversal sequences before storing metadata.
// Good: Path validation and canonicalization in ASP.NET
public IActionResult SaveReport(IFormFile file, string userProvidedName)
{
var baseDirectory = Path.Combine(Directory.GetCurrentDirectory(), "reports");
var safeName = Path.GetFileName(userProvidedName); // Strips directory components
var fullPath = Path.GetFullPath(Path.Combine(baseDirectory, safeName));
if (!fullPath.StartsWith(baseDirectory, StringComparison.OrdinalIgnoreCase))
{
return BadRequest("Path traversal attempt detected");
}
using var stream = new FileStream(fullPath, FileMode.Create);
file.CopyTo(stream);
var reportRef = new BsonDocument
{
{ "Name", safeName },
{ "Path", fullPath },
{ "StoredAt", DateTime.UtcNow }
};
_reportsCollection.InsertOne(reportRef);
return Ok(new { Message = "Report saved" });
}
4. Avoiding injection-like operators in query construction
Never allow user input to directly name operators such as $where or $expr. Use the strongly-typed filter builders instead.
// Good: Using the filter builder API rather than raw JSON/string composition
var username = GetUsernameFromRequest();
var filter = Builders<BsonDocument>.Filter.Eq("username", username);
var result = await _collection.Find(filter).FirstOrDefaultAsync();
These practices reduce the risk of path traversal and injection-like issues in ASP.NET applications using MongoDB. By combining allow-listing, strongly-typed models, and careful path handling, you align with secure coding guidance and make it harder for attackers to manipulate collection, field, or file paths.
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 |