Skip to content

Instantly share code, notes, and snippets.

@ran-isenberg
Created December 27, 2024 09:07
Show Gist options
  • Select an option

  • Save ran-isenberg/be1ae62cc61e0939114c4849fa2ea5cd to your computer and use it in GitHub Desktop.

Select an option

Save ran-isenberg/be1ae62cc61e0939114c4849fa2ea5cd to your computer and use it in GitHub Desktop.
centralized_waf_construct.py
import json
from aws_cdk import (
aws_fms as fms,
aws_wafv2 as wafv2
)
from constructs import Construct
class CentralizedFirewallManagerConstruct(Construct):
def __init__(self, scope: Construct, id_: str) -> None:
super().__init__(scope, id_)
self._create_waf_web_acl()
def _create_waf_web_acl(self):
# Step 1: Create a WAFv2 Rule Group for example to block specific countries
post_rule_group = wafv2.CfnRuleGroup(
self, "BlockCountryRuleGroup",
scope="REGIONAL", # Use 'CLOUDFRONT' for CloudFront distributions
capacity=50, # Adjust the capacity based on complexity
name="BlockCountryRuleGroup",
visibility_config=wafv2.CfnRuleGroup.VisibilityConfigProperty(
cloud_watch_metrics_enabled=True,
metric_name="BlockCountryRuleGroup",
sampled_requests_enabled=True
),
rules=[
wafv2.CfnRuleGroup.RuleProperty(
name="BlockCountries",
priority=1,
action=wafv2.CfnRuleGroup.RuleActionProperty(
block={} # Block traffic from the specified countries
),
statement=wafv2.CfnRuleGroup.StatementProperty(
geo_match_statement=wafv2.CfnRuleGroup.GeoMatchStatementProperty(
country_codes=["X", "Y"] # Blocked country modify as needed
)
),
visibility_config=wafv2.CfnRuleGroup.VisibilityConfigProperty(
cloud_watch_metrics_enabled=True,
metric_name="BlockCountriesRule",
sampled_requests_enabled=True
)
)
],
description="Rule Group to block traffic from specific countries"
)
# Define a managed the setting of the REGIONAL WEB ACL
# create preProcessRuleGroups with common AWS Rules
# create postProcessRuleGroups with personal Rule Group
managed_service_data = {
"type": "WAFV2",
"preProcessRuleGroups": [
{
"ruleGroupArn": None,
"overrideAction": {"type": "NONE"},
"managedRuleGroupIdentifier": {
"versionEnabled": True,
"vendorName": "AWS",
"managedRuleGroupName": "AWSManagedRulesCommonRuleSet"
},
"ruleGroupType": "ManagedRuleGroup",
"excludeRules":
[
{"name": "NoUserAgent_HEADER"}
]
},
{
"ruleGroupArn": None,
"overrideAction": {"type": "NONE"},
"managedRuleGroupIdentifier": {
"versionEnabled": True,
"vendorName": "AWS",
"managedRuleGroupName": "AWSManagedRulesKnownBadInputsRuleSet"
},
"ruleGroupType": "ManagedRuleGroup"
},
{
"ruleGroupArn": None,
"overrideAction": {"type": "NONE"},
"managedRuleGroupIdentifier": {
"versionEnabled": True,
"vendorName": "AWS",
"managedRuleGroupName": "AWSManagedRulesAmazonIpReputationList"
},
"ruleGroupType": "ManagedRuleGroup"
}
],
"postProcessRuleGroups": [
{
"ruleGroupArn": post_rule_group.attr_arn,
"overrideAction": {"type": "NONE"},
"ruleGroupType": "RuleGroup",
"priority": 1
}
],
"defaultAction": {"type": "ALLOW"},
"overrideCustomerWebACLAssociation": False,
# Optional setting for centralized logging
"loggingConfiguration": {
"logDestinationConfigs": [
"bucket_arn" # S3 bucket ARN for logging modify as needed
],
"redactedFields": [
{"redactedFieldType": "SingleHeader", "redactedFieldValue": "authorization"},
{"redactedFieldType": "SingleHeader", "redactedFieldValue": "Cookies"},
{"redactedFieldType": "SingleHeader", "redactedFieldValue": "x-amz-security-token"},
{"redactedFieldType": "SingleHeader", "redactedFieldValue": "x-auth"}
]
}
}
# Create a Firewall Manager Security Policy for WAF
fms.CfnPolicy(
self, "CentralizedWAFWebPolicyPOC",
security_service_policy_data=fms.CfnPolicy.SecurityServicePolicyDataProperty(
type="WAFV2",
managed_service_data=json.dumps(managed_service_data)
),
# resource_type="AWS::ElasticLoadBalancingV2::LoadBalancer Or AWS::CloudFront::Distribution for CloudFront",
resource_type="AWS::ApiGateway::Stage", # this is for API Gateway
exclude_resource_tags=False,
remediation_enabled=False,
policy_name="CentralizedWAFWebPolicyPOC",
exclude_map=fms.CfnPolicy.IEMapProperty(
account=[]
),
resource_tags=[], # You can add resource tags here for specific targeting
# define the OU or account to apply the policy on
include_map=fms.CfnPolicy.IEMapProperty(
orgunit=['ou-xxxx-yyyyyyyy'], # Apply to specific OU
account=["111111111111"] # Replace with your AWS account or Org Unit ID
),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment