GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix NoSQL Injection
in ServiceStack

Executive Summary

NoSQL Injection in ServiceStack usually surfaces when developers bypass the high-level ServiceStack abstractions (like AutoQuery) and manually construct queries for backends like MongoDB or RavenDB. By passing raw, unsanitized input into query filters or BSON documents, you grant attackers the ability to inject operators like $gt, $ne, or $where, leading to authentication bypass, data exfiltration, or DoS.

The Vulnerable Pattern

VULNERABLE CODE
public class UserSearchService : Service
{
    public IMongoDatabase Db { get; set; }
public object Any(SearchUsers request)
{
    // CRITICAL VULNERABILITY: Raw JSON filter construction using string concatenation.
    // An attacker can provide a payload like: admin' , $or: [ {} ]
    var filter = "{ 'Username': '" + request.Username + "' }";
    return Db.GetCollection<User>("Users").Find(filter).ToList();
}

}

The Secure Implementation

The vulnerable code treats user-controlled input as part of the query's structural logic. By injecting a single quote and a comma, an attacker can append additional MongoDB operators to the BSON document, effectively changing the query's behavior (e.g., returning all records). The secure implementation utilizes the MongoDB C# driver's FilterBuilder. This abstraction layer ensures that the value of 'request.Username' is passed as a literal parameter, neutralizing any embedded NoSQL operators and preventing the query structure from being hijacked.

SECURE CODE
public class UserSearchService : Service
{
    public IMongoDatabase Db { get; set; }
public object Any(SearchUsers request)
{
    // SECURE: Use the strongly-typed Filter Definition Builder or LINQ expressions.
    // ServiceStack's recommended pattern for NoSQL drivers is to use type-safe builders
    // which treat user input strictly as a value, not a command/operator.
    var filter = Builders<User>.Filter.Eq(u => u.Username, request.Username);
    return Db.GetCollection<User>("Users").Find(filter).ToList();
}

}

System Alert • ID: 2752
Target: ServiceStack API
Potential Vulnerability

Your ServiceStack API might be exposed to NoSQL Injection

74% of ServiceStack apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.