Search blog for

How to Whitelist Incapsula on AWS to Prevent WAF Bypass Attacks

If you’re hosting your website on Amazon Web Services (AWS) and protecting it with the Incapsula cloud-based web application firewall (WAF), you’ll want to configure things so that your site accepts traffic only after being scrubbed by Incapsula cloud servers. Doing so prevents your site from experiencing WAF bypass attacks that employ host files or other IP spoofing techniques.

The following user-submitted code reads the published IP addresses by using the Incapsula API and then edits the appropriate AWS security groups. It was written on AWS Lambda, but could be easily modified to run on local Python instances which I’ve done.

This code is based on Boto3. Before you implement the Incapsula Python script, please install Boto3 by following the instructions here.

from __future__ import print_function
from copy import deepcopy
import json, urllib2, boto3, botocore
import sys  

##################### Global Variables ####################
url = 'https://my.incapsula.com/api/integration/v1/ips'
aws_id=''
aws_key=''
aws_region='' 
aws_securityGoup=''
###########################################################

def lambda_handler(event, context):

    #Data output from Incapsula API:
    data = 'resp_format=json'
    
    response = urllib2.urlopen(url=url, data=data).read()
    json_data = json.loads(response)
 
    #Generate new CIDR LIST:   
    new_cidr_update = [ x for x in json_data['ipRanges']]

    #Connect to your EC2 region, for example: 
    ec2 = boto3.resource('ec2', aws_access_key_id=aws_id, aws_secret_access_key=aws_key ,region_name=aws_region)
  
    #Read the existing security group:   
    SG = ec2.SecurityGroup(aws_securityGoup)
    SG_CIDR_Current = [ x ['CidrIp'] for x in SG.ip_permissions[0]['IpRanges'] ]
   
    #Define access rules. This example is for https. Modify accordingly if using HTTP or TCP: 
    params_dict = {
        u'PrefixListIds': [],
        u'FromPort': 443,
        u'IpRanges': [],
        u'ToPort': 443,
        u'IpProtocol': "tcp",
        u'UserIdGroupPairs': []
    }
 
    #Define list of security rules to add to the existing rules: 
    SG_Add_Dict = deepcopy(params_dict)
    for ip in new_cidr_update:
        if ip not in SG_CIDR_Current:
            SG_Add_Dict['IpRanges'].append({u'CidrIp': ip})
 
            #Define list of security rules to remove:
            SG_Remove_Dict = deepcopy(params_dict)
            for ip in SG_CIDR_Current:
                if ip not in new_cidr_update:
                    SG_Remove_Dict['IpRanges'].append({u'CidrIp': ip})
 
                    #Edit the security group by applying the adds and the removes:
                    SG.authorize_ingress(IpPermissions=[SG_Add_Dict])
                    SG.revoke_ingress(IpPermissions=[SG_Remove_Dict])

Have questions about using Incapsula with AWS? Please leave me a comment.