Bienvenido! - Willkommen! - Welcome!

Bitácora Técnica de Tux&Cía., Santa Cruz de la Sierra, BO
Bitácora Central: Tux&Cía.
Bitácora de Información Avanzada: Tux&Cía.-Información
May the source be with you!

Saturday, July 3, 2010

IPtables primer

image unavailable
Table of Contents
NoteThe above "IPTabels Flow chart" is used with permission. It was originally published here and is licensed under the GNU FDL.


"Do I need a firewall?" is a FAQ on the Ubuntu Forums. In order to answer that question we need to understand what you want to do accomplish by using (configuring) a firewall. The purpose of this post is to introduce iptables and encourage appropriate use.
The Linux firewall is called iptables. Iptables is very powerful and features include :
  1. Filtering - (blocking unwanted traffic). You can filter incoming and outgoing traffic by user, group, time/date, or service (application).
  2. NAT (Routing). If your computer has two or more network cards (or if you are using virtualization) you can use a spare computer as a router, one network card connected to the Internet and the other to your LAN with iptables monitoring and filtering traffic.
  3. Logging (monitoring) network traffic.
  4. Block brute force or DOS attacks.
Comparison of firewalls : Wikipedia - Comparison of firewalls
Your firewall, iptables, is configured either from the command line (usually with a script) or a configuration tool (UFW, GUFW, Firestarter, guard dog, Shorewall, etc). Unfortunately many of the graphical configuration tools do not offer all the available options, let alone explain the options (Guard dog is an exception to this generalization).
Configuring iptables requires at least a basic understanding of network protocols and is further complicated by a steep learning curve in that one must know a little about networking protocols, servers, and ports to grasp iptables.
Despite the intimidation, once you learn the basics, working with iptables is actually enjoyable (not to mention at least a few geek points). In fact, I find it is often easier to configure iptables then learn the quirks of a GUI tool.
If you simply wish to maintain a blacklist you can look at tools such as denyhosts and fail2ban. There is also a GUI tool "iplist".
The advantage of learning iptables, if you so desire, is that although the learning curve is steep, you can block brute force and DOS attacks with a few simple commands rather then installing, configuring, and maintaining the above packages.

Anatomy of iptables

Iptables is nothing more then a set of rules for processing network packets coming and going to and from your computer (firewall). These rules are organized into tables and chains. A packets fate is determined by following the rules, one at a time, like links in a chain.

Default Tables : tables are named in small letters

    filter - This is what we normally think of as the "Firewall", in that it filters packets.
    nat - Network Allocation Table : Think router or forwarding packets to other machines.
    mangle - Not used by most SOHO - alteration of quality of service bits in the TCP header.
    raw - This table is used less frequently then Mangle is to allow exceptions to iptables.

Default Chains : Each table has a number of default chains

filter : used to filter or block packets

The filter table contains 3 default chains: CHAINS ARE IN ALL CAPS
    FORWARD - Filters packets accessible by another NIC on the firewall (ie packets moving from eth0 [Internet] to eth1 [LAN].
    INPUT - Filters inbound traffic (packets going to the firewall).
    OUTPUT - Filters outbound traffic (packets leaving the firewall).

nat (Network Allocation Table):

The nat table contains 3 default chains :
    PREROUTING - Inbound packets to be routed (via NAT) to your clients.
    OUTPUT - Outbound packets from your firewall.
    POSTROUTING - Outbound packets routed from other computers.
In addition to these default chains you may use custom, or user defined chains.

Actions : What happens to a packet if a rule is matched

If a packet matches a rule, the action is called a target.     Note: Actions are specified with the -j flag, ie -j ACTION
    ACCEPT - The packet is approved, or accepted.
    REJECT - The packet is blocked, and an error message is returned.
    DROP - The packed is blocked, no error message is returned.
    LOG - The packet is logged. After a packed is logged processing continues along the chain.
    JUMP - Just to "jump" to another chain.
In addition to the default actions you may direct iptables to another (user defined) chain.

Using iptables for Filtering

It is very important to understand that the order of your rules is critical. Iptables starts at the top of a chain, with the first rule, and proceeds down the chain until the FIRST instance of Drop, Reject, or Accept.
The basic syntax is
iptables -option [Chain] [Rule] -j [Target]
The term "Target" is confusing. A Target is the action to be taken if there is a match to the rule, for example Drop, Accept, Log, Reject, or send the packet to another,  possibly user defined chain.


-P  [Chain] sets default Policy (target or action) for a packet if no rule in a chain is matched.
iptables -P INPUT DROP # Will drop (block) all incoming packets.
Note: The above policy will immediately terminate your ssh session if you have not allowed ssh connections in your INPUT chain. Very bad if you are managing your server remotely and do not have physical access.
  (Insert rules in the beginning with -I and add them at the end with -A )
 -A  [Chain] Appends a rule to the bottom, or end of the specified chain.
-I  [Chain] Inserts a rule into a chain (you specify the location). If no position is specified the default is #1 (first rule).
iptables -I INPUT 2 [RULE] # Will insert the [RULE] at the second position of the INPUT chain.
-D  [Chain] deletes a rule that matches its argument.
You may specify a rule via a the number in a chain or the rule itself
iptables -D INPUT 2 # Will delete the second rule in the INPUT chain.
iptables -D INPUT [RULE] # Will delete the [RULE] from the input chain.
-F  [Chain] flushes (removes or deletes) all the rules from a chain.
By default, in no arguments are given, this will flush the chains in the filter table. You may specify a table and/or chain.
iptables -F INPUT # Clears the INPUT chain in the filter table.
iptables -t nat -F PREROUTING # Clears the PREROUTING table in the nat table.
iptables -F # Clears all the chains in the filter table (INPUT, OUTPUT, and FORWARD).
iptables -t nat -F # Clears all the chains in the nat table.
-L  [Chain] lists rules in chain
By default this will list the chains in the filter table. You may specify a table with -t ( -t nat ).
-N creates a New, user defined chain (blacklist for example).
iptables -N blacklist
-X deletes a user defined chain.
iptables -X blacklist

Before a chain can be deleted, it must be empty (contain no rules). To remove the rules from a table, use the "-F" option to flush the rules.


-j  specifies target (action) default targets are LOG, ACCEPT, DROP, and REJECT. You may also send processing of a packet to another chain.
iptables INPUT -j DROP # Will drop all packets.
iptables INPUT -j blacklist # Will process packets according to the blacklist (user defined) chain.


Some rules can be reversed with a !
iptables -A INPUT -p tcp ! --dport 22 -j DROP
-p  specifies ip protocol (tcp, udp, and icmp).
iptables -A INPUT -p icmp -j DROP # Blocks ping.
-s  specifies source IP address (where a packet came from).
iptables -A INPUT -s -j DROP # blocks packets from
iptables -A blacklist -s -j DROP # blocks packets from using a user defined chain, "blacklist"
iptables -A INPUT ! -s -p tcp --dport 22 -j DROP # Drops ssh from outside your LAN
-d  specifies destination IP address (where a  packet is going to).
iptables -A OUTPUT -d -j DROP # Blocks all packets going to
Note: source and destination IP address can be specified by IP address, or with a net mask, or with a host name. The use of a host name is discouraged as iptables will then use DNS to resolve the host name, which is slow and DNS can be spoofed.
Ex: -d
i  input interface (INPUT, FORWARD, and PREROUTING chains)
-o output interface (OUTPUT, FORWARD, and POSTROUTING chains)
-f  matches packet fragments

tcp options ( to be used with -p tcp )

--sport  specifies source port number or range
    If using a range, the syntax is LOW:HIGH
    LOW: = all ports including and higher then specified port
    :HIGH = all ports including and below the specified port
--dport  specifies the destination port, similar format to --sport above.
Setting --tcp-flags is a bit complex and requires an understanding of the tcp protocol and the headers.
Ex : The following two examples are have the same effect :
iptables -A INPUT -p tcp --syn --dport 22 -j ACCEPT # Short version
iptables -A INPUT -p tcp --tcp-flags SYN,ACK,RST SYN --dport 22 -j ACCEPT #Long version
The option "--tcp-flags" takes two arguments. The above command (long format) matches when its second argument is flagged, and the rest of the flags specified in its first argument are cleared.
(note that using "ALL" as an argument is the same as using "SYN,ACK,RST,PSH,URG,FIN")
As example of setting --tcp-flags, take the following :
iptables -A INPUT -p tcp --tcp-flags SYN,ACK,RST SYN --dport 21 -j ACCEPT
Matches all incoming packets with the SYN flag set, but the ACK and RST flags must also be cleared as well.
Multiple tcp flags can be set on a packet.
If you do not specify flags when using --tcp-flags, any SYN packet would be accepted, even the combination of SYN + ACK.
Do not worry if this information on tcp flags went over your head at this time, it is not necessary to understand this option to use iptables.

udp options (to be used with -p udp)

--sport same as with tcp
--dport same as with tcp

icmp options (to be used with -p ICMP)

--icmp-type  this option specifies the icmp type of the packet to be matched.
Use iptables -p icmp --help to list the various options here (without arguments will default to all, which is what most of us want).
iptables -A INPUT -p icmp -j DROP
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP # ping only

Additional match (rule) options

The general syntax is : -m [option] rule
Match options include state (of the tcp connection ie NEW, RELATED, ESTABLISHED, INVALID), owner (who is using the network connection), time (restrict connections to times of the day), limit (used to limit DOS or brute force attacks). For additional options see man iptables.

state match (used with -m state)

This is used most commonly to block NEW inbound connections , but allow related and established.

4 "states"
    NEW - This communication is new to the firewall.
    RELATED - Communications (packets) involved in establishing a connection (see three way handshake).
    ESTABLISHED - Once a connection has been confirmed, any further packets are part of an established connection and communication (transfer of data) takes place.
    INVALID - Invalid packets should be dropped.
iptables -A INPUT -m state --state NEW,INVALID -j DROP
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
The above 2 rules blocks new and invalid packets (new = attempts to establish a new connection).

limit match (used with -m limit)

Used to limit the numbers (and sometime types) of connections, ie stop DOS and brute force attacks.
--limit  sets the number of times rule can be matched in a time interval...
    syntax is num/interval
    interval options - s, m, h, or d (for second, minute, hour, and day)
iptables -I INPUT -p tcp -m state --state NEW -m limit --limit 30/minute --limit -burst 5 -j ACCEPT
See the "Tips" section below for additional examples.

Multiport (used with -m multiport)

So far, in our rules, we have specified one port per rule. If you wish to apply rules to more then one port, use the multiport (match) option.
For example, to accept new connections of ports 80 (http) and 443 (https), use:
iptables -A INPUT -p tcp -m state --state NEW --m multiport --dports 80,443 -j ACCEPT
You may specify port by protocol (this line will accept ssh, http, and https):
iptables -A INPUT -p tcp -m state --state NEW -m multiport --dports ssh,http,https -j ACCEPT
Specify a range of ports with a : , syntax is low_port:high_port. For example to allow ports 6881-6889 the default bittorrent ports, use:
iptables -A INPUT -p tcp -m state --state NEW -m multiport --dports 6881:6889 -j ACCEPT

Saving your configuration

Now that you have iptables set up the way you like, how do you save your changes ?

Method 1 "iptables-save"

With iptables-save and iptables-restore
Save your configuration to /etc/iptables.rules
iptables-save > /etc/iptables.rules
To restore, edit /etc/rc.local and add this command anywhere above the line "exit 0"
iptables-restore < /etc/iptables.rules
Note: No need for sudo in that command, /etc/rc.local runs at root at the time of boot.
See Ubuntu Wiki IPtables for tips on using iptables scripts and also in conjunction with Network Manager

Method 2 - Debian / Ubuntu : Add a line to /etc/network/interfaces.

With this method you will need to save your rules ( with iptables-save > /etc/ ) as above. Then disable NetworkManager and manually configure your network.
As you do these steps you will temporarily loose your internet connection.
Start by removing Network Manager:
sudo apt-get remove -purge network-manager network-manager-gnome
Stop networking:
service networking stop
Using any editor, open /etc/network/interfaces. We will use dhcp or a static IP address, and add a line "post-up" to bring our iptables rules up.

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
post-up /sbin/iptables-restore /etc/
Static IP :
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
post-up /sbin/iptables-restore /etc/
Using any editor, edit /etc/resolv.conf and add in your nameserver :
Restart networking :
sudo service network start

No comments: