Creating Demilitarized Zone with NAT gateway in AWS for better security using Terraform

Dipaditya Das
17 min readJul 26, 2020

--

Lets say you want to deploy a Web-app(like WordPress) with a Database(MariaDB) but you don’t know to secure them in the best ways.

Well, in this article I am going to cover something called “Demilitarized Zone”, and how it actually makes a better security for any Web-App Deployment. But before that we need to clear some basics.

What is AWS?

AWS stands for Amazon Web Services. It is a public cloud. It is the world’s most comprehensive and broadly adopted cloud platform, offering over 175 fully featured services from data centers globally. It is a subsidiary of Amazon that provides on-demand cloud computing platforms and APIs to individuals, companies, and governments, on a metered pay-as-you-go basis. There are 24 globally launched Regions with 76 Availability Zones and 216 Points of Presence (205 Edge Locations and 11 Regional Edge Caches).

The AWS Cloud spans 77 Availability Zones within 24 geographic regions around the world.

What is AWS VPC?

Amazon Virtual Private Cloud (Amazon VPC) lets you provision a logically isolated section of the AWS Cloud where you can launch AWS resources in a virtual network that you define. You have complete control over your virtual networking environment, including selection of your own IP address range, creation of subnets, and configuration of route tables and network gateways. You can use both IPv4 and IPv6 in your VPC for secure and easy access to resources and applications. You can easily customize the network configuration of your Amazon VPC. For example, you can create a public-facing subnet for your web servers that have access to the internet. You can also place your backend systems, such as databases or application servers, in a private-facing subnet with no internet access. You can use multiple layers of security, including security groups and network access control lists, to help control access to Amazon EC2 instances in each subnet.

What is Subnets?

A subnet, or subnetwork, is a network inside a network. Subnets make networks more efficient. Through subnetting, network traffic can travel a shorter distance without passing through unnecessary routers to reach its destination.

A VPC spans all of the Availability Zones in the Region. After creating a VPC, you can add one or more subnets in each Availability Zone. You can optionally add subnets in a Local Zone, which is an AWS infrastructure deployment that places compute, storage, database, and other select services closer to your end users. A Local Zone enables your end users to run applications that require single-digit millisecond latencies. For information about the Regions that support Local Zones, see Available Regions in the Amazon EC2 User Guide for Linux Instances. When you create a subnet, you specify the CIDR block for the subnet, which is a subset of the VPC CIDR block. Each subnet must reside entirely within one Availability Zone and cannot span zones. Availability Zones are distinct locations that are engineered to be isolated from failures in other Availability Zones. By launching instances in separate Availability Zones, you can protect your applications from the failure of a single location. We assign a unique ID to each subnet. You can also optionally assign an IPv6 CIDR block to your VPC, and assign IPv6 CIDR blocks to your subnets.

What is Internet Gateway?

An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between your VPC and the internet. An internet gateway serves two purposes: to provide a target in your VPC route tables for internet-routable traffic, and to perform network address translation (NAT) for instances that have been assigned public IPv4 addresses. An internet gateway supports IPv4 and IPv6 traffic. It does not cause availability risks or bandwidth constraints on your network traffic.

What is Route Table?

A route table contains a set of rules, called routes, that are used to determine where network traffic from your subnet or gateway is directed. Your VPC has an implicit router, and you use route tables to control where network traffic is directed. Each subnet in your VPC must be associated with a route table(Route Table Association), which controls the routing for the subnet (subnet route table). You can explicitly associate a subnet with a particular route table. Otherwise, the subnet is implicitly associated with the main route table. A subnet can only be associated with one route table at a time, but you can associate multiple subnets with the same subnet route table.

What is NAT Gateway?

Network address translation (NAT) is a method of remapping an IP address space into another by modifying network address information in the IP header of packets while they are in transit across a traffic routing device. The technique was originally used to avoid the need to assign a new address to every host when a network was moved, or when the upstream Internet service provider was replaced, but could not route the networks address space. It has become a popular and essential tool in conserving global address space in the face of IPv4 address exhaustion. One Internet-routable IP address of a NAT gateway can be used for an entire private network. We can use a network address translation (NAT) gateway to enable instances in a private subnet to connect to the internet or other AWS services, but prevent the internet from initiating a connection with those instances.

What is Elastic IP address?

An Elastic IP address is a static, public IPv4 address designed for dynamic cloud computing. We can associate an Elastic IP address with any instance or network interface for any VPC in our account. With an Elastic IP address, we can mask the failure of an instance by rapidly remapping the address to another instance in our VPC. Note that the advantage of associating the Elastic IP address with the network interface instead of directly with the instance is that we can move all the attributes of the network interface from one instance to another in a single step.

What is Demilitarized Zone?

In computer security, a DMZ or demilitarized zone (sometimes referred to as a perimeter network or screened subnet) is a physical or logical subnetwork that contains and exposes an organization’s external-facing services to an untrusted, usually larger, network such as the Internet. The purpose of a DMZ is to add an additional layer of security to an organization’s local area network (LAN): an external network node can access only what is exposed in the DMZ, while the rest of the organization’s network is firewalled. The DMZ functions as a small, isolated network positioned between the Internet and the private network and, if its design is effective, allows the organization extra time to detect and address breaches before they would further penetrate into the internal networks.

A public subnet is directly routable to the Internet via a route in the route table that points to the Internet gateway. This type of subnet allows the use of Elastic IPs and public IPs, and (if the security group and network ACLs permit) a public subnet is reachable from the Internet. A public subnet is useful as a DMZ infrastructure for web servers and for Internet-facing Elastic Load Balancing (ELB) load balancers.

Private subnets can indirectly route to the Internet via a NAT instance or NAT gateway. These NAT devices reside in a public subnet in order to route directly to the Internet. Instances in a private subnet are not externally reachable from outside the Amazon VPC, regardless of whether they have a public or Elastic IP address attached. A private subnet is useful for application servers and databases.

What is Terraform?

Terraform is the infrastructure as a code offering from HashiCorp. It is a tool for building, changing and managing infrastructure in a safe, repeatable way. Operators and Infrastructure teams can use Terraform to manage environments with a configuration language called the HashiCorp Configuration Language (HCL) for human-readable, automated deployments.

Terraform works with over 160 different providers for a broad set of common infrastructure. Provider SDK makes it simple to create new and custom providers. Providers leverage infrastructure-specific APIs to preserve unique capabilities for each provider.

Prerequisite for the Practical

  1. AWS IAM user with power user policy
  2. AWS CLI and profile of IAM user created
  3. Terraform
  4. Visual Studio Code with Terraform extension
  5. PowerShell 7.0

Let’s Get Started with Terraform Automation

In this practical we will perform the following tasks:

  1. Creating a Virtual Private Cloud(VPC).
  2. Creating an Internet Gateway for VPC.
  3. Creating a Public Subnet within our VPC.
  4. Creating a Private Subnet within our VPC.
  5. Creating a route table for Public Subnet.
  6. Creating an association between the Route table and Public Subnet.
  7. Creating an Elastic IP address for NAT gateway.
  8. Creating a NAT Gateway.
  9. Creating a route table for Private Subnet.
  10. Creating an association between the Route table and Private Subnet.
  11. Creating a Security Group for Web-App(WordPress).
  12. Creating a Security Group for Database(MariaDB).
  13. Creating a Key-Pair for AWS EC2 instances.
  14. Creating a Database EC2 instance(containing MariaDB).
  15. Creating a Web-App EC2 instance(containing WordPress).
  16. Modifying the WordPress Configuration file.
  17. Providing the Key to WordPress Instance(Public Subnet) in order to SSH to Database Instance(Private Subnet).
  18. Launch the WordPress Site in our browser.

Note: WordPress instance has to be part of public subnet so that our client can connect our site. Database instance has to be part of private subnet so that outside world can’t connect to it. Don’t forgot to add auto IP assign and auto DNS name assignment option to be enabled.

The Entire Task

Step-1: Configure AWS CLI

AWS CLI in PowerShell 7(Win10)

Step-2: Create a terraform file (main.tf)

I am creating an main.tf file and coding our cloud provider, i.e., AWS. We are also providing the availability zone (Mumbai) with my AWS CLI profile name.

main.tf

Step-3: Creating a Virtual Private Cloud(VPC).

Amazon Virtual Private Cloud (Amazon VPC) enables us to launch AWS resources into a virtual network that we have defined. This virtual network closely resembles a traditional network that we would operate in our own data center, with the benefits of using the scalable infrastructure of AWS. Its basically the network layering of EC2 instances. Here I have created an AWS VPC in the same availability zone (Mumbai).

aws_vpc.tf

Step-4: Creating an Internet Gateway for VPC.

An internet gateway is a horizontally scaled, redundant, and highly available VPC component that allows communication between our VPC and the internet. An internet gateway serves two purposes: to provide a target in our VPC route tables for internet-routable traffic, and to perform network address translation (NAT) for instances that have been assigned public IPv4 addresses. An internet gateway supports IPv4 and IPv6 traffic. It does not cause availability risks or bandwidth constraints on our network traffic. I have created an Internet gateway for my AWS VPC.

aws_internet_gateway.tf

Step-5: Creating a Public Subnet within our VPC.

Here we will created Public subnet for Web-App(WordPress).

aws_public_subnet.tf

Step-6: Creating a Private Subnet within our VPC.

Here we will created Private subnet for Database(MariaDB).

aws_private_subnet.tf

Step-7: Creating a Route Table for Public Subnet.

A route table contains a set of rules, called routes, that are used to determine where network traffic from our subnet or gateway is directed. This route table is for inbound traffic to VPC through internet gateway.

aws_route_table_igw.tf

Step-8: Creating an association between the Route table and Public Subnet.

Each subnet in our VPC must be associated with a route table. A subnet can be explicitly associated with custom route table, or implicitly or explicitly associated with the main route table.

aws_route_assoc_public.tf

Step-9: Creating an Elastic IP address for NAT gateway.

Here we created and Elastic IP Address for NAT Gateway so that we could establish outbound connectivity for the database instance in private subnet.

aws_eip.tf

Step-10: Creating a NAT Gateway.

Here we creating the NAT Gateway in public subnet to establish the outbound connectivity to the AWS EC2 instances in private subnet.

aws_nat_gateway.tf

Step-11: Creating a route table for Private Subnet.

Here we are creating a route table for the EC2 instances in private subnet.

aws_route_table_nat.tf

Step-12: Creating an association between the Route table and Private Subnet.

Here we explicitly associating the route table with the private subnet.

aws_route_assoc_private.tf

Step-13: Creating a Security Group for Web-App(WordPress).

A security group acts as a virtual firewall for our EC2 instances to control incoming and outgoing traffic. Inbound rules control the incoming traffic to our instance, and outbound rules control the outgoing traffic from your instance. We are going to create a security group for our Web-App EC2 instance which will allow all SSH, ICMP, HTTP, HTTPS inbound traffic as well as all outbound traffic.

aws_security_group_wp.tf

Step-14: Creating a Security Group for Database(MariaDB).

We are going to create a security group for our Database EC2 instance which will allow all SSH inbound traffic from the public subnet as well as all outbound traffic from the internet.

aws_security_group_db.tf

Step-15: Creating a Key-Pair for AWS EC2 instances.

Here we have created a key-pair using Terraform tls_private_key generates a secure RSA 4096 bit private key and encodes it as PEM. This resource is primarily intended for easily bootstrapping throwaway development environments. This is a logical resource, so it contributes only to the current Terraform state and does not create any external managed resources.

aws_key_pair.tf

Step-16: Creating a Database EC2 instance(containing MariaDB).

We will launch Database EC2 instance prior to WordPress EC2 instance because WordPress needed Database in the background. If we do not launch Database before WordPress then WordPress will not connect to Database.

aws_ec2_database.tf

Step-17: Creating a Web-App EC2 instance(containing WordPress).

We are launching WordPress EC2 Instance.

aws_ec2_wordpress.tf

Step-18: Modifying the WordPress Configuration file.

We have to provide the private IP of Database EC2 instance which is also the MySQL Hostname, to the WordPress configuration file in order to store the data in our database present in Private Subnet.

modify_wordpress_config.tf

Step-19: Providing the Key to WordPress Instance(Public Subnet) in order to SSH to Database Instance(Private Subnet).

In order to access our Database Remotely from Public Subnet as the database instance is kept in private subnet. So, we have to provide the private key to the WordPress EC2 instance in order to SSH to Database Instance.

key_to_wordpress.tf

Step-20: Launch the WordPress Site in our browser.

After launching and configuring the setup, we will launch our site in our browser and we will also output the Public IP of WordPress EC2 Instance and Private IP of Database EC2 Instance.

output.tf

Step-21 : Initiate the working directory with Terraform Command

The terraform initcommand is used to initialize a working directory containing Terraform configuration files. This is the first command that should be run after writing a new Terraform configuration or cloning an existing one from version control. It is safe to run this command multiple times.

terraform init

Step-22: Validate the terraform files

The terraform validate command validates the configuration files in a directory, referring only to the configuration and not accessing any remote services such as remote state, provider APIs, etc. Validate runs checks that verify whether a configuration is syntactically valid and internally consistent, regardless of any provided variables or existing state. It is thus primarily useful for general verification of reusable modules, including correctness of attribute names and value types. It is safe to run this command automatically, for example as a post-save check in a text editor or as a test step for a re-usable module in a CI system.

terraform validate

Step-23: Apply all the changes

The terraform apply command is used to apply the changes required to reach the desired state of the configuration, or the pre-determined set of actions generated by a terraform plan execution plan. The --auto-approve option helps us to skip the approval part where terraform program prompts us whether to continue or cancel the process.

terraform apply --auto-approve
It will initiate the process of creation of all the resources one by one.

After creating or modifying the changes, it will provide the output, i.e., the Public IP of WordPress EC2 Instance and Private IP of Database EC2 Instance and it will launch WordPress with the link to the Database stored in private subnet.

First page of WordPress

Selecting the language and continuing to the next page.

After installing WordPress, we have to login to WordPress.

After that we will be welcomed to the dashboard

Now we can create our own article and publish it accordingly, the data is secured and stored in Databases.

Whatever we did above can also be confirmed by going to AWS console.

🌟 VPC created on AWS 🌟

🌟 Internet Gateway created on AWS 🌟

🌟Public and Private Subnet created on AWS🌟

🌟Route Table associated with Public Subnet created on AWS🌟

🌟Elastic IP address created on AWS🌟

🌟In Public Subnet, NAT Gateway created and EIP is associated 🌟

🌟Route Table associated with Private Subnet of VPC created on AWS 🌟

🌟A Security Group for Web-App(WordPress) created on AWS 🌟

🌟A Security Group Database(MariaDB) created on AWS 🌟

🌟A Key-Pair for AWS EC2 instances created on AWS 🌟

🌟A Database EC2 instance(containing MariaDB) created on AWS 🌟

🌟A Web-App EC2 instance(containing WordPress) created on AWS 🌟

🌟Now we can SSH to WordPress EC2 Instance as “ec2-user” with the Tfkey.pem(generated) and public IP of the instance. 🌟

After that we listed all the files present in the home directory and found the key generated for Database Instance, has been successfully provided to WordPress instance. In order to use the Key we have to assign some specific permissions which is 400.

chmod 400 Tfkey.pem

🌟Now we will check “wp-config.php” to confirm whether modification regarding the Database Hostname done correctly.🌟

cat /var/www/html/wp-config.php

🌟Now we can SSH to Database EC2 Instance as “ec2-user” with the Tfkey.pem(generated) and private IP of the instance. 🌟

🌟 After getting inside the Database EC2 instance, then we will login to MariaDB with Database User-name and Password.🌟

show databases;

The command is to show the databases present in the MariaDB.

use wordpress-db;

The above command is to use “wordpress-db” database.

show tables;

The above command is used to show tables in the database.

desc wp_users;

The above command is to describe “wp_users” table.

select ID, user_logins, user_email from wp_users;

The above command is used to show ID, users login and user’s email from “wp_users”.

🎉The above result shows that we have successfully connected WordPress and Database together securely. 🎉

Step-24: Destroy the Entire Infrastructure

The terraform destroy command is used to destroy the Terraform-managed infrastructure. The --auto-approve option helps us to skip the approval part where terraform program prompts us whether to continue or cancel the process.

terraform destroy --auto-approve
First it will refresh the current state

After deletion of all the resources, it will provide a prompt saying that “Destroy Complete! ” and the number of resources destroyed.

This article is based on the task provided by Mr. Vimal Daga Sir,(World Record Holder and Sr. Principal Consultant) in Hybrid Multi Cloud Training. I really enjoyed doing this task as it involved lot of research about each and every service required to do this task and also some additional things. Thank you sir and LinuxWorld India for giving us the opportunity.

--

--

Dipaditya Das
Dipaditya Das

Written by Dipaditya Das

IN ● MLOps Engineer ● Linux Administrator ● DevOps and Cloud Architect ● Kubernetes Administrator ● AWS Community Builder ● Google Cloud Facilitator ● Author