An iptables cheat-sheet

The Linux kernel provides an advanced framework for various network-related operations through the use of the Netfilter module. Netfilter allows various forms of packet filtering and address translation on your network stack. By using the iptables utility, you can customize the behaviour of netfilter to do various tasks and improve security. Here, I will show a brief set of common commands one may want to use when administrating a Linux host.

Delete (Flush) existing rules

Let's start by clearing out all pre-existing rules in the firewall. You can use the "Flush" command to do this.

iptables -F

Set the default chain policies

Now that the firewall is empty, we can initialize the default policies. Any traffic that does not match a rule in the firewall will fallback on the default policy (in this case, we will block all traffic by default).

Show status of your firewall

Now we can get a quick look at the firewall so far, what the policies are set to, and any rules which might exist.

iptables -L -n -v --line-numbers

Block an IP address

We can block individual IPs using a simple command.

iptables -A INPUT -s 1.2.3.4 -j DROP

Similarly, you could have specified a subnet to block as well (.e.g., 10.0.0.0/8)

Block access to remote site

If we wanted to block access from the inside of the network from being able to reach a remote resource, we can also do so easily. Feel free to use IPs, subnets, or even domain names (they will be automatically resolved).

Allow all incoming SSH tunnels to eth0

In addition to setting the type of connection and ports to be used in a rule, you can specify which interface adapter is allowed as well. In this case, we will allow new SSH connections to be stablished from the outside, but only over eth0.