Demystifying AWS VPC Network Firewall using Terraform
Published: 2023-10-24 21:10:32

This post was originally published on [Hackmamba](https://hackmamba.io/blog/2023/10/demystifying-aws-vpc-network-firewall-using-terraform/).

Many organizations that deal with sensitive data, such as financial information, may suffer from cyber attacks such as malware infections, data breaches, distributed denial-of-service (DDoS) attacks, and so on, which could result in financial loss. Fortunately, organizations can avoid such situations by creating a Virtual Private Cloud (VPC) with a tool like Amazon Web Services (AWS), allowing them to monitor their network for security threats and isolate it from the public internet.

Organizations must ensure their infrastructure is always secure by implementing security measures such as firewalls, data encryption, access control, among other features. Organizations can use Terraform, a powerful and reliable tool, to automate the deployment of security groups; this tool can help control access to an organization’s resources while ensuring that the security groups remain compliant with their security policies.

When manually building infrastructure, the organization risks many human errors. However, combining AWS and Terraform reduces the risk of human errors and enables organizations to build a secure and scalable infrastructure.

This article will help you understand the AWS VPC Network Firewall and how it improves cloud security. It will also include a hands-on demonstration of using Terraform to manage and automate your project’s AWS VPC Network Firewall configurations.


## What is AWS VPC Network Firewall?

To understand the AWS VPC Network Firewall, it's essential to grasp the concept of a firewall. A firewall is a network security device that filters incoming and outgoing network traffic based on security rules, acting as a barrier between a private network and the public internet to block bad or malicious traffic.


![Illustration of a network firewall](https://lh5.googleusercontent.com/ZsAshblU9D2aoaRlO32cP85f5rQAXuwqeL6xYdJ4ystkuRMn2KLemif2568B1SIKM6IFsAOFckAcMn8JfPoMxnahXjFrpc2Vn7O_i4c93LOFPyA5vVMDU67JBepoANrzkv51R0a2m2nND2EfggLBmdc)


Depending on an organization's or individual's needs, a private network or public internet can be chosen. If there are concerns about system security, cost, control, or performance, a private network becomes the preferred option due to its significant benefits over the public internet. A private network is more secure than the public internet, using private IP addresses and enabling control through security devices like firewalls to manage network traffic.

Unauthorized access to a private network can severely impact an organization or individual, leading to financial losses from cyber attacks such as data breaches and disruptions, rendering the network unavailable. Implementing security measures such as firewalls and intrusion detection systems is crucial to protect private networks.

AWS VPC Network Firewall secures and protects your AWS VPC from unauthorized access. As an AWS service, it's managed by Amazon, relieving you of infrastructure management. This service watches incoming and outgoing traffic, identifying and blocking malicious activity to maintain VPC security.

**Benefits of AWS VPC Network Firewall**
AWS VPC Network Firewall is an excellent choice for organizations due to its numerous benefits.
Let’s explore a few of them.


- **Scalability**: Applications can experience surges or drops in traffic depending on the number of active users. If your app can't handle more users, it might slow down or crash. To prevent this, monitor for issues and consider adding extra resources, like more servers. It's hard to do this yourself, so the AWS VPC Network Firewall can help. If users suddenly increase, it adjusts automatically, saving time and money.
<br>


- **Performance:** If your app can't handle many users, it becomes slow and might not work well when many people use it simultaneously. This can make your users dissatisfied, make your app less safe, and even cost you money. To avoid this, you can use AWS VPC Network Firewall. It helps your app handle lots of traffic without slowing down using rule-based filtering and stateful inspection techniques.
<br>

- **Cost:** Using AWS VPC Network Firewall is a cost-effective choice as it allows you to only pay for the resources you use. This means that you are charged based on the amount of your application’s traffic and the number of firewalls deployed. Additionally, Since AWS VPC Network Firewall is a managed firewall service, it saves the cost of managing and maintaining your firewall by yourself.
<br>

- **Security:** AWS VPC Network Firewall provides features such as [intrusion prevention](https://aws.amazon.com/network-firewall/features/#Intrusion_prevention) (which helps detect and block malicious traffic), [web filtering](https://aws.amazon.com/network-firewall/features/#Web_filtering) (which can help block traffic), and more for protecting your VPCs from malware and brute force attacks.

**Features of the AWS VPC Network Firewall**
What makes AWS VPC Network Firewall stand out are its extensive features. Let’s take a look at them.


- **Stateful firewall**: This [feature](https://aws.amazon.com/network-firewall/features/#Stateful_firewall) of AWS VPC Network Firewall keeps track of the connections between your network and other networks to allow or block traffic based on the type of traffic and the direction of the connection. A few examples of what the firewall tracks include source and destination IP addresses, ports, and protocol type. 
<br>

- **Automated scaling**: AWS VPC Network Firewall offers [automatic scaling](https://aws.amazon.com/network-firewall/features/#High_availability_and_automated_scaling) for the firewall capacity of your network to scale up or down based on the traffic load. 
<br>

- **Intrusion prevention**: This feature utilizes [signature-based detection](https://docs.aws.amazon.com/network-firewall/latest/developerguide/aws-managed-rule-groups-threat-signature.html) to inspect network traffic patterns for matches against known threat signatures to protect your VPC from unauthorized access or malicious activities.
<br>

- **Web filtering**: This feature blocks unencrypted web traffic to known malicious websites and monitors [fully qualified domain names](https://g.co/kgs/cY4C4a) (FQDNs) for encrypted web traffic using the [Server Name Indication (SNI](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/use-network-firewall-to-capture-the-dns-domain-names-from-the-server-name-indication-sni-for-outbound-traffic.html)) extension that blocks access to specific sites. 
<br>

- **Central management**: [This feature](https://aws.amazon.com/network-firewall/features/#Central_management_and_visibility) centrally manages and enforces firewall policies across multiple VPCs to ensure the same security policies protect all the resources.

**How does AWS Network Firewall work?**
Because it is an AWS service, AWS Network Firewall requires the use of an [Amazon VPC](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html). When you create an AWS account, it will contain a default VPC for each AWS region, and if you choose to, you can create more VPCs. 

After creating your VPC, you can add [subnets](https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html) (where each subnet must reside within one Availability Zone to allow the launching of AWS resources in separate Availability Zones) and then deploy AWS resources like [Elastic Compute Cloud](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) [](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)[(](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)[EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)[)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) [instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) in your VPC. In addition, you’ll need to configure the [route tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) for your VPC to send Network traffic through the Network Firewall endpoints before the AWS Network Firewall is enabled.

So, the AWS Network Firewall protects the subnets you’ve added to your VPC by filtering the traffic between the subnets and locations outside your VPC. 

The following is an illustration from [AWS Documentation](https://docs.aws.amazon.com/network-firewall/latest/developerguide/how-it-works.html) of how AWS Network Firewall works:


![Illustration showing an AWS Network Firewall](https://lh5.googleusercontent.com/FQrf-7JzHmqMoPDeVmeH6_bprYyNm5vkY2wNJEGvokqaCCMXUPdwCZxEA4oFmkijBFtbWZwZWc7vX0LNHlPxnu6MhHQFStUn_sUmNGnu63C8yKbqN1EOXfVaREtNwUX4-3zXnLVSaeFO5tPEHXrsQ98)


The AWS Network Firewall filters the traffic using [r](https://docs.aws.amazon.com/network-firewall/latest/developerguide/rule-groups.html)[ule groups](https://docs.aws.amazon.com/network-firewall/latest/developerguide/rule-groups.html), either [stateless](https://docs.aws.amazon.com/network-firewall/latest/developerguide/stateful-rule-groups-ips.html) (evaluating packets in isolation) or [stateful](https://docs.aws.amazon.com/network-firewall/latest/developerguide/stateful-rule-groups-ips.html) (evaluating packets in the context of their traffic flow). You can configure these rules inside a [firewall policy](https://docs.aws.amazon.com/network-firewall/latest/developerguide/firewall-policies.html). The configuration involves several [settings](https://docs.aws.amazon.com/network-firewall/latest/developerguide/firewall-settings.html), including specifying the subnets for the firewall endpoints for each Availability zone defined and more. 

You can write your stateful rules in Suricata-compatible format, and the Network Firewall will process the rules using a Suricata rules engine.
 
Then, the AWS Network Firewall uses a firewall to connect the inspection rules configured in the firewall policy to the VPC.

## Overview of Amazon Virtual Private Cloud (VPC)

You’ve seen the term Amazon Virtual Private Cloud (VPC) mentioned a couple of times, and from all that has been explained, you may now have some clue about what it is. For clarity, let’s take a look at a brief overview. 

**What is Amazon VPC?**
Amazon Virtual Private Cloud (Amazon VPC) is an AWS service that lets you establish a secure and isolated virtual network for deploying AWS resources. This network resembles a traditional on-premises network but leverages AWS's scalable infrastructure.

**Core features of Amazon VPC**
Amazon VPC consists of primary features, as shown in the illustration below from the Amazon VPC [documentation](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html):

![An Illustration of a VPC (Source: Amazon VPC documentation)](https://paper-attachments.dropboxusercontent.com/s_A1BF7ADE6560CB70515E7D95432F285689294438D7BA0BB371718902A3A2B7BA_1694595751543_VPC.png)


The core features include the following:


- **VPCs**: VPCs (Virtual Private Clouds) are isolated sections of the AWS cloud that you can use to launch AWS resources. Each VPC has its IP address range, subnets, and routing tables.
<br>

- **Subnets**: Subnets are smaller divisions of a VPC. You can launch AWS resources, such as Amazon [EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html), into subnets. Subnets must be located within a single Availability Zone.
<br>

- **Route tables**: Route tables control how traffic is routed within a VPC. Each route table contains a list of routes, specifying the destination IP address range and the next hop router.
<br>

- **Internet gateways**: Internet gateways allow traffic to flow between a VPC and the internet. You can also use internet gateways to connect your VPC to other VPCs or your on-premises network.
<br>

- **VPC Peering**: VPC Peering allows you to connect two VPCs together without using an internet gateway or VPN. This can be useful for connecting VPCs that are in the same region or different regions.

**Types of Amazon VPCs**
There are two types of Amazon VPCs: default VPCs and non-default VPCs. Let’s explore them below.
 

- **Default VPCs**: These [VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) are created automatically when you create an AWS account. They are pre-configured with a single subnet in each Availability Zone in the Region. You can use a default VPC to launch your Amazon EC2 instances, Amazon Relational Database Service (RDS) instances, and other AWS resources. To create a default VPC, check the [user guide](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) provided by Amazon VPC.

The illustration below shows the components of a default VPC from the [Amazon VPC documentation](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html). 


![Illustration of a default VPC (Source: Amazon VPC Documentation)](https://paper-attachments.dropboxusercontent.com/s_A1BF7ADE6560CB70515E7D95432F285689294438D7BA0BB371718902A3A2B7BA_1694596244671_default-vpc.png)



- **Non-default VPCs**: These types of VPCs are VPCs that you create yourself. You have more control over the configuration of a non-default VPC, such as the IP address range, the number of subnets, and the routing configuration. You can also create non-default VPCs in multiple Regions.

**Advantages of using Amazon VPC**
Amazon VPC offers several advantages over a traditional data center, including the following:


- **Cost-effectiveness**: Amazon VPC is a cost-effective way to host your applications and data. You only pay for the resources that you use.
<br>

- **Scalability**: Amazon VPC is scalable, so you can easily add or remove resources. You can also create multiple VPCs to meet the needs of different applications or workloads.
<br>

- **Security**: Amazon VPC provides high security for your data and applications. Your VPC is isolated from other VPCs and the public internet, and you can control who can access your resources.
<br>

- **Reliability**: Amazon VPC is a reliable platform that is backed by Amazon's infrastructure. Your data is stored in multiple Availability Zones, protecting it from unplanned outages.

**Things to consider when setting up an Amazon VPC**
Here are some things to consider when setting up your Amazon VPC.  


- **Determining IP address ranges**: When setting up your VPC, you need to consider how the resources within your VPC would communicate with each other and how they would communicate with resources over the internet. 
<br>

So, depending on the size of your VPC, which also depends on the number of resources that you plan to deploy, you’d need to select a range of IP addresses (such as 172.16.0.0/16, 192.168.0.0/16) that would be used for this purpose. You can use the [Classless Inter-Domain Routing block](https://aws.amazon.com/what-is/cidr/#:~:text=Classless%20Inter%2DDomain%20Routing%20(CIDR)%20allows%20network%20routers%20to,specified%20by%20the%20CIDR%20suffix.) (CIDR) to represent the range of IP addresses. 
<br>

- **Selecting Availability Zones (AZs)**: You must consider your application's availability and fault tolerance when setting up your VPC. When you create your VPC, you can deploy your resources in multiple Availability Zones, isolated locations within a highly available, fault-tolerant region with its own networking infrastructure, power, and cooling. 


Doing so would ensure that your application does not suffer a single point of failure. For instance, if one Availability Zone goes down, the other Availability Zones will still have your application and data.


- **Determining Internet Connection for Resources**: You need to decide how your resources in the VPC will connect to the Internet. You can choose to have a public subnet directly connected to the internet or a private subnet connected to the internet through a VPN or AWS Direct Connect.
<br>

- **Creating the VPC**: Once you have considered the above factors, you can create your VPC. When creating your VPC, you need to specify the IP address range, the number of AZs, and the internet connectivity options.
<br>

- **Consideration of the Applications’ Architectural Design**: When designing your VPC, you need to consider the architectural design of your applications. For example, if you have an application that needs to be highly available, you must place its components in multiple AZs.


## How to utilize Terraform for AWS VPC Network Firewall management

[Terraform](https://www.terraform.io/) is an Infrastructure as Code (IaC) tool used to automate the creation and management of AWS VPC Network Firewall rules. It streamlines the process by providing automated provisioning, ensuring consistent and repeatable deployments, enabling version control for tracking changes and easy rollbacks, and aiding in audibility to maintain compliance with security policies.

Let’s do a quick demo showing how to use Terraform to create and manage AWS VPC Network Firewall rules.

**Prerequisites**
To follow along, you’ll need the following:

- Knowledge of Terraform
- Terraform installed (check the [documentation](https://developer.hashicorp.com/terraform/downloads) to install Terraform for your operating system)
- AWS Command Line Interface (CLI) installed (install [here](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html))
- Terminal

**Creating project directory**
Now, let’s create a directory called **terraform_project** that will house the configuration file called “**conf.tf”**. In your terminal, run the following commands:

```
mkdir terraform_project
cd terraform_project
touch conf.tf
```

Since we want to utilize Terraform for AWS VPC Network Firewall management, we’ll need to define and configure AWS as our Cloud Provider for the project. In your **conf.tf** file, add the following configuration:

```
provider "aws" {
  region = "us-east-1"
}
```

In the configuration above, you set the AWS provider to operate in the “us-east-1” region. AWS has its own set of [regions](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html) available for deployment, so you can use any desired region of your choice. You specified the region by setting the ‘region’ parameter. This means that any resources you define within this configuration will be created in the “us-east-1” region.

Before proceeding, ensure that you have added your Access and Secret access keys from your AWS account. 

**Defining the Resources**
Since you have defined the cloud provider, you can now define the resources you want to create using the AWS provider. As mentioned earlier in the article, AWS provider offers a wide range of resources that you can create using Terraform such as S3 Bucket ("aws_s3_bucket" type), AWS EC2 instance (“aws_instance” resource type), VPC ("aws_vpc" resource type), Security Group ("aws_security_group" resource type), Subnet ("aws_subnet" resource type) and [more](https://registry.terraform.io/providers/hashicorp/aws/latest/docs).

Let’s create an AWS EC2 instance, which would involve setting up networking components like VPC, subnets, and security groups. Using Terraform’s configuration language within the **conf.tf** file defines the following:

```
resource "aws_vpc" "sample_vpc" {
   cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "sample_subnet" {
   vpc_id     = aws_vpc.sample_vpc.id
   cidr_block = "10.0.0.0/24"
}
resource "aws_security_group" "sample_security_group" {
   name_prefix = "sample-security-group"
   ingress {
     from_port = 22
     to_port   = 22
     protocol  = "tcp"
     cidr_blocks = ["0.0.0.0/0"]
   }
 }
 resource "aws_instance" "sample_instance" {
   ami           = "ami-0c55b159cbfafe1f0"
   instance_type = "t2.micro"
   subnet_id     = aws_subnet.sample_subnet.id
   security_groups = [aws_security_group.sample_security_group.name]
      tags = {
        Name = "SampleInstance"
      }
 }
```

From the configuration above, you are setting the following:

- The aws_vpc resource creates a VPC with the specified CIDR block.
- The aws_subnet resource creates a subnet within the VPC.
- The aws_security_group resource defines a security group that allows incoming secure shell (SSH) traffic (port 22) from anywhere (0.0.0.0/0).
- The aws_instance resource uses the previously created VPC, subnet, and security group to launch the EC2 instance. Note that AWS provides several EC2 instance types, differing in terms of memory, CPU, storage, and more. Here, you’re using the "t2.micro" instance that is designed for small to medium workloads.

**Initializing your Terraform configuration**
Now that you have defined the resources, you need to initialize your Terraform configuration to ensure that the necessary components, such as plugins and state dependencies, are in place.

Within your project directory, run the following command to initialize Terraform:

```
terraform init
```

After running the command, Terraform will be initialized:

![](https://lh3.googleusercontent.com/6pWd7c11Z_NmI3KhOw59ErLsqHH9rjjJHNue41ftgQJKFoFFfs-wm-JBm3JVmi3WSS4rcKwOhrDGFbtkWea6B775Mm1UFy6mCRP1HS_2Xo0jtkoq7seOsmeTz9v4Kqhk1wBhDPJhW_0eogUN9WTvnc4)


**Previewing changes**
Based on your configuration, you can take this precautionary step for early detection of errors in your configuration to reduce the chances of failed deployments and to see what changes Terraform will make to your infrastructure.

```
terraform plan
```

After the command runs successfully, Terraform will use the selected providers to generate the execution plan, as shown in the screenshots below:

1. 

![](https://lh3.googleusercontent.com/bDR-il-h-ks7oxgdjNNapGsLQjtyyGY_c_L84ANWpB8C937AdcMjV0nUScxfVD_DWGfosb9Jn6G0Cge8aans6iu8P83oUbn9ShGP0FldirCdsgzB7WvhVxDBYIleMb8wHo6yfeJRWEyw_CtfoW6_QLI)


2.

![](https://lh3.googleusercontent.com/alQezpVI5k5ha-pmWWE4t4R_5QS4Hb9SCkP-1eWBUAbIso09Mmj2HWkObs3JRSdScyC6-AbBVgOkk9EGnXOJlo7grhZqqci06AnfrknK0uMZIRXufhPoSmLKjl1GyckcldcFHlWbWaS8FHVm642ALsc)

3.

![](https://lh5.googleusercontent.com/TNTsTJoJHRVBC-vIQickDfkprY9Vm2vx2s86t3jkMMjLIrJczeinpt7PE_NyhxOdS6Kbff6XQOOwygnpPzC6FbeS_mkK1Kl3vpcO4OIeDpw5oACIYXI3QXNgIZoJZP71VipcPz7CkLjK7YXb4zn2nDc)


4.

![](https://lh3.googleusercontent.com/0fBCBEhj3P6RlLw6T9C3P1ogStx1nj_nJVL2Vbb81Hc062U4K9dzz1nL75c1OWgtpbb62vplkDoSQTtfRjPg1kxD1BonbjwEFQoWB1ENWJEre5U44EQu0yQGBJUo7ZiHUYqnHSx8GaLoBGH6wABXXqw)


**Applying changes**
Executing the planned infrastructure modifications to create or update resources based on your Terraform configuration is necessary. Run the following command in your project’s directory:

```
terraform apply
```

![](https://lh6.googleusercontent.com/KBU9AD13nqS0WpTedBeV7ildbX1n5IBAh6HP80oSrnfnmPRKsQEzbOQtxpDhHfZrclW9ha11YJ4rmi0vvox3g71zZgHvH-mcyWYfOYJqAEI_m1kMrZ4u3NeQgPJYggOrWzsmnXBVsFNYDTqRcPVAK9g)

## Conclusion

You’ve come to the end of this article, where you learned about AWS VPC Network Firewall, including what it is, its benefits, features, and how it works. You also learned about Amazon VPC, including what it is, its core features, types, and advantages. The article also included a demo showing how to set up and use Amazon VPC and Terraform for AWS VPC Network Firewall Management. 

## Resources

You may find the following resources helpful:

- [Terraform Documentation](https://developer.hashicorp.com/terraform/docs)
- [AWS Network Firewall Documentation](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html)