How to Setup AWS WAF and Web ACL using Terraform on Amazon Cloud

Are you protecting your applications or website from web exploits and attacks done by bots? If you want to get rid of attacks and secure your websites, consider using a Web Application Firewall (AWS WAF) to protect your web applications from common web exploits.

AWS WAF allows you to control how traffic reaches your applications by enabling security rules that control bot traffic and block common attack patterns, such as SQL injection or cross-site scripting.

This tutorial teaches AWS WAF and sets up AWS WAF and Web ACL using Terraform on Amazon Cloud.

Join 50 other followers

Table of Content

  1. What is AWS WAF ?
  2. Prerequisites
  3. Terraform files and Terraform directory structure
  4. Building Terraform Configuration files to Create AWS WAF and WAF rules using Terraform
  5. Deploying the AWS WAF using Terraform.
  6. Conclusion

What is AWS WAF ?

AWS WAF stands for Amazon Web services Web Application Firewall. With AWS WAF, you monitor all the HTTP or HTTPS requests forwarded to Amazon Cloud Front, Amazon Load balancer, Amazon API Gateway REST API, etc., from users.

AWS WAF protects the web applications from common web exploits. AWS WAF also controls who can access the required content or data based on specific conditions such as source IP address etc.

For AWS WAF to work, you will need the below components:

  • Web ACLs ➜ Web access control list (ACL) protect the set of AWS resources by adding rules. You can set a default action for the web ACL to block or allow through those requests that pass the rules inspections.
  • Rules ➜ Each rule contains a statement that defines which requests will be blocked or will pass after meeting the the criteria or how handle requests that match the criteria .
  • Rules groups ➜ Instead of using the rules individually, you can add rules in the group so that it can be reused.

AWS WAF architecture
AWS WAF architecture

Prerequisites

  • Ubuntu machine to run terraform command, if you don’t have Ubuntu machine you can create an AWS EC2 instance on AWS account with 4GB RAM and at least 5GB of drive space.
  • Terraform Installed on Ubuntu Machine. If you don’t have Terraform installed refer Terraform on Windows Machine / Terraform on Ubuntu Machine
  • Ubuntu machine should have IAM role attached with full access to create AWS WAF/ AWS WAF rules or administrator permissions.

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

Terraform files and Terraform directory structure

Now that you know what is Amazon Elastic search and Amazon OpenSearch service are. Let’s now dive into Terraform files and Terraform directory structure that will help you write the Terraform configuration files later in this tutorial.

Terraform code, that is, Terraform configuration files, are written in a tree-like structure to ease the overall understanding of code with .tf format or .tf.json or .tfvars format. These configuration files are placed inside the Terraform modules.

Terraform modules are on the top level in the hierarchy where configuration files reside. Terraform modules can further call another child to terraform modules from local directories or anywhere in disk or Terraform Registry.

Terraform contains mainly five files as main.tf , vars.tf , providers.tf , output.tf and terraform.tfvars.

  1. main.tf – Terraform main.tf file contains the main code where you define which resources you need to build, update or manage.
  2. vars.tf – Terraform vars.tf file contains the input variables which are customizable and defined inside the main.tf configuration file.
  3. output.tf : The Terraform output.tf file is the file where you declare what output paraeters you wish to fetch after Terraform has been executed that is after terraform apply command.
  4. .terraform: This directory contains cached provider , modules plugins and also contains the last known backend configuration. This is managed by terraform and created after you run terraform init command.
  5. terraform.tfvars files contains the values which are required to be passed for variables that are refered in main.tf and actually decalred in vars.tf file.
  6. providers.tf – The povider.tf is the most important file whrere you define your terraform providers such as terraform aws provider, terraform azure provider etc to authenticate with the cloud provider.

Building Terraform Configuration files to Create AWS WAF and WAF rules using Terraform

Now that you know what are Terraform configurations files look like and how to declare each of them. In this section, you will learn how to build Terraform configuration files to create AWS WAF on the AWS account before running Terraform commands. Let’s get into it.

  • Log in to the Ubuntu machine using your favorite SSH client.
  • Create a folder in opt directory named terraform-WAF-demo and switch to that folder.
mkdir /opt/Terraform-WAF-demo
cd /opt/Terraform-WAF-demo
  • Create a file named main.tf inside the /opt/Terraform-WAF-demo directory and copy/paste the below content. The below file creates the below components:
# Creating the IP Set tp be defined in AWS WAF 

resource "aws_waf_ipset" "ipset" {
   name = "MyFirstipset"
   ip_set_descriptors {
     type = "IPV4"
     value = "10.111.0.0/20"
   }
}

# Creating the AWS WAF rule that will be applied on AWS Web ACL

resource "aws_waf_rule" "waf_rule" { 
  depends_on = [aws_waf_ipset.ipset]
  name        = var.waf_rule_name
  metric_name = var.waf_rule_metrics
  predicates {
    data_id = aws_waf_ipset.ipset.id
    negated = false
    type    = "IPMatch"
  }
}

# Creating the Rule Group which will be applied on  AWS Web ACL

resource "aws_waf_rule_group" "rule_group" {  
  name        = var.waf_rule_group_name
  metric_name = var.waf_rule_metrics

  activated_rule {
    action {
      type = "COUNT"
    }
    priority = 50
    rule_id  = aws_waf_rule.waf_rule.id
  }
}

# Creating the Web ACL component in AWS WAF

resource "aws_waf_web_acl" "waf_acl" {
  depends_on = [ 
     aws_waf_rule.waf_rule,
     aws_waf_ipset.ipset,
      ]
  name        = var.web_acl_name
  metric_name = var.web_acl_metics

  default_action {
    type = "ALLOW"
  }
  rules {
    action {
      type = "BLOCK"
    }
    priority = 1
    rule_id  = aws_waf_rule.waf_rule.id
    type     = "REGULAR"
 }
}
  • Create one more file named vars.tf inside the /opt/Terraform-WAF-demo directory and copy/paste below content. This file contains all the variables that are referred in the main.tf configuration file.
variable "web_acl_name" {
  type = string
}
variable "web_acl_metics" {
  type = string
}
variable "waf_rule_name" {
  type = string
}
variable "waf_rule_metrics" {
  type = string
}
variable "waf_rule_group_name" {
  type = string
}
variable "waf_rule_group_metrics" {
  type = string
}
  • Create one more file provider.tf file inside the /opt//Terraform-WAF-demo directory and copy/paste below content. The provider.tf file will allows Terraform to connect to the AWS cloud.
provider "aws" {
  region = "us-east-2"
}

  • Create one more file output.tf inside the /opt//Terraform-WAF-demo directory and copy/paste below content. the output fill will extract the output fro the state file and display on the console after running terraform apply command.
output "aws_waf_rule_arn" {
   value = aws_waf_rule.waf_rule.arn
}

output "aws_waf_rule_id" {
   value = aws_waf_rule.waf_rule.id
}

output "aws_waf_web_acl_arn" {
   value = aws_waf_web_acl.waf_acl.arn
}

output "aws_waf_web_acl_id" {
   value = aws_waf_web_acl.waf_acl.id
}

output "aws_waf_rule_group_arn" {
   value = aws_waf_rule_group.rule_group.arn
}

output "aws_waf_rule_group_id" {
   value = aws_waf_rule_group.rule_group.id
}
  • Create one more file terraform.tfvars inside the same folder and copy/paste the below content. This file contains the values of the variables that you declared in vars.tf file and refered in main.tf file.
web_acl_name = "myFirstwebacl"
web_acl_metics = "myFirstwebaclmetics"
waf_rule_name = "myFirstwafrulename"
waf_rule_metrics = "myFirstwafrulemetrics"
waf_rule_group_name = "myFirstwaf_rule_group_name"
waf_rule_group_metrics = "myFirstwafrulgroupmetrics"

  • Now your files and code are all set and your directory should look something like below.
AWS WAF folder and file structure
AWS WAF folder and file structure

Deploying the AWS WAF using Terraform.

Earlier in the previous section, you learned how to configure Terraform configuration files needed to create the AWS WAF in the AWS account. Now, let’s use terraform init ➝ terraform plan ➝ terraform apply commands to deploy the configuration files you build. Let’s execute!

  • Now your files and code are ready for execution. Initialize the terraform using the terraform init command.
terraform init
Initializing the terraform using the terraform init command.
Initializing the terraform using the terraform init command.
  • Terraform initialized successfully , now its time to run the plan command which provides you the details of the deployment. Run terraform plan command to confirm if correct resources is going to provisioned or deleted.
terraform plan
Running the terraform plan command
Running the terraform plan command
  • After verification, now its time to actually deploy the code using terraform apply command.
terraform apply
Running the terraform apply command
Running the terraform apply command

Terraform commands terraform init→ terraform plan→ terraform apply all executed successfully. Now, you should have AWS Web ACL and other components of AWS WAF created. Let’s verify each of them manually in the AWS Management Console.

  • Open your favorite web browser and navigate to the AWS Management Console and log in.
  • While in the Console, click on the search bar at the top, search for ‘WAF’, and click on the WAF menu item.
Searching for AWS WAF in the AWS console.
Searching for AWS WAF in the AWS console.
  • Now you should be on AWS WAF Page, Lets verify each component starting from Web ACL .
Verifying the newly created AWS Web ACL.
Verifying the newly created AWS Web ACL.
  • Now verify the IP Set
Verifying the newly created IP set
Verifying the newly created IP set
  • Now, Verify the Rules which in the Web ACL.
Verifying the newly created AWS WAF rules
Verifying the newly created AWS WAF rules
  • Finally verify the Web ACL Rule Groups.
Verifying the Web ACL Rule Groups
Verifying the Web ACL Rule Groups

Join 50 other followers

Conclusion

In this tutorial, you learned about Web Application Firewall (AWS WAF), and how to set up AWS WAF using Terraform.

It is essential to protect your website from attacks and AWS WAF is your new go friend for the same. Now you have newly created AWS WAF in AWS cloud which website do you plan to protect?

Advertisement

What is AWS WAF (Web Application Firewall) and how to Setup WAF in AWS account.

Are you sure if your applications or website are fully secure and protected? If not, you are at the right place to learn about Amazon web service Web Application Firewall (AWS WAF) that protects your web applications from common web exploits in the best effective way.

AWS WAF allows you to monitor all the HTTP(S) requests that are forwarded to an Amazon CloudFront distribution, Amazon API Gateway REST API, an Application Load Balancer, and takes actions accordingly.

This tutorial will teach what AWS WAF (Web Application Firewall) is and how to set up WAF in an AWS account. Let’s dive in and get started.

Join 50 other followers

Table of Content

  1. What is Amazon web service Web Application Firewall (AWS WAF) ?
  2. Benefits of AWS WAF
  3. Components of AWS WAF
  4. AWS WAF Web ACL (Web Access Control List)
  5. AWS WAF rules
  6. AWS Managed Rules rule group
  7. IP sets and regex pattern sets
  8. Prerequisites
  9. How to create AWS WAF (Web Application Firewall) and AWS WAF rules
  10. Conclusion

What is Amazon web service Web Application Firewall (AWS WAF) ?

AWS WAF allows you to monitor all the HTTP or HTTPS requests forwarded to Amazon Cloud Front, Amazon Load balancer, Amazon API Gateway REST API, etc., from users. AWS WAF controls who can access the required content or data based on specific conditions such as source IP address etc., and protects your applications from common web exploits.

Benefits of AWS WAF

  • AWS WAF is helpful when you want Amazon Cloud Front, Amazon Load balancer, Amazon API Gateway REST to provide the content or serve content to particular users or block particular users.
  • AWS WAF allows you to count the requests that match properties specified without allowing or blocking those requests
  • AWS WAF protects you from web attacks using conditions you specify and also provides real time metrics and details of web requests.
AWS WAF architecture and working
AWS WAF architecture and working

Components of AWS WAF

AWS WAF service contains some important components; let’s discuss each of them now.

AWS WAF Web ACL (Web Access Control List)

AWS WAF Web ACL allows protecting a set of AWS Resources. After you create a web ACL, you need to add AWS WAF rules inside it.

AWS WAF rules define specific conditions applied to web requests coming from users and how to handle these web requests. You also set default action in web ACL to allow or block requests that pass these rules.

AWS WAF rules

AWS WAF rules contain statements that define the criteria, and if the criteria are matched, then the web requests are allowed; else, they are blocked. The rule is based on IP addresses or address ranges, country or geographical location, strings that appear in the request, etc.

AWS Managed Rules rule group

You can use rules individually or in reusable rule groups. There are two types of rules: AWS Managed rule groups and managing your own rule groups.

IP sets and regex pattern sets

AWS WAF stores complex information in sets you use by referencing them in your rules.

  • An IP set is a group of IP addresses and IP address ranges of AWS resources that you want to use together in a rule statement.
  • A regex pattern set provides a collection of regular expressions that you want to use together in a rule statement. Regex pattern sets are AWS resources.

Prerequisites

  • You must have AWS account in order to setup AWS WAF. If you don’t have AWS account, create a AWS account from here AWS account.
  • IAM user with Administrator rights and setup credentials using AWS CLI or using AWS Profile.

How to create AWS WAF (Web Application Firewall) and AWS WAF rules

Now that you have a basic idea of AWS WAF and the components of AWS WAF. To work with AWS WAF, the first thing you need to create is Web Access Control List (ACL) and further add the WAF rules ( individual rules or groups of rules ) such as blocking or allowing web requests.

In this section, let’s learn how to create and set up AWS WAF and create a Web ACL.

  • To create Web ACL open your favorite web browser and navigate to the AWS Management Console and log in.
  • While in the console, click on the search bar at the top, search for WAF, and click on the WAF menu item.
Searching for AWS WAF
Searching for AWS WAF
  • Now further click on on Create Web ACL button as shown below.
Creating a Web ACL
Creating a Web ACL
  • Next provide the Name, cloud Watch metric name of your choice and choose Resource type as CloudFront distributions.

This tutorial already had one CloudFront Distribution in place which will be used If you need to create the cloud Distribution follow here

Cloud Distribution in AWS account
Cloud Distribution in AWS account
  • Next, Click on Add AWS Resources and select the CloudFront distribution and hit NEXT.
Selecting the CloudFront distribution in AWS WAF
Selecting the CloudFront distribution in AWS WAF
  • Further In Add rules and rule groups section choose Add my own rules and rule groups and provide the values as shown below.
    • Name as myrule123
    • Type as Regular Rule
    • Inspect as Header
    • Header field as User-Agent
    • if a request as matches the statement
Adding rules and rule groups in AWS WAF
Adding rules and rule groups in AWS WAF
Defining the values of AWS WAF rules and rule groups
Defining the values of AWS WAF rules and rule groups
  • While building the rules there are 3 types of Rule Actions options available such as
    • Count: AWS WAF counts the request but doesn’t determine whether to allow it or block it
    • Allow: AWS WAF allows the request to be forwarded to the protected AWS resource
    • Block: AWS WAF blocks the request and sends back to the client.
  • Choose Count as the rule action.
Choosing the rule action
Choosing the rule action

You can instruct AWS WAF to insert custom headers into the original HTTP request for rule actions or web ACL default actions that are set to allow or count.

  • Finally hit the next button till end and then Create Web ACL.
Creating the Web ACL
Creating the Web ACL
  • The rules you added previous are manual rules, but at times you need to add AWS Managed rules, to do that select AWS Managed rules.
Adding AWS WAF Managed rules
Adding AWS WAF Managed rules
  • Now the AWS Web ACL is should look like as showb below with both managed and your own created AWS WAF rules.
Viewing the AWS WAF with both managed and your own created AWS WAF rules
Viewing the AWS WAF with both managed and your own created AWS WAF rules

Conclusion

In this tutorial, you learned AWS WAF service, WAF components such as AWS Web ACL, the WAF rules, and applied to WAF web ACL.

You also learned how to apply AWS WAF web ACL on CloudFront to protect your websites from getting exploited from attacks.

So now, which applications and websites do you plan to protect next using AWS WAF?