Cors Wildcard on Aws
How Cors Wildcard Manifests in Aws
CORS wildcard misconfigurations in AWS environments create significant attack vectors that can expose sensitive data and enable cross-origin attacks. The most common manifestation occurs when developers use overly permissive CORS policies across AWS services, particularly in API Gateway, Lambda, and CloudFront configurations.
In API Gateway, wildcard CORS often appears as:
{
"cors": {
"allowOrigins": ["*"],
"allowMethods": ["GET", "POST", "PUT", "DELETE"],
"allowHeaders": ["*"],
"allowCredentials": true
}
}This configuration is fundamentally broken because allowCredentials: true combined with allowOrigins: ["*"] violates the CORS specification. Browsers will reject such responses, but the real danger emerges when attackers craft requests that bypass these browser protections through server-side implementations.
AWS Lambda functions frequently inherit this problem when developers add CORS headers manually:
def lambda_handler(event, context):
response = {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': 'true'
},
'body': json.dumps({'message': 'Hello World'})
}
return responseThe credential flag here creates a critical vulnerability. Attackers can exploit this through CSRF attacks or by leveraging browser bugs to extract sensitive data from authenticated users.
CloudFront distributions compound these issues when misconfigured. A common pattern:
{
"Origins": {
"Quantity": 1,
"Items": [
{
"Id": "api-origin",
"DomainName": "api.example.com",
"OriginPath": "",
"CustomHeaders": {
"Quantity": 0
},
"OriginShield": {
"Enabled": false,
"OriginShieldRegion": ""
}
}
]
},
"DefaultCacheBehavior": {
"AllowedMethods": {
"Quantity": 2,
"Items": ["GET", "HEAD"],
"CachedMethods": {
"Quantity": 2,
"Items": ["GET", "HEAD"]
}
},
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "none"
},
"Headers": {
"Quantity": 0
}
},
"TargetOriginId": "api-origin",
"ViewerProtocolPolicy": "https-only"
},
"Restrictions": {
"GeoRestriction": {
"RestrictionType": "none",
"Quantity": 0
}
},
"WebACLId": ""
}Without proper CORS headers at the origin, CloudFront simply passes through whatever the backend returns, potentially exposing wildcard configurations to all users.
Real-world exploitation scenarios in AWS include:
- Credential leakage through reflected wildcard origins in error responses
- API key exposure when wildcard CORS allows unauthorized domains to interact with protected endpoints
- Session fixation attacks when cookies are accessible across origins
- Data exfiltration from authenticated users via malicious websites
- Supply chain attacks through third-party scripts loaded on compromised origins
The combination of AWS's global infrastructure and wildcard CORS creates particularly dangerous scenarios where a single misconfiguration can affect users across all geographic regions simultaneously.
Aws-Specific Detection
Detecting CORS wildcard vulnerabilities in AWS requires a multi-layered approach that examines both configuration files and runtime behavior. The first step is scanning your AWS infrastructure for permissive CORS settings.
Using AWS CLI to audit API Gateway:
aws apigateway get-rest-apis --query 'items[].[id,name]' --output table
# Check CORS configuration for each API
for api in $(aws apigateway get-rest-apis --query 'items[].id' --output text); do
aws apigateway get-integration --rest-api-id $api --resource-id / --http-method ANY
aws apigateway get-integration-response --rest-api-id $api --resource-id / --http-method ANY --status-code 200
doneFor Lambda functions, examine deployment packages and CloudFormation templates:
# Search for CORS patterns in Lambda code
find . -name "*.py" -exec grep -l "Access-Control-Allow-Origin" {} \;
find . -name "*.js" -exec grep -l "Access-Control-Allow-Origin" {} \;
# Check CloudFormation templates
find . -name "*.yaml" -o -name "*.yml" -o -name "*.json" | xargs grep -n "cors\|Access-Control-Allow-Origin" --colormiddleBrick's AWS-specific scanning identifies CORS wildcard issues by:
- Analyzing API Gateway CORS configurations for wildcard origins with credentials enabled
- Scanning Lambda function code for manual CORS header implementations
- Examining CloudFront distributions for missing or permissive CORS headers
- Testing actual endpoint responses to verify runtime CORS behavior
- Checking for reflected origins in error responses that could be exploited
The scanner performs active testing by making cross-origin requests to your AWS endpoints and analyzing the responses for security violations. This black-box approach catches issues that configuration scanning might miss, such as dynamically generated CORS headers or conditional logic that changes behavior based on request context.
For comprehensive AWS security, integrate middleBrick into your CI/CD pipeline:
# GitHub Actions workflow
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run middleBrick scan
run: |
npm install -g middlebrick
middlebrick scan https://api.yourdomain.com --output json > security-report.json
- name: Fail on high-risk findings
run: |
score=$(jq '.score' security-report.json)
if [ $score -lt 80 ]; then
echo "Security score below threshold: $score"
exit 1
fiThis automated approach ensures CORS vulnerabilities are caught before deployment to production AWS environments.
Aws-Specific Remediation
Remediating CORS wildcard vulnerabilities in AWS requires implementing strict origin validation and leveraging AWS-native security features. The goal is to replace wildcard policies with explicit, domain-specific configurations.
API Gateway CORS configuration should specify exact origins:
{
"cors": {
"allowOrigins": ["https://yourdomain.com", "https://app.yourdomain.com"],
"allowMethods": ["GET", "POST"],
"allowHeaders": ["Content-Type", "Authorization"],
"allowCredentials": true,
"exposeHeaders": ["Content-Length"],
"maxAge": 600
}
}For Lambda functions, implement origin validation middleware:
import json
from urllib.parse import urlparse
def validate_origin(event, allowed_origins):
origin = event.get('headers', {}).get('origin')
if not origin:
return False
parsed = urlparse(origin)
return parsed.netloc in allowed_origins
def cors_headers(event, allowed_origins):
origin = event.get('headers', {}).get('origin', '*')
if not validate_origin(event, allowed_origins):
return {}
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '600'
}
def lambda_handler(event, context):
if event['httpMethod'] == 'OPTIONS':
return {
'statusCode': 200,
'headers': cors_headers(event, ['yourdomain.com', 'app.yourdomain.com']),
'body': json.dumps({'message': 'OK'})
}
# Your business logic here
response = {
'statusCode': 200,
'headers': cors_headers(event, ['yourdomain.com', 'app.yourdomain.com']),
'body': json.dumps({'data': 'secure response'})
}
return responseCloudFront can enforce CORS at the edge using Lambda@Edge:
exports.handler = async (event, context) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
// Only allow requests from trusted origins
const allowedOrigins = ['https://yourdomain.com'];
const origin = headers.origin ? headers.origin[0].value : headers.referer ? headers.referer[0].value : null;
if (origin && allowedOrigins.includes(origin)) {
request.origin = {
custom: {
domainName: 'api.yourdomain.com',
port: 443,
protocol: 'https',
path: '',
sslProtocols: ['TLSv1', 'TLSv1.1', 'TLSv1.2'],
readTimeout: 5,
keepaliveTimeout: 5
}
};
// Add CORS headers to response
request.origin.custom.customHeaders = {
'x-forwarded-for': [{ key: 'X-Forwarded-For', value: headers['x-forwarded-for'] }]
};
}
return request;
};For comprehensive AWS security, implement WAF rules to block suspicious cross-origin requests:
{
"Name": "CorsProtectionRule",
"Priority": 1,
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsGranted": 1000,
"CloudWatchMetricsEnabled": true,
"MetricName": "CorsProtection"
},
"Statement": {
"ByteMatchStatement": {
"FieldToMatch": {
"UriPath": {}
},
"PositionalConstraint": "Contains",
"SearchString": "sensitive-endpoint",
"TextTransformations": [
{
"Priority": 0,
"Type": "Lowercase"
}
]
}
}
}Finally, implement monitoring and alerting for CORS-related security events using CloudWatch:
{
"Type": "Subscription",
"Status": "Enabled",
"Address": "[email protected]",
"ForwardingOptions": {}
}These remediation strategies transform your AWS environment from a permissive CORS configuration to a secure, domain-specific implementation that prevents cross-origin attacks while maintaining legitimate functionality.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |