Iptables Firewall Recommended Configuration on Ubuntu Linux

Iptables is a firewall utility that uses policy chains to allow or block traffic.  It can configure IPv4 tables, chains or rules provided by the Linux kernel firewall.

Some key things to consider:

1. Installation:

apt install iptables
apt install iptables-persistent

2. Verify if iptables is enabled and see the firewall rules:

iptables -L -n -v

3. Flush iptables rules

iptables -F

4. When working remotely, it is recommended to allow incoming SSH or port 22 connections

iptables -A INPUT -p tcp –dport 22 -m state –state NEW -j ACCEPT

5. Take note that there’s a chance of conflict if running both iptables,ufw and nftables, so it is recommended to remove it.

apt purge nftables

apt purge ufw

ufw disable

6. Loopback interface is allowed to accept traffic. Other interfaces should be configured to deny traffic to the loopback network:

IPv4: 127.0.0.0/8

Apply the rules:

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -s 127.0.0.0/8 -j DROP

7. Outbound connections are allowed for all interfaces. Configure also to allow established connections.

iptables -A OUTPUT -p tcp -m state –state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p udp -m state –state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p icmp -m state –state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -m state –state ESTABLISHED -j ACCEPT
iptables -A INPUT -p udp -m state –state ESTABLISHED -j ACCEPT
iptables -A INPUT -p icmp -m state –state ESTABLISHED -j ACCEPT

8. Allow only open ports that are needed

There are few ways to verify open or listening ports, e.g. using “ss” command

Sample Output:

root@freelinux:~# ss -4tuln
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 *:5355 *:*
udp UNCONN 0 0 127.0.0.53%lo:53 *:*
udp UNCONN 0 0 10.0.2.15%enp0s3:68 *:*
tcp LISTEN 0 80 127.0.0.1:3306 *:*
tcp LISTEN 0 128 *:5355 *:*
tcp LISTEN 0 128 *:22 *:*

Syntax to allow open ports:

iptables -A INPUT -p <protocol> –dport <port> -m state –state NEW -j ACCEPT

9. Default deny should be configured

The concept is to allow ports or hosts then last rule is to default deny to drop all the traffic.

iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

About the author

Free Linux

View all posts

Leave a Reply