Skip to content

Update aws WAFv2 with all PubIps in Account

Quick POC here, I may update later… But probably not. The idea here is that I might want a WAF rule to auto-permit public IPs from my own account, and I might want this to dynamically update. This Python code can be leveraged in a Lambda function that can be called two different ways:

  • Cron Job in CloudWatch Events to trigger a lambda every 5-10-15 minutes or whatever works
  • More ideally, a CloudWatch Event that looks for any Interface Association adds/removal API calls and triggers the Lambda

If I get around to refining this a little more I may detail the latter here and maybe make a cloudformation stack. For now, here is the core issue solved. Get all Pub IPs in account, and update a WAF rule with that output.

https://raw.githubusercontent.com/mtz4718/updateWafv2AccountIps/main/wafv2Update.py
import boto3
import json

# Define IP-Set Info
wafIpName='Local-Account_IPSet'
wafIpSetId='09b16840-689d-4c57-b977-92d119d7bd6d'
wafIpSetScope='REGIONAL'


# Define credential session
client = boto3.client('wafv2')
# Get all pub ips from all regions in account, return <list>
def pullPubIps():
    session = boto3.session.Session()
    client = boto3.client('ec2')
    regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    foundIps = []
    appendCidr = '/32'
    for region in regions:
        ec2 = session.resource('ec2', region_name=region)
        for vpc in ec2.vpcs.all():
            for eni in vpc.network_interfaces.all():
                if eni.association_attribute:
                    foundIps.append(eni.association_attribute['PublicIp'])
    formatIps = [ip + appendCidr for ip in foundIps]
    return formatIps
# Get Lock Token for defined IP Set
def getLockToken():
    lockToken = client.get_ip_set(Id=wafIpSetId,Scope=wafIpSetScope,Name=wafIpName)['LockToken']
    return lockToken

# Push Updated IpSet
def pushIpSet():
    response = client.update_ip_set(
        Name=wafIpName,
        Scope=wafIpSetScope,
        Id=wafIpSetId,
        Addresses=pullPubIps(),
        LockToken=getLockToken()
    )
    return response

pushIpSet()