@codedazur/cdk-firewall
v2.3.0
Published
Maintainers
Keywords
Readme
@codedazur/cdk-firewall
An AWS WAF web ACL for CloudFront distributions, with sensible defaults. AWS CDK only offers the low-level CfnWebACL resources for WAF, so this construct takes care of rule priorities, metrics, count mode, rate limit exclusions and logging.
Pass it to a SiteDistribution, or to any construct that is based on it, such as a StaticSite, DockerCluster or NextApp.
Regions
A firewall for CloudFront must be created in us-east-1. If your application is deployed to us-east-1, create the firewall in the same stack.
new DockerCluster(this, "DockerCluster", {
// ...
distribution: {
firewall: new Firewall(this, "Firewall"),
},
});If your application is deployed to another region, create the firewall in a separate us-east-1 stack and pass it to the stack of your application.
const edge = new Stack(app, "Edge", {
env: { account, region: "us-east-1" },
});
const firewall = new Firewall(edge, "Firewall");
const site = new Stack(app, "Site", {
env: { account, region: "eu-central-1" },
});
new DockerCluster(site, "DockerCluster", {
// ...
distribution: { firewall },
});The distribution imports the firewall into its own region with firewall.importInto(this), which uses importAcrossRegions from cdk-essentials. The firewall then stores its ARN in an SSM parameter in us-east-1, which a custom resource in the stack of your application reads on every deploy. The stack of your application depends on the us-east-1 stack, so deploying it deploys the firewall first. The account must be bootstrapped in us-east-1 as well.
Call importInto yourself to use the firewall with a distribution that isn't a SiteDistribution. If the scope is in the same region as the firewall, it returns the firewall itself.
Unlike CDK's crossRegionReferences, this deploys no Lambda functions in us-east-1, which some organizations' policies don't allow. CloudFront certificates must also be in us-east-1, and a SiteDistribution imports those the same way.
Existing Web ACLs
If you already have a web ACL, for example one that was created in the AWS console or by another CDK app, import it by its ARN instead of creating a new firewall. Nothing is created, so this works from a stack in any region.
new DockerCluster(this, "DockerCluster", {
// ...
distribution: {
firewall: Firewall.fromWebAclArn(
this,
"Firewall",
"arn:aws:wafv2:us-east-1:...",
),
},
});Defaults
The default firewall contains:
- The AWS managed
AmazonIpReputationList,CommonRuleSet,KnownBadInputsRuleSet,LinuxRuleSetandUnixRuleSetrule groups. TheSizeRestrictions_BODYrule of the common rule set, which blocks request bodies over 8 KB, is set to count, because it breaks most uploads. - No rate limit. See Rate Limiting.
- Masking of the
authorizationandcookieheaders in the request data that WAF stores, because they typically contain session tokens. - No logging. See Logging and Personal Data.
Configuration
Use FirewallMode.COUNT to see which requests would be blocked, by looking at the metrics and sampled requests in the WAF console, without blocking them.
new Firewall(this, "Firewall", {
mode: FirewallMode.COUNT,
managedRuleGroups: [
...Firewall.defaultManagedRuleGroups,
{ name: "AWSManagedRulesAnonymousIpList" },
],
rules: [
{
name: "BlockCountries",
action: { block: {} },
statement: { geoMatchStatement: { countryCodes: ["XX"] } },
},
],
});Custom rules are evaluated first, then the rate limit, then the managed rule groups. Priorities and visibility configuration are assigned automatically.
A firewall costs roughly $5 per month for the web ACL, $1 per month per rule or managed rule group, and $0.60 per million requests, plus the cost of the logs if logging is enabled. The default firewall costs roughly $10 per month plus requests.
A firewall can be shared by multiple distributions, for example several static sites that need the same protection.
Rate Limiting
Rate limiting per IP address is opt-in, because visitors behind a shared IP address, such as an office building or a campus, count towards the same limit, which causes false positives. CloudFront applies the firewall before its cache, so cached responses count towards the limit too. Exclude paths that every page view requests in large numbers, such as static assets.
new Firewall(this, "Firewall", {
rateLimit: {
limit: 3000,
window: Duration.minutes(5),
excludePaths: ["/_next/static/"],
},
});Logging and Personal Data
WAF processes the IP address of every visitor to apply its rules, but by default, the only request data it stores are sampled requests: a sample of recent requests per rule, including their IP addresses and headers, which AWS keeps for 3 hours and shows in the WAF console. CloudWatch metrics per rule contain no personal data.
Sampled requests are stored in the region of the firewall, which is us-east-1. If that isn't acceptable, turn them off and use logging to S3 in another region instead. Custom rules with their own visibilityConfig keep their own setting.
new Firewall(this, "Firewall", {
sampledRequests: false,
});Logging of blocked and counted requests is opt-in. Logs are useful to analyze attacks or false positives after the fact, but they contain personal data, so you must choose how long they are kept, and where.
S3
A FirewallLogBucket can be in any region, for example to keep logs in the EU. Logs are delivered every 5 minutes as compressed files, which you can query with Athena. Firewalls in multiple stacks can share one bucket.
Give the bucket a fixed name, so the us-east-1 stack can import it by that name. The name must start with aws-waf-logs- and be globally unique.
const logs = new Stack(app, "Logs", {
env: { account, region: "eu-central-1" },
});
const bucketName = `aws-waf-logs-${account}-website`;
new FirewallLogBucket(logs, "FirewallLogs", {
expiration: Duration.days(7),
bucketName,
});
const firewall = new Firewall(edge, "Firewall", {
logging: FirewallLogging.toBucket(
Bucket.fromBucketName(edge, "FirewallLogs", bucketName),
),
});
edge.addDependency(logs);The bucket can not be in the stack of your application if that stack uses the firewall, because the firewall stack would then depend on the application stack and vice versa. Deploying the stack of your application deploys the Logs and Edge stacks first.
The bucket is retained when its stack is deleted, but its logs still expire.
CloudWatch Logs
A CloudWatch log group must be in the region of the firewall, which is us-east-1. It is the simplest option if that is acceptable, and lets you query the logs with CloudWatch Logs Insights.
new Firewall(this, "Firewall", {
logging: FirewallLogging.toLogGroup({ retention: RetentionDays.ONE_WEEK }),
});Personal Data
Keep in mind that:
- Logs contain the IP addresses of visitors, which are personal data. WAF can not mask IP addresses.
- Logs contain all request headers and the full URL, including the query string. Only the
authorizationandcookieheaders are masked by default. - When a rule matches part of the request body, such as a form submission, that part is included in the log.
Masking
Masking applies to both logs and sampled requests. If other headers, cookies, query parameters or the body of your application contain personal data or secrets, mask those as well. Your masking is merged with the defaults, so the authorization and cookie headers stay masked unless you set them to MaskingAction.NONE.
new Firewall(this, "Firewall", {
masking: {
headers: {
authorization: MaskingAction.HASH,
"x-api-key": MaskingAction.HASH,
},
queryParameters: { email: MaskingAction.SUBSTITUTION },
},
});SUBSTITUTION replaces the value with REDACTED, while HASH replaces it with a hash, so you can still tell whether requests contain the same value, such as the same session token. You can mask headers, cookies and queryParameters by name, or the entire queryString, which includes all query parameters, and the body.
