Missing Tls in Aspnet with Mongodb
Missing Tls in Aspnet with Mongodb — how this specific combination creates or exposes the vulnerability
When an ASP.NET application connects to a MongoDB deployment without enforcing TLS, credentials, queries, and session data can traverse the network in cleartext. This is particularly risky in cloud or shared environments where traffic may pass through multiple network segments. middleBrick’s scan checks for missing TLS by verifying that the MongoDB connection string uses mongodb+srv:// or mongodb:// with an explicit TLS flag and that the server presents a valid certificate chain during the handshake.
In an ASP.NET context, developers sometimes rely on localhost or internal network assumptions and disable certificate validation for convenience, for example by setting SslSettings to CheckCertificateRevocation without enforcing SslMode as Require. If TLS is not required, an attacker on the same network or a malicious actor performing ARP spoofing can intercept traffic. middleBrick tests for unauthenticated endpoints and unencrypted data paths; without TLS, findings such as Data Exposure and Insecure Transport are surfaced, often mapped to OWASP API Top 10:2023 A5 (Security Misconfiguration) and relevant PCI-DSS requirements.
Additionally, MongoDB drivers used in ASP.NET may inadvertently accept unencrypted connections when the connection string omits or tls=true is overridden by code. middleBrick’s OpenAPI/Swagger analysis cross-references declared schemes and server variables with runtime behavior. If the spec indicates HTTPS but the runtime accepts cleartext MongoDB traffic, or if the application performs Active LLM security probes that reveal unauthenticated endpoints, the scanner flags insecure patterns. Real-world attack patterns include credential theft via packet capture and manipulation of database operations through injected packets, which can lead to privilege escalation or unauthorized data access.
Mongodb-Specific Remediation in Aspnet — concrete code fixes
To remediate missing TLS when using MongoDB in an ASP.NET application, enforce TLS at the driver level and validate server certificates. Use a strongly typed options pattern so that TLS settings are explicit and auditable. The following examples show a secure configuration for both synchronous and asynchronous usage.
Connection string and MongoClient configuration
Always use a connection string that explicitly requires TLS and verify certificates. Avoid mongodb:// for production unless wrapped in TLS via other means; prefer mongodb+srv:// with DNS seedlist and TLS enforced.
// appsettings.json
{
"MongoDbSettings": {
"ConnectionString": "mongodb+srv://user:password@cluster0.example.net/?tls=true&retryWrites=true&w=majority",
"DatabaseName": "mydb"
}
}
// Models/MongoSettings.cs
public class MongoSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
// Services/MongoService.cs
using MongoDB.Driver;
using Microsoft.Extensions.Options;
public class MongoService
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _database;
public MongoService(IOptions<MongoSettings> options)
{
var settings = options.Value;
var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(settings.ConnectionString));
// Enforce TLS and validate certificate chain
clientSettings.SslSettings = new SslSettings
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13,
CheckCertificateRevocation = true
};
clientSettings.ServerSelectionTimeout = TimeSpan.FromSeconds(30);
_client = new MongoClient(clientSettings);
_database = _client.GetDatabase(settings.DatabaseName);
}
public IMongoCollection<T> GetCollection<T>(string name) => _database.GetCollection<T>(name);
}
Usage in controllers with dependency injection
Register the service in Program.cs and inject it into controllers. This ensures that every operation uses the TLS-enabled client.
// Program.cs
builder.Services.Configure<MongoSettings>(builder.Configuration.GetSection("MongoDbSettings"));
builder.Services.AddScoped<MongoService>();
// Controllers/ItemsController.cs
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
private readonly MongoService _mongoService;
public ItemsController(MongoService mongoService)
{
_mongoService = mongoService;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetItem(string id)
{
var collection = _mongoService.GetCollection<BsonDocument>("items");
var filter = Builders<BsonDocument>.Filter.Eq("_id", new ObjectId(id));
var item = await collection.Find(filter).FirstOrDefaultAsync();
if (item == null)
{
return NotFound();
}
return Ok(item);
}
}
For hosts using SRV records, ensure your DNS and driver version support TLS via SRV. middleBrick’s scans validate that TLS is effectively enforced by testing unauthenticated attack surfaces and inspecting spec-to-runtime consistency. If your deployment requires custom CA certificates, add them to the machine or container trust store rather than disabling validation.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |