├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── cloudformation-template └── customized-block-period-template.yaml └── validation-script └── customized-block-period-validation-script.sh /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT No Attribution 2 | 3 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 13 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 14 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 15 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 16 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 17 | 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Customize AWS WAF rate-based rule blocking period 2 | 3 | This solution helps to customize the block period for an AWS WAF rate-based rule to prevent malicious actors from reusing the same set of IP addresses for generating HTTP request floods. By blocking the IPs for longer durations and restricting the malicious users from reusing the IPs, the rate-based rules can be made more effective against HTTP request floods. 4 | 5 | ## Solution overview 6 | 7 | This solution lets you configure the time period for which you want the originating IP address to be blocked if it has previously violated the configured threshold for the rate-based rule. 8 | - It works with both IPv4 and IPv6 traffic. 9 | - It blocks the IP addresses blocked by a rate-based rule for a **configurable time period**. Minimum block period is 06 minutes. 10 | - The solution blocks a maximum of 10000 IPs for both IPv4 and IPv6 at a time. 11 | - The solution might release the blocked IP addresses with a delay of up to 75 seconds than the configured block period. 12 | 13 | ## Deploying the solution 14 | 15 | The solution assumes that you’ve previously set up an AWS WAF WebACL with a rate-based rule. If you have not done so, then follow the instructions for creating [AWS WAF Rate-Based Rule.](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-type-rate-based.html) 16 | 17 | Create a CloudFormation stack using the [template](https://github.com/aws-samples/aws-waf-rate-based-rule-customized-block-period/blob/main/cloudformation-template/customized-block-period-template.yaml) in the AWS Region where your WebACL is deployed. 18 | 19 | **Note:** To use this solution with a WebACL associated with Amazon CloudFront, deploy the stack in the US East (N. Virginia) Region. 20 | 21 | Provide the following parameters while launching the stack: 22 | - Custom Block Period: Specify the time in minutes to keep the IP address blocked, minimum is 06 minutes 23 | - Rate-Based Rule Name: Existing rate-based rule’s name 24 | - Scope: CLOUDFRONT or REGIONAL 25 | - WebACL Id: Existing WebACL Id 26 | - Web ACL Name: Existing WebACL name 27 | 28 | The template spins up multiple cloud resources, such as the following: 29 | - AWS WAF IPSets 30 | - Amazon EventBridge Rule 31 | - Amazon S3 buckets 32 | - AWS Identity and Access Management (IAM) Role 33 | - AWS Lambda Function 34 | 35 | The solution is quickly deployed to your account and is ready to use in less than 15 minutes. Once the stack status changes to CREATE_COMPLETE the next step is to create a custom AWS WAF rule to block the IPs present in the IPSet created by the template. 36 | 37 | **Note:** You must make sure that the IP field for this rule (source IP address or IP address in header) is same as your rate-based rule. 38 | 39 | ## Validating the solution 40 | 41 | Once solution is deployed, you can run a validation test using the [bash script](https://github.com/aws-samples/aws-waf-rate-based-rule-customized-block-period/blob/main/validation-script/customized-block-period-validation-script.sh) which generates a flood of HTTP GET requests at the beginning to the specified test URL, and then sends a request every 3 seconds to check the IP block status. It measures the time for which the source IP was blocked by calculating the time difference between the first and the last request with the 403 Forbidden status code. 42 | 43 | **Prerequisites** before using this script: 44 | 1. Make sure that your test URL returns a 200 status code by using the following command: 45 | ``` 46 | curl -s -o /dev/null -w "%{http_code}\n" http://example.com 47 | ``` 48 | **Note:** Ensure to replace the URL in the command with your own test URL. 49 | 50 | 2. Make sure that the rate-based rule and the custom rule doesn't have a custom response code set, as the validation script expects a 403 status code on getting blocked by AWS WAF. 51 | 52 | 3. Set the rate-based rule’s threshold limit to around 150 for using this script. 53 | 54 | To execute this script, use the following commands from a Linux terminal. In the second command below, replace the given URL with your test URL: 55 | ``` 56 | [ec2-user@ip-10-0-0-89 ~]$ chmod +x customized-block-period-validation-script.sh 57 | [ec2-user@ip-10-0-0-89 ~]$ ./customized-block-period-validation-script.sh http://example.com 58 | Completed 10 requests without block 59 | Completed 20 requests without block 60 | Completed 30 requests without block 61 | …… 62 | Completed 820 requests without block 63 | Completed 830 requests without block 64 | Your IP is blocked now 65 | Your IP is blocked now 66 | 2023-06-03 17:22:27 HTTP Status Code= 403 67 | 2023-06-03 17:22:28 HTTP Status Code= 403 68 | …… 69 | 2023-06-03 18:02:16 HTTP Status Code= 403 70 | 2023-06-03 18:02:19 HTTP Status Code= 403 71 | Your IP was blocked for around: 10 minutes 25 seconds 72 | ``` 73 | For this validation test, I had specified the custom block period as 10 minutes while deploying the solution and as my source IP was blocked for around 10 minutes 25 seconds which is within the expected range of variance in block period by the solution(a delay of up to 75 seconds than the configured block period). Therefore the solutions works as expected. 74 | 75 | ## Security 76 | 77 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 78 | 79 | ## License 80 | 81 | This library is licensed under the MIT-0 License. See the LICENSE file. -------------------------------------------------------------------------------- /cloudformation-template/customized-block-period-template.yaml: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | AWSTemplateFormatVersion: '2010-09-09' 5 | Parameters: 6 | Scope: 7 | Type: String 8 | Description: Enter WebACL Scope CLOUDFRONT or REGIONAL 9 | AllowedValues: [REGIONAL, CLOUDFRONT] 10 | WebACLName: 11 | Type: String 12 | Description: Enter WebACL name 13 | WebACLId: 14 | Type: String 15 | Description: Enter WebACL ID 16 | RateBasedRuleName: 17 | Type: String 18 | Description: Enter Rate Based Rule name 19 | CustomBlockPeriod: 20 | Type: Number 21 | Description: Enter custom block period for blocking the IP addresses in minutes. Minimum is 06 minutes 22 | MinValue: 6 23 | 24 | Resources: 25 | CustomRBRLogBucket: 26 | Type: "AWS::S3::Bucket" 27 | Properties: 28 | BucketName: !Join 29 | - "-" 30 | - - "custom-rbr-log-bucket" 31 | - !Select 32 | - 0 33 | - !Split 34 | - "-" 35 | - !Select 36 | - 2 37 | - !Split 38 | - "/" 39 | - !Ref "AWS::StackId" 40 | BucketEncryption: 41 | ServerSideEncryptionConfiguration: 42 | - ServerSideEncryptionByDefault: 43 | SSEAlgorithm: AES256 44 | PublicAccessBlockConfiguration: 45 | BlockPublicAcls: true 46 | BlockPublicPolicy: true 47 | IgnorePublicAcls: true 48 | RestrictPublicBuckets: true 49 | LoggingConfiguration: 50 | DestinationBucketName: !Ref AccessLoggingBucket 51 | 52 | CustomRBRLogBucketPolicy: 53 | Type: AWS::S3::BucketPolicy 54 | Properties: 55 | Bucket: 56 | Ref: CustomRBRLogBucket 57 | PolicyDocument: 58 | Statement: 59 | - Action: "s3:*" 60 | Condition: 61 | Bool: 62 | aws:SecureTransport: 'false' 63 | Effect: Deny 64 | Principal: "*" 65 | Resource: 66 | - !GetAtt CustomRBRLogBucket.Arn 67 | - !Join ["/", [!GetAtt CustomRBRLogBucket.Arn, "*"]] 68 | Sid: HttpsOnly 69 | Version: '2012-10-17' 70 | 71 | AccessLoggingBucket: 72 | Type: AWS::S3::Bucket 73 | Properties: 74 | BucketEncryption: 75 | ServerSideEncryptionConfiguration: 76 | - ServerSideEncryptionByDefault: 77 | SSEAlgorithm: AES256 78 | PublicAccessBlockConfiguration: 79 | BlockPublicAcls: True 80 | BlockPublicPolicy: True 81 | IgnorePublicAcls: True 82 | RestrictPublicBuckets: True 83 | Metadata: 84 | cfn_nag: 85 | rules_to_suppress: 86 | - id: W35 87 | reason: "This bucket is an access logging bucket for another bucket and does not require access logging to be configured for it." 88 | 89 | AccessLoggingBucketPolicy: 90 | Type: AWS::S3::BucketPolicy 91 | Properties: 92 | Bucket: 93 | Ref: AccessLoggingBucket 94 | PolicyDocument: 95 | Statement: 96 | - Action: "s3:*" 97 | Condition: 98 | Bool: 99 | aws:SecureTransport: 'false' 100 | Effect: Deny 101 | Principal: "*" 102 | Resource: 103 | - !GetAtt AccessLoggingBucket.Arn 104 | - !Join ["/", [!GetAtt AccessLoggingBucket.Arn, "*"]] 105 | Sid: HttpsOnly 106 | Version: '2012-10-17' 107 | 108 | IPv4IPset: 109 | Type: "AWS::WAFv2::IPSet" 110 | Properties: 111 | Name: !Join 112 | - "-" 113 | - - "IPv4-IPset" 114 | - !Select 115 | - 0 116 | - !Split 117 | - "-" 118 | - !Select 119 | - 2 120 | - !Split 121 | - "/" 122 | - !Ref "AWS::StackId" 123 | Scope: !Ref Scope 124 | Description: "IPv4 IP set for custom rate based block rule" 125 | IPAddressVersion: "IPV4" 126 | Addresses: [] 127 | 128 | IPv6IPset: 129 | Type: "AWS::WAFv2::IPSet" 130 | Properties: 131 | Name: !Join 132 | - "-" 133 | - - "IPv6-IPset" 134 | - !Select 135 | - 0 136 | - !Split 137 | - "-" 138 | - !Select 139 | - 2 140 | - !Split 141 | - "/" 142 | - !Ref "AWS::StackId" 143 | Scope: !Ref Scope 144 | Description: "IPv6 IP set for custom rate based block rule" 145 | IPAddressVersion: "IPV6" 146 | Addresses: [] 147 | 148 | CustomRBRLambdaFunction: 149 | Type: 'AWS::Lambda::Function' 150 | Properties: 151 | FunctionName: !Join 152 | - "-" 153 | - - "CustomRBRLambdaFunction" 154 | - !Select 155 | - 0 156 | - !Split 157 | - "-" 158 | - !Select 159 | - 2 160 | - !Split 161 | - "/" 162 | - !Ref "AWS::StackId" 163 | Description: Lambda function containing the logic for custom RBR 164 | Handler: index.lambda_handler 165 | Role: !GetAtt LambdaRole.Arn 166 | Runtime: python3.9 167 | Environment: 168 | Variables: 169 | SCOPE: !Ref Scope 170 | WEB_ACL_NAME: !Ref WebACLName 171 | WEB_ACL_ID: !Ref WebACLId 172 | RATE_BASED_RULE_NAME: !Ref RateBasedRuleName 173 | CUSTOM_BLOCK_PERIOD: !Ref CustomBlockPeriod 174 | CONFIG_LOG_BUCKET: !Ref CustomRBRLogBucket 175 | CONFIG_LOG_KEY: blocked_ips_list.json 176 | IP_SET_ID_CUSTOM_V4: !GetAtt IPv4IPset.Id 177 | IP_SET_NAME_CUSTOM_V4: !Select 178 | - "0" 179 | - !Split [ "|" , Ref: IPv4IPset] 180 | IP_SET_ID_CUSTOM_V6: !GetAtt IPv6IPset.Id 181 | IP_SET_NAME_CUSTOM_V6: !Select 182 | - "0" 183 | - !Split [ "|" , Ref: IPv6IPset] 184 | Code: 185 | ZipFile: | 186 | import json 187 | import boto3 188 | import logging 189 | import datetime 190 | import os 191 | 192 | wafv2_client = boto3.client('wafv2') 193 | s3_client = boto3.client('s3') 194 | 195 | def update_custom_ipset_and_config(log, latest_ipv4_blocked_list, 196 | latest_ipv6_blocked_list): 197 | try: 198 | # update the custom v4 IP set 199 | ipv4_lock_token = get_lock_token( 200 | log, wafv2_client, 201 | os.getenv('IP_SET_ID_CUSTOM_V4'), 202 | os.getenv('IP_SET_NAME_CUSTOM_V4') 203 | ) 204 | update_ip_set( 205 | log, wafv2_client, 206 | os.getenv('IP_SET_ID_CUSTOM_V4'), 207 | list(latest_ipv4_blocked_list.keys()), 208 | ipv4_lock_token, 209 | os.getenv('IP_SET_NAME_CUSTOM_V4') 210 | ) 211 | 212 | # update the custom v6 IP set 213 | ipv6_lock_token = get_lock_token( 214 | log, wafv2_client, 215 | os.getenv('IP_SET_ID_CUSTOM_V6'), 216 | os.getenv('IP_SET_NAME_CUSTOM_V6') 217 | ) 218 | update_ip_set( 219 | log, wafv2_client, 220 | os.getenv('IP_SET_ID_CUSTOM_V6'), 221 | list(latest_ipv6_blocked_list.keys()), 222 | ipv6_lock_token, 223 | os.getenv('IP_SET_NAME_CUSTOM_V6') 224 | ) 225 | except Exception as e: 226 | # log error message 227 | log.error("[update_custom_ipset_and_config] " 228 | "Error updating custom ipset.") 229 | raise e 230 | 231 | try: 232 | # create json object of the latest custom config 233 | latest_custom_config = { 234 | 'IPv4': latest_ipv4_blocked_list, 235 | 'IPv6': latest_ipv6_blocked_list 236 | } 237 | byte_latest_custom_config = json.dumps(latest_custom_config).encode() 238 | 239 | # upload the config to s3 240 | s3_client.put_object( 241 | Bucket=os.getenv('CONFIG_LOG_BUCKET'), 242 | Body=byte_latest_custom_config, 243 | Key=os.getenv('CONFIG_LOG_KEY') 244 | ) 245 | except Exception as e: 246 | # log error message 247 | log.error("[update_custom_ipset_and_config] " 248 | "Error uploading config to S3.") 249 | raise e 250 | 251 | 252 | def get_lock_token(log, wafv2_client, ip_set_id, name): 253 | try: 254 | ipv4_get_response = wafv2_client.get_ip_set( 255 | Scope=os.getenv('SCOPE'), 256 | Name=name, 257 | Id=ip_set_id 258 | ) 259 | return ipv4_get_response['LockToken'] 260 | except Exception as e: 261 | log.error(f"Error in get_lock_token: {e}") 262 | raise 263 | 264 | 265 | def update_ip_set(log, wafv2_client, ip_set_id, addresses, 266 | lock_token, name): 267 | try: 268 | wafv2_client.update_ip_set( 269 | Scope=os.getenv('SCOPE'), 270 | Name=name, 271 | Id=ip_set_id, 272 | Description='Last Update: ' + 273 | datetime.datetime.now(datetime.timezone.utc).strftime( 274 | "%Y-%m-%d %H:%M:%S %Z%z"), 275 | Addresses=addresses, 276 | LockToken=lock_token 277 | ) 278 | except Exception as e: 279 | log.error("Error in update_ip_set: {}".format(e)) 280 | raise 281 | 282 | 283 | def sync_ip_from_rbr_to_custom_ipset(log, rbr_managed_ip_list, 284 | custom_managed_ip_config): 285 | # Get the current timestamp in UTC format 286 | utc_now_timestamp = datetime.datetime.now( 287 | datetime.timezone.utc) 288 | # Convert the timestamp to string 289 | utc_now_timestamp_str = utc_now_timestamp.strftime( 290 | "%Y-%m-%d %H:%M:%S %Z%z") 291 | 292 | # Iterate over the managed IPs in the RBR list 293 | for managed_ip in rbr_managed_ip_list: 294 | # If the IP is already in the custom IP config 295 | if managed_ip in custom_managed_ip_config.keys(): 296 | # Get the timestamp when the IP was blocked in UTC format 297 | utc_blocked_at = datetime.datetime.strptime( 298 | custom_managed_ip_config[managed_ip], 299 | "%Y-%m-%d %H:%M:%S %Z%z").astimezone( 300 | datetime.timezone.utc) 301 | # Calculate the difference in minutes between now and when the IP 302 | # was blocked 303 | total_diff_min = ((utc_now_timestamp - utc_blocked_at) 304 | .total_seconds()) / 60 305 | 306 | # If the difference is greater than block period, update the timestamp 307 | if round(total_diff_min) >= int(os.getenv('CUSTOM_BLOCK_PERIOD')): 308 | custom_managed_ip_config[managed_ip] = utc_now_timestamp_str 309 | # If the IP is not in the custom IP config, add it with the current 310 | # timestamp 311 | else: 312 | custom_managed_ip_config[managed_ip] = utc_now_timestamp_str 313 | 314 | # Create a new dictionary to store the latest blocked IPs 315 | latest_ip_blocked_list = {} 316 | 317 | # Iterate over the custom IP config 318 | for blocked_ip, blocked_at_str in custom_managed_ip_config.items(): 319 | # Get the timestamp when the IP was blocked in UTC format 320 | utc_blocked_at = datetime.datetime.strptime( 321 | custom_managed_ip_config[blocked_ip], 322 | "%Y-%m-%d %H:%M:%S %Z%z").astimezone(datetime.timezone.utc) 323 | # Calculate the difference in minutes between now and when the IP 324 | # was blocked 325 | total_diff_min = ((utc_now_timestamp - utc_blocked_at) 326 | .total_seconds()) / 60 327 | # If the difference is less than the custom block period 328 | #then add it to the latest blocked IPs list 329 | if round(total_diff_min) < int(os.getenv('CUSTOM_BLOCK_PERIOD')): 330 | latest_ip_blocked_list[blocked_ip] = blocked_at_str 331 | 332 | return latest_ip_blocked_list 333 | 334 | 335 | def get_custom_config_file(log): 336 | try: 337 | # Get the custom config file from S3 338 | s3_response = s3_client.get_object( 339 | Bucket=os.getenv('CONFIG_LOG_BUCKET'), 340 | Key=os.getenv('CONFIG_LOG_KEY') 341 | ) 342 | # Load the custom config file as a JSON object 343 | custom_managed_ip_config = json.loads( 344 | s3_response['Body'].read() 345 | ) 346 | except Exception as e: 347 | log.error("[get_custom_config_file] Error to get the custom config " 348 | "file from S3") 349 | log.error(e) 350 | # If there is an error, return an empty config 351 | custom_managed_ip_config = {'IPv4': {}, 'IPv6': {}} 352 | 353 | return custom_managed_ip_config 354 | 355 | 356 | def get_rbr_managed_ip_list(log): 357 | try: 358 | # Get the list of IPs blocked by the rate based rule 359 | wafv2_response = wafv2_client.get_rate_based_statement_managed_keys( 360 | Scope=os.getenv('SCOPE'), 361 | WebACLName=os.getenv('WEB_ACL_NAME'), 362 | WebACLId=os.getenv('WEB_ACL_ID'), 363 | RuleName=os.getenv('RATE_BASED_RULE_NAME') 364 | ) 365 | 366 | return wafv2_response 367 | except Exception as e: 368 | log.error("[get_rbr_managed_ip_list] " 369 | "Error to get the list of IP blocked by rate based rule") 370 | log.error(e) 371 | # If there is an error, raise the exception 372 | raise e 373 | 374 | 375 | def lambda_handler(event, context): 376 | log = logging.getLogger() 377 | 378 | try: 379 | # Set Log Level 380 | log.setLevel(logging.ERROR) 381 | 382 | # Get the list of IP blocked by rate based rule 383 | rbr_managed_list = get_rbr_managed_ip_list(log) 384 | 385 | # Get custom config file from S3 386 | custom_managed_ip_config = get_custom_config_file(log) 387 | 388 | # Update IP from rate based rule list to custom list 389 | latest_ipv4_blocked_list = sync_ip_from_rbr_to_custom_ipset( 390 | log, rbr_managed_list['ManagedKeysIPV4']['Addresses'], 391 | custom_managed_ip_config['IPv4']) 392 | latest_ipv6_blocked_list = sync_ip_from_rbr_to_custom_ipset( 393 | log, rbr_managed_list['ManagedKeysIPV6']['Addresses'], 394 | custom_managed_ip_config['IPv6']) 395 | 396 | # Update latest blocked list to S3 and WAF IPset 397 | update_custom_ipset_and_config(log, latest_ipv4_blocked_list, 398 | latest_ipv6_blocked_list) 399 | 400 | return { 401 | 'statusCode': 200, 402 | 'body': json.dumps('Update Success!') 403 | } 404 | except Exception as e: 405 | log.error(e) 406 | return { 407 | 'statusCode': 500, 408 | 'body': e 409 | } 410 | Timeout: 10 411 | Metadata: 412 | cfn_nag: 413 | rules_to_suppress: 414 | - id: W89 415 | reason: There is no need to run this lambda in a VPC 416 | - id: W92 417 | reason: There is no need for Reserved Concurrency 418 | 419 | LambdaRole: 420 | Type: "AWS::IAM::Role" 421 | Properties: 422 | AssumeRolePolicyDocument: 423 | Version: "2012-10-17" 424 | Statement: 425 | 426 | - Effect: "Allow" 427 | Principal: 428 | Service: 429 | - "lambda.amazonaws.com" 430 | Action: "sts:AssumeRole" 431 | 432 | ManagedPolicyArns: 433 | - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 434 | 435 | Policies: 436 | - PolicyName: !Join 437 | - "-" 438 | - - "LambdaRolePolicy" 439 | - !Select 440 | - 0 441 | - !Split 442 | - "-" 443 | - !Select 444 | - 2 445 | - !Split 446 | - "/" 447 | - !Ref "AWS::StackId" 448 | 449 | PolicyDocument: 450 | Version: "2012-10-17" 451 | Statement: 452 | - Sid: "S3BucketPermissions" 453 | Effect: "Allow" 454 | Action: 455 | - "s3:PutObject" 456 | - "s3:GetObject" 457 | Resource: 458 | - !Sub 'arn:${AWS::Partition}:s3:::${CustomRBRLogBucket}/blocked_ips_list.json' 459 | - Sid: "WAFIPSetPermissions" 460 | Effect: "Allow" 461 | Action: 462 | - "wafv2:GetIPSet" 463 | - "wafv2:UpdateIPSet" 464 | Resource: 465 | - !GetAtt IPv6IPset.Arn 466 | - !GetAtt IPv4IPset.Arn 467 | - Sid: "WAFRBRPermissions" 468 | Effect: "Allow" 469 | Action: "wafv2:GetRateBasedStatementManagedKeys" 470 | Resource: !Sub 471 | - 'arn:${AWS::Partition}:wafv2:${AWS::Region}:${AWS::AccountId}:${WebACLSope}/webacl/${WebACLName}/${WebACLId}' 472 | - WebACLSope: !If [IsRegional, "regional", "cloudfront"] 473 | 474 | 475 | EventBridgeRule: 476 | Type: "AWS::Events::Rule" 477 | Properties: 478 | Name: !Join 479 | - "-" 480 | - - "EventBridgeRule" 481 | - !Select 482 | - 0 483 | - !Split 484 | - "-" 485 | - !Select 486 | - 2 487 | - !Split 488 | - "/" 489 | - !Ref "AWS::StackId" 490 | ScheduleExpression: "rate(1 minute)" 491 | State: "ENABLED" 492 | Targets: 493 | - Id: "CustomRBRLambdaFunction" 494 | Arn: !GetAtt CustomRBRLambdaFunction.Arn 495 | 496 | LambdaPermissionForEventBridge: 497 | Type: "AWS::Lambda::Permission" 498 | Properties: 499 | FunctionName: !Ref CustomRBRLambdaFunction 500 | Action: "lambda:InvokeFunction" 501 | Principal: "events.amazonaws.com" 502 | SourceArn: !GetAtt EventBridgeRule.Arn 503 | 504 | Outputs: 505 | IPv4IPsetName: 506 | Description: IPv4 IPSet for custom rate based block rule 507 | Value: !Select 508 | - "0" 509 | - !Split [ "|" , Ref: IPv4IPset] 510 | IPv6IPsetName: 511 | Description: IPv6 IPSet for custom rate based block rule 512 | Value: !Select 513 | - "0" 514 | - !Split [ "|" , Ref: IPv6IPset] 515 | 516 | Conditions: 517 | IsRegional: 518 | !Equals [!Ref Scope, "REGIONAL"] 519 | -------------------------------------------------------------------------------- /validation-script/customized-block-period-validation-script.sh: -------------------------------------------------------------------------------- 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | #!/bin/bash 5 | 6 | if [ $# -eq 0 ]; then 7 | echo "Please add URL after script name like: $0 " 8 | exit 1 9 | fi 10 | 11 | url=$1 12 | 13 | counter_started=false 14 | i=1 15 | 16 | while true; do 17 | response=$(curl -s -o /dev/null -w "%{http_code}" "$url") 18 | if [[ $response -eq 403 && $counter_started == false ]]; then 19 | start_time=$(date +%s) 20 | counter_started=true 21 | echo "Your IP is blocked now" 22 | echo "$(date +%Y-%m-%d\ %H:%M:%S) HTTP Status Code= $response" 23 | sleep 3 24 | break 25 | fi 26 | if ((i % 10 == 0)); then 27 | echo "Completed $i requests without block"; 28 | fi 29 | i=$((i+1)) 30 | done 31 | 32 | while true; do 33 | response=$(curl -s -o /dev/null -w "%{http_code}" "$url") 34 | if [[ $response -eq 200 && $counter_started == true ]]; then 35 | end_time=$(date +%s) 36 | time_diff=$((end_time - start_time)) 37 | minutes=$(expr $time_diff / 60) 38 | seconds=$(expr $time_diff % 60) 39 | echo "Your IP was blocked for around: $minutes minutes $seconds seconds" 40 | break 41 | fi 42 | echo "$(date +%Y-%m-%d\ %H:%M:%S) HTTP Status Code= $response" 43 | sleep 3 44 | done 45 | --------------------------------------------------------------------------------