AWS WAF:如何使用Terraform阻止不包含特定标头的请求

问题描述

我想阻止不包含授权标头的请求。我提出了以下规则,但我发现不包含此标头的请求也被允许。指定此条件的正确方法是什么?

rule {
    name = "restrict-requests-without-authorization-header"
    priority = 2

    action {
      block {}
    }

    statement {
      size_constraint_statement {
        field_to_match {
          single_header {
            name = "authorization"
          }
        }

        comparison_operator = "LE"
        size = 0
        text_transformation {
          priority = 0
          type = "NONE"
        }
      }
    }

    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name = "restrict-requests-without-authorization-header-metrics"
      sampled_requests_enabled = true
    }
  }

解决方法

您需要创建一个规则和正则表达式模式(可以是通配符),如下所示:

规则:

rule {
    name     = "AuthorizationHeaderRule"
    priority = 1

    action {
      allow {}
    }

        statement {
          regex_pattern_set_reference_statement {
            arn = aws_wafv2_regex_pattern_set.your_regex_pattern.arn

            field_to_match {
              single_header {
                name = "authorization"
              }
            }

            text_transformation {
              priority = 2
              type     = "NONE"
            }
          }
      }

这可能是正则表达式的模式:

resource "aws_wafv2_regex_pattern_set" "your_regex_pattern" {
  name  = "your-regex-pattern"
  scope = "REGIONAL"

  regular_expression {
    regex_string = "prefix-.*"
  }
}