Introduction to iptables
iptables is a user-space utility program that allows a system administrator to configure the IP packet filter rules of the Linux kernel firewall, implemented as different Netfilter modules. The filters are organized in different tables, which contain chains of rules for how to treat network traffic packets. Wikipedia provides a good overview of iptables.
Installing iptables
Before we start configuring iptables, we need to ensure that it’s installed on our Linux system. Most Linux distributions come with iptables pre-installed. If not, you can install it using the package manager of your Linux distribution.
On Ubuntu/Debian:
sudo apt-get update
sudo apt-get install iptables
On CentOS/RHEL:
sudo yum install iptables-services
Understanding iptables Tables and Chains
iptables operates on a set of tables. Each table contains a number of built-in chains and may also contain user-defined chains.
Table | Description |
---|---|
Filter | This is the default table (if no -t option is passed). It contains the built-in chains INPUT (for packets destined to local sockets), FORWARD (for packets being routed through the box), and OUTPUT (for locally-generated packets). |
NAT | This table is consulted when a packet that creates a new connection is encountered. It consists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out). |
Mangle | This table is used for specialized packet alteration. Until kernel 2.4.17 it had two built-in chains: PREROUTING (for altering incoming packets before routing) and OUTPUT (for altering locally-generated packets before routing). |
Configuring iptables Rules
Now that we have a basic understanding of iptables, let’s move on to configuring some basic rules. Remember, configuring iptables requires root privileges, so make sure to use ‘sudo’ before each command if you’re not logged in as the root user.
Allowing Established Sessions
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Allowing Incoming SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Saving iptables Rules
By default, rules added to iptables are volatile and lost after a system reboot. To save them permanently, you can use the iptables-persistent package on Debian-based systems or the service iptables save command on RedHat-based systems.
On Ubuntu/Debian:
sudo apt-get install iptables-persistent
sudo netfilter-persistent save
On CentOS/RHEL:
sudo service iptables save
Conclusion
This guide has provided a basic introduction to iptables and how to configure it on a Linux system. Remember, iptables is a powerful tool, and with great power comes great responsibility. Always ensure you understand a rule before adding it to your firewall configuration. For more detailed information, check out the Netfilter Documentation.