Basic Iptables - Debian/RedHat

Want to support HowtoForge? Become a subscriber!
 
Submitted by themachine (Contact Author) (Forums) on Mon, 2005-10-17 02:21. :: Kernel

Summary

You can find an easier to read version here: 5dollarwhitebox.org

Alot of people are freaked out by IPTables and find it hard to understand. However, once you get the grasp of it the basics are easy. This document will serve as a basic how-to on using iptables. I am in no way an iptables guru, but have been using it like this for quite a while. If I've made any mistakes please don't hesitate to email me.


The System

Debian Sarge 3.1 Vanilla 2.6.12.4 kernel from mirrors.kernel.org iptables administration utility version 1.2.11-10


Preparation

This How-To is performed on a Debian Sarge 3.1 box, though the commands and syntax should work for any linux distro. Before you can configure iptables, you first must ensure that it has been compiled into the kernel, and that you have the proper userland utilities installed.


You should have a config file from when the kernel was compiled. Grep'ing it for "CONFIG_IP_NF" should produce '=y' or '=m' for most of the lines/options. Here you see that "CONFIG_IP_NF_IPTABLES" was compiled as a kernel module.

# cat /boot/config-2.4.30 | grep -i "CONFIG_IP_NF"

CONFIG_IP_NF_CONNTRACK=m
CONFIG_IP_NF_FTP=m
CONFIG_IP_NF_AMANDA=m
CONFIG_IP_NF_TFTP=m
CONFIG_IP_NF_IRC=m
CONFIG_IP_NF_QUEUE=m
CONFIG_IP_NF_IPTABLES=m
CONFIG_IP_NF_MATCH_LIMIT=m
CONFIG_IP_NF_MATCH_MAC=m
CONFIG_IP_NF_MATCH_PKTTYPE=m
CONFIG_IP_NF_MATCH_MARK=m
CONFIG_IP_NF_MATCH_MULTIPORT=m
CONFIG_IP_NF_MATCH_TOS=m
CONFIG_IP_NF_MATCH_RECENT=m
CONFIG_IP_NF_MATCH_ECN=m
CONFIG_IP_NF_MATCH_DSCP=m
CONFIG_IP_NF_MATCH_AH_ESP=m
CONFIG_IP_NF_MATCH_LENGTH=m
CONFIG_IP_NF_MATCH_TTL=m
CONFIG_IP_NF_MATCH_TCPMSS=m
CONFIG_IP_NF_MATCH_HELPER=m
CONFIG_IP_NF_MATCH_STATE=m
CONFIG_IP_NF_MATCH_CONNTRACK=m
CONFIG_IP_NF_MATCH_UNCLEAN=m
CONFIG_IP_NF_MATCH_OWNER=m
CONFIG_IP_NF_FILTER=m
CONFIG_IP_NF_TARGET_REJECT=m
CONFIG_IP_NF_TARGET_MIRROR=m
CONFIG_IP_NF_NAT=m
CONFIG_IP_NF_NAT_NEEDED=y
CONFIG_IP_NF_TARGET_MASQUERADE=m
CONFIG_IP_NF_TARGET_REDIRECT=m
CONFIG_IP_NF_NAT_AMANDA=m
CONFIG_IP_NF_NAT_SNMP_BASIC=m
CONFIG_IP_NF_NAT_IRC=m
CONFIG_IP_NF_NAT_FTP=m
CONFIG_IP_NF_NAT_TFTP=m
CONFIG_IP_NF_MANGLE=m
CONFIG_IP_NF_TARGET_TOS=m
CONFIG_IP_NF_TARGET_ECN=m
CONFIG_IP_NF_TARGET_DSCP=m
CONFIG_IP_NF_TARGET_MARK=m
CONFIG_IP_NF_TARGET_LOG=m
CONFIG_IP_NF_TARGET_ULOG=m
CONFIG_IP_NF_TARGET_TCPMSS=m
CONFIG_IP_NF_ARPTABLES=m
CONFIG_IP_NF_ARPFILTER=m
CONFIG_IP_NF_ARP_MANGLE=m
CONFIG_IP_NF_COMPAT_IPCHAINS=m
CONFIG_IP_NF_NAT_NEEDED=y
CONFIG_IP_NF_COMPAT_IPFWADM=m
CONFIG_IP_NF_NAT_NEEDED=y


This isn't all that necessary, since you'll find out real quick whether iptables works or not once we try to add some rules.


You can check whether you have the iptables administration utility installed by executing:

# dpkg -l iptables
iptables 1.2.11-10 Linux kernel 2.4+ iptables administration to


...or for rpm based distro:

# rpm -qa | grep iptablesiptables-xxxxx


...or you can just see if the binary is there!

# which iptables
/sbin/iptables



If the utility is missing you can install it like so:

APT

# apt-get update && apt-get install iptables


RPM

# rpm -Uvh iptables-xxxx.rpm
Preparing ################################# [100%]



The Main Files


Debian

  • /etc/init.d/iptables – INIT script to start|stop|restart the service (and save rulesets). This file is no longer default as of Sarge but you can still get it (I'll show you).
  • /var/lib/iptables – Debian's home for the 'active' and 'inactive' iptables-save counter files (i.e. The saved rulesets). On RedHat you would find the saved rules in '/etc/sysconfig/iptables'.
  • /var/lib/iptables/active – Active Counters (more on that later)
  • /var/lib/iptables/inactive – Inactive Counters
  • /sbin/iptables – The administration utility/binary.


RedHat

  • /etc/init.d/iptables – INIT script to start|stop|restart the service (and save rulesets).
  • /etc/sysconfig/iptables – RedHat's file for the iptables-save counter files (i.e. The saved rulesets).
  • /sbin/iptables – The administration utility/binary.


A Little About IPTables


To see what rulesets we currently have in place, execute:

# iptables --list
Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination



This is what you will see when there are no rule sets in place. Looking at this we see 3 'Chains'.


  • INPUT - Holds rules for traffic directed at this server.
  • FORWARD – Holds rules for traffic that will be forwarding on to an IP behind this server (i.e. If this box serves as a firewall for other servers).
  • OUTPUT – Holds rules for traffic that is coming from this server out to the internet.



Mainly we will be dealing with traffic directed at this server, and will be issuing rules for the INPUT Chain. When traffic passes through the kernel, it determines a “TARGET� based on whether the packet matches a rule or not. General targets are:


  • ACCEPT – Traffic is accepted for delivery.
  • REJECT – Traffic is rejected, sending a packet back to the sending host.
  • DROP - The traffic is dropped. Nothing is sent back to the sending host.



Configuring Rule Sets


So, lets get down to it. Its important to note that the order in which rules are appended is very important. For example, if your first rule is to deny everything... then no matter what you specifically allow, it will be denied.


Also to note is that nothing you do is saved on disk until you execute 'iptables-save' (or use the init script to save). All counters/rulesets are in memory. Once the server reboots, or you execute 'iptables --flush' everything you've worked on is gone. Personally I work out of a bash script file called 'iptables-rules.sh', which allows me to keep everything organized and commented. If I make a mistake, I have no worries if I just want to flush all the rules out, I just go right back to my bash script and start editing again, save it out and execute the script (this however will not run at startup... that will be covered in the next section).


Its very important that if you are working on this server remotely through ssh, that you make every effort to not lock yourself out. Therefore, our first rule will be to ensure that no matter what, I can still access ssh from my IP address.

# iptables -A INPUT -s 192.168.1.10 -d 10.1.15.1 -p tcp --dport 22 -j ACCEPT


Lets break that down:

  • -A => Tells iptables to 'append' this rule to the INPUT Chain
  • -s => Source Address. This rule only pertains to traffic coming FROM this IP. Substitute with the IP address you are SSHing from.
  • -d => Destination Address. This rule only pertains to traffic going TO this IP. Substitute with the IP of this server.
  • -p => Protocol. Specifying traffic which is TCP.
  • --dport => Destination Port. Specifying traffic which is for TCP Port 22 (SSH)
  • -j => Jump. If everything in this rule matches then 'jump' to ACCEPT


Next, we will want to use some standard rules for general network traffic. This goes a bit beyond the basic stuff, however iptables can determine the 'state' that a packet is in. This has to do with standard TCP communication. For example, the 3 way handshake between two hosts when transmitting data.


  • NEW => Server1 connects to Server2 issuing a SYN (Synchronize) packet.
  • RELATED => Server 2 receives the SYN packet, and then responds with a SYN-ACK (Synchronize Acknowledgment) packet.
  • ESTABLISHED => Server 1 receives the SYN-ACK packet and then responds with the final ACK (Acknowledgment) packet.



After this 3 way handshake is complete, the traffic is now ESTABLISHED. In order for this type of TCP communication, something similar to these three rules are necessary:

# iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
# iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

The last rule obviously allows any traffic the leave the server.



Now that we have our basics set in place, lets see what iptables lists for our rulesets:

# iptables --list
Chain INPUT (policy ACCEPT)
target prot opt source destination

ACCEPT tcp -- 192.168.1.10 10.1.15.1 tcp dpt:ssh
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere state NEW,RELATED,ESTABLISHED



From here you can add whatever rules you like. If your running a basic webserver, you'll probably need something similar to:


INIVIDUAL REJECTS FIRST:


-----------------------------------------------------------------------

BAD GUYS (Block Source IP Address):
# iptables -A INPUT -s 172.34.5.8 -j DROP

NO SPAMMERS (notice the use of FQDN):
# iptables -A INPUT -s mail.spammer.org -d 10.1.15.1 -p tcp --dport 25 -j REJECT

-----------------------------------------------------------------------


THEN OPEN IT UP:-----------------------------------------------------------------------

MYSQL (Allow Remote Access To Particular IP):
# iptables -A INPUT -s 172.50.3.45 -d 10.1.15.1 -p tcp --dport 3306 -j ACCEPT

SSH:
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 22 -j ACCEPT

Sendmail/Postfix:
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 25 -j ACCEPT

FTP: (Notice how you can specify a range of ports 20-21)
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 20:21 -j ACCEPT

Passive FTP Ports Maybe: (Again, specifying ports 50000 through 50050 in one rule)
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 50000:50050 -j ACCEPT

HTTP/Apache
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 80 -j ACCEPT

SSL/Apache
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 443 -j ACCEPT

IMAP
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 143 -j ACCEPT

IMAPS
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 993 -j ACCEPT

POP3
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 110 -j ACCEPT

POP3S
# iptables -A INPUT -d 10.1.15.1 -p tcp --dport 995 -j ACCEPT

Any Traffic From Localhost:
# iptables -A INPUT -d 10.1.15.1 -s 127.0.0.1 -j ACCEPT

ICMP/Ping:
# iptables -A INPUT -d 10.1.15.1 -p icmp -j ACCEPT-----------------------------------------------------------------------



GLOBAL REJECTS LAST:

-----------------------------------------------------------------------

Reject everything else to that IP:

# iptables -A INPUT -d 10.1.15.1 -j REJECT

Or, reject everything else coming through to any IP:
# iptables -A INPUT -j REJECT
# iptables -A FORWARD -j REJECT
-----------------------------------------------------------------------

Notice the we do the global REJECT lines last! These must be last.


Saving Rule Sets


With the init scripts, saving rule sets is quite easy. Once you are happy with your config, just do one of the following:


The Debian Way

The old style init script is no longer in Sarge by default, but it is still around for legacy use. I believe the new way is to use ' /etc/network/if-up.d' and '/etc/network/if-down.d' for iptables scripts (but I don't like that).


You can grab the legacy INIT script this way:

# gunzip /usr/share/doc/iptables/examples/oldinitdscript.gz -c > /etc/init.d/iptables
# chmod +x /etc/init.d/iptables
# mkdir /var/lib/iptables
# chmod 700 /var/lib/iptables

Now that you have the script in place you can do the needful.


Active Rules

The Active rules are those loaded when starting iptables:

# /etc/init.d/iptables save active
Saving iptables ruleset: save "active" with counters.

This saves your rules in /var/lib/iptables/active


Inactive Rules

You can also configure a second set of rules for when you stop iptables called 'inactive'. Iptables doesn't actually “stop�, it just flushes out the rule sets that are in place and then loads the 'inactive' rules.

# /etc/init.d/iptables stop
Loading iptables ruleset: load "inactive"


Therefore, you can set your 'inactive' rules, and then save them with:

# /etc/init.d/iptables save inactive
Saving iptables ruleset: save "inactive" with counters.


The RedHat Way

The RedHat INIT script is very similar. You can use it to start and stop iptables, as well as save rule sets.


To save your active rules execute the following:

# /etc/init.d/iptables save

This will save your rules to '/etc/sysconfig/iptables'.


When you start iptables, the rules are read from '/etc/sysconfig/iptables':

# /etc/init.d/iptables start
Starting iptables [OK]


And when you stop iptables, all rules are flushed:

# /etc/init.d/iptables stop
Stopping iptables [OK]



Manual Save and Restore

You can also manually use the iptables-save and iptables-restore utilities like so:


Save the rules to a files

# iptables-save > /root/iptables-save.out


Restore the rules

# iptables-restore -c /root/iptables-save.out

The -c tells iptables-restore that this is file was created using iptables-save, which outputs the rules as “counters�.



Conclusion

And there you go, iptables at its very basic. The uses of iptables are too numerous to even start truly doing a howto on them. However, for basic security and understanding of IPTables, I hope this might have helped you. If there is anything I could add, please feel free to email me.



---
BJ Dierkes, RHCE4-LPIC1
wdierkes [at] 5dollarwhitebox [dot] org
Texas, USA


Resources


Please do not use the comment function to ask for help! If you need help, please use our forum.
Comments will be published after administrator approval.
Submitted by Anonymous (not registered) on Fri, 2006-07-07 17:02.

Remember that automated tools like Fail2Ban and PortSentry leave you open to denial of service attacks. If someone were spoof the address of an SSH client you regularly connect from, you could be locked out of your server. While it's not easy to spoof enough of an SSH connection to trigger Fail2Ban, it is possible.

Another senario is where you SSH to your home server from behind a corporate NAT router.  Anyone else on you your corporate network could lock you out by simply trying to log in a few times.

I'm not trying to talk anyone out of using Fail2Ban (I use it!), but I think it's important to know the implications of doing so.

Rich B.

 

Submitted by Anonymous (not registered) on Sun, 2006-02-26 21:05.

Just wanted to thankyou for something very rare in the linux world: An easy to understand howto, covering the basics!

Everywhere else, you find badly written solutions to extremely uncommon problems.

Thanks!
&flix

Submitted by Prog (not registered) on Sat, 2010-07-31 01:41.

I second that!

Too many Linux tutorials (and softwares for that matter) fall victim to Pareto inefficiency (80% of features and documentation for 20% of people) and try to be everything to everyone and end up being overkill for the majority of people.

Kudos on providing concise information that will meet most peoples needs.

Submitted by Anonymous (not registered) on Wed, 2006-06-21 19:51.

The following page is also pretty good:

http://www.siliconvalleyccie.com/linux-hn/iptables-intro.htm

It outlines how the mangle and nat chains work, which is obviously less useful for most people, but anyway.

Submitted by Anonymous (not registered) on Sat, 2006-01-21 11:59.

http://www.fwbuilder.org/

It creates fw scripts for that can be automatically deployed to all of yer fw´s using ssh. Best thing is that it´s gui is simular to checkpoints interface, all for free (using linux!) Creating fw setups using windows is gonna cost 49,95 dollars. hahahahah

Thanks for the howto! always nice to see the inner workings!

Submitted by Anonymous (not registered) on Tue, 2005-11-22 17:29.
Thanks so much for your article here. Every document I ever tried to read about iptables before was like a freaking Chinese Instruction Manual! I never realized it could be so easy. Thanks a million.
Submitted by IaMMai (registered user) on Fri, 2005-12-02 10:45.


Wow... and here I thought I might be wasting my time.... ;)

Submitted by Anonymous (not registered) on Thu, 2005-11-03 07:40.
Hi, you seem to have missed that the init skript is not part of iptables in Sarge anymore: iptables (1.2.7-8) unstable; urgency=low * removed init.d, /var/lib/iptables, and debconf-ization If you still have that file it is probably a relic of older iptables versions from which you upgraded. Because init scripts are treated like configuration files, they are not automatically removed when you remove or upgrade the package. If you want to initialize iptables, you need your own skript, or you can run iptables when the interfaces come up (see /etc/network/interfaces and /etc/network/if-ip.d).
Submitted by IaMMai (registered user) on Thu, 2005-11-03 14:54.

You are correct... this system was upgraded from woody... which I've had running over a year before Sarge was stable.... I shall update this howto as "Pre-Sarge"... and when I get a second do a Sarge install from scratch and update as necessary.

Thanks for the note.

---
BJ Dierkes, RHCE4 - LPIC1
wdierkes [at] machinehost [dot] org
Texas, USA

Submitted by Anonymous (not registered) on Fri, 2005-10-28 02:30.

I added a nice init script that does the work for me, all I have to do is to edit the file from time to time according to my needs.

Here is the script: (/etc/init.d/iptables)

====== CUT BELOW HERE ======

#!/bin/bash
#
if [ ! -x /sbin/iptables ]; then
exit 0
fi

start()
{
# clear all
clearall

# Create new chain (I called it filter) which blocks new
# connections, except if coming from inside.
iptables -N filter
iptables -A filter -m state --state ESTABLISHED,RELATED -j ACCEPT
# The next rule depends on what connection to the NET you have
# It could be ppp0 instead of eth0, suit your own needs
iptables -A filter -m state --state NEW -i ! eth0 -j ACCEPT

# Allowed Services - Here you can put all the actually needed
# ports, a few common examples below:
iptables -A filter -p tcp --dport http -j ACCEPT
iptables -A filter -p tcp --dport ftp -j ACCEPT
iptables -A filter -p tcp --dport smtp -j ACCEPT
iptables -A filter -p tcp --dport pop3 -j ACCEPT
iptables -A filter -p udp --dport 53 -j ACCEPT
# Allowed IPs/Networks
iptables -A filter -p all -s 192.168.0.0/24 -j ACCEPT
iptables -A filter -p all -s 192.168.1.15 -j ACCEPT
# Blacklisted IPs/Networks
iptables -A filter -p all -s 192.168.100.0/24 -j DROP
iptables -A filter -p all -s 10.0.0.32 -j DROP
# drop tcp priv'd ports
iptables -A filter -p tcp --dport 0:1023 -j DROP
# drop udp priv'd ports
iptables -A filter -p udp --dport 0:1023 -j DROP
iptables -A filter -j DROP

# Jump to that chain from INPUT and FORWARD chains.
iptables -A INPUT -j filter
iptables -A FORWARD -j filter


}

clearall()
{
iptables -F
iptables -X
}


case "$1" in
restart|start)
start
;;
stop)
clearall
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac

exit 0

===== END CUT =====

After saving this script as /etc/init.d/iptables , don't forget to chmod it

chmod 755 /etc/init.d/iptables

Now you need to add it to the default runlevels, make this command:

update-rc.d iptables defaults 12

Have fun!

Ziv

Submitted by Anonymous (not registered) on Thu, 2005-10-20 04:23.
In year 2005, writing hand-crafted iptables rules makes about as much sense as using assembly language to produce dynamic webpages. Sure, you can do it and it offers the best possible performance, but does it make sense?

There are dozens of tools that makes it easy to manage iptables. Among those, 2 open source projects stand out far above the rest:

1. Shorewall - http://www.shorewall.net/
2. FireHOL - http://firehol.sourceforge.net/

It is very easy to make mistakes with hand-crafted iptables rules that is hard to detect. You can end up with numerous security holes without even being aware of their existence until someone exploits them.

Seriously consider using one of the above tools, you'll find that they provide all the flexibility you need for managing iptables without having to hand-craft rules using iptables syntax.

I started using shorewall to manage my iptables and I've never looked back. And this includes gateways with multiple ethernet cards, public servers, and secure desktops.

Try any 3 iptables-related projects--the 2 mentioned above and 1 other of your choice. Pick one and you'll end up far better than directly writing iptables rules.

Submitted by Anonymous (not registered) on Tue, 2005-11-15 00:00.

I have to disagree with you. You're making some assumptions that might not be correct.

You say that people would use iptables rules because they offer "the best possible performance"; or alternatively people would use a tool because that "makes it easy to manage iptables". Neither is necessarily true.

I use a custom iptables script because that makes firewalling *easier* for me. No, it's not so easy to learn the syntax of iptables for a beginner; but once you learn, having a firewall script lets you see and (more importantly) proofread all your rules in one file.

If you know anything at all about security, you know that policy is paramount. That's why a firewall script is ideal: you can have the rules, accompanied by comments that describe your policy.

Having a script also makes your firewall easier to distribute. You can copy it to other hosts & modify to suit. You can send or show it to someone who knows more about security than you do, for them to proofread and find holes.

Using a GUI tool just gets in the way. You have to trust that what you *think* you're specifying in the GUI actually gets implemented in the way you intended. And how do you check? By using "iptables -L -v" of course; but now you're back to using iptables anyway!

If you understand firewalling, then iptables is just a tool and it shouldn't be too hard to understand. If not, then is a GUI really going to save you? You'd be better off downloading a boilerplate iptables script that's well-documented, from a reputable source. Or getting a friend who understands firewalling to help you.

the_dave at fastmail dot fm

Submitted by Anonymous (not registered) on Fri, 2005-12-16 14:14.
I agree about using a gui, but shorewall is just a set of scripts that uses txt config files. Easy, efficient and double checked by many people that know.
Submitted by Anonymous (not registered) on Mon, 2005-10-17 12:13.

Sarge not exist the iptables exist in /etc/init.d/

for default iptables is installed...but not have a script in these location


Submitted by Anonymous (not registered) on Thu, 2005-11-03 22:54.

You can find a copy of the script in Sarge at /usr/share/doc/iptables/examples/oldinitdscript.gz

Just gunzip it into /etc/init.d/ as super user

gunzip -c -d /usr/share/doc/iptables/examples/oldinitdscript.gz > /etc/init.d/iptables

and chmod 755 /etc/init.d/iptables

Submitted by Anonymous (not registered) on Thu, 2005-11-17 13:57.
mkdir /var/lib/iptables
chmod 700 /var/lib/iptables
cd /var/lib/iptables/
touch active inactive
Submitted by Anonymous (not registered) on Tue, 2005-10-25 16:23.
SEE: zcat /usr/share/doc/iptables/README.Debian.gz |less

METHOD:
... in /etc/network/interfaces
...run the a packet filtering script (with the interface name and address as arguments) before actually bringing up the interface.

auto eth0
iface eth0 inet dhcp
pre-up /etc/myfirewall.sh $IFACE $IF_ADDRESS