ლ(ಠ益ಠლ)

Server Hardening With Iptables, Part One

Shifting the SSH listening port to non-22 and enabling fail2ban filters are solid steps toward hardening your server environment. Let’s take it a step further and leverage the power of the iptables firewall.

The following is a basic configuration for web, email, and SSH traffic.

Allow already established connections on all available interfaces, in this case eth0 and eth1:

1
2
$ sudo iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
$ sudo iptables -A INPUT -i eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT

Allow TCP connection attempts for SSH, replace with the listening port you have configured:

1
$ sudo iptables -I INPUT 1 -p tcp  --dport <PORT> -j ACCEPT

Allow HTTP and HTTPS:

1
2
$ sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
$ sudo iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT

Allow SMTP and IMAP, ports 25 and 993 respectively:

1
2
$ sudo iptables -I INPUT 1 -p tcp --dport 25 -j ACCEPT
$ sudo iptables -I INPUT 1 -p tcp --dport 993 -j ACCEPT

Change the default policy for the INPUT chain to DROP all, i.e. drop all connections and only allowed traffic for the policies that match the above. *Only implement this once you have confirmed you can maintain access to the server over SSH:

1
$ sudo iptables -P INPUT DROP

Save your new ruleset, for Debian:

1
$ iptables-save > /etc/iptables.rules

Your configuration should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [132:54176]
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 993 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22222 -j ACCEPT
COMMIT

Edit: Feb 3, 2014

I’ve posted part two of this ever-evolving series of security-related posts–whitelisting ICMP traffic.

Comments