Server Side Template Injection in Aspnet with Cockroachdb
Server Side Template Injection in Aspnet with Cockroachdb — how this specific combination creates or exposes the vulnerability
Server Side Template Injection (SSTI) in an ASP.NET application that uses CockroachDB as the backend datastore can amplify the impact of injection flaws by coupling template processing logic with database operations. SSTI occurs when an attacker can control a template string that is rendered by a server-side templating engine, such as Razor or other view engines. If user input is directly embedded into templates or into data used to construct templates, the attacker can execute arbitrary code during rendering.
In ASP.NET, this often arises when a controller passes unsanitized user input into a view model that is later used in Razor syntax or dynamic view composition. Because CockroachDB is commonly accessed via an ORM or raw SQL in .NET, the interaction chain becomes: attacker-controlled input → model or view data → template rendering → database query or command construction. If the injected template can reach database-related helpers—for example, through inclusion of raw SQL fragments, dynamic table or column names, or serialized query parameters—template injection can lead to unintended query behavior or exposure of sensitive data stored in CockroachDB.
Real-world patterns that increase risk include using user input to select database identifiers, constructing dynamic LINQ expressions from templates, or embedding serialized query configurations into view components. Because CockroachDB supports PostgreSQL-compatible syntax, attackers may attempt to exploit this compatibility to inject statements or influence execution plans if templates affect how queries are assembled. Even when the database enforces parameterized queries, the template layer may bypass parameterization by directly embedding values into identifiers or raw SQL strings, creating a second-order injection path.
Consider an endpoint that renders a dashboard based on a tenant identifier provided by the user. If the tenant name is used both to fetch data from CockroachDB and to populate a Razor template that generates further SQL fragments, an attacker could inject template code that alters the query structure or exposes rows from other tenants. This cross-layer exposure is particularly dangerous because it combines application logic flaws (template injection) with data store misconfigurations or insufficient isolation in CockroachDB.
middleBrick detects such multi-layer risks by correlating runtime behavior with OpenAPI specifications and by testing unauthenticated attack surfaces across the API stack. This includes checks for unsafe data exposure and unsafe consumption patterns that can arise when templates interact with database responses. The scanner highlights findings mapped to OWASP API Top 10 and provides remediation guidance rather than attempting to fix the code.
Cockroachdb-Specific Remediation in Aspnet — concrete code fixes
To mitigate SSTI when working with CockroachDB in ASP.NET, ensure strict separation between template rendering and data access. Never allow user input to influence template logic or database identifiers. Use parameterized queries for all data operations, and validate and sanitize any identifiers or schema-related inputs using an allowlist approach.
Below are concrete code examples for safe patterns in ASP.NET with CockroachDB.
- Use parameterized SQL with Npgsql for data access:
// Safe data query with parameters
var sql = "SELECT id, name FROM accounts WHERE tenant_id = @tenantId AND status = @status";
using var cmd = new NpgsqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@tenantId", tenantId);
cmd.Parameters.AddWithValue("@status", "active");
using var reader = await cmd.ExecuteReaderAsync();
- Avoid dynamic SQL built from templates; if dynamic queries are required, use an allowlist for identifiers:
// Safe dynamic table selection using allowlist
var allowedTables = new HashSet<string> { "users", "orders", "events" };
if (!allowedTables.Contains(tableName))
{
throw new ArgumentException("Invalid table name");
}
var sql = $"SELECT id, email FROM {tableName} WHERE tenant_id = @tenantId";
// Still use parameters for values
using var cmd = new NpgsqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@tenantId", tenantId);
- When using Razor views, never inject raw data into markup that could be interpreted as code:
// Safe Razor usage: encode output
<div>@Html.Encode(Model.TenantName)</div>
// Prefer strongly typed models and avoid @Html.Raw with user input
- Validate and encode any data used in view components or partial templates:
// In a view component
public async Task<IViewComponentResult> InvokeAsync(string userSuppliedKey)
{
var safeKey = AllowedKeys.Intersect(new[] { userSuppliedKey }).FirstOrDefault();
if (safeKey == null) return Content(string.Empty);
var data = await _db.FetchAsync(safeKey);
return View(data);
}
- Configure your ORM (e.g., Entity Framework Core) to use parameterized conventions and avoid raw SQL unless strictly necessary:
// EF Core with CockroachDB — prefer LINQ over raw SQL
var results = await context.Accounts
.Where(a => a.TenantId == tenantId && a.Status == "active")
.ToListAsync();
These practices reduce the attack surface by ensuring templates cannot alter control flow or query structure, and that CockroachDB interactions remain predictable and isolated. middleBrick supports secure development by scanning APIs for unsafe consumption patterns and data exposure risks, helping teams identify where such separation is missing.