What is iptables?
A firewall is a guard for your server. It decides which network traffic may come in and which may not. iptables is a tool on Linux that lets you write those rules.
Traffic enters through numbered doors called ports. For example, websites use port 80 and 443. SSH, the remote login, usually uses port 22.
Steps
- Log in to your server as root using SSH.
- Save your current rules as a backup:
iptables-save > /root/iptables-backup.txt
This writes all current rules into a file.
- See the current rules:
iptables -L -n -v
This lists every rule with numbers instead of names.
- Allow traffic that belongs to connections already open. This keeps your SSH session alive:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
- Allow traffic on the local loopback. This is the server talking to itself:
iptables -A INPUT -i lo -j ACCEPT
- Allow SSH so you can still log in:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
- Allow web traffic:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
- Block one bad IP address if needed. Replace the example number with the real one:
iptables -I INPUT -s 203.0.113.25 -j DROP
- Only after the allow rules are in place, drop everything else:
iptables -P INPUT DROP
This sets the default answer to "no" for anything not allowed above.
- Open a new SSH window and check you can still log in.
- Make the rules survive a reboot. On many systems you can run
service iptables save. On Debian or Ubuntu, install theiptables-persistentpackage.
If you get locked out
Use the console or rescue tool from your provider. Ask Hostvento support if you are unsure. You can open a support ticket. Then restore the backup with iptables-restore < /root/iptables-backup.txt.
Quick recap
- iptables writes firewall rules on Linux.
- Back up the rules before you start.
- Allow established traffic, SSH and web ports first.
- Set the default policy to DROP last.
- Test in a second window and save the rules.