How to fix SQL Injection (Legacy & Modern)
in ServiceStack
Executive Summary
SQL Injection in ServiceStack typically occurs when developers bypass OrmLite's expression tree API in favor of raw SQL strings or manual concatenation. While ServiceStack provides robust abstractions, legacy codebases often contain 'escape hatches' that allow untrusted input to reach the database driver unparameterized. Securing these requires a shift to typed expressions or the AutoQuery plugin, which enforces safe parameterization by design.
The Vulnerable Pattern
public class GetUserVulnerable : Service
{
public object Any(GetUser request)
{
// CRITICAL: String interpolation creates a classic SQLi vector
var sql = $"SELECT * FROM Users WHERE Username = '{request.Username}'";
return Db.Select(sql);
}
}
The Secure Implementation
The vulnerable example uses string interpolation to build a query, allowing an attacker to break out of the string literal (e.g., ' OR 1=1 --). The secure modern approach leverages ServiceStack AutoQuery, which maps Request DTO properties to SQL parameters automatically, ensuring input is never executed as code. For manual queries, OrmLite's Expression API (u => u.Username == request.Username) translates C# logic into parameterized T-SQL/PL-SQL at runtime. If raw SQL is unavoidable, always pass an anonymous object as the second argument to Db.ExecuteSql to ensure the underlying ADO.NET provider handles parameter binding.
public class GetUserSecure : Service { // Modern Approach: Using AutoQuery for automatic, safe filtering public IAutoQueryDb AutoQuery { get; set; }public object Any(SearchUsers request) { var q = AutoQuery.CreateQuery(request, Request); return AutoQuery.Execute(request, q); } // Legacy/Direct Approach: Using OrmLite Typed Expressions public object Get(GetUser request) { return Db.Select<User>(u => u.Username == request.Username); } // Parameterized Raw SQL (if absolutely necessary) public object Post(UpdateUser request) { return Db.ExecuteSql("UPDATE Users SET Email = @email WHERE Id = @id", new { email = request.Email, id = request.Id }); }
}
Your ServiceStack API
might be exposed to SQL Injection (Legacy & Modern)
74% of ServiceStack 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.