Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

A Complete Guide for AWS WAF

What is AWS WAF?

Basic Workflow of AWS WAF?

AWS Web Application Firewall (AWS WAF) can be applied to the following resources

Amazon CloudFront Distributions: AWS WAF can protect web applications and APIs that are served by Amazon CloudFront, AWS’s global Content Delivery Network (CDN). By integrating with CloudFront, AWS WAF provides protection at the edge locations, reducing the latency for users.

Application Load Balancers (ALB): AWS WAF can be used to protect applications served through Application Load Balancers. This is typically used in conjunction with Amazon Elastic Load Balancing (ELB) to distribute traffic among multiple EC2 instances or containers.

Amazon API Gateway: AWS WAF can be used to secure APIs managed by Amazon API Gateway. This helps in protecting APIs against common web exploits and bots that can affect availability, compromise security, or consume excessive resources.

AWS App Runner: AWS WAF can also be used with AWS App Runner, a fully managed service that makes it easy for developers to quickly deploy containerized web applications and APIs, at scale, with no prior infrastructure experience required.

List of CloudWatch Metrices for AWS Application LoadBalancer

Here is a list of CloudWatch metrics for an AWS Application Load Balancer (ALB) presented in tabular format:

Metric NameDescription
ActiveConnectionCountThe total number of active connections.
ClientTLSNegotiationErrorCountThe number of TLS connections initiated by the client that did not establish a session with the ALB.
ConsumedLCUsThe number of load balancer capacity units (LCUs) used by the ALB.
HealthyHostCountThe number of healthy targets in a target group.
HTTP_Fixed_Response_CountThe number of fixed-response actions that were successful.
HTTP_Redirect_CountThe number of redirect actions that were successful.
HTTP_Redirect_Url_Limit_Exceeded_CountThe number of redirect actions that couldn’t be completed due to the URL exceeding the limit.
HTTPCode_ELB_3XX_CountThe number of HTTP 3XX redirection codes generated by the ALB.
HTTPCode_ELB_4XX_CountThe number of HTTP 4XX client error codes generated by the ALB.
HTTPCode_ELB_5XX_CountThe number of HTTP 5XX server error codes generated by the ALB.
HTTPCode_Target_2XX_CountThe number of HTTP 2XX successful response codes generated by the targets.
HTTPCode_Target_3XX_CountThe number of HTTP 3XX redirection codes generated by the targets.
HTTPCode_Target_4XX_CountThe number of HTTP 4XX client error codes generated by the targets.
HTTPCode_Target_5XX_CountThe number of HTTP 5XX server error codes generated by the targets.
IPv6ProcessedBytesThe number of bytes processed by the ALB for IPv6 requests.
IPv6RequestCountThe number of IPv6 requests received by the ALB.
NewConnectionCountThe number of new connections established by the ALB.
ProcessedBytesThe total number of bytes processed by the ALB.
RejectedConnectionCountThe number of connections rejected by the ALB.
RequestCountThe number of requests received by the ALB.
RuleEvaluationsThe number of rules processed by the ALB.
TargetConnectionErrorCountThe number of connections to targets that were not successfully established.
TargetResponseTimeThe time elapsed in seconds after the request leaves the ALB until a response is received.
TargetTLSNegotiationErrorCountThe number of TLS connections initiated by the ALB that did not establish a session with the target.
UnHealthyHostCountThe number of unhealthy targets in a target group.

List of CloudWatch Metrices for AWS Api Gateway

Here is a list of CloudWatch metrics for AWS API Gateway presented

Metric NameDescription
4XXErrorThe number of client-side errors (HTTP 4XX status codes).
5XXErrorThe number of server-side errors (HTTP 5XX status codes).
CacheHitCountThe number of requests served from the API Gateway cache.
CacheMissCountThe number of requests served from the backend due to a cache miss.
CountThe total number of API requests received.
IntegrationLatencyThe time between when API Gateway relays a request to the backend and when it receives a response.
LatencyThe time between when API Gateway receives a request from a client and when it returns a response.
CacheEvictionsThe number of evicted cache entries to make room for new entries.
CacheHitRateThe percentage of requests served from the cache.
CacheMissRateThe percentage of requests not served from the cache.
ConnectionErrorsThe number of connection errors between API Gateway and the backend.
IntegrationErrorThe number of integration errors.
IntegrationRequestCountThe number of requests sent to the backend.
IntegrationResponseCountThe number of responses received from the backend.
IntegrationLatencyPercentileThe integration latency in percentiles (e.g., p50, p90, p99).
RequestCountThe total number of requests received.
ThrottleCountThe number of requests that were throttled.
ThrottleRateThe rate of requests that were throttled.
IntegrationTimeoutThe number of integration timeouts.
GatewayResponseLatencyThe time between when the backend responds and API Gateway returns a response to the client.
GatewayResponseCountThe number of responses returned by API Gateway.
VpcLinkIntegrationLatencyThe integration latency for requests handled through a VPC Link.
VpcLinkIntegrationLatencyPercentileThe integration latency in percentiles for requests handled through a VPC Link.
VpcLinkIntegrationRequestCountThe number of requests handled through a VPC Link.
VpcLinkIntegrationErrorThe number of integration errors for requests handled through a VPC Link.
VpcLinkIntegrationTimeoutThe number of integration timeouts for requests handled through a VPC Link.

List of CloudWatch Metrices for AWS Application LoadBalancer which is for AWS WAF and DDOS

Here is a list of CloudWatch metrics specifically related to AWS WAF (Web Application Firewall) and DDoS (Distributed Denial of Service) protection for an AWS Application Load Balancer (ALB), presented in tabular format:

Metric NameDescription
AllowedRequestsThe number of web requests that were allowed by the AWS WAF rules.
BlockedRequestsThe number of web requests that were blocked by the AWS WAF rules.
CountedRequestsThe number of web requests that were counted (logged) by the AWS WAF rules.
PassedRequestsThe number of web requests that passed through the AWS WAF without any rule being triggered.
WAFAllowedRequestsThe number of requests that matched a rule with an ALLOW action in the Web ACL.
WAFBlockedRequestsThe number of requests that matched a rule with a BLOCK action in the Web ACL.
WAFCountedRequestsThe number of requests that matched a rule with a COUNT action in the Web ACL.
WAFRequestCountThe total number of requests inspected by AWS WAF.
AWSShieldDetectedThe number of events detected by AWS Shield.
AWSShieldMitigatedThe number of DDoS events mitigated by AWS Shield.
AWSShieldDiagnosticDetailed diagnostics related to DDoS attacks detected by AWS Shield.
AWSShieldAttackVolumeThe volume of traffic in DDoS attacks detected by AWS Shield.
AWSShieldEventRateThe rate of events (requests per second) detected by AWS Shield during an attack.

Steps to Determine the Threshold Value

Calculate the Transactions Per Minute:

  • Since you have 2 crore (20 million) transactions each day, first, determine the transactions per second.

Consider Peak Load:

  • Traffic often has peak periods. If peak traffic is double the average, then consider this for the threshold.
  • Peak Transactions Per Minute (TPM):

Set the Threshold:

  • Based on the peak transactions, you can set your AWS WAF threshold.
  • The threshold should be slightly higher than the peak to avoid false positives but within a reasonable range to catch malicious activity.
  • Recommended Threshold: 30,000 transactions per 60 seconds

Recommended Threshold:

Evaluation WindowRecommended Threshold
60 seconds30,000 transactions

DDOS transaction calculator Ecxel Sheet

DOWNLOAD HERE

Differnece between AWS WAF ACLS Vs Rules Vs Conditions

Here is a comparison of AWS WAF ACLs, Rules, and Conditions presented in tabular format to highlight their differences:

FeatureWeb ACLs (Access Control Lists)RulesConditions
DefinitionCollection of rules that control the traffic to your web applications.Individual entities defining inspection logic within a Web ACL.Criteria used within rules to inspect requests.
PurposeManage and apply security policies across AWS resources.Specify actions to be taken based on request inspection.Define detailed criteria for inspecting web requests.
ComponentsConsists of multiple rules and rule groups.Composed of one or more conditions and specifies actions.Includes match types like IP match, string match, size constraint, etc.
ActionsApplies rules to allow, block, or count requests.Allows, blocks, or counts requests based on conditions.Evaluates specific request attributes.
ScopeHighest level in the hierarchy.Intermediate level, contained within a Web ACL.Lowest level, used within rules.
AssociationAssociated with AWS resources such as CloudFront distributions, API Gateway stages, and ALBs.Defined within a Web ACL.Defined within a rule.
ExamplesMyWebACL – A Web ACL applied to an ALB.BlockSQLInjection – A rule to block SQL injection attempts.SQL injection match condition.
ManagementOrganizes and applies a set of rules.Defines specific inspection logic and actions.Specifies criteria for rule evaluation.
TypesN/AManaged Rules and Custom Rules.Various match conditions (IP, string, size, etc.).

List of recommended value for AWS WAF to avoid DDOS attack on AWS ELB

To effectively protect your AWS Elastic Load Balancer (ELB) from Distributed Denial of Service (DDoS) attacks using AWS Web Application Firewall (WAF), it’s important to configure various rules and limits to mitigate the attack vectors. Here’s a list of recommended values and configurations for AWS WAF to enhance protection:

1. IP Rate-based Rules

  • Limit: Set a rate limit on requests from a single IP address. A typical value could be 2,000 requests per 5 minutes (400 requests per minute).

2. IP Block/Allow Lists

  • Trusted IP List: Allow known, trusted IP addresses.
  • Blocked IP List: Block known malicious IP addresses or ranges. Update this list based on threat intelligence feeds.

3. Geo-Blocking

  • Country Blocking: Block traffic from countries where you do not expect legitimate traffic.

4. SQL Injection Rule

  • SQL Injection Detection: Enable SQL injection detection rule to block requests containing SQL injection attempts.

5. XSS Rule

  • Cross-Site Scripting (XSS) Detection: Enable XSS detection rule to block requests containing cross-site scripting payloads.

6. Size Constraint Rule

  • Request Size Limit: Set a maximum size for request headers and bodies. A typical value is 10 KB for headers and 100 KB for bodies.

7. Request Rate Limit

  • Rate-based Rule: Implement rate-based rules to automatically block IPs that exceed a specified rate of requests. Example value: 1,000 requests in a 5-minute period.

8. Regular Expressions Pattern Sets

  • Custom Rules: Create custom rules using regular expressions to detect and block patterns typical of malicious traffic.

9. Managed Rule Groups

  • AWS Managed Rules: Use AWS Managed Rules for common threats, which are regularly updated by AWS.
    • AWSManagedRulesCommonRuleSet
    • AWSManagedRulesKnownBadInputsRuleSet
    • AWSManagedRulesLinuxRuleSet
    • AWSManagedRulesSQLiRuleSet

10. Custom Rule Groups

  • Application-specific Rules: Create custom rule groups tailored to your specific application requirements and traffic patterns.

11. Rate Limit for Specific URIs

  • URI Rate Limiting: Apply rate limits to specific URIs that are more susceptible to abuse (e.g., login pages, search endpoints). Example value: 100 requests per minute per IP.

12. Header Constraint Rule

  • Header Size Limit: Enforce size limits on request headers. Example values: 8 KB for headers, 512 bytes for individual header fields.

13. JSON and XML Body Parsing

  • Inspection: Enable inspection of JSON and XML bodies to detect and block malicious payloads.

14. Automation and Monitoring

  • AWS Shield Advanced: Use AWS Shield Advanced for enhanced DDoS protection and automated attack mitigation.
  • AWS CloudWatch: Set up CloudWatch alarms to monitor for spikes in traffic and other anomalies.

15. Logging and Analysis

  • AWS WAF Logging: Enable logging to analyze requests and fine-tune your rules based on real traffic data.

Example Configuration Summary

  1. Rate Limit per IP: 2,000 requests per 5 minutes
  2. Request Size Limit: Headers: 10 KB, Bodies: 100 KB
  3. Rate-based Rule: 1,000 requests per 5 minutes
  4. URI-specific Rate Limit: 100 requests per minute per IP

AWS WAF RULE ACTION

Here’s a detailed description of AWS WAF rule actions in a tabular format:

ActionDescriptionUsageExample
AllowPermits requests that match the specified rule conditions.Whitelisting trusted traffic.Allow traffic from trusted IP addresses or specific HTTP methods.
BlockDenies requests that match the specified rule conditions, returning an HTTP 403 Forbidden response.Preventing access from malicious sources or harmful requests.Block requests from a specific IP range known for malicious activity or blocking SQL injection attempts.
CountLogs requests that match the specified rule conditions without affecting their flow.Monitoring traffic patterns and gathering data.Count the number of requests matching a specific pattern to analyze traffic before taking action.
CAPTCHAPresents a CAPTCHA challenge to users when their requests match the rule conditions, verifying they are human.Mitigating bot traffic.Challenge suspicious traffic patterns, like repeated login attempts, with a CAPTCHA.
ChallengePresents an additional verification step to users when their requests match the rule conditions.Applying additional verification to suspicious requests.Challenge requests with unusual behavior with simple verifications like JavaScript execution.

Example terraform code

Write a terraform code where you set the sample list of value for AWS WAF to avoid DDOS attack on AWS ELB


provider "aws" {
  region = "us-west-2"
}

# Create a WAFv2 Web ACL
resource "aws_wafv2_web_acl" "example" {
  name        = "example-web-acl"
  description = "Example Web ACL to mitigate DDoS attacks"
  scope       = "REGIONAL"
  default_action {
    allow {}
  }
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "exampleWebACL"
    sampled_requests_enabled   = true
  }
}

# IP set for allowed IPs
resource "aws_wafv2_ip_set" "allow_list" {
  name        = "allow-list"
  description = "List of allowed IPs"
  scope       = "REGIONAL"
  ip_address_version = "IPV4"
  addresses = [
    "192.0.2.0/24", # example IP range
  ]
}

# IP set for blocked IPs
resource "aws_wafv2_ip_set" "block_list" {
  name        = "block-list"
  description = "List of blocked IPs"
  scope       = "REGIONAL"
  ip_address_version = "IPV4"
  addresses = [
    "203.0.113.0/24", # example malicious IP range
  ]
}

# Rate limit rule
resource "aws_wafv2_rule_group" "rate_limit" {
  name        = "rate-limit"
  description = "Rate limit rule group"
  scope       = "REGIONAL"
  capacity    = 100

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "rateLimitRuleGroup"
    sampled_requests_enabled   = true
  }

  rule {
    name     = "RateLimitRule"
    priority = 1
    action {
      block {}
    }
    statement {
      rate_based_statement {
        limit          = 2000
        aggregate_key_type = "IP"
      }
    }
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "rateLimitRule"
      sampled_requests_enabled   = true
    }
  }
}

# SQL Injection Rule
resource "aws_wafv2_rule_group" "sql_injection" {
  name        = "sql-injection"
  description = "SQL Injection rule group"
  scope       = "REGIONAL"
  capacity    = 50

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "sqlInjectionRuleGroup"
    sampled_requests_enabled   = true
  }

  rule {
    name     = "SQLInjectionRule"
    priority = 2
    action {
      block {}
    }
    statement {
      sqli_match_statement {
        field_to_match {
          query_string {}
        }
        text_transformation {
          priority = 1
          type     = "URL_DECODE"
        }
      }
    }
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "sqlInjectionRule"
      sampled_requests_enabled   = true
    }
  }
}

# Add rules to Web ACL
resource "aws_wafv2_web_acl_association" "example_association" {
  resource_arn = aws_lb.example.arn
  web_acl_arn  = aws_wafv2_web_acl.example.arn
}

resource "aws_wafv2_web_acl_rule" "allow_rule" {
  name     = "AllowRule"
  priority = 1
  action {
    allow {}
  }
  statement {
    ip_set_reference_statement {
      arn = aws_wafv2_ip_set.allow_list.arn
    }
  }
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "allowRule"
    sampled_requests_enabled   = true
  }
  web_acl_arn = aws_wafv2_web_acl.example.arn
}

resource "aws_wafv2_web_acl_rule" "block_rule" {
  name     = "BlockRule"
  priority = 2
  action {
    block {}
  }
  statement {
    ip_set_reference_statement {
      arn = aws_wafv2_ip_set.block_list.arn
    }
  }
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "blockRule"
    sampled_requests_enabled   = true
  }
  web_acl_arn = aws_wafv2_web_acl.example.arn
}

resource "aws_wafv2_web_acl_rule" "rate_limit_rule" {
  name     = "RateLimitRule"
  priority = 3
  action {
    block {}
  }
  statement {
    rate_based_statement {
      limit          = 2000
      aggregate_key_type = "IP"
    }
  }
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "rateLimitRule"
    sampled_requests_enabled   = true
  }
  web_acl_arn = aws_wafv2_web_acl.example.arn
}

resource "aws_wafv2_web_acl_rule" "sql_injection_rule" {
  name     = "SQLInjectionRule"
  priority = 4
  action {
    block {}
  }
  statement {
    sqli_match_statement {
      field_to_match {
        query_string {}
      }
      text_transformation {
        priority = 1
        type     = "URL_DECODE"
      }
    }
  }
  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "sqlInjectionRule"
    sampled_requests_enabled   = true
  }
  web_acl_arn = aws_wafv2_web_acl.example.arn
}

# Sample ALB resource for association
resource "aws_lb" "example" {
  name               = "example-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.lb_sg.id]
  subnets            = aws_subnet.public.*.id

  enable_deletion_protection = true
}
Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x