Insecure Deserialization on Aws
How Insecure Deserialization Manifests in Aws
Insecure deserialization in Aws applications typically occurs when untrusted data is deserialized without proper validation. Aws's serverless architecture and distributed systems create unique attack vectors for this vulnerability.
The most common Aws-specific deserialization scenarios involve:
- Aws Lambda functions processing serialized payloads from API Gateway or S3 events
- Amazon DynamoDB storing serialized objects that are later deserialized
- Aws Step Functions passing serialized state between workflow steps
- Aws SQS/SNS messages containing serialized Java objects
- Aws Elastic Beanstalk applications using Java serialization
Consider this vulnerable Aws Lambda function pattern:
exports.handler = async (event) => {
const payload = event.body;
const obj = JSON.parse(payload); // Basic deserialization
// Object injection vulnerability
if (obj.action === 'execute') {
const command = obj.command;
execSync(command); // Remote code execution possible
}
return {
statusCode: 200,
body: JSON.stringify({ success: true })
};
};This pattern is particularly dangerous in Aws Lambda because attackers can trigger functions through multiple vectors: direct API calls, S3 object creations, or CloudWatch events. The serverless nature means the function executes in a potentially privileged context with access to Aws services.
Another Aws-specific scenario involves Java-based applications on Elastic Beanstalk:
public class VulnerableServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectInputStream ois = new ObjectInputStream(
request.getInputStream());
try {
Object obj = ois.readObject(); // Unsafe deserialization
processObject(obj); // Could be malicious payload
} catch (ClassNotFoundException e) {
// Exception handling without validation
}
}
}This code accepts serialized Java objects from HTTP requests, allowing attackers to craft malicious serialized payloads that execute arbitrary code when deserialized. Aws's network architecture makes this particularly concerning since Elastic Beanstalk instances often have network access to other Aws services.
Aws Step Functions also present deserialization risks when using the Pass or Task states with untrusted input:
{
"StartAt": "DeserializeState",
"States": {
"DeserializeState": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:DeserializeFunction",
"Parameters": {
"input.$": "$"
},
"ResultSelector": {
"data": "$.payload"
},
"ResultPath": "$.deserialized",
"Next": "ProcessState"
}
}
}The workflow passes serialized data between states without validation, creating opportunities for object injection attacks that can compromise the entire workflow execution.
Aws-Specific Detection
Detecting insecure deserialization in Aws environments requires understanding the platform's unique characteristics. Traditional static analysis tools often miss Aws-specific patterns.
middleBrick's Aws-focused scanning identifies deserialization vulnerabilities through:
- Runtime analysis of Lambda functions processing serialized input
- API Gateway endpoint inspection for unsafe deserialization patterns
- Code analysis of deployed functions for dangerous deserialization libraries
- Configuration review of Step Functions workflows
- Event source analysis for S3, SNS, and SQS-triggered functions
The scanner examines actual runtime behavior rather than just source code, which is crucial for Aws's dynamic deployment model where code changes frequently.
For manual detection, look for these Aws-specific indicators:
# Check Lambda functions for deserialization patterns
aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime]' --output table
# Examine function code for unsafe deserialization
aws lambda get-function --function-name MyFunction --query 'Code.Location'
# Review API Gateway for endpoints accepting serialized data
aws apigateway get-rest-apis --query 'items[*].[id,name]'
# Check Step Functions for unsafe state transitions
aws stepfunctions list-state-machines --query 'stateMachines[*].[name,status]'middleBrick automatically tests for deserialization vulnerabilities by sending crafted payloads to Aws endpoints and analyzing responses. The scanner's black-box approach is particularly effective for Aws services since it doesn't require source code access.
Key detection patterns include:
| Pattern | Aws Context | Risk Level |
|---|---|---|
| ObjectInputStream usage | Java Lambda/Beanstalk | Critical |
| JSON.parse without validation | Node.js Lambda/API Gateway | High |
| YAML.load with unsafe loader | Python Lambda | Critical |
| Pickle.loads | Python Lambda | Critical |
| XML External Entity processing | Any Lambda runtime | High |
middleBrick's scanning takes 5-15 seconds and provides a security score with specific findings about deserialization vulnerabilities, including the exact location and recommended fixes.
Aws-Specific Remediation
Remediating insecure deserialization in Aws requires platform-specific approaches that leverage Aws's native security features.
For Lambda functions, implement input validation and use Aws's native serialization formats:
const { validate } = require('jsonschema');
const inputSchema = {
type: 'object',
properties: {
action: { type: 'string', enum: ['safeAction'] },
data: { type: 'object' }
},
required: ['action', 'data']
};
exports.handler = async (event) => {
const payload = event.body;
// Validate input against schema
const result = validate(JSON.parse(payload), inputSchema);
if (!result.valid) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid input' })
};
}
// Safe processing
const obj = result.instance;
return {
statusCode: 200,
body: JSON.stringify({ success: true })
};
};For Java applications on Elastic Beanstalk, use Aws's built-in serialization security:
public class SecureServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Use safe JSON parsing instead of ObjectInputStream
StringBuilder jsonBuilder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
jsonBuilder.append(line);
}
String json = jsonBuilder.toString();
// Validate JSON structure before processing
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(json);
// Validate against expected schema
validateJsonStructure(rootNode);
processSafeData(rootNode);
} catch (JsonProcessingException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JSON");
return;
}
}
}For Step Functions, implement validation at each state transition:
{
"StartAt": "ValidateState",
"States": {
"ValidateState": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ValidateFunction",
"Parameters": {
"input.$": "$"
},
"ResultSelector": {
"validated": "$.result"
},
"ResultPath": "$.validated",
"Next": "ProcessState"
},
"ProcessState": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ProcessFunction",
"Parameters": {
"input.$": "$.validated"
},
"End": true
}
}
}Use Aws WAF to add an additional layer of protection for API Gateway endpoints:
{
"Type": "AWS::WAFv2::WebACL",
"Properties": {
"Name": "DeserializationProtection",
"Scope": "REGIONAL",
"DefaultAction": {
"Allow": {}
},
"Rules": [
{
"Name": "BlockSerializedObjects",
"Priority": 1,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsGranted": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "blockSerialized"
},
"Statement": {
"ByteMatchStatement": {
"FieldToMatch": {
"Body": {}
},
"PositionalConstraint": "CONTAINS",
"SearchString": "aced0005", // Java serialization magic bytes
"TextTransformations": [
{
"Priority": 0,
"Type": "LOWERCASE"
}
]
}
}
}
],
"VisibilityConfig": {
"SampledRequestsGranted": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "DeserializationACL"
}
}
}middleBrick's remediation guidance includes specific Aws-native fixes for each vulnerability type, helping teams implement these security controls efficiently.