HIGH server side template injectionaspnetdynamodb

Server Side Template Injection in Aspnet with Dynamodb

Server Side Template Injection in Aspnet with Dynamodb — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) in an ASP.NET context occurs when an attacker can control a template string that the server processes before sending output to a downstream service. When the downstream service is Amazon DynamoDB, the interaction can lead to unintended data access or exposure of sensitive attributes. In ASP.NET, templates are often used for formatting responses, generating emails, or transforming view models. If user input is merged into these templates without strict validation or isolation, an attacker can inject template directives that cause the server-side engine to evaluate expressions.

With DynamoDB, the risk is amplified when the templating logic is used to construct query keys, filter expressions, or to serialize item attributes. For example, if an ASP.NET application builds a DynamoDB query using a template like ${userId} and the userId value comes from user-controlled data, an attacker might inject ${@ctx.aws.credentials} or other expressions depending on the template engine. While DynamoDB itself does not execute templates, the server-side rendering layer can leak sensitive context or produce malformed requests that expose more data than intended.

Consider an endpoint that retrieves a user profile by ID and returns formatted output using a Razor-like or string template. If an attacker supplies a malicious value such as {{7*7}} or template-specific syntax, the server might evaluate it and return computed results or stack traces. When the resulting data is passed to DynamoDB operations, the application might inadvertently construct a Scan or Query request with an unsafe filter expression. This can lead to over-permissive scans or exposure of items that should remain restricted.

An example of a vulnerable code pattern in ASP.NET Core:

var template = userInput; // attacker-controlled
var result = string.Format(template, userId); // unsafe interpolation
var request = new QueryRequest
{
    TableName = "Users",
    KeyConditionExpression = $"Id = {result}"
};

In this pattern, userInput can contain template-like tokens that are resolved at runtime, potentially injecting expressions that affect how the key condition is built. Although DynamoDB does not parse .NET format strings, the surrounding application logic can misinterpret injected content, leading to malformed expressions or unsafe attribute access when serializing items.

Another scenario involves serialization of DynamoDB items to JSON for logging or debugging. If the serialization step uses a template engine that processes field values, injected template code could cause evaluation of system properties or invocation of helper methods, leading to data exposure. For instance, an item attribute named email might be rendered as ${email} in a log template, and if the template engine evaluates this, it could expose values in logs or error messages that are then stored or transmitted.

Because DynamoDB stores schemaless attributes, the impact of SSTI often relates to how the server-side layer interprets and passes data to the database rather than a vulnerability in DynamoDB itself. The primary defense is to treat all user input as untrusted, avoid dynamic template construction, and use parameterized requests or strict allowlists when interacting with DynamoDB.

Dynamodb-Specific Remediation in Aspnet — concrete code fixes

To prevent SSTI when working with DynamoDB in ASP.NET, avoid constructing queries or expressions from concatenated strings that include user input. Use the built-in parameterization features of the AWS SDK and ensure templates are isolated from data paths.

Safe Query Construction

Instead of embedding values directly in expression strings, use placeholder syntax and supply values through the SDK’s parameter collection. This prevents injected content from being interpreted as part of the expression.

var request = new QueryRequest
{
    TableName = "Users",
    KeyConditionExpression = "Id = :uid",
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>
    {
        { ":uid", new AttributeValue { S = userId } }
    }
};
var response = await client.QueryAsync(request);

Strict Input Validation and Allowlists

Validate incoming identifiers against a strict allowlist of known formats (e.g., UUID or integer patterns). Reject any value that does not match the expected pattern before it reaches DynamoDB logic.

if (!System.Text.RegularExpressions.Regex.IsMatch(userId, ^[a-f0-9-]{36}$))
{
    throw new ArgumentException("Invalid user ID format");
}

Safe Serialization for Logging

When serializing DynamoDB items for non-Database purposes, use a dedicated JSON serializer with no template evaluation. Avoid string-based formatting on attribute values that may originate from user input.

var item = await client.GetItemAsync(new GetItemRequest
{
    TableName = "Users",
    Key = new Dictionary<string, AttributeValue>
    {
        { "Id", new AttributeValue { S = userId } }
    }
});
var json = System.Text.Json.JsonSerializer.Serialize(item.Item);
// Use json for logging; do not apply string templates to item values

Disable Unnecessary Template Features

If you use a templating library, configure it to disable expression evaluation and only permit plain text substitution. For Razor views, ensure @ syntax is not used to evaluate arbitrary code based on user input.

// In Razor view, prefer displaying raw data instead of evaluating expressions
&lt;div&gt;@Html.DisplayFor(m =&gt; m.UserName)&lt;/div&gt;
// Avoid:
&lt;div&gt;@(userTemplate) // where userTemplate may include injected syntax&lt;/div&gt;

Middleware-Based Sanitization

Add request validation middleware that inspects incoming payloads for known template injection patterns (e.g., ${, @ with context keywords) and rejects suspicious inputs before they reach controller logic.

app.Use(async (context, next) =&gt;
{
    using var reader = new StreamReader(context.Request.Body);
    var body = await reader.ReadToEndAsync();
    if (body.Contains("${") || body.Contains("@(") )
    {
        context.Response.StatusCode = 400;
        await context.Response.WriteAsync("Invalid input detected");
        return;
    }
    // Restore body stream for downstream middleware
    var newStream = new MemoryStream(Encoding.UTF8.GetBytes(body));
    context.Request.Body = newStream;
    await next();
});

By combining parameterized DynamoDB requests, strict input validation, and safe serialization practices, you can effectively neutralize SSTI risks in ASP.NET applications that interact with DynamoDB.

Frequently Asked Questions

Can SSTI in ASP.NET lead to unauthorized DynamoDB access?
Yes, if user-controlled input is used to construct query expressions or filter strings without validation, attackers may manipulate logic to access unintended items or attributes. Always use parameterized requests and strict allowlists.
Does middleBrick test for SSTI when scanning APIs connected to DynamoDB?
middleBrick runs 12 parallel security checks including Input Validation and Property Authorization. While it does not fix issues, findings include SSTI-related observations with severity, remediation guidance, and mapping to frameworks such as OWASP API Top 10.