After tightening up the Apache, WordPress and Mediawiki security it’s time to implement a firewall on the webserver. I’m using the famous ‘iptables’. There are a lot of sites that explain how to write rules for iptables.

I’ve read:

The most important thing to remember is that iptables reads the configuration top-down. This means that the first firewall rule shouldn’t be “block everything” because you will lock yourself out. If you want to write iptables rules but don’t know how there’s also a program called FWbuilder. With that program it’s easy to click a rule together and export it to iptables format. On the console there is a program called ipmenu that shows a GUI for writing iptables.

Some examples from the above read articles:

SSH

## open port SSH tcp port 22 ##
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
## max. 3 SSH connections per client host ##
iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT

Apache

## open http/https (Apache) server port to all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT

E-mail

## open tcp port 25 (smtp) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
## open tcp port 143 (imap) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
## open tcp port 587 (smtp) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 587 -j ACCEPT
## open tcp port 993 (imaps) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 993 -j ACCEPT

And the last rules

# Reject all other inbound - default deny unless explicitly allowed policy:
iptables -A INPUT -j REJECT
iptables -A FORWARD -j REJECT

Off course you don’t want to add the rules again after a restart of the machine so saving the rules and automatically loading them during start-up of the machine will make sure that the firewall is always active with the created rules. For Debian it’s easy to make sure that iptables starts during start-up.

The rules they can be saved to a file with the command:

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

To make sure the iptables rules are started on a reboot create a new file:

editor /etc/network/if-pre-up.d/iptables

Add these lines to it:

#!/bin/sh
/sbin/iptables-restore < /etc/iptables.up.rules

The file needs to be executable so change the permissions:

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

 

Learned today

  • When writing rules for iptables don’t forget to write a rule for already established connections before blocking everything, otherwise you will lock yourself out.
  • Put the block everything that isn’t allowed iptables rule as last rule and make sure you have another way of accessing your machine (physical or virtual screen) if anything goes wrong.

 

Music video of the day

Share This