Quick Guide to iptables

Introduction

This is a quick guide on how to install and use the Netfilter/iptables firewall on Linux. Netfilter/iptables is the successor to ipfwadm (Linux 2.0) and ipchains (2.2).

Install

Before running the user-land "iptables" binary, you must first make sure the Linux kernel includes Netfilter and any extension you need (eg. the "string" module.)

After rebooting with the new kernel, run "dmesg | grep ip_" to check that Netfilter/iptables is included.

Configuration

Configuring iptables means writing rules that belong to a given chain. Chains themselves belong to a given table. iptables offers four default tables: Filter (which contains chains Input, Output, and Forward), NAT (PREROUTING, POSTROUTING, OUTPUT), Mangle (PREROUTING, OUTPUT, FORWARD, INPUT, POSTROUTING), and Raw (PREROUTING, OUTPUT).

In the Filter table, the Input chain is used to handle packets destined for the local system, the Output chain is used to handle packets created by the local system, and the Forward chain is used for packets passing through the system (ie. when the host has two more network interfaces and the host is used as a router).

The NAT table is used to rewrite packets, and has three chains: PREROUTING (where packets are handled prior to the routing table), POSTROUTING (where packets are sent after going through the routing table), and OUTPUT.

The standard way to add a rule to chain MYCHAIN: iptables -A MYCHAIN [options] -j ACTION

There are two ways to add a rule to a chain: -A (Append) adds it at the end, while -I (Insert) adds it at a specific location in the chain.

An empty configuration means that all connections are allowed.

"iptables -L" lists the "filter" table. If you want to see the contents of another table, use the "-t mytable" option, eg. "iptables -t nat -L".

You can save the current iptables configuration into a file by using "iptables-save > file", and read it back through "iptables-restore < file". The location of that command is system-dependant, so you'll have to check (eg. /etc/rc.local).

To flush iptables entirely, use "iptables -F".

Protecting Asterisk

After opening your Asterisk server to the Net so that remote users can register and anyone can call an extension, it won't take long before someone tries to hack and register in order to make calls to the PSTN for free.

Although some external applications exist to watch logs and reconfigure iptables on the fly to block non-legitimate connections (SSHGuard, Bash shell script BruteForceDetection, Python application Fail2Ban, etc.), iptables itself supports some form of protection.

Here's how to stop connections from a range of IP's (requires compiling iptables with the "iprange" module):

iptables -F
iptables -A INPUT -m iprange --src-range 1.2.3.4-5.6.7.8 -j DROP
iptables-save > iptables.conf

Resources