iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛡️

[AWS CDK] Sample Code for Directing AWS WAF Logs to S3 or CloudWatch Logs

に公開

[Update] AWS WAF logs can now be delivered directly to CloudWatch Logs and S3 | DevelopersIO

I couldn't find much information in Japanese about building this with CDK, so I'm writing this article.

As a side note, keep in mind that the resource names for the log destination S3 bucket and CloudWatch log group must always start with the prefix aws-waf-logs- (I didn't realize this at first and spent a bit of time troubleshooting).

Environment

  • aws-cdk-lib 2.30.0
  • constructs 10.1.43

Defining APIGW + WebACL

First, I prepared the CDK code to link API Gateway logs with a WAF WebACL.

import { Construct } from "constructs"
import * as cdk from "aws-cdk-lib"

export class WafStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props)

    // APIGW+Lambda
    const restApi = new cdk.aws_apigateway.RestApi(this, "restApi", {
      restApiName: "restApi",
      deployOptions: {
        stageName: "dev",
      },
    })
    const pingFn = new cdk.aws_lambda.Function(this, "pingFn", {
      code: cdk.aws_lambda.Code.fromInline(`
        exports.handler = (event, context, callback) => {
          callback(null, { statusCode: 200, body: JSON.stringify({ message: "pong" }) });
        };
      `),
      handler: "index.handler",
      runtime: cdk.aws_lambda.Runtime.NODEJS_16_X,
    })
    restApi.root.addMethod(
      "GET",
      new cdk.aws_apigateway.LambdaIntegration(pingFn)
    )

    // WAF Web ACL
    const webAcl = new cdk.aws_wafv2.CfnWebACL(this, "wafV2WebAcl", {
      defaultAction: { allow: {} },
      scope: "REGIONAL",
      visibilityConfig: {
        cloudWatchMetricsEnabled: true,
        sampledRequestsEnabled: true,
        metricName: "wafV2WebAcl",
      },
      rules: [
        {
          name: "AWSManagedRulesCommonRuleSet",
          priority: 1,
          statement: {
            managedRuleGroupStatement: {
              vendorName: "AWS",
              name: "AWSManagedRulesCommonRuleSet",
            },
          },
          overrideAction: { none: {} },
          visibilityConfig: {
            cloudWatchMetricsEnabled: true,
            sampledRequestsEnabled: true,
            metricName: "AWSManagedRulesCommonRuleSet",
          },
        },
      ],
    })

    // Associate APIGW with WebACL
    const webAclAssociation = new cdk.aws_wafv2.CfnWebACLAssociation(
      this,
      "webAclAssociation",
      {
        resourceArn: `arn:aws:apigateway:${this.region}:${this.account}:/restapis/${restApi.restApiId}/stages/dev`,
        webAclArn: webAcl.attrArn,
      }
    )
    webAclAssociation.addDependsOn(webAcl)
    webAclAssociation.addDependsOn(
      restApi.deploymentStage.node.defaultChild as cdk.CfnResource
    )
  }
}

Logging to S3

First, here is how to output logs to an S3 bucket.

    webAclAssociation.addDependsOn(webAcl)
    webAclAssociation.addDependsOn(
      restApi.deploymentStage.node.defaultChild as cdk.CfnResource
    )
+
+   // S3 bucket for WAF logs
+   const bucket = new cdk.aws_s3.Bucket(this, "awsWafLogsBucket", {
+     bucketName: `aws-waf-logs-${this.account}-bucket`,
+     removalPolicy: cdk.RemovalPolicy.DESTROY,
+     blockPublicAccess: cdk.aws_s3.BlockPublicAccess.BLOCK_ALL,
+     encryption: cdk.aws_s3.BucketEncryption.S3_MANAGED,
+   })
+
+   // WAF logging configuration
+   const logConfig = new cdk.aws_wafv2.CfnLoggingConfiguration(
+     this,
+     "wafV2LoggingConfiguration",
+     {
+       logDestinationConfigs: [bucket.bucketArn],
+       resourceArn: webAcl.attrArn,
+     }
+   )
+   logConfig.addDependsOn(webAcl)
+   logConfig.addDependsOn(bucket.node.defaultChild as cdk.CfnResource)
  }
}

I deployed it and confirmed the settings in the AWS Management Console.

Logging to CloudWatch

Next, here is how to output logs to CloudWatch Logs.

    webAclAssociation.addDependsOn(webAcl)
    webAclAssociation.addDependsOn(
      restApi.deploymentStage.node.defaultChild as cdk.CfnResource
    )
+
+   // CloudWatch log group for WAF logs
+   const logGroup = new cdk.aws_logs.LogGroup(this, "awsWafLogsLogGroup", {
+     logGroupName: "aws-waf-logs-log-group",
+     removalPolicy: cdk.RemovalPolicy.DESTROY,
+   })
+
+   // WAF logging configuration
+   const logConfig = new cdk.aws_wafv2.CfnLoggingConfiguration(
+     this,
+     "wafV2LoggingConfiguration",
+     {
+       logDestinationConfigs: [
+         `arn:aws:logs:${this.region}:${this.account}:log-group:${logGroup.logGroupName}`,
+       ],
+       resourceArn: webAcl.attrArn,
+     }
+   )
+   logConfig.addDependsOn(webAcl)
+   logConfig.addDependsOn(logGroup.node.defaultChild as cdk.CfnResource)
  }
}

I also deployed this and confirmed the settings in the AWS Management Console.

By the way, it might seem like the value for logDestinationConfigs: could be [logGroup.logGroupArn], but that value includes a trailing :* like arn:aws:logs:ap-northeast-1:xxxxxxxxxxxx:log-group:aws-waf-logs-log-group:*, which results in an error.

 ❌  WafStack failed: Error: The stack named WafStack failed to deploy: UPDATE_ROLLBACK_COMPLETE: Resource handler returned message: "Error reason: The ARN isn't valid. A valid ARN begins with arn: and includes other information separated by colons or slashes., field: LOG_DESTINATION, parameter: arn:aws:logs:ap-northeast-1:xxxxxxxxxxxx:log-group:aws-waf-logs-log-group:* (Service: Wafv2, Status Code: 400, Request ID: xxxxxxxxxxxxxxxxx, Extended Request ID: null)" (RequestToken: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, HandlerErrorCode: InvalidRequest)
    at prepareAndExecuteChangeSet

Therefore, the log group ARN is manually concatenated as a string.

References

Discussion