Simple stateful firewall
Source: archlinux.org
This page explains how to set up a stateful firewall using iptables. It also explains what the rules mean and why they are needed. For simplicity, it is split into two major sections. The first section deals with a firewall for a single machine, the second sets up a NAT gateway in addition to the firewall from the first section.
Warning: The rules are given in the order that they are executed. If you are logged into a remote machine, you may be locked out of the machine while setting up the rules. You should only follow the steps below while you are logged in locally.The example config file can be used to get around this problem.
Prerequisites
First, install the userland utilities iptables or verify that they are already installed.
This article assumes that there are currently no iptables rules set. To check the current ruleset and verify that there are currently no rules run the following:
# iptables-save # Generated by iptables-save v1.4.19.1 on Thu Aug 1 19:28:53 2013 *filter :INPUT ACCEPT [50:3763] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [30:3472] COMMIT # Completed on Thu Aug 1 19:28:53 2013
or
# iptables -nvL --line-numbers Chain INPUT (policy ACCEPT 156 packets, 12541 bytes) num pkts bytes target prot opt in out source destination Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 82 packets, 8672 bytes) num pkts bytes target prot opt in out source destination
If there are rules, you may be able to reset the rules by loading a default rule set:
# iptables-restore < /etc/iptables/empty.rules
Otherwise, see Iptables#Resetting rules.