Pii Leakage in Aspnet with Mongodb
Pii Leakage in Aspnet with Mongodb — how this specific combination creates or exposes the vulnerability
When an ASP.NET application interacts with MongoDB, PII leakage often arises from a mismatch between the application’s data handling logic and MongoDB’s document structure. Inadequate field filtering, permissive query projections, and improper schema design can expose sensitive fields such as email addresses, phone numbers, national identifiers, or authentication tokens to unauthorized API consumers or logs.
ASP.NET APIs that expose MongoDB collections directly—either through custom controllers or OData-like dynamic queries—may return entire documents unless explicit projection is applied. For example, a controller action that queries collection.Find(filter).ToList() without specifying which fields to include can inadvertently return stored passwords, internal identifiers, or audit metadata embedded in the document. Even when developers intend to return only a subset of fields, missing or inconsistent projection logic can cause sensitive fields to surface in API responses, particularly if the schema evolves and new sensitive fields are added without corresponding projection updates.
Additionally, MongoDB’s flexible schema allows nested documents and arrays that may contain PII at varying depths. If an ASP.NET application maps these structures to dynamic objects or loosely typed models, developers might inadvertently serialize and transmit nested sensitive data. Logging mechanisms that capture query results or exception details can also become an unintentional channel for PII exposure, especially when debug information includes full BSON documents.
The combination of ASP.NET’s default behaviors—such as automatic model binding and JSON serialization—and MongoDB’s document-centric storage creates multiple avenues for PII leakage. Without strict field-level control, authentication tokens stored as plain strings, or personally identifiable fields stored without encryption at rest, can be exposed through seemingly benign API endpoints. Regular schema reviews, explicit field selection, and runtime scanning for PII patterns are essential to mitigate these risks in this specific technology stack.
Mongodb-Specific Remediation in Aspnet — concrete code fixes
To prevent PII leakage in an ASP.NET application using MongoDB, apply explicit projections, avoid returning full documents, and enforce strict schema governance. The following approaches and code examples focus on minimizing the data surface exposed through API endpoints.
- Use projection to return only required fields. Instead of returning entire documents, specify inclusion of safe fields and exclusion of sensitive ones.
// Example: Return only non-PII fields for a user profile
var filter = Builders<BsonDocument>.Filter.Eq("UserId", userId);
var projection = Builders<BsonDocument>.Projection
.Include("UserId")
.Include("DisplayName")
.Exclude("Email")
.Exclude("PhoneNumber")
.Exclude("PasswordHash")
.Exclude("SecurityStamp");
var user = await collection.Find(filter).Project(projection).FirstOrDefaultAsync();
- Define a strongly typed DTO and map only safe properties to avoid accidental inclusion of nested PII.
public class UserProfileDto
{
public string UserId { get; set; }
public string DisplayName { get; set; }
// Do not include Email, PhoneNumber, or other PII here
}
// In the controller or service
var dto = await collection.Find(filter)
.Project<UserProfileDto>(p => new UserProfileDto
{
UserId = p.UserId,
DisplayName = p.DisplayName
})
.FirstOrDefaultAsync();
- Apply schema design rules that separate sensitive data into restricted collections or encrypted fields, and avoid storing PII in arrays that are eagerly loaded.
// Example: Query a dedicated, restricted profile collection instead of a full-user collection
var safeFilter = Builders<BsonDocument>.Filter.Eq("UserId", userId);
var safeProjection = Builders<BsonDocument>.Projection
.Include("UserId")
.Include("Role")
.Exclude("Email")
.Exclude("Address");
var safeProfile = await restrictedCollection.Find(safeFilter).Project(safeProjection).FirstOrDefaultAsync();
- Validate and sanitize inputs to prevent injection-driven data exposure, and configure MongoDB driver options to suppress verbose logging of query results.
// Example: Disable client-side logging of full command payloads in sensitive contexts
var clientSettings = MongoClientSettings.FromConnectionString(connectionString);
clientSettings.ClusterConfigurator = cb =>
{
cb.Subscribe<CommandStartedEvent>(evt =>
{
// Avoid logging evt.Command in full; mask or omit PII fields if logging is required
});
};
var client = new MongoClient(clientSettings);
By combining explicit field selection, DTO-based serialization, and careful schema management, you reduce the likelihood that ASP.NET endpoints will expose PII stored in MongoDB documents.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |