Nosql Injection in Actix with Hmac Signatures
Nosql Injection in Actix with Hmac Signatures — how this specific combination creates or exposes the vulnerability
When an Actix web service uses Hmac Signatures for request authentication but still accepts user input that is directly interpolated into NoSQL queries, the combination can expose injection risks despite the integrity checks. Hmac Signatures help ensure that requests originate from a known client by validating a shared secret, but they do not sanitize or validate the content of the parameters themselves. If a developer uses signature validation to authorize an operation and then builds a NoSQL query by concatenating user-controlled values, an attacker can manipulate the data layer even when the signature is valid.
Consider a scenario where an endpoint accepts user_id and filter parameters, signs them with Hmac, and then uses those parameters to construct a MongoDB query. The signature confirms the parameters were not tampered with after signing, but it does not prevent malicious payloads such as { "$where": "return true" } or { "$in": { "$ne": [] } } from being interpreted by the NoSQL engine. Because the signature is verified before the query is built, the server may treat the request as trusted and execute the unsafe query. This pattern maps to common injection vectors such as NoSQL operators that bypass authentication or extract unintended data, aligning with findings from middleBrick scans that highlight BOLA/IDOR and Property Authorization issues when parameter handling is inconsistent.
In practice, an Actix handler that trusts signed parameters without additional validation might look like an API that uses JSON payloads and an Hmac header. The signature is computed over selected headers and the request body, and if the server uses the same user input in both the signature base and the NoSQL query, it creates a trust boundary mismatch. middleBrick’s checks for Input Validation and Property Authorization are designed to detect whether untrusted data reaches the query layer without normalization or type checks. Even with Hmac Signatures, missing validation allows attackers to probe for NoSQL-specific operators that alter query semantics, leading to data exposure or privilege escalation.
Hmac Signatures-Specific Remediation in Actix — concrete code fixes
To remediate the risk, treat Hmac Signatures as integrity verification only and apply strict input validation and type-safe query construction separately. Do not assume that a valid signature implies safe data. In Actix, this means validating and sanitizing each parameter before it is used in a NoSQL query, and using structured query builders that do not concatenate raw user input.
Below are concrete Actix examples that demonstrate secure handling. The first example shows an unsafe pattern where signed parameters are directly used in a MongoDB-like query construction. The second example shows the corrected approach with validation and parameterized query building.
// Unsafe pattern in Actix (illustrative)
use actix_web::{web, HttpResponse, HttpRequest};
use hmac::{Hmac, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac;
async fn unsafe_handler(
req: web::Json,
headers: web::Header<actix_web::http::header::Authorization>,
) -> HttpResponse {
// Extract and verify Hmac signature (simplified)
let signature = headers.get("X-API-Signature")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let data = req.body();
let mut mac = HmacSha256::new_from_slice(b"secret").expect("HMAC can take key of any size");
mac.update(data.as_bytes());
// naive verification for illustration
if format!("{:x}", mac.finalize().into_bytes()) != signature {
return HttpResponse::Unauthorized().finish();
}
// Directly using user input in a NoSQL query (unsafe)
let user_id = data["user_id"].as_str().unwrap_or("");
let filter = data["filter"].clone();
let query = format!("{{'_id': '{}', 'filter': {} }}", user_id, filter); // vulnerable
// execute query...
HttpResponse::Ok().body(query)
}
The unsafe example concatenates user_id and filter into a query string after verifying the Hmac, which allows injection through the filter field. To fix this, validate and serialize the query using a type-safe builder, and treat the Hmac as a binding assurance rather than a content sanitizer.
// Safe pattern in Actix with validation and parameterized query
use actix_web::{web, HttpResponse, HttpRequest};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde_json::{json, Value};
type HmacSha256 = Hmac;
async fn safe_handler(
body: web::Json,
) -> HttpResponse {
// Signature verification omitted for brevity; assume validated
let user_id = body.get("user_id")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.unwrap_or_default();
// Validate filter structure instead of raw concatenation
let filter_value = body.get("filter")
.and_then(|v| v.as_object())
.map(|obj| {
// Ensure only allowed keys/operators
let allowed_keys = ["status", "count"];
let mut sanitized = serde_json::Map::new();
for (k, v) in obj {
if allowed_keys.contains(&k.as_str()) && v.is_string() {
sanitized.insert(k.clone(), json!(v.as_str().unwrap()));
}
}
sanitized
})
.unwrap_or_default();
// Build query using structured data, avoiding string interpolation
let query = json!({
"filter": {
"user_id": user_id,
"criteria": filter_value
}
});
// Execute query safely
HttpResponse::Ok().json(query)
}
The safe handler validates each field, restricts allowed keys, and constructs the query from structured JSON rather than interpolated strings. This approach ensures that even with a valid Hmac Signature, untrusted input cannot alter query semantics. middleBrick’s checks for BFLA/Privilege Escalation and Unsafe Consumption help verify that such validation is consistently applied across endpoints.