Last active
December 24, 2025 05:59
-
-
Save hanancs/a87a8f6229b36bd53b7fcb2a697fb37c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import boto3 | |
| import os | |
| import json | |
| waf = boto3.client('wafv2') | |
| IP_SET_NAME = os.environ['IP_SET_NAME'] | |
| IP_SET_ID = os.environ['IP_SET_ID'] | |
| SCOPE = 'REGIONAL' | |
| def lambda_handler(event, context): | |
| print("Event:", json.dumps(event)) | |
| try: | |
| source_ip = event['requestContext']['identity']['sourceIp'] | |
| except KeyError: | |
| print("Could not find IP in event") | |
| return {"statusCode": 500, "body": "Could not determine IP"} | |
| print(f"Intruder detected from IP: {source_ip}") | |
| try: | |
| response = waf.get_ip_set( | |
| Name=IP_SET_NAME, | |
| Scope=SCOPE, | |
| Id=IP_SET_ID | |
| ) | |
| lock_token = response['LockToken'] | |
| current_ips = response['IPSet']['Addresses'] | |
| ip_cidr = f"{source_ip}/32" | |
| if ip_cidr not in current_ips: | |
| current_ips.append(ip_cidr) | |
| waf.update_ip_set( | |
| Name=IP_SET_NAME, | |
| Scope=SCOPE, | |
| Id=IP_SET_ID, | |
| Addresses=current_ips, | |
| LockToken=lock_token | |
| ) | |
| print(f"BANNED: {ip_cidr}") | |
| msg = f"Restricted Access. Your IP {source_ip} has been flagged." | |
| else: | |
| msg = "You are already flagged." | |
| except Exception as e: | |
| print(f"Error updating WAF: {str(e)}") | |
| return {"statusCode": 500, "body": "Internal Server Error"} | |
| return { | |
| "statusCode": 403, | |
| "body": msg | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment