logo

CodeHiRise

setup and configure iptables in Ubuntu

2ish minutes read

cloudlinuxnetworking
setup and configure iptables in Ubuntu cover

Hi everyone,

while you are working on Linux systems, you might have come across firewalls. but what is a firewall anyway?

Firewall is a computer program that monitors and controls the incoming and outgoing network traffic based on predetermined security rules. A firewall typically establishes a barrier between a trusted network and an untrusted network, such as the Internet.

Iptables is one such popular and powerful tool in the Linux operating system, designed to enable users to configure, maintain, and examine the tables of IP packet filter rules within the Linux kernel.

By configuring iptables we can allow or deny network traffic based on a set of configurable rules like

  • source ip
  • destination port
  • network interface

so without further ado let's dig in.

for this post, I have already created an instance in AWS with ubuntu os.

I provisioned an ec2 instance with ubuntu latest image which has iptables pre-installed

iptables version

we can use iptables -L to list all rules setup

list rules

for this example, I will install nginx webserver and then add http (port 80) block rule for demonstration.

for that, I installed nginx using the below commands

sudo apt update
sudo apt install nginx
Nginx status

after the above step, we can see nginx default page when we visit the instance public ip

Nginx default page

now let's add an iptables firewall rule to block all incoming http (port 80) connections.

sudo iptables -A INPUT -p tcp --dport 80 -j DROP

above command will DROP all incoming requests to port 80.

iptables block list

now if we try to access nginx it will not load.

Nginx blocked

now to unblock port 80 we can remove the previously added rule.

for that first, we need to list all rules with line numbers

sudo iptables -L --line-numbers

iptables list with line numbers

then run sudo iptables -D INPUT 1 which indicates that remove rule 1 in input rules which corresponds to what we created earlier.

after removing iptables block rule we can access nginx default webpage.

iptables rules are ephemeral, they will not persist after a reboot. we need to use iptables-persistent package to make rules persist.

install iptables-persistent
install iptables-persistent
run iptables-persistent

And there you have it.

Thank you for reading.

Share if you loved it

CodeHiRise

All rights reserved 2023