Ubuntu 12.04‎ > ‎

Iptables in Ubuntu 12.04

By default, Ubuntu only opens ports for services that are running on a server. You can manage which ports are available on each network interface using iptables. Iptables rules are implemented from top to bottom and should thus be added accordingly.

Here are some commands to start a basic iptables firewall:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p icmp -j ACCEPT
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -d 127.0.0.0/8 ! -i lo -j DROP
sudo iptables -A INPUT -i eth0 -j DROP
Without going into detail, each command appends (-A) a new rule-specification to the iptables INPUT chain.

By default, the iptables rules are flushed after each restart. To make the iptables rules persist, you must export the rules into a file which will be reloaded during boot time. To export the rules:
sudo iptables-save > /etc/iptables.rules
This creates a file called iptables.rules that contains all the rules that are currently being applied by iptables. To apply the saved rules after a restart:
sudo iptables-restore < /etc/iptables.rules

To automatically apply the firewall rules during boot, create an exectutable script in the /etc/network/if-pre-up.d/ folder that contains the following text:
#!/bin/bash
iptables -F
iptables-restore < /etc/iptables.rules
exit 0