Hallucination Attacks in Aspnet with Dynamodb
Hallucination Attacks in Aspnet with Dynamodb — how this specific combination creates or exposes the vulnerability
Hallucination attacks in an ASP.NET application that uses Amazon DynamoDB as a persistence layer occur when an attacker manipulates application logic or input to produce false or fabricated responses, often by exploiting unchecked or loosely validated data pathways between the web layer and the database. In this stack, the risk is elevated when the ASP.NET backend deserializes user-controlled input and uses it to construct DynamoDB queries without strict schema enforcement or type validation. For example, if an endpoint accepts a JSON payload that specifies a TableName or key attribute values and passes them directly to the AWS SDK, an attacker can supply malformed or unexpected values that cause the application to read from incorrect tables, misinterpret index names, or fall back to default or empty responses that the application then synthesizes into plausible but incorrect data.
The vulnerability is not in DynamoDB itself, which enforces strict schema and access policies, but in the ASP.NET layer that builds requests and interprets results. If the application uses dynamic or loosely typed objects (e.g., ExpandoObject or JObject) to map query results, it may fill missing fields with inferred or invented values when the expected attributes are absent. This can happen when scans test unauthenticated endpoints that expose item retrieval by ID, where missing items trigger fallback logic that fabricates data to maintain a consistent response shape. The ASP.NET runtime may also mask underlying query failures by catching exceptions and returning synthesized content, which effectively becomes a hallucinated response that appears authoritative to the client.
An attacker can probe these behaviors using crafted requests that reference nonexistent items, malformed keys, or inconsistent partition key designs. For example, sending a malformed sort key or an unexpected attribute type can cause the deserialization logic to produce partial or empty results, which the application then embellishes with plausible defaults. Because the scan testing for this issue runs unauthenticated checks across the attack surface, it can detect endpoints that lack strict input validation and schema-bound deserialization. The OpenAPI/Swagger analysis performed by middleBrick cross-references the declared response schemas with runtime observations, highlighting discrepancies where actual responses contain fields not defined in the spec or where null/missing values are replaced with synthetic content.
In the context of compliance mappings, hallucination risks intersect with OWASP API Top 10 categories such as API1:2023 Broken Object Level Authorization and API10:2023 Excessive Data Exposure, because fabricated responses can leak internal logic or sensitive defaults. Unlike traditional injection, these attacks do not rely on malicious data exfiltration but on the manipulation of output integrity. middleBrick’s LLM/AI Security checks are particularly relevant here, as they include output scanning for PII, API keys, and executable code, ensuring that hallucinated content does not inadvertently expose sensitive information or code-like artifacts in API responses.
Dynamodb-Specific Remediation in Aspnet — concrete code fixes
To remediate hallucination risks in ASP.NET applications using DynamoDB, enforce strict schema validation, typed deserialization, and defensive handling of missing or malformed data. Avoid dynamic or loosely typed mappings for query results, and instead use explicitly defined POCO classes that match the DynamoDB table schema. Validate all incoming identifiers against expected formats before constructing requests, and ensure that missing items result in consistent error responses rather than synthesized data.
Use the AWS SDK for .NET with strongly typed models and the Document Model pattern where appropriate. Below is a secure example of an ASP.NET Core endpoint that retrieves an item by ID using a typed model and returns a 404 when the item does not exist, avoiding any fabrication:
using Amazon.DynamoDBv2;using Amazon.DynamoDBv2.DocumentModel;using Amazon.DynamoDBv2.Model;using Microsoft.AspNetCore.Mvc;using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IAmazonDynamoDB _dynamoDb;
private const string TableName = "Products";
public ProductsController(IAmazonDynamoDB dynamoDb)
{
_dynamoDb = dynamoDb;
}
[HttpGet("{id}")]
public async Task<IActionResult>GetProductAsync(string id)
{
if (string.IsNullOrWhiteSpace(id) || !id.StartsWith("prod_"))
{
return BadRequest(new { Error = "Invalid product ID format." });
}
var request = new GetItemRequest
{
TableName = TableName,
Key = new Dictionary<string, AttributeValue>
{
{ "Id", new AttributeValue { S = id } }
},
ConsistentRead = true
};
var response = await _dynamoDb.GetItemAsync(request);
if (response.Item == null || response.Item.Count == 0)
{
return NotFound(new { Error = "Product not found." });
}
// Use DocumentModel to map to a typed object
var document = Document.FromAttributeMap(response.Item);
var product = document.ToObject<Product>();
return Ok(product);
}
}
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
When using the Document Model, ensure that the attribute names in your POCO match the DynamoDB attribute names or use the [DynamoDBProperty] attribute for mapping. This prevents misinterpretation of missing attributes and ensures that deserialization errors are surfaced explicitly rather than being silently filled with hallucinated values.
Additionally, enforce strict input validation at the API gateway and application layers. For query parameters and path variables, use model binding with type constraints and regular expression patterns. For example, limit ID formats to known patterns and reject unexpected attribute keys in request bodies. Combine this with centralized error handling to ensure that all exceptions from DynamoDB (such as ResourceNotFoundException or ProvisionedThroughputExceededException) result in appropriate HTTP status codes and generic error messages, not fabricated content.
For applications that consume DynamoDB streams or use asynchronous processing, validate the shape of incoming records and avoid assuming the presence of optional attributes. Use schema versioning and reject messages that do not conform to the expected structure. middleBrick’s CLI tool can be used to scan your endpoints and verify that responses conform to declared schemas, while the GitHub Action can enforce these checks in CI/CD pipelines to prevent regressions that could reintroduce hallucination risks.
Related CWEs: llmSecurity
| CWE ID | Name | Severity |
|---|---|---|
| CWE-754 | Improper Check for Unusual or Exceptional Conditions | MEDIUM |