Using and Configuring Linux Packet Filtering
an
Networking eBook
Using and Configuring Linux Packet Filtering
L
inux is the operating system of choice for most modern consumer electronic devices for a variety of reasons -the absence of initial cost and subsequent royalty payments, its flexibility and ease of configuration, its platform independence and ability to run on most modern computer systems and architectures, and its rich pool of available software and built-in capabilities. One of the most popular capabilities of Linux is its integrated support for sophisticated analysis and manipulation of network traffic, known as packet filtering because it examines and acts upon network traffic at the packet level. Current versions of Linux support packet filtering through the Linux kernel's netfilter framework and an associated user-level configuration command. Packet filtering refers to the ability to analyze network packets and perform various actions based on their source, destination, type, or other meta information. Linux packet filtering uses pre-defined rules to analyze incoming and outgoing packets and route packets internally. The two basic approaches to packet filtering are known as stateful and stateless packet filtering. Stateless packet filtering rules analyze and act upon each packet in isolation. Stateful packet filtering analyzes streams of packets from each network connection using mechanisms such as connection tracking to maintain state information and identify related connections, analyze the relationships between previous and current packets and connections, and uses the results of that analysis to determine how (or if) to modify, re-route, or perform other actions on those packets. Linux supports stateless packet filtering for both IPv4 and IPv6 connections, but currently only support stateful packet filtering for IPv4 connections. This eBook discusses Linux packet filtering, the syntax and organization of different types of packet filtering rules, and the use-space command that you use to define them, providing the information necessary to create or fine-tune packet filtering rule sets on your systems. This will enable you to activate the rules that you need to provide maximum protection and performance optimizations while still supporting the types of networking communication that are required in your computing environment.
Network communications work at a variety of different levels, more specifically known as layers. At the lowest layer, network communication is based on a physical transport medium, such as special types of wired or fiber-optic cables, and the hardware-oriented network addresses required to send and receive packets from one specific device to another. At the highest layer, network communications are application-specific, but just below that are similarly high-level logical layers such as TCP and IP, where addresses follow the familiar AAA.BBB.CCC.DDD convention and the successful delivery and acknowledgment of packets is enforced by the system. The sum of all of these layers of network communications is known as a network stack. Different network stacks are used by different network architectures, each of which therefore has its own set of levels. The most well-known and general network stack is the stack formalized by the Open Systems Interconnect (OSI) Reference Model, and consists of the following layers, from highest to lowest: 1. 2. 3. 4. 5. 6. 7. Application layer Presentation layer Session layer Transport layer Network layer Data Link layer Physical layer
The OSI reference model provides many different layers to support a variety of network communications and protocols. The TCP/IP (Transmission Control Protocol/Internet Protocol) network stack has fewer levels, since it focuses on the requirements for TCP/IP. These are the following: 1. 2. 3. 4. Application layer Transport layer Internet layer Network Access layer
Linux Packet Filtering Overview
The packet filtering mechanism used by the current Linux kernel (2.6.xx) is a combination of a loadable kernel module framework and API called netfilter and an interface and associated and user-space administrative command called iptables. The iptables interface is one of several kernel modules 1
Each packet that is sent by a computer system goes through each of the layers in the network stack that it is using, beginning at the highest layer and proceeding to the lowest layer. Each layer wraps the packet
continued next page
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 module that implements and supports connection tracking. Throughout the rest of this eBook, I will collectively refer to this interface as iptables, since that is the interface that is most commonly associated with modern Linux firewalls and packet filtering. Iptables and the netfilter framework are actually the fourth generation of Linux packet filtering solutions. The original Linux packet filtering implementation, ipfw, was liberated from BSD-based systems and was introduced in Linux by Alan Cox in the 1.1 Linux kernel. It was designed to support the creation of simple IP firewalls and routers through packet inspection and filtering. The iwfwadmin tool and associated ipfw changes, which simplified creating ipfw-based firewalls, was added for the Linux 2.0 kernel and makes up the second generation. The third generation of Linux packet filtering, consisting of a major rewrite of the entire Linux networking layer and introducing the user-space ipchains tool, was introduced in the 2.1 kernel series. The current netfilter framework and iptables interface were introduced in the 2.4 kernel, and have been the standard mechanism for packet filtering, network address and port translation, and general packet manipulation (often referred to as packet mangling) in the 2.6 series of Linux kernels. Linux packet filtering works by inspecting incoming and outgoing packets and acting upon them based on filtering rules that have been loaded into the netfilter framework's filter table by the iptables command. By default, the iptables command supports three default sets of rules, known as chains, for filtering network packets using the information stored in the iptables filter table. These default chains are the INPUT, OUTPUT, and FORWARD chains. The rules in the INPUT chain are used to examine and process incoming packets intended for ports on the local machine. The rules in the OUTPUT chain are for examining and processing outgoing packets that are being sent from the local machine. The rules in the FORWARD chain are used to examine and process packets that are being routed through the local machine. Each of the default filtering rule chains can have its own set of filtering rules. In addition, you can also define other sets of rules and use them for your own purposes. Most modern Linux and other Unix-like systems come with predefined INPUT, OUTPUT, and FORWARD rule chains and automatically load them at boot time. When network connectivity or visibility problems arise, a quick and dirty diagnostic step is often 2
with its own set of headers to provide the information required by that layer while preserving the contents of the packet and the header information that was provided by each preceding layer. This is therefore often referred to as a packet's encapsulation phase. When a packet reaches its destination, the packet moves backwards through the list of layers, each layer stripping off and utilizing its header information until the data contained in the packet reaches the application that it is intended for, The packet filtering provided by the Linux kernel's netfilter package and related utilities takes place at the TCP/IP stack's Internet and Transport layers, and focuses on analyzing and acting upon the contents of the headers added by these layers. Focusing on these layers is what makes the Linux netfilter package such a powerful routing tool. Though it is possible to analyze and modify the headers used by the Network Access and Application layers and even the contents of a packet, this eBook (and the netfilter package in general) focuses on analyzing and manipulating the Transport and Internet layer packet headers. The IP protocol is the core of the TCP/IP stack's Internet layer, and is the protocol that is responsible for identifying the destination of a specific packet and routing that packet to its destination. The IP protocol encapsulates each Transport layer packet with information about the protocol (TCP, UDP, ICMP, and so on), the origin of the packet, and its destination, each address expressed in traditional dotted-quad IP address format (AAA.BBB.CCC.DDD). Finally, the IP protocol must also be able to fragment or recombine packets in order to suit the packet size of the network for which a packet is targeted. The IP protocol is a connectionless protocol, which means that no handshake is required in order to send or receive packets from other hosts, but also means that packet delivery is not confirmed or guaranteed. Both of these aspects of the IP protocol minimize network overhead and therefore maximize throughput at this level of the network stack. The TCP protocol resides on top of the IP protocol, and
continued next page
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 than this solution, and therefore leave kernel packet filtering disabled. A far better solution is to inspect the system's filtering rules and disable or fine-tune the specific rules that are causing the problem. Other netfilter-based modules use packet-matching tables other than the filter table. The NAT module uses the nat table, which contains three built-in rule chains: OUTPUT, POSTROUTING, and PREROUTING. Specialized packet manipulation operations use the mangle table, which contains pre-built FORWARD, INPUT, OUTPUT, PREROUTING, and POSTROUTING chains. The connection tracking module uses the raw table, which contains pre-configured OUTPUT and PREROUTING chains. You must have superuser privileges to examine, create, or modify any netfilter-based rule chains. You can do this by putting iptables commands in a script that is executed as part of the system's boot process, by running iptables commands manually when logged in as the root user, or by using a command such as sudo as a normal user to run the iptables commands with root privileges.
provides functions that negotiate and correctly set up connections with remote machines, confirm delivery and enforce that packets are received and processed in the right order. Each TCP packet also provides a checksum to validate the correct transmission of each packet. In order to support sequencing, the TCP protocol looks at a network connection as a continuous data stream delimited by a start and a stop signal. Initiating a TCP/IP connection begins with the originating host sending a single packet with the SYN bit set. The target host responds with a packet that has the SYN/ACK bits set, indicating that the connection was accepted, or the SYN/RST bits set, indicating that the connection was refused. If the target system responded with a SYNC/ACK packet, the originating host responds with an ACK packet that confirms that the connection was correctly established, and begins to transmit additional data. Within the context of an established connection, each 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 therefore be delivered to the target application in the correct order. When the connection is no longer needed, it is closed by either host sending a FIN packet, which the other host responds to with a FIN/ACK packet. At this point, only the host that received the FIN packet can continue to send data. When it is finished, it sends its own FIN packet, which the other host responds to with FIN/ACK, and the connection is completely and cleanly closed. Other protocols that are commonly used on top of the IP protocol are UDP (User Datagram Protocol) and ICMP (Internet Control Message Protocol). The former is a connectionless, stateless, protocol that supports networked data transmission without any error detection. ICMP messages are used for various types of error and status reporting between hosts.
Listing and Purging Current Rule Chains
As mentioned previously, most modern Linux systems come with some sort of iptables-based firewall installed. The iptables command's _l (list) option displays any current rules associated with the three default rule chains, as in the following example: # iptables -L Chain INPUT (policy ACCEPT) target prot opt source Chain FORWARD (policy ACCEPT) target prot opt source Chain OUTPUT (policy ACCEPT) target prot opt source
destination
destination
destination
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 following 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 DROP icmp -- anywhere
destination 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 processing 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 previous 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 network connection mechanism that is insecure (all standard telnet transmissions are done in the clear, without encryption) and has largely been replaced by Secure Shell (ssh) connections on most Linux systems. For example, the iptables 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 existing rule and would therefore never be reached: # iptables -L OUTPUT Chain OUTPUT (policy ACCEPT) target prot opt source DROP tcp -- anywhere
destination 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 system 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 ACCEPT tcp -- 198.168.0.0 REJECT tcp -- !198.168.0.0 icmp-port-unreachable
destination anywhere anywhere
tcp dpt:telnet tcp dpt:telnet reject-with
Similarly, you can block connections that are sent to specific destination addresses by using the iptables command'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 telnet 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 mentioned 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 PointTo-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 single outbound (-o) Ethernet interface. The third iptables command appends a rule to the standard iptables packet filtering 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 related 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 system'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.