image unavailable

Note:The above "IPTables Flow chart" was originally published here,

is licensed under the GNU FDL, and is used with permission.

Dhammapada

He who has no attachments and has been freed from uncertainty by realisation, who has plunged into the deathless - that is what I call a brahmin.


Overview

"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 - (rejecting 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.

Basic Networking Concepts

I apologize in advance for the over simplification of network communications that follows, but understanding a few basic concepts is fundamental to understanding iptables.

How is it then that computers, running a variety of operating systems and applications, can communicate and transfer information over a network ?

If you are not familiar with the OSI (Open Systems Interconnection) Model you might wish to glance at this Wikipedia page.

Linuxtropia TCP/IP layers
Wikipedia OSI Model

Network communications has some similarities to mail (postage), although computers should be thought as office buildings. So just as a specific office is identified by a street address and suite, servers on your computer are identified by an IP address (street) and port (suite).

Using an Apache server as an example,

Street address -> IP Address
1234 A Street -> 192.168.1.15

Suite -> Port
Suite 100 -> Port 80

DNS (Domain Name Service) is akin to a phone book, allowing us to type "ubuntuforums.org" rather then "91.189.94.12" into your browser.

Information to be transferred across a network is broken into smaller units called packets. A packet contains header and the data. The header contains information such as source IP address (where the packet originated), destination IP address (where the packet is going), and the protocol/port (Apache).

Communication or transfer of packets takes place using protocols, the most common by far is TCP.

Network protocols

TCP : (Transmission Control Protocol)

Understanding the concept of the "Three Way Handshake" allows to understand the terms NEW, RELATED, and ESTABLISHED.

UDP : (User Datagram Protocol)

ICMP (Internet Control Message Protocol)

Example - ping, traceroute

Other network protocols exist as well but are beyond what I will cover in this how-to.

Servers / open ports

A "server" or "service" is an application (Apache, SSH, FTP, Samba) that "listens" for incoming requests for information or, in the case of ssh, connections. The server application then sends information back to the client that make the request. Services can be run on Desktops or on dedicated Servers. In general dedicated (Linux) Servers do not run graphical interfaces, although several web based interfaces are popular.

Ports are akin to mail boxes and servers listen on dedicated ports. For example, the default port for Apache (http) is 80, ssh uses port 22 , etc.

There is a special interface, the loop back, or lo device that your computer uses to communicate internally.

You can see the listing of default ports with the text editor of your choice:

gedit /etc/services

The list is long, so for a specific port or service you may want to grep

grep ssh /etc/services

A default installation of most distros will have no servers installed and, at least with Ubuntu, by default, with the exception of the loop back, all ports are closed to listening connections.

If you install and configure a server, Apache for example, the corresponding port will then be open, or available for inbound network communications as a server.

Clients, such as Firefox, typically use pseudorandom ports on the client to connect to port 80 on the server (Firefox uses a random port on your computer to connect to port 80 at ubuntuforums.org). This randomness makes it more complex to filter outbound traffic, especially P2P connections.

Scanning your computer for open ports

Several tools can be used to check for open ports or scan your computer. In general, because connections from localhost (your computer) will automatically be accepted, you should scan from a second computer on your LAN. nmap is one of several options.

Only scan computers (servers) you own or that you have permission to scan, otherwise you could easily risk legal action or jail time. See: Master Foo and the Script Kiddie

nmap -v -A ip_address

Or if the server is pesky about pings ...

nmap -v -A -PN ip_address

nmap has additional capabilities which will not be covered here.

Additional tools you can use on your computer (rather then scanning from a remote location):

netstat -an | grep LISTEN | grep -v ^unix

netstat -ntulp

lsof -i -n -P

lsof is particularly informative >:)

Note:

In summary, a port is "opened" when you install a server (Apache, FTP, Samba, NFS, SSH, etc) and "closed" when you either remove the server or filter (reject) connections with your firewall.

If you try to scan your computer with Internet tools, such as "ShieldsUp" you are scanning your ROUTER. To use a scanner over the Internet, you must bypass your router and connect your computer directly to the Internet.

"Shields up"

ShieldsUP! is a web based scanner you may use to scan for open ports. One common source of confusion, if you have a router you will be scanning your router and not your computer(s) behind the router.

Another perennial source of confusion is the term "Stealth Ports". This term sounds sexy, but what does it mean? Please take the time to understand the DROP and REJECT options.

When a packet is rejected by iptables you can use 2 options, DROP or REJECT. Both options are secure in that the respective port is closed and the attempted connection is rejected. DROP is just that, think of it as if the packet is delivered to /dev/null. In addition to dropping the packet, REJECT sends an (icmp) error message.

Anatomy of iptables

This description of the anatomy of iptables was adapted from a comment on my blog.

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. Each table (by convention, a lowercase name) has a number of chains (uppercase name). Each chain may contain multiple rules that determine how a packet should be handled.

A packet's fate is determined by following the rules, one at a time, like links in a chain. The diagram at the top of this page diagrams the tables/chains and the sequence of processing packets.

As the packet arrives from the network, it is processed according to each of the ovals shown. The specified table is searched for a matching chain. If one exists, the packet is tested against each of the rules in that chain, and processed accordingly. The arriving packet then passes to the next oval, where that table is searched for a corresponding chain, and so on until the packet is either delivered or dropped.

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 reject/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 rejected, and an error message is returned.

DROP - The packed is dropped (rejected), no error message is returned.

Some people WRONGLY feel DROP is more secure (security through obscurity or "Stealth") or that is somehow slows down automated scanners. THIS PAGE should clarify why REJECT is preferred to DROP.

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

I

Some people WRONGLY feel DROP is more secure (security through obscurity or "Stealth") or that is somehow slows down automated scanners. THIS PAGE should clarify why REJECT is preferred to DROP.

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.

Options

-P [Chain] sets default Policy (target or action) for a packet if no rule in a chain is matched.

iptables -P INPUT REJECT --reject-with icmp-host-prohibited # Will reject (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.

-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 chain 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.

Target

-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 REJECT --reject-with icmp-host-prohibited # Will reject all packets.
iptables INPUT -j blacklist # Will process packets according to the blacklist (user defined) chain.

Rules

Some rules can be reversed with a !

iptables -A INPUT -p tcp ! --dport 22 -j REJECT --reject-with icmp-host-prohibited

-p  specifies ip protocol (tcp, udp, and icmp).

iptables -A INPUT -p icmp -j REJECT --reject-with icmp-host-prohibited # Blocks ping.

-s  specifies source IP address (where a packet came from).

iptables -A INPUT -s 111.222.33.444 -j REJECT --reject-with icmp-host-prohibited # rejects (blocks) packets from 111.222.33.444

iptables -A blacklist -s 111.222.33.444 -j REJECT --reject-with icmp-host-prohibited # rejects (blocks) packets from 111.222.33.444 using a user defined chain, "blacklist"

iptables -A INPUT ! -s 192.168.0.0/24 -p tcp --dport 22 -j REJECT --reject-with icmp-host-prohibited # Drops ssh from outside your LAN

-d  specifies destination IP address (where a  packet is going to).

iptables -A OUTPUT -d 111.222.33.444 -j REJECT --reject-with icmp-host-prohibited # Blocks all packets going to 111.222.33.444

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.

For example, -d 192.168.0.0/24 would drop packets from the 192.168.0.0/24 network.

-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.

--tcp-flags

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 REJECT --reject-with icmp-host-prohibited
iptables -A INPUT -p icmp --icmp-type echo-request -j REJECT --reject-with icmp-host-prohibited # 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 reject/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 REJECT --reject-with icmp-host-prohibited
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

The above 2 rules rejects (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/iptables.save ) 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.

DHCP :

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
post-up /sbin/iptables-restore /etc/iptables.save

Static IP :

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.0.10
netmask 255.255.255.0
broadcast 192.168.0.255
gateway 192.168.0.1
post-up /sbin/iptables-restore /etc/iptables.save

Using any editor, edit /etc/resolv.conf and add in your nameserver :

nameserver 192.168.0.1

Restart networking :

sudo service network start

Method 3 - Fedora / Centos

With Fedora or Centos you can simiply save your changes (as root) with :

service iptables save

This command saves your current iptables rules and they will be restored on (re)boot.

Method 4 - Use a command line or graphical tools

There are several tools to help manage your firewall. In Debian/Ubuntu use UFW / GUFW. On Fedora Desktops use the graphical tool (in the menu). Alternately you may use any number of tools to configure your firewall.

Additional Tips

Limit network access

by user / group

Use the owner module

This module applies to locally generated packets, not incoming or forwarded packets, and is thus used in the OUTPUT (filter) chain.

You may specify a user/group by name, uid, or gid. In the following examples I use the group "net" to demonstrate restricting access to root and members of the group "net". "net" is a custom group and you will need to create this group and add members to it.

General syntax:
-m owner --uid-owner 0
-m owner --uid-owner root
-m owner --gid-owner net

Example - by user (assuming a user name = bodhi)

iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -o eth0 -m owner --uid-owner 0 -j ACCEPT
iptables -A OUTPUT -o eth0 -m owner --uid-owner bodhi -j ACCEPT
iptables -A OUTPUT -j REJECT --reject-with icmp-host-prohibited

Example - by group (assuming a group name = net)

iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -o eth0 -m owner --uid-owner 0 -j ACCEPT
iptables -A OUTPUT -o eth0 -m owner --gid-owner net -j ACCEPT
iptables -A OUTPUT -j REJECT --reject-with icmp-host-prohibited

In most Linux distributions, your default active group is the same as your user (login) name.
To view your group memberships use the command "id".

id bodhi
uid=1000(bodhi) gid=1000(bodhi) groups=1000(bodhi),1100(net) ....

As you can see, this command shows your active group [ gid=10000 (bodhi) ]. It is this active group that is used by iptables to grant or reject/block access.

Assuming you are restricting access to a group "net", you may temporarily change your active group to "net" with the command "newgrp".

Example:

# Ping initially fails
id bodhi
uid=1000(bodhi) gid=1000(bodhi) groups=1000(bodhi),1100(net) ....
ping -c 1 google.com
ping: unknown host google.com

# Change active group with "newgrp"
newgrp net
id
uid=1000(bodhi) gid=1100(net) groups=1000(bodhi),1100(net) ....
ping -c 1 google.com
PING google.com (74.125.95.99) 56(84) bytes of data.
64 bytes from iw-in-f99.1e100.net (74.125.95.99): icmp_seq=1 ttl=48 time=83.4 ms

--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 83ms
rtt min/avg/max/mdev = 83.434/83.434/83.434/0.000 ms

You can change your default group with usermod (or your graphical group management tool).

sudo usermod -g net bodhi

You will need to log out and back in (or start a new shell) for changes to take effect

by time / date

Use the time module.

Syntax:

-m time --timestart HH:MM --timestop HH:MM

ex Lunch hour only

iptables -A OUTPUT -o lo -j ACCEPT

iptables -A OUTPUT -o eth0 -p tcp -m multiport --dports 80,443 -m time --timestart 12:00 --timestop 13:00 -j ACCEPT

iptables -A OUTPUT -o eth0 -p tcp -m multiport --dports 80,443 -j REJECT --reject-with icmp-host-prohibited

Caveats: The time module works by analyzing the time stamp of locally generated packets. Thus use these rules in OUTPUT specifying either --sport or --dport.

Blacklist / Whitelist

I use small letters for user defined chains.

iptables -N blacklist
iptables -A INPUT -j blacklist
iptables -A OUTPUT -j blacklist
iptables -A blacklist -d <Bad_IP_1> -j REJECT --reject-with icmp-host-prohibited
iptables -A blacklist -s <Bad_IP_1> -j REJECT --reject-with icmp-host-prohibited

Use iptables to reject/block failed connections

You will have to adjust these settings for your server. For example settings are very different for ssh, http, and samba servers.

Block Brute Force attempts (SSH or other connections)

iptables -A INPUT -p tcp -m tcp --dport 22 -m tcp -m state --state NEW -m recent --set --name SSH --rsource

iptables -A INPUT -p tcp -m tcp --dport 22 -m recent --update --seconds 600 --hitcount 8 --rttl --name SSH --rsource -j REJECT --reject-with icmp-host-prohibited

iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

Modified from:

Kevin van Zonneveld - Blog
SAMHAIR LABS

Block Brute Force attempts (http [Apache] or other connections)

# General new connection rate limiting for DOS and Brute Force protection
iptables -I INPUT -p tcp -m state --state NEW -m limit --limit 30/minute --limit-burst 5 -j ACCEPT

Thanks to HermanAB @ Ubuntu Forums

NAT - Network Allocation Table

This section of under development.

Think of NAT as using your firewall as a router (firewall = the computer we are configuring iptables on).

Typically you will use multiple interfaces, although one (or more) interfaces may be a virtual interface such as Virtualbox, VMWare, or KVM.

For a consice overview of how to set up a router see:

Stateful Firewall and Masquerading on Linux - by Werner Puschitz

For a more detailed guide see :

"Novell coolsolutions" - Simple Firewall Configuration Using NetFilter/iptables

Terminology:

DNAT - Destination Network Address Translation. Changes the destination IP of a packet.

SNAT - Source Network Address Translation. Likewise, changes the source IP of a packet.

References