Create and install a firewall on Debian or Ubuntu Linux

A firewall is a program that secures a server by filtering the network accesses made from and to the outside. An effective way to create a firewall is to restrict access to the ports used by the server’s applications.

This post describes how to create and install a firewall on Debian or Ubuntu Linux using iptables.


  • Login as root.

Create a firewall

In order not to lose the SSH connection to the server, verify that the port specified in the file /etc/ssh/sshd_config is the same port used in the firewall.

nano /root/firewall.v4


# Tables initializing
iptables -F
iptables -X
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# Local connections accepting
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# ICMP protocol accepting
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT

# DNS queries accepting on port 53
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

# NTP protocol accepting on port 123
iptables -A OUTPUT -p udp --dport 123 -j ACCEPT

# SSH protocol accepting on port 22
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT

# HTTP protocol accepting on port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT

# HTTPS protocol accepting on port 443
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT

# SMTP protocol accepting on port 25
iptables -A OUTPUT -p tcp --dport 25 -j ACCEPT

chmod 744 /root/firewall.v4

The command /root/firewall.v4 activates the firewall. See the following paragraphs to load the firewall at server startup.

The IPv6 firewall is created using the file /root/firewall.v6 instead of /root/firewall.v4, the command ip6tables instead of iptables and the protocol icmpv6 instead of icmp.

Load the firewall at server startup

apt-get install iptables-persistent
iptables-save > /etc/iptables/rules.v4

The firewall now loads automatically at server startup.

The IPv6 firewall loads at server startup using the file /root/firewall.v6 instead of /root/firewall.v4, the command ip6tables-save instead of iptables-save and the file /etc/iptables/rules.v6 instead of /etc/iptables/rules.v4.

» Backup a server on Debian or Ubuntu Linux

Leave a Reply

Your email address will not be published. Required fields are marked *