Prototype Pollution on Aws
How Prototype Pollution Manifests in Aws
Prototype pollution in Aws applications typically occurs when user-controlled data is merged into JavaScript objects without proper sanitization, allowing attackers to modify object prototypes and inject malicious properties. In Aws Lambda functions and Node.js-based services, this vulnerability often appears in request body parsing, configuration merging, and data transformation pipelines.
A common Aws-specific pattern involves merging configuration objects from multiple sources. Consider a Lambda function that combines default settings with user-provided configuration:
const merge = require('lodash.merge');
exports.handler = async (event) => {
const defaultConfig = {
timeout: 30,
maxRetries: 3,
__proto__: {} // default prototype
};
const userConfig = JSON.parse(event.body);
const finalConfig = merge(defaultConfig, userConfig);
// Configuration is now polluted if userConfig contained __proto__ keys
return {
statusCode: 200,
body: JSON.stringify(finalConfig)
};
};The critical vulnerability here is that lodash.merge performs deep merging without prototype protection. An attacker can send a request with __proto__.isAdmin: true to elevate privileges across all objects.
Another Aws-specific scenario occurs in API Gateway integrations where path parameters or query strings are merged into request objects. Aws SAM templates often define API structures that automatically merge parameters:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs18.x
Events:
ApiEvent:
Type: Api
Properties:
Path: /config
Method: post
# Aws automatically merges path params, query strings, and bodyWhen handling S3 event triggers, prototype pollution can occur through event record merging. Aws S3 events contain nested objects that might be merged with user data:
exports.handler = async (event) => {
const s3Record = event.Records[0].s3;
const userData = JSON.parse(event.body);
// Vulnerable merge - attacker controls userData structure
const combined = { ...s3Record, ...userData };
// If userData contains __proto__.malicious: true, it affects all objects
return combined;
};Serverless Framework applications face similar risks when using serverless-http middleware that merges Express request properties with Aws event data.
Aws-Specific Detection
Detecting prototype pollution in Aws environments requires both static analysis and runtime scanning. middleBrick's black-box scanning approach is particularly effective for Aws applications since it tests the actual deployed endpoints without requiring source code access.
middleBrick scans Aws API Gateway endpoints by sending specially crafted payloads that test for prototype pollution vulnerabilities. The scanner attempts to modify object prototypes through common attack vectors:
POST /api/config HTTP/1.1
Host: your-aws-endpoint.amazonaws.com
Content-Type: application/json
{
"__proto__": {
"isAdmin": true,
"permissions": ["read", "write", "delete"]
},
"constructor": {
"prototype": {
"secretMethod": "exploit"
}
}
}The scanner then analyzes responses to detect if the prototype modifications succeeded. middleBrick's Aws-specific detection includes checking for:
- Unexpected properties appearing in JSON responses that weren't in the original request
- Prototype chain modifications affecting object behavior
- Constructor prototype pollution that could lead to RCE
- Global object modifications through
Object.prototypepollution - Symbol-based prototype pollution attempts
For Aws Lambda functions, middleBrick can scan through API Gateway endpoints or direct function URLs. The scanner tests various merge scenarios common in Aws applications:
// middleBrick test patterns for Aws environments
const testPayloads = [
{ '__proto__': { 'isAdmin': true } },
{ 'constructor': { 'prototype': { 'secret': 'value' } } },
{ Symbol.for('prototype'): { 'hack': true } },
{ 'toString': () => 'malicious' }
];middleBrick's dashboard provides Aws-specific insights by mapping findings to the Lambda function or API Gateway endpoint where vulnerabilities were detected. The tool generates reports showing which Aws services are affected and provides severity ratings based on the potential impact.
For organizations using Aws SAM or Serverless Framework, middleBrick can integrate with CI/CD pipelines to automatically scan deployed stacks. The GitHub Action can be configured to scan Aws endpoints after deployment:
- name: Scan Aws API with middleBrick
uses: middleBrick/middlebrick-action@v1
with:
url: https://${{ secrets.AWS_API_ID }.execute-api.${{ secrets.AWS_REGION }}.amazonaws.com
fail-on-severity: high
output-format: jsonAws-Specific Remediation
Remediating prototype pollution in Aws applications requires a multi-layered approach. The primary defense is input sanitization combined with safe object merging practices. For Aws Lambda functions, implement strict input validation before any object manipulation:
const sanitizeInput = (input) => {
const forbiddenKeys = ['__proto__', 'constructor', 'prototype'];
const sanitized = {};
for (const [key, value] of Object.entries(input)) {
if (forbiddenKeys.includes(key)) {
throw new Error(`Invalid key: ${key}`);
}
if (typeof value === 'object' && value !== null) {
sanitized[key] = sanitizeInput(value);
} else {
sanitized[key] = value;
}
}
return sanitized;
};
exports.handler = async (event) => {
const userConfig = JSON.parse(event.body);
const sanitizedConfig = sanitizeInput(userConfig);
// Safe merge using object spread without deep merging
const finalConfig = { ...defaultConfig, ...sanitizedConfig };
return {
statusCode: 200,
body: JSON.stringify(finalConfig)
};
};For Aws applications using Lodash or similar libraries, upgrade to versions that include prototype protection or use alternative merging strategies:
// Safer alternatives for Aws applications
const safeMerge = (target, source) => {
const merged = { ...target };
for (const [key, value] of Object.entries(source)) {
if (Object.prototype.hasOwnProperty.call(merged, key)) {
merged[key] = value;
}
}
return merged;
};
// Or use structuredClone for deep cloning without prototype pollution
const safeDeepClone = (obj) => structuredClone(obj);When using Aws API Gateway with Lambda integrations, configure request validation at the API Gateway level to reject malicious payloads before they reach your function:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
DefinitionUri: swagger.yaml
EndpointConfiguration: REGIONAL
# Add request validation models
Models:
SafeRequest:
ContentType: application/json
Schema: ${file(models/safe-request.json)}For Aws applications processing S3 events or other Aws service events, implement strict type checking and avoid merging event data with user input:
const processS3Event = (event) => {
if (!event || !event.Records || !event.Records[0].s3) {
throw new Error('Invalid S3 event structure');
}
// Process event data without merging with external input
const s3Record = event.Records[0].s3;
// ... handle s3Record safely
};middleBrick's remediation guidance includes Aws-specific recommendations such as using Aws WAF to filter malicious requests, implementing API Gateway request validation, and using Aws X-Ray for tracing prototype pollution attempts in production.