Simple iptables firewall script with NAT and SFQ sceduling

I have been working with firewalls and security for quite many years at this point. Therefore friends and people I know ask me every now and then to write a firewall script for them. So instead of basically writing the same script over and over again I decided to write this article that explains how you can set up a basic iptables box by yourself.

If you do not know what iptables is the best way to start is to do some reading:

Wikipedia about iptables
Home of iptables/netfilter

In its most basic form iptables has three (3) built in tables. These tables are INPUT, OUTPUT and FORWARD

INPUT: Packets that are destined to a interface and/or address of your host
OUTPUT: Packets that origin from a interface and/or address of your host
FORWARD: Packets that pass through your hosts interfaces and/or addresses

To set up a linux router/firewall/NAT box you need a computer with at least two network interfaces. One interface for the internal network and one for the external network (usually the internet). You also need to install linux on that computer 😉

There are many networking features besides firewall and NAT in Linux. There are things like TC. With the tc command your can configure the packet queuing mechanism of your network interfaces. The default mechanism is FIFO which stands for FirstInFirstOut.  I recommend that you change the queuing mechanism of your external network interface from FIFO to SFQ.

Stochastic Fairness Queueing reorders  queued  traffic  so  each ’session’ gets to send a packet in turn.

You can enable SFQ by entering the following into a terminal as root: tc qdisc add dev <your external NIC here> root sfq perturb 10

You can put the example above into your /etc/rc.local or some other start up file in order for it to be run at each boot.

Now you just need a small shell script which configures iptables for you. It is a good idea to execute this script on boot via the init procedure of your Linux distribution.

I hope that the script is somewhat self explaining. If you have questions about it please feel free to comment this post.

Leave a Reply

Your email address will not be published.