Cross Site Request Forgery on Aws
How Cross Site Request Forgery Manifests in Aws
Cross Site Request Forgery (CSRF) in Aws applications occurs when an attacker tricks a user into executing unwanted actions on a web application where they're authenticated. In Aws Lambda functions and API Gateway integrations, CSRF vulnerabilities typically manifest through unvalidated state-changing requests that rely on the user's authenticated session.
A common Aws-specific CSRF scenario involves API Gateway endpoints that modify DynamoDB tables or S3 buckets without proper anti-CSRF tokens. For example, consider a Lambda function that deletes items from a DynamoDB table:
exports.handler = async (event) => {
const { id } = JSON.parse(event.body);
const params = {
TableName: process.env.TABLE_NAME,
Key: { id }
};
await dynamodb.deleteItem(params).promise();
return {
statusCode: 200,
body: JSON.stringify({ message: 'Item deleted' })
};
};This function is vulnerable because it accepts DELETE requests without any CSRF protection. An attacker could create a malicious website that automatically submits a form to this endpoint while the victim is authenticated with their Aws credentials.
Another Aws-specific CSRF pattern appears in Cognito user pool workflows. If your application uses AWS Amplify or Cognito for authentication but doesn't implement CSRF tokens in state-changing API calls, attackers can exploit the authenticated session. This is particularly dangerous when combined with AWS Secrets Manager or Parameter Store access where credentials might be temporarily exposed.
Serverless applications using AWS SAM or Serverless Framework often have multiple Lambda functions that interact with AWS services. If these functions don't validate the origin of requests or implement anti-CSRF measures, they become vulnerable to cross-site attacks. The stateless nature of Lambda functions makes CSRF prevention critical since there's no traditional session management.
API Gateway's CORS configuration can also contribute to CSRF vulnerabilities. If your API allows requests from any origin ("*") without proper validation, malicious sites can make authenticated requests to your Aws services on behalf of users.
Aws-Specific Detection
Detecting CSRF vulnerabilities in Aws applications requires examining both the API Gateway configuration and the Lambda function code. With middleBrick's black-box scanning approach, you can identify CSRF vulnerabilities without needing access to the source code or deployment configuration.
middleBrick scans for CSRF by testing state-changing endpoints with forged requests from different origins. The scanner attempts to submit POST, PUT, DELETE, and PATCH requests to your Aws API Gateway endpoints while monitoring the responses. If the endpoint accepts requests without proper anti-CSRF validation, it's flagged as vulnerable.
For Aws-specific detection, middleBrick examines several key indicators:
| Indicator | What It Reveals |
|---|---|
| State-changing endpoints without anti-CSRF tokens | Direct CSRF vulnerability |
| API Gateway CORS allowing all origins | Increased CSRF risk |
| DynamoDB or S3 operations without authentication validation | Potential for unauthorized data modification |
| Cognito user pool endpoints without CSRF protection | Authentication bypass risk |
The scanner also checks for proper SameSite cookie attributes and examines whether your Aws application implements double-submit cookies or synchronizer tokens. For applications using AWS Amplify, middleBrick verifies that the Amplify configuration includes proper CSRF protection settings.
middleBrick's LLM/AI security module specifically checks for CSRF vulnerabilities in applications that integrate with AWS Bedrock or other AI services. This includes testing whether AI model endpoints accept unauthenticated requests that could be exploited through CSRF attacks.
To manually verify CSRF protection in your Aws application, you can use tools like curl or Postman to send cross-origin requests to your API Gateway endpoints. Check if the endpoint rejects requests from unauthorized origins or requires anti-CSRF tokens for state-changing operations.
Aws-Specific Remediation
Remediating CSRF vulnerabilities in Aws applications requires implementing proper anti-CSRF mechanisms at both the API Gateway and Lambda function levels. Here are Aws-specific approaches to prevent CSRF attacks:
Double-Submit Cookie Pattern: Implement a double-submit cookie where the server sets a random token in both a cookie and a hidden form field. The server then verifies that both tokens match on state-changing requests.
// Lambda function with double-submit cookie validation
exports.handler = async (event) => {
const body = JSON.parse(event.body);
const csrfToken = body.csrfToken;
const cookieCsrf = event.headers['cookie']?.match(/csrfToken=([^;]+)/)?.[1];
if (csrfToken !== cookieCsrf) {
return {
statusCode: 403,
body: JSON.stringify({ error: 'CSRF token mismatch' })
};
}
// Process the request
};API Gateway Custom Authorizer: Create a custom authorizer Lambda function that validates CSRF tokens before allowing requests to reach your main business logic.
exports.handler = async (event, context) => {
const token = event.headers['csrf-token'];
if (!token || token !== process.env.CSRF_SECRET) {
return generateUnauthorizedResponse();
}
return generateAuthorizedResponse();
};Synchronizer Token Pattern: Generate a unique token per user session and require it for all state-changing operations. Store the token in the user's session (if using traditional sessions) or in a secure cookie.
// Generate CSRF token on session creation
exports.createSession = async (userId) => {
const csrfToken = crypto.randomBytes(32).toString('hex');
await dynamodb.put({
TableName: 'Sessions',
Item: {
userId,
csrfToken,
expires: new Date(Date.now() + 3600000).toISOString()
}
}).promise();
return csrfToken;
};API Gateway CORS Configuration: Restrict CORS to only allow requests from your application's domains rather than using wildcard (*) origins.
Cors:
AllowOrigins:
- https://yourapp.com
- https://www.yourapp.com
AllowHeaders:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-CSRF-TokenAWS WAF Integration: Use AWS WAF to create rules that block cross-origin requests to state-changing endpoints. You can configure rules based on the Origin header and request method.
SameSite Cookie Attributes: When using cookies for authentication, set the SameSite attribute to 'Strict' or 'Lax' to prevent cross-site request forgery.
// Set SameSite cookie in Lambda response
return {
statusCode: 200,
headers: {
'Set-Cookie': `sessionId=${sessionId}; HttpOnly; Secure; SameSite=Strict`
}
};For applications using AWS Amplify, ensure that the Amplify configuration includes proper CSRF protection settings and that your API endpoints validate the Amplify-provided CSRF tokens.