Fix NoSQL Injection in Ktor
NoSQL Injection in Ktor/MongoDB stacks occurs when untrusted user input is interpolated directly into query objects or raw BSON strings. Attackers can inject operators like $gt, $ne, or $where to bypass authentication or exfiltrate the entire database. If you're building queries by concatenating strings or using Document.parse() with raw input, your app is owned.
The Vulnerable Pattern
get("/user") { val username = call.request.queryParameters["username"] // VULNERABLE: Direct string interpolation into a JSON parser val query = Document.parse("{ 'username': '$username' }") val result = collection.find(query).firstOrNull() call.respond(result ?: "Not found") }
// Exploit: /user?username=’ } , { ‘password’: { ‘$ne’: ‘admin’ }
The Secure Implementation
The vulnerability stems from treating data as code. In the insecure example, Document.parse() interprets the interpolated string, allowing an attacker to break out of the 'username' field and inject new query logic. The secure implementation uses the MongoDB Java/Kotlin driver's 'Filters' API. This API uses parameterized builders that ensure input is escaped and treated exclusively as a literal value, preventing any modification of the query structure. Always avoid raw BSON strings and prefer type-safe DSLs like KMongo or the official MongoDB Kotlin driver's DSL.
get("/user") { val username = call.request.queryParameters["username"] ?: return@get call.respond(HttpStatusCode.BadRequest)// SECURE: Use the MongoDB Driver's Type-Safe Filters // This treats the input strictly as a value, not part of the query structure val filter = Filters.eq("username", username) val result = collection.find(filter).firstOrNull() if (result == null) { call.respond(HttpStatusCode.NotFound) } else { call.respond(result) }
}
Your Ktor API
might be exposed to NoSQL Injection
74% of Ktor apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.