Knowledgebase
Debian/Ubuntu IPTables Firewall Configuration
Posted by zz-James Moir on 21 June 2016 04:08 PM

Issue

The firewall does not automatically load when the server starts.

Cause

Debian/Ubuntu servers do not have any default IPTables configuration files or /etc/init.d scripts.

Solution

Create /etc/iptables.up.rules. Example below to allow SSH (22), SMTP (25), HTTP (80), HTTPS (443), POP3 (110) and MySQL (3306)

First create your /etc/iptables.up.rules file by running this command:

iptables-save > /etc/iptables.up.rules

Then edit that file and use the example content below to create your rules.

*filter

# Drop any traffic not explicitly allowed in the rules below.
:INPUT DROP
:FORWARD DROP
:OUTPUT DROP

# Accept inbound traffic for already established connections.
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# Allow connection to the services running on this server.
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 110 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT

# Effectively allow all outbound traffic.
-A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

COMMIT

## If the firewall needs to be disabled, run the following command:
##
## iptables-save | sed "/-/d;/^#/d;s/DROP/ACCEPT/" | iptables-restore


Create /etc/network/if-pre-up.d/iptables with the following content:.

#!/bin/bash

/sbin/iptables-restore < /etc/iptables.up.rules


Make /etc/network/if-pre-up.d/iptables executable.

chmod +x /etc/network/if-pre-up.d/iptables