You are on page 1of 8

Using and

Configuring
Linux Packet
Filtering

an Networking eBook
Using and Configuring Linux Packet Filtering

inux is the operating system of choice for most modern

L consumer electronic devices for a variety of reasons --


the absence of initial cost and subsequent royalty pay-
ments, its flexibility and ease of configuration, its platform
Network communications work at a variety of different
levels, more specifically known as layers. At the low-
independence and ability to run on most modern computer est layer, network communication is based on a physi-
systems and architectures, and its rich pool of available soft- cal transport medium, such as special types of wired
ware and built-in capabilities. One of the most popular capa- or fiber-optic cables, and the hardware-oriented net-
bilities of Linux is its integrated support for sophisticated work addresses required to send and receive packets
analysis and manipulation of network traffic, known as packet from one specific device to another. At the highest
filtering because it examines and acts upon network traffic at layer, network communications are application-specif-
the packet level. Current versions of Linux support packet fil- ic, but just below that are similarly high-level logical
tering through the Linux kernel's netfilter framework and an layers such as TCP and IP, where addresses follow the
associated user-level configuration command. familiar AAA.BBB.CCC.DDD convention and the suc-
cessful delivery and acknowledgment of packets is
Packet filtering refers to the ability to analyze network packets enforced by the system.
and perform various actions based on their source, destina-
tion, type, or other meta information. Linux packet filtering The sum of all of these layers of network communica-
uses pre-defined rules to analyze incoming and outgoing tions is known as a network stack. Different network
packets and route packets internally. The two basic stacks are used by different network architectures,
approaches to packet filtering are known as stateful and each of which therefore has its own set of levels. The
stateless packet filtering. Stateless packet filtering rules ana- most well-known and general network stack is the
lyze and act upon each packet in isolation. Stateful packet fil- stack formalized by the Open Systems Interconnect
tering analyzes streams of packets from each network con- (OSI) Reference Model, and consists of the following
nection using mechanisms such as connection tracking to layers, from highest to lowest:
maintain state information and identify related connections,
analyze the relationships between previous and current pack- 1. Application layer
ets and connections, and uses the results of that analysis to 2. Presentation layer
determine how (or if) to modify, re-route, or perform other 3. Session layer
actions on those packets. Linux supports stateless packet fil- 4. Transport layer
tering for both IPv4 and IPv6 connections, but currently only 5. Network layer
support stateful packet filtering for IPv4 connections. 6. Data Link layer
7. Physical layer
This eBook discusses Linux packet filtering, the syntax and
organization of different types of packet filtering rules, and the The OSI reference model provides many different lay-
use-space command that you use to define them, providing ers to support a variety of network communications
the information necessary to create or fine-tune packet filter- and protocols. The TCP/IP (Transmission Control
ing rule sets on your systems. This will enable you to activate Protocol/Internet Protocol) network stack has fewer
the rules that you need to provide maximum protection and levels, since it focuses on the requirements for TCP/IP.
performance optimizations while still supporting the types of These are the following:
networking communication that are required in your comput-
ing environment. 1. Application layer
2. Transport layer
3. Internet layer
4. Network Access layer
Linux Packet Filtering
Overview Each packet that is sent by a computer system goes
through each of the layers in the network stack that it
The packet filtering mechanism used by the current Linux ker- is using, beginning at the highest layer and proceed-
nel (2.6.xx) is a combination of a loadable kernel module ing to the lowest layer. Each layer wraps the packet
framework and API called netfilter and an interface and asso- continued next page
ciated and user-space administrative command called ipta-
bles. The iptables interface is one of several kernel modules

1 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

based on the netfilter framework; others include a module


that handles Native Address Translation (NAT, which enables
multiple machines to share one public IP address), and the with its own set of headers to provide the information
module that implements and supports connection tracking. required by that layer while preserving the contents of
Throughout the rest of this eBook, I will collectively refer to the packet and the header information that was pro-
this interface as iptables, since that is the interface that is vided by each preceding layer. This is therefore often
most commonly associated with modern Linux firewalls and referred to as a packet's encapsulation phase.
packet filtering.
When a packet reaches its destination, the packet
Iptables and the netfilter framework are actually the fourth moves backwards through the list of layers, each
generation of Linux packet filtering solutions. The original layer stripping off and utilizing its header information
Linux packet filtering implementation, ipfw, was liberated from until the data contained in the packet reaches the
BSD-based systems and was introduced in Linux by Alan application that it is intended for,
Cox in the 1.1 Linux kernel. It was designed to support the
creation of simple IP firewalls and routers through packet The packet filtering provided by the Linux kernel's
inspection and filtering. The iwfwadmin tool and associated netfilter package and related utilities takes place at
ipfw changes, which simplified creating ipfw-based firewalls, the TCP/IP stack's Internet and Transport layers, and
was added for the Linux 2.0 kernel and makes up the second focuses on analyzing and acting upon the contents of
generation. The third generation of Linux packet filtering, the headers added by these layers. Focusing on these
consisting of a major rewrite of the entire Linux networking layers is what makes the Linux netfilter package such
layer and introducing the user-space ipchains tool, was intro- a powerful routing tool. Though it is possible to ana-
duced in the 2.1 kernel series. The current netfilter framework lyze and modify the headers used by the Network
and iptables interface were introduced in the 2.4 kernel, and Access and Application layers and even the contents
have been the standard mechanism for packet filtering, net- of a packet, this eBook (and the netfilter package in
work address and port translation, and general packet manip- general) focuses on analyzing and manipulating the
ulation (often referred to as packet mangling) in the 2.6 series Transport and Internet layer packet headers.
of Linux kernels.
The IP protocol is the core of the TCP/IP stack's
Linux packet filtering works by inspecting incoming and out- Internet layer, and is the protocol that is responsible
going packets and acting upon them based on filtering rules for identifying the destination of a specific packet and
that have been loaded into the netfilter framework's filter table routing that packet to its destination. The IP protocol
by the iptables command. By default, the iptables command encapsulates each Transport layer packet with infor-
supports three default sets of rules, known as chains, for fil- mation about the protocol (TCP, UDP, ICMP, and so on),
tering network packets using the information stored in the ipt- the origin of the packet, and its destination, each
ables filter table. address expressed in traditional dotted-quad IP
address format (AAA.BBB.CCC.DDD). Finally, the IP
These default chains are the INPUT, OUTPUT, and FORWARD protocol must also be able to fragment or recombine
chains. The rules in the INPUT chain are used to examine and packets in order to suit the packet size of the network
process incoming packets intended for ports on the local for which a packet is targeted.
machine. The rules in the OUTPUT chain are for examining
and processing outgoing packets that are being sent from the The IP protocol is a connectionless protocol, which
local machine. The rules in the FORWARD chain are used to means that no handshake is required in order to send
examine and process packets that are being routed through or receive packets from other hosts, but also means
the local machine. that packet delivery is not confirmed or guaranteed.
Both of these aspects of the IP protocol minimize net-
Each of the default filtering rule chains can have its own set of work overhead and therefore maximize throughput at
filtering rules. In addition, you can also define other sets of this level of the network stack.
rules and use them for your own purposes. Most modern
Linux and other Unix-like systems come with predefined The TCP protocol resides on top of the IP protocol, and
INPUT, OUTPUT, and FORWARD rule chains and automatical-
ly load them at boot time. When network connectivity or visi- continued next page
bility problems arise, a quick and dirty diagnostic step is often

2 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

to disable all existing filtering chains and see if this removes


the problem. Unfortunately, if this does indeed remove the
problem, some system administrators don't look any further provides functions that negotiate and correctly set up
than this solution, and therefore leave kernel packet filtering connections with remote machines, confirm delivery
disabled. A far better solution is to inspect the system's filter- and enforce that packets are received and processed
ing rules and disable or fine-tune the specific rules that are in the right order. Each TCP packet also provides a
causing the problem. checksum to validate the correct transmission of each
packet.
Other netfilter-based modules use packet-matching tables
other than the filter table. The NAT module uses the nat table, In order to support sequencing, the TCP protocol looks
which contains three built-in rule chains: OUTPUT, at a network connection as a continuous data stream
POSTROUTING, and PREROUTING. Specialized packet delimited by a start and a stop signal. Initiating a
manipulation operations use the mangle table, which contains TCP/IP connection begins with the originating host
pre-built FORWARD, INPUT, OUTPUT, PREROUTING, and sending a single packet with the SYN bit set. The tar-
POSTROUTING chains. The connection tracking module uses get host responds with a packet that has the SYN/ACK
the raw table, which contains pre-configured OUTPUT and bits set, indicating that the connection was accepted,
PREROUTING chains. or the SYN/RST bits set, indicating that the connection
was refused. If the target system responded with a
You must have superuser privileges to examine, create, or SYNC/ACK packet, the originating host responds with
modify any netfilter-based rule chains. You can do this by put- an ACK packet that confirms that the connection was
ting iptables commands in a script that is executed as part of correctly established, and begins to transmit addition-
the system's boot process, by running iptables commands al data.
manually when logged in as the root user, or by using a com-
mand such as sudo as a normal user to run the iptables Within the context of an established connection, each
commands with root privileges. TCP packet contains a unique sequence number that
is automatically incremented with each new packet.
The sequence number enables both hosts to verify
that all packets were successfully received, and can
Listing and Purging therefore be delivered to the target application in the
Current Rule Chains correct order.

When the connection is no longer needed, it is closed


As mentioned previously, most modern Linux systems come
by either host sending a FIN packet, which the other
with some sort of iptables-based firewall installed. The ipta-
host responds to with a FIN/ACK packet. At this point,
bles command's _l (list) option displays any current rules
only the host that received the FIN packet can contin-
associated with the three default rule chains, as in the follow-
ue to send data. When it is finished, it sends its own
ing example:
FIN packet, which the other host responds to with
# iptables -L FIN/ACK, and the connection is completely and cleanly
Chain INPUT (policy ACCEPT) closed.
target prot opt source destination
Other protocols that are commonly used on top of the
Chain FORWARD (policy ACCEPT) IP protocol are UDP (User Datagram Protocol) and
target prot opt source destination ICMP (Internet Control Message Protocol). The former
is a connectionless, stateless, protocol that supports
Chain OUTPUT (policy ACCEPT) networked data transmission without any error detec-
target prot opt source destination tion. ICMP messages are used for various types of
error and status reporting between hosts.
This example shows that the sample system on which I ran
this command doesn't currently have any rules defined. If you
are only interested in examining a specific rule chain, you can
provide the name of that chain as an argument, as in the fol-
lowing example:

3 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

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

In both of these examples, you'll notice that each rule chain that has been defined has a default policy. This policy
defines what the system should do with packets that are not matched by any of the rules that are currently defined
on the system. The default policy, ACCEPT, indicates that the system should simply accept any packets that are not
addressed by any rule(s).

The rules within any iptables chain are evaluated in the order that they are listed using the iptables -L command.
Evaluation within a chain ceases when the end of a chain is reached and the default policy is applied, or when a rule
accepts the packet using the ACCEPT target, returns control to any other calling chain by using the RETURN target,
or transfers a packet to another chain for processing.

Dropping Specific Protocols


The most common use for iptables-based firewalls is to disallow certain types of network traffic or to disallow traffic
on certain ports. You can drop certain types of traffic by adding a rule for that type of traffic to the INPUT chain. This
requires using the iptables command's -A (append) option to identify the chain that you want to append the new
rule to, the -p option to identify the protocol that you're interested in, and the -j (jump) option to identify a target
action for any packets that match a particular rule. For example, the following command sets up a rule that tells the
netfilter framework to drop all ICMP packets:

# iptables -A INPUT -p ICMP -j DROP

After executing this command, the iptables -L INPUT command shows that the new rule has been created in the
input chain:

# iptables -L INPUT
Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP icmp -- anywhere anywhere

DROP is a target action that is built into iptables. Other built-in targets are ACCEPT (accept the packet), QUEUE
(accept the packet and move it to a specific network queue for subsequent processing), and RETURN (stop pro-
cessing the packet in the current rule chain and resume processing the packet in the next rule in any parent chain).

Deleting Existing Rules


When defining and testing rules on a new system, you can use the iptables -L command to see the current state of
all rule chains before applying your changes. You can then remove all existing rules by using the iptables command's
-F (flush) option with no arguments. As with the iptables -L command, you can limit the rules that are affected by the -
F option to a specific chain by specifying the name of that chain as an argument. For example, the command iptables
-F INPUT removes all existing rules in the input rule chain without affecting the rules in any other chain.

You can use the iptables command's -D option to delete a single rule from an existing rule chain, identifying the rule
that you want to delete by number or by its contents. (Identifying a rule by number is much simpler.) Though rules
within a chain are not explicitly numbered in iptables output, rule numbering within a chain begins with 1. For exam-

4 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

ple, the following two commands are equivalent ways of deleting the ICMP filtering rule that was created in the pre-
vious section:

# iptables -D INPUT -p ICMP -j DROP


# iptables -D INPUT 1

Dropping Specific Types of Packets


An equally common use for iptables is to drop packets that are intended for certain ports on your system. The most
common example of this type of rule is a rule that rejects connection to the telnet port, since telnet is an older net-
work connection mechanism that is insecure (all standard telnet transmissions are done in the clear, without encryp-
tion) and has largely been replaced by Secure Shell (ssh) connections on most Linux systems. For example, the ipta-
bles command to drop all incoming TCP connections to the telnet port (port 23) is the following:

# iptables -A INPUT -p TCP --destination-port telnet -j DROP

If you wanted to prevent your users from attempting to use the telnet command to connect to remote systems, you
could write an equivalent rule for the OUTPUT chain, as in the following example:

# iptables -A OUTPUT -p TCP --destination-port telnet -j DROP

Using the DROP target causes the packets to be dropped without notifying the user-space telnet command that the
user executed. When preventing connections to specific ports, a more user-friendly approach is to use the REJECT
target, which causes the netfilter framework to reject the packets and send an ICMP rejection message, which the
user-space telnet application will notice. These rules are identical to the previous rules except for the target, as in the
following example. Note that you must first delete the existing rule, or your new rule would be added after the exist-
ing rule and would therefore never be reached:

# iptables -L OUTPUT
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
DROP tcp -- anywhere anywhere tcp dpt:telnet

# iptables -D OUTPUT 1
# iptables -L OUTPUT
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
# iptables -A OUTPUT -p TCP --destination-port telnet -j REJECT
# iptables -L OUTPUT
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
REJECT tcp -- anywhere anywhere tcp dpt:telnet reject-with
icmp-port-unreachable

After adding these rules, users attempting to use the telnet command from your system to connect to a remote sys-
tem would get a more familiar rejection message:

# telnet testhost
Trying 192.168.6.64...
telnet: connect to address 192.168.6.64: Connection refused

5 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

You can specify more than one destination port in a single rule. For example, to extend the previous rule to disable
FTP, a similarly insecure protocol for file transfer, change the rule to the following:

# iptables -A OUTPUT -p TCP --destination-port telnet,ftp -j REJECT

Applying Rules to Specific Sources and Destinations


The previous section provided rules that completely blocked certain types of connections (telnet) in both the INPUT and
OUTPUT chains. The iptables interface also enables you to block connections coming from specific hosts by using the
iptables command's -s option and specifying a particular IP address or range of IP addresses as an argument.

Continuing with this example, suppose that you were willing to allow incoming telnet connections from hosts on your
internal network. To do this, you would first delete the general rule that was defined in the previous section and then
add a new rule to explicitly allow connections from certain addresses. Assuming that hosts on your internal network
all have addresses in the non-routable IP address family 192.168.0.0, you could do this with the following rule:

# iptables -A INPUT -p TCP --destination-port telnet -s 198.168.0.0 -j ACCEPT

This rule allows incoming telnet connections from any hosts with IP addresses in the 192.168.0.0 family.
Unfortunately, this rule doesn't reject telnet connections from other IP addresses. To reject incoming connections
from other networks, you would need to add a rule like the following:

# iptables -A INPUT -p TCP --destination-port telnet -s ! 198.168.0.0 -j REJECT

This command uses standard Linux/Unix regular expression syntax in the argument to the -s option to identify hosts
whose addresses are not (!) in the 192.168.0.0 family. After executing these commands, your rules for the INPUT
chain would look like the following:

# iptables -L INPUT
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- 198.168.0.0 anywhere tcp dpt:telnet
REJECT tcp -- !198.168.0.0 anywhere tcp dpt:telnet reject-with
icmp-port-unreachable

Similarly, you can block connections that are sent to specific destination addresses by using the iptables com-
mand's -d option and specifying a particular IP address or range of IP addresses as an argument.

Continuing with the previous example, you might want to add a rule to the OUTPUT chain that rejects outgoing tel-
net packets that are not from IP addresses in the 192.168.0.0 family, as in the following example:

# iptables -A OUTPUT -p TCP --destination-port telnet -d ! 192.168.0.0 -j REJECT

Native Address Translation and Masquerading


Native Address Translation (NAT), where multiple systems on an internal network can share a single external IP
address, is one of the most common uses for the Linux netfilter framework and the iptables command. As men-
tioned in the introduction to this article, many off-the-shelf consumer electronic devices such as home gateways,
cable and DSL modems, and home routers use Linux internally for this reason. As mentioned previously, the netfilter

6 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.
Using and Configuring Linux Packet Filtering

framework's support for NAT is provided by a nat module, which uses its own table for recording and looking up IP
address information.

In order to use NAT or any other IP address forwarding technique, the system that you are configuring must have
two Ethernet interfaces, either network adaptors or serial-over-Ethernet connections such as that used by the Point-
To-Point (PPP) protocol. You must also configure this system, known as a gateway system, to perform IP forwarding
by doing the following:

echo 1 > /proc/sys/net/ipv4/ip_forward

The /proc filesystem is an in-memory filesystem that is recreated each time you boot the gateway device. For this
reason, this command must be placed in one of your gateway system's start-up files so that it is done each time
that you restart that system.

After executing this command, the iptables commands to do NAT are quite simple. On a system where the Ethernet
interface connected to the Internet is eth0 and the internal LAN is connected to the Ethernet interface eth1:

# iptables --table nat -F


# iptables --table nat -A POSTROUTING -o eth0 -j MASQUERADE
# iptables -A FORWARD -i eth1 -j ACCEPT

The first of these commands flushes any existing rules in the nat table. The second command appends a rule to the
nat table's POSTROUTING chain, which tells the netfilter framework that multiple IP addresses will be using the sin-
gle outbound (-o) Ethernet interface. The third iptables command appends a rule to the standard iptables packet fil-
tering table that accepts all incoming traffic from eth1 and forwards it for internal processing through the nat table.

Summary
This eBook provides a firm foundation for understanding the Linux network stack and how packet filtering and relat-
ed packet processing tasks are supported by the Linux kernel's netfilter framework and iptables command. This
eBook will help you understand any existing packet filtering and processing commands that are part of your sys-
tem's start-up mechanism. A short eBook such as this can only scratch the surface of the power of the netfilter
framework and iptables command on Linux system, but should help you add other commands or fine-tune existing
ones to reflect your system's network environment.

This guide was written by Bill von Hagen. Copyright 2006, Jupitermedia Corp.

JupiterWeb eBooks bring together the best in technical information, ideas and coverage of important IT trends
that help technology professionals build their knowledge and shape the future of their IT organizations. For more
information and resources on networking, visit any of our category-leading sites:

www.enterprisenetworkingplanet.com
www.instantmessagingplanet.com
www.opticallynetworked.com
www.practicallynetworked.com
www.voipplanet.com
www.wi-fiplanet.com
www.opennetworkstoday.com

For the latest live and on-demand Webcasts on networking, visit: www.jupiterwebcasts.com/networking/

7 Using and Configuring Linux Packet Filtering, an Internet.com Networking eBook. Copyright 2006, Jupitermedia Corp.

You might also like