SEC05-BP04: Automate network protection

Automate your protective controls to provide a self-defending network based on threat intelligence and anomaly detection. For example, intrusion detection and prevention tools can adapt to current threats and reduce their impact. A web application firewall can automatically block or rate limit requests based on patterns in the traffic.

Implementation guidance

Automating network protection enables your security infrastructure to respond to threats in real-time without human intervention. By implementing automated protective controls, you can significantly reduce response times and ensure consistent application of security policies across your network infrastructure.

Key steps for implementing this best practice:

  1. Implement automated threat response:
    • Configure automatic blocking of malicious IP addresses
    • Set up automated quarantine of compromised resources
    • Implement dynamic security group rule updates
    • Configure automatic traffic redirection during attacks
    • Enable automated incident escalation procedures
  2. Deploy adaptive security controls:
    • Implement machine learning-based anomaly detection
    • Configure behavioral analysis for network traffic
    • Set up adaptive rate limiting based on traffic patterns
    • Deploy dynamic firewall rules based on threat intelligence
    • Implement context-aware access controls
  3. Configure automated policy enforcement:
    • Implement Infrastructure as Code for consistent security policies
    • Set up automated compliance checking and remediation
    • Configure automatic security configuration drift detection
    • Deploy policy-based network segmentation
    • Implement automated security baseline enforcement
  4. Enable intelligent traffic management:
    • Configure automatic load balancing during DDoS attacks
    • Implement geo-blocking based on threat intelligence
    • Set up automated content delivery network (CDN) protection
    • Deploy intelligent traffic routing for threat mitigation
    • Configure automatic capacity scaling for attack resilience
  5. Integrate threat intelligence feeds:
    • Configure automatic updates from threat intelligence sources
    • Implement real-time indicator of compromise (IoC) blocking
    • Set up automated reputation-based filtering
    • Deploy dynamic blacklist and whitelist management
    • Configure threat hunting automation
  6. Implement automated monitoring and alerting:
    • Set up real-time security event correlation
    • Configure automated anomaly detection and alerting
    • Implement predictive threat analysis
    • Deploy automated security metrics collection
    • Set up intelligent alert prioritization and routing

Implementation examples

Example 1: Automated threat response with Lambda and EventBridge

Example 2: Automated security group management

python import boto3 import json from datetime import datetime

def setup_automated_ddos_protection(): “"”Configure automated DDoS protection with CloudFront and Shield Advanced”””

cloudfront = boto3.client('cloudfront')
shield = boto3.client('shield')
route53 = boto3.client('route53')

# Enable Shield Advanced for enhanced DDoS protection
try:
    shield.create_subscription()
    print("Shield Advanced subscription created")
except shield.exceptions.ResourceAlreadyExistsException:
    print("Shield Advanced already enabled")

# Create CloudFront distribution with DDoS protection
distribution_config = {
    'CallerReference': f'ddos-protection-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}',
    'Comment': 'Automated DDoS protection distribution',
    'DefaultCacheBehavior': {
        'TargetOriginId': 'primary-origin',
        'ViewerProtocolPolicy': 'redirect-to-https',
        'TrustedSigners': {
            'Enabled': False,
            'Quantity': 0
        },
        'ForwardedValues': {
            'QueryString': False,
            'Cookies': {'Forward': 'none'}
        },
        'MinTTL': 0,
        'Compress': True
    },
    'Origins': {
        'Quantity': 1,
        'Items': [
            {
                'Id': 'primary-origin',
                'DomainName': 'example.com',
                'CustomOriginConfig': {
                    'HTTPPort': 80,
                    'HTTPSPort': 443,
                    'OriginProtocolPolicy': 'https-only',
                    'OriginSslProtocols': {
                        'Quantity': 1,
                        'Items': ['TLSv1.2']
                    }
                }
            }
        ]
    },
    'Enabled': True,
    'WebACLId': 'arn:aws:wafv2:us-east-1:123456789012:global/webacl/DDoSProtection/12345678-1234-1234-1234-123456789012'
}

try:
    distribution_response = cloudfront.create_distribution(
        DistributionConfig=distribution_config
    )
    
    distribution_id = distribution_response['Distribution']['Id']
    distribution_domain = distribution_response['Distribution']['DomainName']
    
    print(f"Created CloudFront distribution: {distribution_id}")
    
    # Configure Route 53 health checks for failover
    setup_health_checks_and_failover(route53, distribution_domain)
    
    return distribution_id
    
except Exception as e:
    print(f"Error creating CloudFront distribution: {str(e)}")
    return None

def setup_health_checks_and_failover(route53, distribution_domain): “"”Set up Route 53 health checks and automated failover”””

try:
    # Create health check for primary endpoint
    health_check_response = route53.create_health_check(
        Type='HTTPS',
        ResourcePath='/health',
        FullyQualifiedDomainName=distribution_domain,
        Port=443,
        RequestInterval=30,
        FailureThreshold=3,
        Tags=[
            {
                'Key': 'Name',
                'Value': 'Primary-Endpoint-Health-Check'
            }
        ]
    )
    
    health_check_id = health_check_response['HealthCheck']['Id']
    
    # Create CloudWatch alarm for health check
    cloudwatch = boto3.client('cloudwatch')
    
    cloudwatch.put_metric_alarm(
        AlarmName='PrimaryEndpointHealthCheck',
        ComparisonOperator='LessThanThreshold',
        EvaluationPeriods=2,
        MetricName='HealthCheckStatus',
        Namespace='AWS/Route53',
        Period=60,
        Statistic='Minimum',
        Threshold=1.0,
        ActionsEnabled=True,
        AlarmActions=[
            'arn:aws:sns:us-west-2:123456789012:DDoSProtectionAlerts'
        ],
        AlarmDescription='Primary endpoint health check failure',
        Dimensions=[
            {
                'Name': 'HealthCheckId',
                'Value': health_check_id
            }
        ]
    )
    
    print(f"Created health check and alarm: {health_check_id}")
    
except Exception as e:
    print(f"Error setting up health checks: {str(e)}")

def create_automated_waf_rules(): “"”Create WAF rules with automated DDoS protection”””

wafv2 = boto3.client('wafv2')

# Create rate-based rule with automatic scaling
rate_based_rule = {
    'Name': 'AutomatedRateLimiting',
    'Priority': 1,
    'Action': {'Block': {}},
    'Statement': {
        'RateBasedStatement': {
            'Limit': 2000,
            'AggregateKeyType': 'IP',
            'ScopeDownStatement': {
                'NotStatement': {
                    'Statement': {
                        'GeoMatchStatement': {
                            'CountryCodes': ['US', 'CA', 'GB']  # Allow from trusted countries
                        }
                    }
                }
            }
        }
    },
    'VisibilityConfig': {
        'SampledRequestsEnabled': True,
        'CloudWatchMetricsEnabled': True,
        'MetricName': 'AutomatedRateLimiting'
    }
}

# Create adaptive rule based on request patterns
adaptive_rule = {
    'Name': 'AdaptiveProtection',
    'Priority': 2,
    'Action': {'Block': {}},
    'Statement': {
        'AndStatement': {
            'Statements': [
                {
                    'ByteMatchStatement': {
                        'SearchString': 'bot',
                        'FieldToMatch': {'SingleHeader': {'Name': 'user-agent'}},
                        'TextTransformations': [
                            {'Priority': 1, 'Type': 'LOWERCASE'}
                        ],
                        'PositionalConstraint': 'CONTAINS'
                    }
                },
                {
                    'RateBasedStatement': {
                        'Limit': 100,
                        'AggregateKeyType': 'IP'
                    }
                }
            ]
        }
    },
    'VisibilityConfig': {
        'SampledRequestsEnabled': True,
        'CloudWatchMetricsEnabled': True,
        'MetricName': 'AdaptiveProtection'
    }
}

try:
    web_acl_response = wafv2.create_web_acl(
        Name='AutomatedDDoSProtection',
        Scope='CLOUDFRONT',
        DefaultAction={'Allow': {}},
        Rules=[rate_based_rule, adaptive_rule],
        Description='Automated DDoS protection with adaptive rules',
        Tags=[
            {
                'Key': 'Name',
                'Value': 'Automated-DDoS-Protection'
            }
        ],
        VisibilityConfig={
            'SampledRequestsEnabled': True,
            'CloudWatchMetricsEnabled': True,
            'MetricName': 'AutomatedDDoSProtection'
        }
    )
    
    return web_acl_response['Summary']['ARN']
    
except Exception as e:
    print(f"Error creating automated WAF rules: {str(e)}")
    return None

Example 4: Infrastructure as Code for automated network security

AWS services to consider

AWS Lambda

Lets you run code without provisioning or managing servers. Essential for implementing automated response functions and security orchestration workflows.

Amazon EventBridge

A serverless event bus that makes it easy to connect applications together. Enables automated response to security events from multiple AWS services.

AWS Systems Manager

Gives you visibility and control of your infrastructure on AWS. Provides automation capabilities for security configuration management and incident response.

Amazon CloudWatch

Monitors your AWS resources and applications in real time. Provides metrics, alarms, and automated actions for network security monitoring.

AWS CloudFormation

Gives you an easy way to model a collection of related AWS and third-party resources. Enables Infrastructure as Code for consistent security deployments.

Amazon GuardDuty

Provides intelligent threat detection for your AWS accounts and workloads. Integrates with automated response systems for immediate threat mitigation.

Benefits of automating network protection

  • Rapid threat response: Automated systems can respond to threats in seconds rather than minutes or hours
  • Consistent policy enforcement: Automation ensures security policies are applied uniformly across all network resources
  • Reduced human error: Automated processes eliminate mistakes that can occur during manual security operations
  • 24/7 protection: Automated systems provide continuous protection without requiring human oversight
  • Scalable security: Automation scales with your infrastructure growth without proportional increases in security staff
  • Improved threat intelligence: Automated systems can process and act on threat intelligence feeds in real-time
  • Cost efficiency: Reduces operational costs by minimizing manual security operations and faster incident resolution

```