NoteThe above "IPTabels Flow chart" is used with permission. It was originally published here and is licensed under the GNU FDL.
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 :
- Filtering - (blocking unwanted traffic). You can filter
incoming and outgoing traffic by user, group, time/date, or service
(application).
- 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.
- Logging (monitoring) network traffic.
- Block brute force or DOS attacks.
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".
- How to iplist ~Thanks uljanow
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.
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, tracerouteOther 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. :(
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:
- cupsd == printing (common unix printing system daemon)
- Avahi Home Page
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 (block) 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!Another perennial source of confusion is the term "Stealth Ports". This term sounds sexy, but what does it mean ?
When a packet is blocked 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 blocked. 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 error message. Some people feel DROP is more secure (security through obscurity or "Stealth").
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.
Options
-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.
-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).
iiptables -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
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 DROP # Will drop 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 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 111.222.33.444 -j
DROP # blocks packets from
111.222.33.444
iptables -A blacklist -s 111.222.33.444 -j
DROP # 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 DROP #
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 DROP # 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.
Ex: -d 192.168.0.0/24
-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 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.
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 - write a script to start and configure iptables.
Additional Tips
Limit network access
by user / group
Use the owner module
-m owner --uid-owner 0
-m owner --gid-owner <user>
Example (assuming 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 DROP
- Match must be by group (-m owner --gid-owner), but this
must be the
active group.
- You may change your default group with the newgrp command
(this
starts a new shell).
- In Ubuntu your default group is the same as your user name.
- If you make a new group "net" and allow this group Internet access you can change your primary group to "net" with the command "newgrp net" (without quotes).
ping google.com # this fails
change your primary group (temporarily) with newgrp:
newgrp net
Ping now works !!!
ping google.com -> works
You can change your
default group with usermod (or your graphical group
management tool).
sudo usermod -g net user
- user = log in name to change
- You must log out and back in for changes to take effect
by time / date
Use the time module
-m time --timestart HH:MM --timestop HH:MM
ex Lunch hour only
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -o eth0 -m time
--timestart 12:00 --timestop 13:00
-j ACCEPT
iptables -A OUTPUT -o eth0 -j DROP
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 DROP
iptables -A blacklist -s
<Bad_IP_1> -j DROP
Use iptables to 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 DROP
iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
Modified from:
Kevin van Zonneveld - BlogSAMHAIR 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
Think of NAT as using your firewall as a router. Typically you will use multiple interfaces, although one (or more) interfaces may be a virtual interface such as Virtualbox, VMWare, or KVM.
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.
The NAT section is forthcoming. For now my favorite link on the topic is at:
"Novell coolsolutions"
Simple Firewall Configuration Using NetFilter/iptables
References
- Ubuntu Wiki - How to IPTABLES
- Linux Home Networking
- iptables & NetFilter - How to get started
- Linux Network Administrators Guide
- The 7 Layers of the OSI Model