Contents:
Methods of Attack
What Is a Firewall?
What Is IP Filtering?
Setting Up Linux for Firewalling
Three Ways We Can Do Filtering
Original IP Firewall (2.0 Kernels)
IP Firewall Chains (2.2 Kernels)
Netfilter and IP Tables (2.4 Kernels)
TOS Bit Manipulation
Testing a Firewall Configuration
A Sample Firewall Configuration
Security is increasingly important for companies and individuals alike. The Internet has provided them with a powerful tool to distribute information about themselves and obtain information from others, but it has also exposed them to dangers that they have previously been exempt from. Computer crime, information theft, and malicious damage are all potential dangers.
An unauthorized and unscrupulous person who gains access to a computer system may guess system passwords or exploit the bugs and idiosyncratic behavior of certain programs to obtain a working account on that machine. Once they are able to log in to the machine, they may have access to information that may be damaging, such as commercially sensitive information like marketing plans, new project details, or customer information databases. Damaging or modifying this type of data can cause severe setbacks to the company.
The safest way to avoid such widespread damage is to prevent unauthorized people from gaining network access to the machine. This is where firewalls come in.
WARNING: Constructing secure firewalls is an art. It involves a good understanding of technology, but equally important, it requires an understanding of the philosophy behind firewall designs. We won't cover everything you need to know in this book; we strongly recommend you do some additional research before trusting any particular firewall design, including any we present here.
There is enough material on firewall configuration and design to fill a whole book, and indeed there are some good resources that you might like to read to expand your knowledge on the subject. Two of these are:
-
Building Internet Firewalls
-
by D. Chapman and E. Zwicky (O'Reilly). A guide explaining how to design and install firewalls for Unix, Linux, and Windows NT, and how to configure Internet services to work with the firewalls.
-
Firewalls and Internet Security
-
by W. Cheswick and S. Bellovin (Addison Wesley). This book covers the philosophy of firewall design and implementation.
We will focus on the Linux-specific technical issues in this chapter. Later we will present a sample firewall configuration that should serve as a useful starting point in your own configuration, but as with all security-related matters, trust no one. Double check the design, make sure you understand it, and then modify it to suit your requirements. To be safe, be sure.
As a network administrator, it is important that you understand the nature of potential attacks on computer security. We'll briefly describe the most important types of attacks so that you can better understand precisely what the Linux IP firewall will protect you against. You should do some additional reading to ensure that you are able to protect your network against other types of attacks. Here are some of the more important methods of attack and ways of protecting yourself against them:
- Unauthorized access
-
This simply means that people who shouldn't use your computer services are able to connect and use them. For example, people outside your company might try to connect to your company accounting machine or to your NFS server.
There are various ways to avoid this attack by carefully specifying who can gain access through these services. You can prevent network access to all except the intended users.
- Exploitation of known weaknesses in programs
-
Some programs and network services were not originally designed with strong security in mind and are inherently vulnerable to attack. The BSD remote services (rlogin, rexec, etc.) are an example.
The best way to protect yourself against this type of attack is to disable any vulnerable services or find alternatives. With Open Source, it is sometimes possible to repair the weaknesses in the software.
- Denial of service
-
Denial of service attacks cause the service or program to cease functioning or prevent others from making use of the service or program. These may be performed at the network layer by sending carefully crafted and malicious datagrams that cause network connections to fail. They may also be performed at the application layer, where carefully crafted application commands are given to a program that cause it to become extremely busy or stop functioning.
Preventing suspicious network traffic from reaching your hosts and preventing suspicious program commands and requests are the best ways of minimizing the risk of a denial of service attack. It's useful to know the details of the attack method, so you should educate yourself about each new attack as it gets publicized.
- Spoofing
-
This type of attack causes a host or application to mimic the actions of another. Typically the attacker pretends to be an innocent host by following IP addresses in network packets. For example, a well-documented exploit of the BSD rlogin service can use this method to mimic a TCP connection from another host by guessing TCP sequence numbers.
To protect against this type of attack, verify the authenticity of datagrams and commands. Prevent datagram routing with invalid source addresses. Introduce unpredictablility into connection control mechanisms, such as TCP sequence numbers and the allocation of dynamic port addresses.
- Eavesdropping
-
This is the simplest type of attack. A host is configured to "listen" to and capture data not belonging to it. Carefully written eavesdropping programs can take usernames and passwords from user login network connections. Broadcast networks like Ethernet are especially vulnerable to this type of attack.
To protect against this type of threat, avoid use of broadcast network technologies and enforce the use of data encryption.
IP firewalling is very useful in preventing or reducing unauthorized access, network layer denial of service, and IP spoofing attacks. It not very useful in avoiding exploitation of weaknesses in network services or programs and eavesdropping.
A firewall is a secure and trusted machine that sits between a private network and a public network.[] The firewall machine is configured with a set of rules that determine which network traffic will be allowed to pass and which will be blocked or refused. In some large organizations, you may even find a firewall located inside their corporate network to segregate sensitive areas of the organization from other employees. Many cases of computer crime occur from within an organization, not just from outside.
Firewalls can be constructed in quite a variety of ways. The most sophisticated arrangement involves a number of separate machines and is known as a perimeter network. Two machines act as "filters" called chokes to allow only certain types of network traffic to pass, and between these chokes reside network servers such as a mail gateway or a World Wide Web proxy server. This configuration can be very safe and easily allows quite a great range of control over who can connect both from the inside to the outside, and from the outside to the inside. This sort of configuration might be used by large organizations.
Typically though, firewalls are single machines that serve all of these functions. These are a little less secure, because if there is some weakness in the firewall machine itself that allows people to gain access to it, the whole network security has been breached. Nevertheless, these types of firewalls are cheaper and easier to manage than the more sophisticated arrangement just described. Figure 9.1 illustrates the two most common firewall configurations.
The Linux kernel provides a range of built-in features that allow it to function quite nicely as an IP firewall. The network implementation includes code to do IP filtering in a number of different ways, and provides a mechanism to quite accurately configure what sort of rules you'd like to put in place. The Linux firewall is flexible enough to make it very useful in either of the configurations illustrated in Figure 9.1. Linux firewall software provides two other useful features that we'll discuss in separate chapters: IP Accounting (Chapter 10, IP Accounting) and IP masquerade (Chapter 11, IP Masquerade and Network Address Translation).
IP filtering is simply a mechanism that decides which types of IP datagrams will be processed normally and which will be discarded. By discarded we mean that the datagram is deleted and completely ignored, as if it had never been received. You can apply many different sorts of criteria to determine which datagrams you wish to filter; some examples of these are:
-
Protocol type: TCP, UDP, ICMP, etc.
-
Socket number (for TCP/UPD)
-
Datagram type: SYN/ACK, data, ICMP Echo Request, etc.
-
Datagram source address: where it came from
-
Datagram destination address: where it is going to
It is important to understand at this point that IP filtering is a network layer facility. This means it doesn't understand anything about the application using the network connections, only about the connections themselves. For example, you may deny users access to your internal network on the default telnet port, but if you rely on IP filtering alone, you can't stop them from using the telnet program with a port that you do allow to pass trhough your firewall. You can prevent this sort of problem by using proxy servers for each service that you allow across your firewall. The proxy servers understand the application they were designed to proxy and can therefore prevent abuses, such as using the telnet program to get past a firewall by using the World Wide Web port. If your firewall supports a World Wide Web proxy, their telnet connection will always be answered by the proxy and will allow only HTTP requests to pass. A large number of proxy-server programs exist. Some are free software and many others are commercial products. The Firewall-HOWTO discusses one popular set of these, but they are beyond the scope of this book.
The IP filtering ruleset is made up of many combinations of the criteria listed previously. For example, let's imagine that you wanted to allow World Wide Web users within the Virtual Brewery network to have no access to the Internet except to use other sites' web servers. You would configure your firewall to allow forwarding of:
-
datagrams with a source address on Virtual Brewery network, a destination address of anywhere, and with a destination port of 80 (WWW)
-
datagrams with a destination address of Virtual Brewery network and a source port of 80 (WWW) from a source address of anywhere
Note that we've used two rules here. We have to allow our data to go out, but also the corresponding reply data to come back in. In practice, as we'll see shortly, Linux simplifies this and allows us to specify this in one command.
To build a Linux IP firewall, it is necessary to have a kernel built with IP firewall support and the appropriate configuration utility. In all production kernels prior to the 2.2 series, you would use the ipfwadm utility. The 2.2.x kernels marked the release of the third generation of IP firewall for Linux called IP Chains. IP chains use a program similar to ipfwadm called ipchains. Linux kernels 2.3.15 and later support the fourth generation of Linux IP firewall called netfilter. The netfilter code is the result of a large redesign of the packet handling flow in Linux. The netfilter is a multifaceted creature, providing direct backward-compatible support for both ipfwadm and ipchains as well as a new alternative command called iptables. We'll talk about the differences between the three in the next few sections.
The Linux kernel must be configured to support IP firewalling. There isn't much more to it than selecting the appropriate options when performing a make menuconfig
of your kernel.[] We described how to do this is in Chapter 3, Configuring the Networking Hardware". In 2.2 kernels you should select the following options:
Networking options ---> [*] Network firewalls [*] TCP/IP networking [*] IP: firewalling [*] IP: firewall packet logging
In kernels 2.4.0 and later you should select this option instead:
Networking options ---> [*] Network packet filtering (replaces ipchains) IP: Netfilter Configuration ---> . <M> Userspace queueing via NETLINK (EXPERIMENTAL) <M> IP tables support (required for filtering/masq/NAT) <M> limit match support <M> MAC address match support <M> netfilter MARK match support <M> Multiple port match support <M> TOS match support <M> Connection state match support <M> Unclean match support (EXPERIMENTAL) <M> Owner match support (EXPERIMENTAL) <M> Packet filtering <M> REJECT target support <M> MIRROR target support (EXPERIMENTAL) . <M> Packet mangling <M> TOS target support <M> MARK target support <M> LOG target support <M> ipchains (2.2-style) support <M> ipfwadm (2.0-style) support
The ipfwadm (IP Firewall Administration) utility is the tool used to build the firewall rules for all kernels prior to 2.2.0. Its command syntax can be very confusing because it can do such a complicated range of things, but we'll provide some common examples that will illustrate the most important variations of these.
The ipfwadm utility is included in most modern Linux distributions, but perhaps not by default. There may be a specific software package for it that you have to install. If your distribution does not include it, you can obtain the source package from ftp.xos.nl in the /pub/linux/ipfwadm/ directory, and compile it yourself.
Just as for the ipfwadm utility, the ipchains utility can be somewhat baffling to use at first. It provides all of the flexibility of ipfwadm with a simplified command syntax, and additionally provides a "chaining" mechanism that allows you to manage multiple rulesets and link them together. We'll cover rule chaining in a separate section near the end of the chapter, because for most situations it is an advanced concept.
The ipchains command appears in most Linux distributions based on the 2.2 kernels. If you want to compile it yourself, you can find the source package from its developer's site at http://www.rustcorp.com/linux/ipchains/. Included in the source package is a wrapper script called ipfwadm-wrapper that mimics the ipfwadm command, but actually invokes the ipchains command. Migration of an existing firewall configuration is much more painless with this addition.
The syntax of the iptables utility is quite similar to that of the ipchains syntax. The changes are improvements and a result of the tool being redesigned to be extensible through shared libraries. Just as for ipchains, we'll present iptables equivalents of the examples so you can compare and contrast its syntax with the others.
The iptables utility is included in the netfilter source package available at http://www.samba.org/netfilter/. It will also be included in any Linux distribution based on the 2.4 series kernels.
We'll talk a bit about netfilter's huge step forward in a section of its own later in this chapter.
Consider how a Unix machine, or in fact any machine capable of IP routing, processes IP datagrams. The basic steps, shown in Figure 9.2 are:
-
The IP datagram is received. (1)
-
The incoming IP datagram is examined to determine if it is destined for a process on this machine.
-
If the datagram is for this machine, it is processed locally. (2)
-
If it is not destined for this machine, a search is made of the routing table for an appropriate route and the datagram is forwarded to the appropriate interface or dropped if no route can be found. (3)
-
Datagrams from local processes are sent to the routing software for forwarding to the appropriate interface. (4)
-
The outgoing IP datagram is examined to determine if there is a valid route for it to take, if not, it is dropped.
-
The IP datagram is transmitted. (5)
In our diagram, the flow 135 represents our machine routing data between a host on our Ethernet network to a host reachable via our PPP link. The flows 12 and 45 represent the data input and output flows of a network program running on our local host. The flow 432 would represent data flow via a loopback connection. Naturally data flows both into and out of network devices. The question marks on the diagram represent the points where the IP layer makes routing decisions.
The Linux kernel IP firewall is capable of applying filtering at various stages in this process. That is, you can filter the IP datagrams that come in to your machine, filter those datagrams being forwarded across your machine, and filter those datagrams that are ready to be transmitted.
In ipfwadm and ipchains, an Input rule applies to flow 1 on the diagram, a Forwarding rule to flow 3, and an Output rule to flow 5. We'll see when we discuss netfilter later that the points of interception have changed so that an Input rule is applied at flow 2, and an Output rule is applied at flow 4. This has important implications for how you structure your rulesets, but the general principle holds true for all versions of Linux firewalling.
This may seem unnecessarily complicated at first, but it provides flexibility that allows some very sophisticated and powerful configurations to be built.
The first generation IP firewall support for Linux appeared in the 1.1 series kernel. It was a port of the BSD ipfw firewall support to Linux by Alan Cox. The firewall support that appeared in the 2.0 series kernels and is the second generation was enhanced by Jos Vos, Pauline Middelink, and others.
The ipfwadm command was the configuration tool for the second generation Linux IP firewall. Perhaps the simplest way to describe the use of the ipfwadm command is by example. To begin, let's code the example we presented earlier.
Let's suppose that we have a network in our organization and that we are using a Linux-based firewall machine to connect our network to the Internet. Additionally, let's suppose that we wish the users of that network to be able to access web servers on the Internet, but to allow no other traffic to be passed.
We will put in place a forwarding rule to allow datagrams with a source address on our network and a destination socket of port 80 to be forwarded out, and for the corresponding reply datagrams to be forwarded back via the firewall.
Assume our network has a 24-bit network mask (Class C) and an address of 172.16.1.0. The rules we might use are:
#
ipfwadm -F -f
#
ipfwadm -F -p deny
#
ipfwadm -F -a accept -P tcp -S 172.16.1.0/24 -D 0/0 80
#
ipfwadm -F -a accept -P tcp -S 0/0 80 -D 172.16.1.0/24
The -F command-line argument tells ipfwadm that this is a forwarding rule. The first command instructs ipfwadm to "flush" all of the forwarding rules. This ensures we are working from a known state before we begin adding specific rules.
The second rule sets our default forwarding policy. We tell the kernel to deny or disallow forwarding of IP datagrams. It is very important to set the default policy, because this describes what will happen to any datagrams that are not specifically handled by any other rule. In most firewall configurations, you will want to set your default policy to "deny," as shown, to be sure that only the traffic you specifically allow past your firewall is forwarded.
The third and fourth rules are the ones that implement our requirement. The third command allows our datagrams out, and the fourth rule allows the responses back.
Let's review each of the arguments:
- -F
-
This is a Forwarding rule.
- -a accept
-
Append this rule with the policy set to "accept," meaning we will forward any datagrams that match this rule.
- -P tcp
-
This rule applies to tcp datagrams (as opposed to UDP or ICMP).
- -S 172.16.1.0/24
-
The Source address must have the first 24 bits matching those of the network address 172.16.1.0.
- -D 0/0 80
-
The destination address must have zero bits matching the address 0.0.0.0. This is really a shorthand notation for "anything." The 80 is the destination port, in this case WWW. You may also use any entry that appears in the /etc/services file to describe the port, so -D 0/0 www
would have worked just as well.
ipfwadm accepts network masks in a form with which you may not be familiar. The /nn
notation is a means of describing how many bits of the supplied address are significant, or the size of the mask. The bits are always counted from left to right; some common examples are listed in Table 9.1.
Table 9.1: Common Netmask Bit Values
Netmask |
Bits |
255.0.0.0 |
8 |
255.255.0.0 |
16 |
255.255.255.0 |
24 |
255.255.255.128 |
25 |
255.255.255.192 |
26 |
255.255.255.224 |
27 |
255.255.255.240 |
28 |
255.255.255.248 |
29 |
255.255.255.252 |
30 |
We mentioned earlier that ipfwadm implements a small trick that makes adding these sorts of rules easier. This trick is an option called -b, which makes the command a bidirectional rule.
The bidirectional flag allows us to collapse our two rules into one as follows:
#
ipfwadm -F -a accept -P tcp -S 172.16.1.0/24 -D 0/0 80 -b
Take a closer look at our ruleset. Can you see that there is still one method of attack that someone outside could use to defeat our firewall?
Our ruleset allows all datagrams from outside our network with a source port of 80 to pass. This will include those datagrams with the SYN bit set! The SYN bit is what declares a TCP datagram to be a connection request. If a person on the outside had privileged access to a host, they could make a connection through our firewall to any of our hosts, provided they use port 80 at their end. This is not what we intended.
Fortunately there is a solution to this problem. The ipfwadm command provides another flag that allows us to build rules that will match datagrams with the SYN bit set. Let's change our example to include such a rule:
#
ipfwadm -F -a deny -P tcp -S 0/0 80 -D 172.16.10.0/24 -y
#
ipfwadm -F -a accept -P tcp -S 172.16.1.0/24 -D 0/0 80 -b
The -y flag causes the rule to match only if the SYN flag is set in the datagram. So our new rule says: "Deny any TCP datagrams destined for our network from anywhere with a source port of 80 and the SYN bit set," or "Deny any connection requests from hosts using port 80."
Why have we placed this special rule before the main rule? IP firewall rules operate so that the first match is the rule that is used. Both rules would match the datagrams we want to stop, so we must be sure to put the deny
rule before the accept
rule.
After we've entered our rules, we ask ipfwadm to list them for us using the command:
#
ipfwadm -F -l
This command will list all of the configured forwarding rules. The output should look something like this:
#
ipfwadm -F -l
IP firewall forward rules, default policy: accept type prot source destination ports deny tcp anywhere 172.16.10.0/24 www -> any acc tcp 172.16.1.0/24 anywhere any -> www
The ipfwadm command will attempt to translate the port number into a service name using the /etc/services if an entry exists there. The default output is lacking in some important detail for us. In the default listing output, we can't see the effect of the -y
argument. The ipfwadm command is able to produce a more detailed listing output if you specify the -e
(extended output) argument too. We won't show the whole output here because it is too wide for the page, but it includes an opt
(options) column that shows the -y option controlling SYN packets:
#
ipfwadm -F -l -e
P firewall forward rules, default policy: accept pkts bytes type prot opt tosa tosx ifname ifaddress source ... 0 0 deny tcp --y- 0xFF 0x00 any any anywhere ... 0 0 acc tcp b--- 0xFF 0x00 any any 172.16.1.0/24 ...
The previous example was a simple one. Not all network services are as simple as the WWW service to configure; in practice, a typical firewall configuration would be much more complex. Let's look at another common example, this time FTP. We want our internal network users to be able to log into FTP servers on the Internet to read and write files. But we don't want people on the Internet to be able to log into our FTP servers.
We know that FTP uses two TCP ports: port 20 (ftp-data) and port 21 (ftp), so:
#
ipfwadm -a deny -P tcp -S 0/0 20 -D 172.16.1.0/24 -y
#
ipfwadm -a accept -P tcp -S 172.16.1.0/24 -D 0/0 20 -b
# #
ipfwadm -a deny -P tcp -S 0/0 21 -D 172.16.1.0/24 -y
#
ipfwadm -a accept -P tcp -S 172.16.1.0/24 -D 0/0 21 -b
Right? Well, not necessarily. FTP servers can operate in two different modes: passive mode and active mode.[] In passive mode, the FTP server listens for a connection from the client. In active mode, the server actually makes the connection to the client. Active mode is usually the default. The differences are illustrated in Figure 9.3. Many FTP servers make their data connection from port 20 when operating in active mode, which simplifies things for us a little, but unfortunately not all do.[]
But how does this affect us? Take a look at our rule for port 20, the FTP-data port. The rule as we have it now assumes that the connection will be made by our client to the server. This will work if we use passive mode. But it is very difficult for us to configure a satisfactory rule to allow FTP active mode, because we may not know in advance what ports will be used. If we open up our firewall to allow incoming connections on any port, we are exposing our network to attack on all services that accept connections.
The dilemna is most safely resolved by insisting that our users operate in passive mode. Most FTP servers and many FTP clients will operate this way. The popular ncftp client also supports passive mode, but it may require a small configuration change to make it default to passive mode. Many World Wide Web browsers such as the Netscape browser also support passive mode FTP, so it shouldn't be too hard to find appropriate software to use. Alternatively, you can avoid the issue entirely by using an FTP proxy server that accepts a connection from the internal network and establishes connections to the outside network.
In building your firewall, you will probably find a number of these sorts of problems. You should always give careful thought to how a service actually operates to be sure you have put in place an appropriate ruleset for it. A real firewall configuration can be quite complex.
The ipfwadm has many different arguments that relate to IP firewall configuration. The general syntax is:
ipfwadm category command parameters [options]
Let's take a look at each of these.
One and only one of the following must be supplied. The category tells the firewall what sort of firewall rule you are configuring:
- -I
-
Input rule
- -O
-
Output rule
- -F
-
Forwarding rule
At least one of the following must be supplied and applies only to those rules that relate to the supplied category. The command tells the firewall what action to take.
- -a [policy]
-
Append a new rule
- -i [policy]
-
Insert a new rule
- -d [policy]
-
Delete an existing rule
- -p policy
-
Set the default policy
- -l
-
List all existing rules
- -f
-
Flush all existing rules
The policies relevant to IP firewall and their meanings are:
- accept
-
Allows matching datagrams to be received, forwarded, or transmitted
- deny
-
Blocks matching datagrams from being received, forwarded, or transmitted
- reject
-
Blocks matching datagrams from being received, forwarded, or transmitted, and sends the host that sent the datagram and ICMP error message
At least one of the following must be supplied. Use the parameters to specify to which datagrams this rule applies:
- -P protocol
-
Can be TCP, UDP, ICMP, or all. Example:
-P tcp
- -S address[/mask] [port]
-
Source IP address that this rule will match. A netmask of "/32" will be assumed if you don't supply one. You may optionally specify which ports this rule will apply to. You must also specify the protocol using the -P argument described above for this to work. If you don't specify a port or port range, "all" ports will be assumed to match. Ports may be specified by name, using their /etc/services entry if you wish. In the case of the ICMP protocol, the port field is used to indicate the ICMP datagram types. Port ranges may be described; use the general syntax: lowport:highport. Here is an example:
-S 172.29.16.1/24 ftp:ftp-data
- -D address[/mask] [port]
-
Specify the destination IP address that this rule will match. The destination address is coded with the same rules as the source address described previously. Here is an example:
-D 172.29.16.1/24 smtp
- -V address
-
Specify the address of the network interface on which the packet is received (-I) or is being sent (-O). This allows us to create rules that apply only to certain network interfaces on our machine. Here is an example:
-V 172.29.16.1
- -W name
-
Specify the name of the network interface. This argument works in the same way as the -V argument, except you supply the device name instead of its address. Here is an example:
-W ppp0
These arguments are sometimes very useful:
- -b
-
This is used for bidirectional mode. This flag matches traffic flowing in either direction between the specified source and destination. This saves you from having to create two rules: one for the forward direction of a connection and one for the reverse.
- -o
-
This enables logging of matching datagrams to the kernel log. Any datagram that matches this rule will be logged as a kernel message. This is useful to enable you to detect unauthorized access.
- -y
-
This is used to match TCP connect datagrams. The option causes the rule to match only datagrams that attempt to establish TCP connections. Only datagrams that have their SYN bit set, but their ACK bit unset, will match. This is useful to filter TCP connection attempts and is ignored for other protocols.
- -k
-
This is used to match TCP acknowledgement datagrams. This option causes the rule to match only datagrams that are acknowledgements to packets attempting to establish TCP connections. Only datagrams that have their ACK bit set will match. This is useful to filter TCP connection attempts and is ignored for all other protocols.
Each of the firewall configuration commands allows you to specify ICMP datagram types. Unlike TCP and UDP ports, there is no convenient configuration file that lists the datagram types and their meanings. The ICMP datagram types are defined in RFC-1700, the Assigned Numbers RFC. The ICMP datagram types are also listed in one of the standard C library header files. The /usr/include/netinet/ip_icmp.h file, which belongs to the GNU standard library package and is used by C programmers when writing network software that uses the ICMP protocol, also defines the ICMP datagram types. For your convenience, we've listed them in Table 9.2. The iptables command interface allows you to specify ICMP types by name, so we've listed the mnemonics it uses, as well.
Table 9.2: ICMP Datagram Types
Type Number |
iptables Mnemonic |
Type Description |
0 |
echo-reply |
Echo Reply |
3 |
destination-unreachable |
Destination Unreachable |
4 |
source-quench |
Source Quench |
5 |
redirect |
Redirect |
8 |
echo-request |
Echo Request |
11 |
time-exceeded |
Time Exceeded |
12 |
parameter-problem |
Parameter Problem |
13 |
timestamp-request |
Timestamp Request |
14 |
timestamp-reply |
Timestamp Reply |
15 |
none |
Information Request |
16 |
none |
Information Reply |
17 |
address-mask-request |
Address Mask Request |
18 |
address-mask-reply |
Address Mask Reply |
Most aspects of Linux are evolving to meet the increasing demands of its users; IP firewall is no exception. The traditional IP firewall implementation is fine for most applications, but can be clumsy and inefficient to configure for complex environments. To solve this problem, a new method of configuring IP firewall and related features was developed. This new method was called "IP Firewall Chains" and was first released for general use in the 2.2.0 Linux kernel.
The IP Firewall Chains support was developed by Paul Russell and Michael Neuling.[] Paul has documented the IP Firewall Chains software in the IPCHAINS-HOWTO.
IP Firewall Chains allows you to develop classes of firewall rules to which you may then add and remove hosts or networks. An artifact of firewall rule chaining is that it may improve firewall performance in configurations in which there are lots of rules.
IP Firewall Chains are supported by the 2.2 series kernels and are also available as a patch against the 2.0.* kernels. The HOWTO describes where to obtain the patch and provides lots of useful hints about how to effectively use the ipchains configuration utility.
There are two ways you can use the ipchains utility. The first way is to make use of the ipfwadm-wrapper shell script, which is mostly a drop-in replacement for ipfwadm that drives the ipchains program in the background. If you want to do this, then read no further. Instead, reread the previous sections describing ipfwadm, and substitute ipfwadm-wrapper in its place. This will work, but there is no guarantee that the script will be maintained, and you will not be taking advantage of any of the advanced features that the IP Firewall Chains have to offer.
The second way to use ipchains is to learn its new syntax and modify any existing configurations you have to use the new syntax instead of the old. With some careful consideration, you may find you can optimize your configuration as you convert. The ipchains syntax is easier to learn than the ipfwadm, so this is a good option.
The ipfwadm manipulated three rulesets for the purpose of configuring firewalling. With IP Firewall Chains you can create arbitrary numbers of rulesets, each linked to one another, but there are three rulesets related to firewalling that are always present. The standard rulesets are direct equivalents of those used with ipfwadm, except they have names: input
, forward
and output
.
Let's first look at the general syntax of the ipchains command, then we'll look at how we'd use ipchains instead of ipfwadm without worrying about any of the advanced chaining features. We'll do this by revisiting our previous examples.
The ipchains command syntax is straightforward. We'll now look at the most important of those. The general syntax of most ipchains commands is:
ipchains command rule-specification options
There are a number of ways we can manipulate rules and rulesets with the ipchains command. Those relevant to IP firewalling are:
- -A chain
-
Append one or more rules to the end of the nominated chain. If a hostname is supplied as either source or destination and it resolves to more than one IP address, a rule will be added for each address.
- -I chain rulenum
-
Insert one or more rules to the start of the nominated chain. Again, if a hostname is supplied in the rule specification, a rule will be added for each of the addresses it resolves to.
- -D chain
-
Delete one or more rules from the specified chain that matches the rule specification.
- -D chain rulenum
-
Delete the rule residing at position rulenum in the specified chain. Rule positions start at one for the first rule in the chain.
- -R chain rulenum
-
Replace the rule residing at position rulenum in the specific chain with the supplied rule specification.
- -C chain
-
Check the datagram described by the rule specification against the specific chain. This command will return a message describing how the datagram was processed by the chain. This is very useful for testing your firewall configuration, and we look at it in detail a little later.
- -L [chain]
-
List the rules of the specified chain, or for all chains if no chain is specified.
- -F [chain]
-
Flush the rules of the specified chain, or for all chains if no chain is specified.
- -Z [chain]
-
Zero the datagram and byte counters for all rules of the specified chain, or for all chains if no chain is specified.
- -N chain
-
Create a new chain with the specified name. A chain of the same name must not already exist. This is how user-defined chains are created.
- -X [chain]
-
Delete the specified user-defined chain, or all user-defined chains if no chain is specified. For this command to be successful, there must be no references to the specified chain from any other rules chain.
- -P chain policy
-
Set the default policy of the specified chain to the specified policy. Valid firewalling policies are ACCEPT
, DENY
, REJECT
, REDIR
, or RETURN
. ACCEPT
, DENY
, and REJECT
have the same meanings as those for the tradition IP firewall implementation. REDIR
specifies that the datagram should be transparently redirected to a port on the firewall host. The RETURN
target causes the IP firewall code to return to the Firewall Chain that called the one containing this rule and continues starting at the rule after the calling rule.
A number of ipchains parameters create a rule specification by determining what types of packets match. If any of these parameters is omitted from a rule specification, its default is assumed:
- -p [!]protocol
-
Specifies the protocol of the datagram that will match this rule. Valid protocol names are tcp
, udp
, icmp
, or all
. You may also specify a protocol number here to match other protocols. For example, you might use 4
to match the ipip
encapsulation protocol. If the !
is supplied, the rule is negated and the datagram will match any protocol other than the protocol specified. If this parameter isn't supplied, it will default to all
.
- -s [!]address[/mask] [!] [port]
-
Specifies the source address and port of the datagram that will match this rule. The address may be supplied as a hostname, a network name, or an IP address. The optional mask
is the netmask to use and may be supplied either in the traditional form (e.g., /255.255.255.0) or the modern form (e.g., /24). The optional port
specifies the TCP or UDP port, or the ICMP datagram type that will match. You may supply a port specification only if you've supplied the -p parameter with one of the tcp
, udp
, or icmp
protocols. Ports may be specified as a range by specifying the upper and lower limits of the range with a colon as a delimiter. For example, 20:25
described all of the ports numbered from 20 up to and including 25. Again, the !
character may be used to negate the values.
- -d [!]address[/mask] [!] [port]
-
Specifies the destination address and port of the datagram that will match this rule. The coding of this parameter is the same as that of the -s parameter.
- -j target
-
Specifies the action to take when this rule matches. You can think of this parameter as meaning "jump to." Valid targets are ACCEPT
, DENY
, REJECT
, REDIR
, and RETURN
. We described the meanings of each of these targets earlier. However, you may also specify the name of a user-defined chain where processing will continue. If this parameter is omitted, no action is taken on matching rule datagrams at all other than to update the datagram and byte counters.
- -i [!]interface-name
-
Specifies the interface on which the datagram was received or is to be transmitted. Again, the !
inverts the result of the match. If the interface name ends with +
, then any interface that begins with the supplied string will match. For example, -i ppp+
would match any PPP network device and -i ! eth+
would match all interfaces except Ethernet devices.
- [!] -f
-
Specifies that this rule applies to everything but the first fragment of a fragmented datagram.
The following ipchains options are more general in nature. Some of them control rather esoteric features of the IP chains software:
- -b
-
Causes the command to generate two rules. One rule matches the parameters supplied, and the other rule added matches the corresponding parameters in the reverse direction.
- -v
-
Causes ipchains to be verbose in its output. It will supply more information.
- -n
-
Causes ipchains to display IP address and ports as numbers without attempting to resolve them to their corresponding names.
- -l
-
Enables kernel logging of matching datagrams. Any datagram that matches the rule will be logged by the kernel using its printk() function, which is usually handled by the sysklogd program and written to a log file. This is useful for making unusual datagrams visible.
- -o[maxsize]
-
Causes the IP chains software to copy any datagrams matching the rule to the userspace "netlink" device. The maxsize argument limits the number of bytes from each datagram that are passed to the netlink device. This option is of most use to software developers, but may be exploited by software packages in the future.
- -m markvalue
-
Causes matching datagrams to be marked with a value. Mark values are unsigned 32-bit numbers. In existing implementations this does nothing, but at some point in the future, it may determine how the datagram is handled by other software such as the routing code. If a markvalue begins with a +
or -
, the value is added or subtracted from the existing markvalue.
- -t andmask xormask
-
Enables you to manipulate the "type of service" bits in the IP header of any datagram that matches this rule. The type of service bits are used by intelligent routers to prioritize datagrams before forwarding them. The Linux routing software is capable of this sort prioritization. The andmask and xormask represent bit masks that will be logically ANDed and ORed with the type of service bits of the datagram respectively. This is an advanced feature that is discussed in more detail in the IPCHAINS-HOWTO.
- -x
-
Causes any numbers in the ipchains output to be expanded to their exact values with no rounding.
- -y
-
Causes the rule to match any TCP datagram with the SYN bit set and the ACK and FIN bits clear. This is used to filter TCP connection requests.
Let's again suppose that we have a network in our organization and that we are using a Linux-based firewall machine to allow our users access to WWW servers on the Internet, but to allow no other traffic to be passed.
If our network has a 24-bit network mask (class C) and has an address of 172.16.1.0, we'd use the following ipchains rules:
#
ipchains -F forward
#
ipchains -P forward DENY
#
ipchains -A forward -s 0/0 80 -d 172.16.1.0/24 -p tcp -y -j DENY
#
ipchains -A forward -s 172.16.1.0/24 -d 0/0 80 -p tcp -b -j ACCEPT
The first of the commands flushes all of the rules from the forward
rulesets and the second set of commands sets the default policy of the forward
ruleset to DENY
. Finally, the third and fourth commands do the specific filtering we want. The fourth command allows datagrams to and from web servers on the outside of our network to pass, and the third prevents incoming TCP connections with a source port of 80.
If we now wanted to add rules that allowed passive mode only access to FTP servers in the outside network, we'd add these rules:
#
ipchains -A forward -s 0/0 20 -d 172.16.1.0/24 -p tcp -y -j DENY
#
ipchains -A forward -s 172.16.1.0/24 -d 0/0 20 -p tcp -b -j ACCEPT
#
ipchains -A forward -s 0/0 21 -d 172.16.1.0/24 -p tcp -y -j DENY
#
ipchains -A forward -s 172.16.1.0/24 -d 0/0 21 -p tcp -b -j ACCEPT
To list our rules with ipchains, we use its -L argument. Just as with ipfwadm, there are arguments that control the amount of detail in the output. In its simplest form, ipchains produces output that looks like:
#
ipchains -L -n
Chain input (policy ACCEPT): Chain forward (policy DENY): target prot opt source destination ports DENY tcp -y---- 0.0.0.0/0 172.16.1.0/24 80 -> * ACCEPT tcp ------ 172.16.1.0/24 0.0.0.0/0 * -> 80 ACCEPT tcp ------ 0.0.0.0/0 172.16.1.0/24 80 -> * ACCEPT tcp ------ 172.16.1.0/24 0.0.0.0/0 * -> 20 ACCEPT tcp ------ 0.0.0.0/0 172.16.1.0/24 20 -> * ACCEPT tcp ------ 172.16.1.0/24 0.0.0.0/0 * -> 21 ACCEPT tcp ------ 0.0.0.0/0 172.16.1.0/24 21 -> * Chain output (policy ACCEPT):
If you don't supply the name of a chain to list, ipchains will list all rules in all chains. The -n
argument in our example tells ipchains not to attempt to convert any address or ports into names. The information presented should be self-explanatory.
A verbose form, invoked by the -u option, provides much more detail. Its output adds fields for the datagram and byte counters, Type of Service AND and XOR flags, the interface name, the mark, and the outsize.
All rules created with ipchains have datagram and byte counters associated with them. This is how IP Accounting is implemented and will be discussed in detail in Chapter 10. By default these counters are presented in a rounded form using the suffixes K
and M
to represent units of one thousand and one million, respectively. If the -x
argument is supplied, the counters are expanded to their full unrounded form.
You now know that the ipchains command is a replacement for the ipfwadm with a simpler command-line syntax and some interesting enhancements, but you're no doubt wanting to know where you'd use the user-defined chains and why. You'll also probably want to know how to use the support scripts that accompany the ipchains command in its software package. We'll now explore these subjects and address the questions.
The three rulesets of the traditional IP firewall code provided a mechanism for building firewall configurations that were fairly simple to understand and manage for small networks with simple firewalling requirements. When the configuration requirements are not simple, a number of problems become apparent. Firstly, large networks often require much more than the small number of firewalling rules we've seen so far; inevitably needs arise that require firewalling rules added to cover special case scenarios. As the number of rules grows, the performance of the firewall deterioriates as more and more tests are conducted on each datagram and managability becomes an issue. Secondly, it is not possible to enable and disable sets of rules atomically; instead, you are forced to expose yourself to attack while you are in the middle of rebuilding your ruleset.
The design of IP Firewall Chains helps to alleviate these problems by allowing the network administrator to create arbitrary sets of firwewall rules that we can link to the three inbuilt rulesets. We can use the -N option of ipchains to create a new chain with any name we please of eight characters or less. (Restricting the name to lowercase letters only is probably a good idea.) The -j option configures the action to take when a datagram matches the rule specification. The -j option specifies that if a datagram matches a rule, further testing should be performed against a user-defined chain. We'll illustrate this with a diagram.
Consider the following ipchains commands:
ipchains -P input DENY ipchains -N tcpin ipchains -A tcpin -s ! 172.16.0.0/16 ipchains -A tcpin -p tcp -d 172.16.0.0/16 ssh -j ACCEPT ipchains -A tcpin -p tcp -d 172.16.0.0/16 www -j ACCEPT ipchains -A input -p tcp -j tcpin ipchains -A input -p all
We set the default input chain policy to deny
. The second command creates a user-defined chain called "tcpin." The third command adds a rule to the tcpin
chain that matches any datagram that was sourced from outside our local network; the rule takes no action. This rule is an accounting rule and will be discussed in more detail in Chapter 10. The next two rules match any datagram that is destined for our local network and either of the ssh
or www
ports; datagrams matching these rules are accepted. The next rule is when the real ipchains magic begins. It causes the firewall software to check any datagram of protocol TCP against the tcpin user-defined chain. Lastly, we add a rule to our input
chain that matches any datagram; this is another accounting rule. They will produce the following Firewall Chains shown in Figure 9-4.
Our input
and tcpin
chains are populated with our rules. Datagram processing always beings at one of the inbuilt chains. We'll see how our user-defined chain is called into play by following the processing path of different types of datagrams.
First, let's look at what happens when a UDP datagram for one of our hosts is received. Figure 9.5 illustrates the flow through the rules.
The datagram is received by the input
chain and falls through the first two rules because they match ICMP and TCP protocols, respectively. It matches the third rule in the input
chain, but it doesn't specify a target, so its datagram and byte counters are updated, but no other action takes place. The datagram reaches the end of the input
chain, meets with the default input
chain policy, and is denied.
To see our user-defined chain in operation, let's now consider what happens when we receive a TCP datagram destined for the ssh
port of one of our hosts. The sequence is shown in Figure 9.6.
This time the second rule in the input
chain does match and it specifies a target of tcpin
, our user-defined chain. Specifying a user-defined chain as a target causes the datagram to be tested against the rules in that chain, so the next rule tested is the first rule in the tcpin
chain. The first rule matches any datagram that has a source address outside our local network and specifies no target, so it too is an accounting rule and testing falls through to the next rule. The second rule in our tcpin
chain does match and specifies a target of ACCEPT
. We have arrived at target, so no further firewall processing occurs. The datagram is accepted.
Finally, let's look at what happens when we reach the end of a user-defined chain. To see this, we'll map the flow for a TCP datagram destined for a port other than than the two we are handling specifically, as shown in Figure 9.7.
The user-defined chains do not have default policies. When all rules in a user-defined chain have been tested, and none have matched, the firewall code acts as though a RETURN
rule were present, so if this isn't what you want, you should ensure you supply a rule at the end of the user-defined chain that takes whatever action you wish. In our example, our testing returns to the rule in the input
ruleset immediately following the one that moved us to our user-defined chain. Eventually we reach the end of the input
chain, which does have a default policy and our datagram is denied.
This example is very simple, but illustrates our point. A more practical use of IP chains would be much more complex. A slightly more sophisticated example is provided in the following list of commands:
# # Set default forwarding policy to REJECT ipchains -P forward REJECT # # create our user-defined chains ipchains -N sshin ipchains -N sshout ipchains -N wwwin ipchains -N wwwout # # Ensure we reject connections coming the wrong way ipchains -A wwwin -p tcp -s 172.16.0.0/16 -y -j REJECT ipchains -A wwwout -p tcp -d 172.16.0.0/16 -y -j REJECT ipchains -A sshin -p tcp -s 172.16.0.0/16 -y -j REJECT ipchains -A sshout -p tcp -d 172.16.0.0/16 -y -j REJECT # # Ensure that anything reaching the end of a user-defined chain is rejected. ipchains -A sshin -j REJECT ipchains -A sshout -j REJECT ipchains -A wwwin -j REJECT ipchains -A wwwout -j REJECT # # divert www and ssh services to the relevant user-defined chain ipchains -A forward -p tcp -d 172.16.0.0/16 ssh -b -j sshin ipchains -A forward -p tcp -s 172.16.0.0/16 -d 0/0 ssh -b -j sshout ipchains -A forward -p tcp -d 172.16.0.0/16 www -b -j wwwin ipchains -A forward -p tcp -s 172.16.0.0/16 -d 0/0 www -b -j wwwout # # Insert our rules to match hosts at position two in our user-defined chains. ipchains -I wwwin 2 -d 172.16.1.2 -b -j ACCEPT ipchains -I wwwout 2 -s 172.16.1.0/24 -b -j ACCEPT ipchains -I sshin 2 -d 172.16.1.4 -b -j ACCEPT ipchains -I sshout 2 -s 172.16.1.4 -b -j ACCEPT ipchains -I sshout 2 -s 172.16.1.6 -b -j ACCEPT #
In this example, we've used a selection of user-defined chains both to simplify management of our firewall configuration and improve the efficiency of our firewall as compared to a solution involving only the built-in chains.
Our example creates user-defined chains for each of the ssh
and www
services in each connection direction. The chain called wwwout
is where we place rules for hosts that are allowed to make outgoing World Wide Web connections, and sshin
is where we define rules for hosts to which we want to allow incoming ssh connections. We've assumed that we have a requirement to allow and deny individual hosts on our network the ability to make or receive ssh
and www
connections. The simplication occurs because the user-defined chains allow us to neatly group the rules for the host incoming and outgoing permissions rather than muddling them all together. The improvement in efficiency occurs because for any particular datagram, we have reduced the average number of tests required before a target is found. The efficiency gain increases as we add more hosts. If we hadn't used user-defined chains, we'd potentially have to search the whole list of rules to determine what action to take with each and every datagram received. Even if we assume that each of the rules in our list matches an equal proportion of the total number of datagrams processed, we'd still be searching half the list on average. User-defined chains allow us to avoid testing large numbers of rules if the datagram being tested doesn't match the simple rule in the built-in chain that jumps to them.
The ipchains software package is supplied with three support scripts. The first of these we've discussed briefly already, while the remaining two provide an easy and convenient means of saving and restoring your firewall configuration.
The ipfwadm-wrapper script emulates the command-line syntax of the ipfwadm command, but drives the ipchains command to build the firewall rules. This is a convenient way to migrate your existing firewall configuration to the kernel or an alternative to learning the ipchains syntax. The ipfwadm-wrapper script behaves differently from the ipfwadm command in two ways: firstly, because the ipchains command doesn't support specification of an interface by address, the ipfwadm-wrapper script accepts an argument of -V but attempts to convert it into the ipchains equivalent of a -W by searching for the interface name configured with the supplied address. The ipfwadm-wrapper script will always provide a warning when you use the -V option to remind you of this. Secondly, fragment accounting rules are not translated correctly.
The ipchains-save and ipchains-restore scripts make building and modifying a firewall configuration much simpler. The ipchains-save command reads the current firewall configuration and writes a simplified form to the standard output. The ipchains-restore command reads data in the output format of the ipchains-save command and configures the IP firewall with these rules. The advantage of using these scripts over directly modifying your firewall configuration script and testing the configuration is the ability to dynamically build your configuration once and then save it. You can then restore that configuration, modify it, and resave it as you please.
To use the scripts, you'd enter something like:
ipchains-save >/var/state/ipchains/firewall.state
to save your current firewall configuration. You'd restore it, perhaps at boot time, with:
ipchains-restore </var/state/ipchains/firewall.state
The ipchains-restore script checks if any user-defined chain listed in its input already exists. If you've supplied the -f
argument, it will automatically flush the rules from the user-defined chain before configuring those in the input. The default behavior asks you whether to skip this chain or to flush it.
While developing IP Firewall Chains, Paul Russell decided that IP firewalling should be less difficult; he soon set about the task of simplifying aspects of datagram processing in the kernel firewalling code and produced a filtering framework that was both much cleaner and much more flexible. He called this new framework netfilter.
NOTE: At the time of preparation of this book the netfilter design had not yet stabilized. We hope you'll forgive any errors in the description of netfilter or its associated configuration tools that result from changes that occurred after preparation of this material. We considered the netfilter work important enough to justify the inclusion of this material, despite parts of it being speculative in nature. If you're in any doubt, the relevant HOWTO documents will contain the most accurate and up-to-date information on the detailed issues associated with the netfilter configuration.
So what was wrong with IP chains? They vastly improved the efficiency and management of firewall rules. But the way they processed datagrams was still complex, especially in conjunction with firewall-related features like IP masquerade (discussed in Chapter 11) and other forms of address translation. Part of this complexity existed because IP masquerade and Network Address Translation were developed independently of the IP firewalling code and integrated later, rather than having been designed as a true part of the firewall code from the start. If a developer wanted to add yet more features in the datagram processing sequence, he would have had difficulty finding a place to insert the code and would have been forced to make changes in the kernel in order to do so.
Still, there were other problems. In particular, the "input" chain described input to the IP networking layer as a whole. The input chain affected both datagrams to be destined for this host and datagrams to be routed by this host. This was somewhat counterintuitive because it confused the function of the input chain with that of the forward chain, which applied only to datagrams to be forwarded, but which always followed the input chain. If you wanted to treat datagrams for this host differently from datagrams to be forwarded, it was necessary to build complex rules that excluded one or the other. The same problem applied to the output chain.
Inevitably some of this complexity spilled over into the system administrator's job because it was reflected in the way that rulesets had to be designed. Moreover, any extensions to filtering required direct modifications to the kernel, because all filtering policies were implemented there and there was no way of providing a transparent interface into it. netfilter addresses both the complexity and the rigidity of older solutions by implementing a generic framework in the kernel that streamlines the way datagrams are processed and provides a capability to extend filtering policy without having to modify the kernel.
Let's take a look at two of the key changes made. Figure 9.8 illustrates how datagrams are processed in the IP chains implementation, while Figure 9.9 illustrates how they are processed in the netfilter implementation. The key differences are the removal of the masquerading function from the core code and a change in the locations of the input and output chains. To accompany these changes, a new and extensible configuration tool called iptables was created.
In IP chains, the input chain applies to all datagrams received by the host, irrespective of whether they are destined for the local host or routed to some other host. In netfilter, the input chain applies only to datagrams destined for the local host, and the forward chain applies only to datagrams destined for another host. Similarly, in IP chains, the output chain applies to all datagrams leaving the local host, irrespective of whether the datagram is generated on the local host or routed from some other host. In netfilter, the output chain applies only to datagrams generated on this host and does not apply to datagrams being routed from another host. This change alone offers a huge simplification of many firewall configurations.
In Figure 9.8, the components labeled "demasq" and "masq" are separate kernel components responsible for the incoming and outgoing processing of masqueraded datagrams. These have been reimplemented as netfilter modules.
Consider the case of a configuration for which the default policy for each of the input, forward, and output chains is deny
. In IP chains, six rules would be needed to allow any session through a firewall host: two each in the input, forward, and output chains (one would cover each forward path and one would cover each return path). You can imagine how this could easily become extremely complex and difficult to manage when you want to mix sessions that could be routed and sessions that could connect to the local host without being routed. IP chains allow you to create chains that would simplify this task a little, but the design isn't obvious and requires a certain level of expertise.
In the netfilter implementation with iptables, this complexity disappears completely. For a service to be routed across the firewall host, but not terminate on the local host, only two rules are required: one each for the forward and the reverse directions in the forward chain. This is the obvious way to design firewalling rules, and will serve to simplify the design of firewall configurations immensely.
The PACKET-FILTERING-HOWTO offers a detailed list of the changes that have been made, so let's focus on the more practical aspects here.
The remarkable flexibility of Linux netfilter is illustrated by its ability to emulate the ipfwadm and ipchains interfaces. Emulation makes transition to the new generation of firewall software a little easier.
The two netfilter kernel modules called ipfwadm.o and ipchains.o provide backward compatibility for ipfwadm and ipchains. You may load only one of these modules at a time, and use one only if the ip_tables.o module is not loaded. When the appropriate module is loaded, netfilter works exactly like the former firewall implementation.
netfilter mimics the ipchains interface with the following commands:
rmmod ip_tables modprobe ipchains ipchains ...
The iptables utility is used to configure netfilter filtering rules. Its syntax borrows heavily from the ipchains command, but differs in one very significant respect: it is extensible. What this means is that its functionality can be extended without recompiling it. It manages this trick by using shared libraries. There are standard extensions and we'll explore some of them in a moment.
Before you can use the iptables command, you must load the netfilter kernel module that provides support for it. The easiest way to do this is to use the modprobe command as follows:
modprobe ip_tables
The iptables command is used to configure both IP filtering and Network Address Translation. To facilitate this, there are two tables of rules called filter and nat. The filter table is assumed if you do not specify the -t option to override it. Five built-in chains are also provided. The INPUT
and FORWARD
chains are available for the filter
table, the PREROUTING
and POSTROUTING
chains are available for the nat
table, and the OUTPUT
chain is available for both tables. In this chapter we'll discuss only the filter table. We'll look at the nat table in Chapter 11
The general syntax of most iptables commands is:
iptables command rule-specification extensions
Now we'll take a look at some options in detail, after which we'll review some examples. There are a number of ways we can manipulate rules and rulesets with the iptables command. Those relevant to IP firewalling are:
- -A chain
-
Append one or more rules to the end of the nominated chain. If a hostname is supplied as either a source or destination and it resolves to more than one IP address, a rule will be added for each address.
- -I chain rulenum
-
Insert one or more rules to the start of the nominated chain. Again, if a hostname is supplied in the rule specification, a rule will be added for each of the addresses to which it resolves.
- -D chain
-
Delete one or more rules from the specified chain matching the rule specification.
- -D chain rulenum
-
Delete the rule residing at position rulenum in the specified chain. Rule positions start at 1 for the first rule in the chain.
- -R chain rulenum
-
Replace the rule residing at position rulenum in the specific chain with the supplied rule specification.
- -C chain
-
Check the datagram described by the rule specification against the specific chain. This command will return a message describing how the chain processed the datagram. This is very useful for testing your firewall configuration and we will look at it in detail later.
- -L [chain]
-
List the rules of the specified chain, or for all chains if no chain is specified.
- -F [chain]
-
Flush the rules of the specified chain, or for all chains if no chain is specified.
- -Z [chain]
-
Zero the datagram and byte counters for all rules of the specified chain, or for all chains if no chain is specified.
- -N chain
-
Create a new chain with the specified name. A chain of the same name must not already exist. This is how user-defined chains are created.
- -X [chain]
-
Delete the specified user-defined chain, or all user-defined chains if no chain is specified. For this command to be successful, there must be no references to the specified chain from any other rules chain.
- -P chain policy
-
Set the default policy of the specified chain to the specified policy. Valid firewalling policies are ACCEPT
, DROP
, QUEUE
, and RETURN
. ACCEPT
allows the datagram to pass. DROP
causes the datagram to be discarded. QUEUE
causes the datagram to be passed to userspace for further processing. The RETURN
target causes the IP firewall code to return to the Firewall Chain that called the one containing this rule, and continue starting at the rule after the calling rule.
There are a number of iptables parameters that constitute a rule specification. Wherever a rule specification is required, each of these parameters must be supplied or their default will be assumed.
- -p [!]protocol
-
Specifies the protocol of the datagram that will match this rule. Valid protocol names are tcp
, udp
, icmp
, or a number, if you know the IP protocol number.[] For example, you might use 4
to match the ipip
encapsulation protocol. If the !
character is supplied, the rule is negated and the datagram will match any protocol other than the specified protocol. If this parameter isn't supplied, it will default to match all protocols.
- -s [!]address[/mask]
-
Specifies the source address of the datagram that will match this rule. The address may be supplied as a hostname, a network name, or an IP address. The optional mask
is the netmask to use and may be supplied either in the traditional form (e.g., /255.255.255.0) or in the modern form (e.g., /24).
- -d [!]address[/mask]
-
Specifies the destination address and port of the datagram that will match this rule. The coding of this parameter is the same as that of the -s parameter.
- -j target
-
Specifies what action to take when this rule matches. You can think of this parameter as meaning "jump to." Valid targets are ACCEPT
, DROP
, QUEUE
, and RETURN
. We described the meanings of each of these previously in the "Commands" section. You may also specify the name of a user-defined chain where processing will continue. You may also supply the name of a target supplied by an extension. We'll talk about extensions shortly. If this parameter is omitted, no action is taken on matching datagrams at all, other than to update the datagram and byte counters of this rule.
- -i [!]interface-name
-
Specifies the interface on which the datagram was received. Again, the !
inverts the result of the match. If the interface name ends with "+
" then any interface that begins with the supplied string will match. For example, -i ppp+
would match any PPP network device and -i ! eth+
would match all interfaces except ethernet devices.
- -o [!]interface-name
-
Specifies the interface on which the datagram is to be transmitted. This argument has the same coding as the -i argument.
- [!] -f
-
Specifies that this rule applies only to the second and later fragments of a fragmented datagram, not to the first fragment.
The following iptables options are more general in nature. Some of them control rather esoteric features of the netfilter software.
- -v
-
causes iptables to be verbose in its output; it will supply more information.
- -n
-
causes iptables to display IP address and ports as numbers without attempting to resolve them to their corresponding names.
- -x
-
causes any numbers in the iptables output to be expanded to their exact values with no rounding.
- - -line-numbers
-
causes line numbers to be displayed when listing rulesets. The line number will correspond to the rule's position within the chain.
We said earlier that the iptables utility is extensible through optional shared library modules. There are some standard extensions that provide some of the features ipchains provided. To make use of an extension, you must specify its name through the -m name argument to iptables. The following list shows the -m and -p options that set up the extension's context, and the options provided by that extension.
- - -sport [!] [port[:port]]
-
Specifies the port that the datagram source must be using to match this rule. Ports may be specified as a range by specifying the upper and lower limits of the range using the colon as a delimiter. For example, 20:25
described all of the ports numbered 20 up to and including 25. Again, the !
character may be used to negate the values.
- - -dport [!] [port[:port]]
-
Specifies the port that the datagram destination must be using to match this rule. The argument is coded identically to the - -sport option.
- - -tcp-flags [!] mask comp
-
Specifies that this rule should match when the TCP flags in the datagram match those specified by mask and comp. mask is a comma-separated list of flags that should be examined when making the test. comp is a comma-separated list of flags that must be set for the rule to match. Valid flags are: SYN, ACK, FIN, RST, URG, PSH, ALL or NONE. This is an advanced option: refer to a good description of the TCP protocol, such as RFC-793, for a description of the meaning and implication of each of these flags. The !
character negates the rule.
- [!] - -syn
-
Specifies the rule to match only datagrams with the SYN
bit set and the ACK
and FIN
bits cleared. Datagrams with these options are used to open TCP connections, and this option can therefore be used to manage connection requests. This option is shorthand for:
- -tcp-flags SYN,RST,ACK SYN
When you use the negation operator, the rule will match all datagrams that do not have both the SYN
and ACK
bits set.
- - -sport [!] [port[:port]]
-
Specifies the port that the datagram source must be using to match this rule. Ports may be specified as a range by specifying the upper and lower limits of the range using the colon as a delimiter. For example, 20:25
describes all of the ports numbered 20 up to and including 25. Again, the !
character may be used to negate the values.
- - -dport [!] [port[:port]]
-
Specifies the port that the datagram destination must be using to match this rule. The argument is coded identically to the - -sport option.
- - -icmp-type [!] typename
-
Specifies the ICMP message type that this rule will match. The type may be specified by number or name. Some valid names are: echo-request
, echo-reply
, source-quench
, time-exceeded
, destination-unreachable
, network-unreachable
, host-unreachable
, protocol-unreachable
, and port-unreachable
.
- - -mac-source [!] address
-
Specifies the host's Ethernet address that transmitted the datagram that this rule will match. This only makes sense in a rule in the input or forward chains because we will be transmitting any datagram that passes the output chain.
To implement our naïve example using the netfilter, you could simply load the ipchains.o module and pretend it is the ipchains version. Instead, we'll reimplement it using iptables to illustrate how similar it is.
Yet again, let's suppose that we have a network in our organization and that we are using a Linux-based firewall machine to allow our users to be able to access WWW servers on the Internet, but to allow no other traffic to be passed.
If our network has a 24-bit network mask (class C) and has an address of 172.16.1.0, then we'd use the following iptables rules:
#
modprobe ip_tables
#
iptables -F FORWARD
#
iptables -P FORWARD DROP
#
iptables -A FORWARD -m tcp -p tcp -s 0/0 --sport 80 -d 172.16.1.0/24 / --syn -j DROP
#
iptables -A FORWARD -m tcp -p tcp -s 172.16.1.0/24 --sport / 80 -d 0/0 -j ACCEPT
#
iptables -A FORWARD -m tcp -p tcp -d 172.16.1.0/24 --dport 80 -s 0/0 -j / ACCEPT
In this example the iptables commands are interpreted exactly as the equivalent ipchains commands. The major exception that the ip_tables.o module must load. Note that iptables doesn't support the -b option, so we must supply a rule for each direction.
The Type Of Service (TOS) bits are a set of four-bit flags in the IP header. When any one of these bit flags is set, routers may handle the datagram differently than datagrams with no TOS bits set. Each of the four bits has a different purpose and only one of the TOS bits may be set at any time, so combinations are not allowed. The bit flags are called Type of Service bits because they enable the application transmitting the data to tell the network the type of network service it requires.
The classes of network service available are:
- Minimum delay
-
Used when the time it takes for a datagram to travel from the source host to destination host (latency) is most important. A network provider might, for example, use both optical fiber and satellite network connections. Data carried across satellite connections has farther to travel and their latency is generally therefore higher than for terrestrial-based network connections between the same endpoints. A network provider might choose to ensure that datagrams with this type of service set are not carried by satellite.
- Maximum throughput
-
Used when the volume of data transmitted in any period of time is important. There are many types of network applications for which latency is not particularly important but the network throughput is; for example, bulk-file transfers. A network provider might choose to route datagrams with this type of service set via high-latency, high-bandwidth routes, such as satellite connections.
- Maximum reliability
-
Used when it is important that you have some certainty that the data will arrive at the destination without retransmission being required. The IP protocol may be carried over any number of underlying transmission mediums. While SLIP and PPP are adequate datalink protocols, they are not as reliable as carrying IP over some other network, such as an X.25 network. A network provider might make an alternate network available, offering high reliability, to carry IP that would be used if this type of service is selected.
- Minimum cost
-
Used when it is important to minimize the cost of data transmission. Leasing bandwidth on a satellite for a transpacific crossing is generally less costly than leasing space on a fiber-optical cable over the same distance, so network providers may choose to provide both and charge differently depending on which you use. In this scenario, your "minimum cost" type of service bit may cause your datagrams to be routed via the lower-cost satellite route.
The ipfwadm and ipchains commands deal with the TOS bits in much the same manner. In both cases you specify a rule that matches the datagrams with particular TOS bits set, and use the -t argument to specify the change you wish to make.
The changes are specified using two-bit masks. The first of these bit masks is logically ANDed with the IP options field of the datagram and the second is logically eXclusive-ORd with it. If this sounds complicated, we'll give you the recipes required to enable each of the types of service in a moment.
The bit masks are specified using eight-bit hexadecimal values. Both ipfwadm and ipchains use the same argument syntax:
-t andmask xormask
Fortunately the same mask arguments can be used each time you wish to set a particular type of service, to save you having to work them out. They are presented with some suggested uses in Table 9.3.
Table 9.3: Suggested Uses for TOS Bitmasks
TOS |
ANDmask |
XORmask |
Suggested Use |
Minimum Delay |
0x01
|
0x10
|
ftp, telnet, ssh |
Maximum Throughput |
0x01
|
0x08
|
ftp-data, www |
Maximum Reliability |
0x01
|
0x04
|
snmp, dns |
Minimum Cost |
0x01
|
0x02
|
nntp, smtp |
The iptables tool allows you to specify rules that capture only datagrams with TOS bits matching some predetermined value using the -m tos option, and for setting the TOS bits of IP datagrams matching a rule using the -j TOS
target. You may set TOS bits only on the FORWARD
and OUTPUT
chains. The matching and the setting occur quite independently. You can configure all sort of interesting rules. For example, you can configure a rule that discads all datagrams with certain TOS bit combinations, or a rule that sets the TOS bits of datagrams only from certain hosts. Most often you will use rules that contain both matching and setting to perform TOS bit translations, just as you could for ipfwadm or ipchains.
Rather than the complicated two-mask configuration of ipfwadm and ipchains, iptables uses the simpler approach of plainly specifying what the TOS bits should match, or to what the TOS bits should be set. Additionally, rather than having to remember and use the hexadecimal value, you may specify the TOS bits using the more friendly mnemonics listed in the upcoming table.
The general syntax used to match TOS bits looks like:
-m tos --tos mnemonic [other-args] -j target
The general syntax used to set TOS bits looks like:
[other-args] -j TOS --set mnemonic
Remember that these would typically be used together, but they can be used quite independently if you have a configuration that requires it.
After you've designed an appropriate firewall configuration, it's important to validate that it does in fact do what you want it to do. One way to do this is to use a test host outside your network to attempt to pierce your firewall: this can be quite clumsy and slow, though, and is limited to testing only those addresses that you can actually use.
A faster and easier method is available with the Linux firewall implementation. It allows you to manually generate tests and run them through the firewall configuration just as if you were testing with actual datagrams. All varieties of the Linux kernel firewall software, ipfwadm, ipchains, and iptables, provide support for this style of testing. The implementation involves use of the relevant check command.
The general test procedure is as follows:
-
Design and configure your firewall using ipfwadm, ipchains, or iptables.
-
Design a series of tests that will determine whether your firewall is actually working as you intend. For these tests you may use any source or destination address, so choose some address combinations that should be accepted and some others that should be dropped. If you're allowing or disallowing only certain ranges of addresses, it is a good idea to test addresses on either side of the boundary of the range -- one address just inside the boundary and one address just outside the boundary. This will help ensure that you have the correct boundaries configured, because it is sometimes easy to specify netmasks incorrectly in your configuration. If you're filtering by protocol and port number, your tests should also check all important combinations of these parameters. For example, if you intend to accept only TCP under certain circumstances, check that UDP datagrams are dropped.
-
Develop ipfwadm, ipchains, or iptables rules to implement each test. It is probably worthwhile to write all the rules into a script so you can test and re-test easily as you correct mistakes or change your design. Tests use almost the same syntax as rule specifications, but the arguments take on slightly differing meanings. For example, the source address argument in a rule specification specifies the source address that datagrams matching this rule should have. The source address argument in test syntax, in contrast, specifies the source address of the test datagram that will be generated. For ipfwadm, you must use the -c option to specify that this command is a test, while for ipchains and iptables, you must use the -C option. In all cases you must always specify the source address, destination address, protocol, and interface to be used for the test. Other arguments, such as port numbers or TOS bit settings, are optional.
-
Execute each test command and note the output. The output of each test will be a single word indicating the final target of the datagram after running it through the firewall configuration -- that is, where the processing ended. For ipchains and iptables, user-specified chains will be tested in addition to the built-in ones.
-
Compare the output of each test against the desired result. If there are any discrepancies, you will need to analyse your ruleset to determine where you've made the error. If you've written your test commands into a script file, you can easily rerun the test after correcting any errors in your firewall configuration. It's a good practice to flush your rulesets completely and rebuild them from scratch, rather than to make changes dynamically. This helps ensure that the active configuration you are testing actually reflects the set of commands in your configuration script.
Let's take a quick look at what a manual test transcript would look like for our naïve example with ipchains. You will remember that our local network in the example was 172.16.1.0 with a netmask of 255.255.255.0, and we were to allow TCP connections out to web servers on the net. Nothing else was to pass our forward chain. Start with a transmission that we know should work, a connection from a local host to a web server outside:
#
ipchains -C forward -p tcp -s 172.16.1.0 1025 -d 44.136.8.2 80 -i eth0
accepted
Note the arguments had to be supplied and the way they've been used to describe a datagram. The output of the command indicates that that the datagram was accepted for forwarding, which is what we hoped for.
Now try another test, this time with a source address that doesn't belong to our network. This one should be denied:
#
ipchains -C forward -p tcp -s 172.16.2.0 1025 -d 44.136.8.2 80 -i eth0
denied
Try some more tests, this time with the same details as the first test, but with different protocols. These should be denied, too:
#
ipchains -C forward -p udp -s 172.16.1.0 1025 -d 44.136.8.2 80 -i eth0
denied #
ipchains -C forward -p icmp -s 172.16.1.0 1025 -d 44.136.8.2 80 -i eth0
denied
Try another destination port, again expecting it to be denied:
#
ipchains -C forward -p tcp -s 172.16.1.0 1025 -d 44.136.8.2 23 -i eth0
denied
You'll go a long way toward achieving peace of mind if you design a series of exhaustive tests. While this can sometimes be as difficult as designing the firewall configuration, it's also the best way of knowing that your design is providing the security you expect of it.
We've discussed the fundamentals of firewall configuration. Let's now look at what a firewall configuration might actually look like.
The configuration in this example has been designed to be easily extended and customized. We've provided three versions. The first version is implemented using the ipfwadm command (or the ipfwadm-wrapper script), the second uses ipchains, and the third uses iptables. The example doesn't attempt to exploit user-defined chains, but it will show you the similarities and differences between the old and new firewall configuration tool syntaxes:
#!/bin/bash ########################################################################## # IPFWADM VERSION # This sample configuration is for a single host firewall configuration # with no services supported by the firewall machine itself. ########################################################################## # USER CONFIGURABLE SECTION # The name and location of the ipfwadm utility. Use ipfwadm-wrapper for # 2.2.* kernels. IPFWADM=ipfwadm # The path to the ipfwadm executable. PATH="/sbin" # Our internal network address space and its supporting network device. OURNET="172.29.16.0/24" OURBCAST="172.29.16.255" OURDEV="eth0" # The outside address and the network device that supports it. ANYADDR="0/0" ANYDEV="eth1" # The TCP services we wish to allow to pass - "" empty means all ports # note: space separated TCPIN="smtp www" TCPOUT="smtp www ftp ftp-data irc" # The UDP services we wish to allow to pass - "" empty means all ports # note: space separated UDPIN="domain" UDPOUT="domain" # The ICMP services we wish to allow to pass - "" empty means all types # ref: /usr/include/netinet/ip_icmp.h for type numbers # note: space separated ICMPIN="0 3 11" ICMPOUT="8 3 11" # Logging; uncomment the following line to enable logging of datagrams # that are blocked by the firewall. # LOGGING=1 # END USER CONFIGURABLE SECTION ########################################################################### # Flush the Incoming table rules $IPFWADM -I -f # We want to deny incoming access by default. $IPFWADM -I -p deny # SPOOFING # We should not accept any datagrams with a source address matching ours # from the outside, so we deny them. $IPFWADM -I -a deny -S $OURNET -W $ANYDEV # SMURF # Disallow ICMP to our broadcast address to prevent "Smurf" style attack. $IPFWADM -I -a deny -P icmp -W $ANYDEV -D $OURBCAST # TCP # We will accept all TCP datagrams belonging to an existing connection # (i.e. having the ACK bit set) for the TCP ports we're allowing through. # This should catch more than 95 % of all valid TCP packets. $IPFWADM -I -a accept -P tcp -D $OURNET $TCPIN -k -b # TCP - INCOMING CONNECTIONS # We will accept connection requests from the outside only on the # allowed TCP ports. $IPFWADM -I -a accept -P tcp -W $ANYDEV -D $OURNET $TCPIN -y # TCP - OUTGOING CONNECTIONS # We accept all outgoing tcp connection requests on allowed TCP ports. $IPFWADM -I -a accept -P tcp -W $OURDEV -D $ANYADDR $TCPOUT -y # UDP - INCOMING # We will allow UDP datagrams in on the allowed ports. $IPFWADM -I -a accept -P udp -W $ANYDEV -D $OURNET $UDPIN # UDP - OUTGOING # We will allow UDP datagrams out on the allowed ports. $IPFWADM -I -a accept -P udp -W $OURDEV -D $ANYADDR $UDPOUT # ICMP - INCOMING # We will allow ICMP datagrams in of the allowed types. $IPFWADM -I -a accept -P icmp -W $ANYDEV -D $OURNET $UDPIN # ICMP - OUTGOING # We will allow ICMP datagrams out of the allowed types. $IPFWADM -I -a accept -P icmp -W $OURDEV -D $ANYADDR $UDPOUT # DEFAULT and LOGGING # All remaining datagrams fall through to the default # rule and are dropped. They will be logged if you've # configured the LOGGING variable above. # if [ "$LOGGING" ] then # Log barred TCP $IPFWADM -I -a reject -P tcp -o # Log barred UDP $IPFWADM -I -a reject -P udp -o # Log barred ICMP $IPFWADM -I -a reject -P icmp -o fi # # end.
Now we'll reimplement it using the ipchains command:
#!/bin/bash ########################################################################## # IPCHAINS VERSION # This sample configuration is for a single host firewall configuration # with no services supported by the firewall machine itself. ########################################################################## # USER CONFIGURABLE SECTION # The name and location of the ipchains utility. IPCHAINS=ipchains # The path to the ipchains executable. PATH="/sbin" # Our internal network address space and its supporting network device. OURNET="172.29.16.0/24" OURBCAST="172.29.16.255" OURDEV="eth0" # The outside address and the network device that supports it. ANYADDR="0/0" ANYDEV="eth1" # The TCP services we wish to allow to pass - "" empty means all ports # note: space separated TCPIN="smtp www" TCPOUT="smtp www ftp ftp-data irc" # The UDP services we wish to allow to pass - "" empty means all ports # note: space separated UDPIN="domain" UDPOUT="domain" # The ICMP services we wish to allow to pass - "" empty means all types # ref: /usr/include/netinet/ip_icmp.h for type numbers # note: space separated ICMPIN="0 3 11" ICMPOUT="8 3 11" # Logging; uncomment the following line to enable logging of datagrams # that are blocked by the firewall. # LOGGING=1 # END USER CONFIGURABLE SECTION ########################################################################## # Flush the Input table rules $IPCHAINS -F input # We want to deny incoming access by default. $IPCHAINS -P input deny # SPOOFING # We should not accept any datagrams with a source address matching ours # from the outside, so we deny them. $IPCHAINS -A input -s $OURNET -i $ANYDEV -j deny # SMURF # Disallow ICMP to our broadcast address to prevent "Smurf" style attack. $IPCHAINS -A input -p icmp -w $ANYDEV -d $OURBCAST -j deny # We should accept fragments, in ipchains we must do this explicitly. $IPCHAINS -A input -f -j accept # TCP # We will accept all TCP datagrams belonging to an existing connection # (i.e. having the ACK bit set) for the TCP ports we're allowing through. # This should catch more than 95 % of all valid TCP packets. $IPCHAINS -A input -p tcp -d $OURNET $TCPIN ! -y -b -j accept # TCP - INCOMING CONNECTIONS # We will accept connection requests from the outside only on the # allowed TCP ports. $IPCHAINS -A input -p tcp -i $ANYDEV -d $OURNET $TCPIN -y -j accept # TCP - OUTGOING CONNECTIONS # We accept all outgoing TCP connection requests on allowed TCP ports. $IPCHAINS -A input -p tcp -i $OURDEV -d $ANYADDR $TCPOUT -y -j accept # UDP - INCOMING # We will allow UDP datagrams in on the allowed ports. $IPCHAINS -A input -p udp -i $ANYDEV -d $OURNET $UDPIN -j accept # UDP - OUTGOING # We will allow UDP datagrams out on the allowed ports. $IPCHAINS -A input -p udp -i $OURDEV -d $ANYADDR $UDPOUT -j accept # ICMP - INCOMING # We will allow ICMP datagrams in of the allowed types. $IPCHAINS -A input -p icmp -w $ANYDEV -d $OURNET $UDPIN -j accept # ICMP - OUTGOING # We will allow ICMP datagrams out of the allowed types. $IPCHAINS -A input -p icmp -i $OURDEV -d $ANYADDR $UDPOUT -j accept # DEFAULT and LOGGING # All remaining datagrams fall through to the default # rule and are dropped. They will be logged if you've # configured the LOGGING variable above. # if [ "$LOGGING" ] then # Log barred TCP $IPCHAINS -A input -p tcp -l -j reject # Log barred UDP $IPCHAINS -A input -p udp -l -j reject # Log barred ICMP $IPCHAINS -A input -p icmp -l -j reject fi # # end.
In our iptables example, we've switched to using the FORWARD
ruleset because of the difference in meaning of the INPUT
ruleset in the netfilter implementation. This has implications for us; it means that none of the rules protect the firewall host itself. To accurately mimic our ipchains example, we would replicate each of our rules in the INPUT
chain. For clarity, we've dropped all incoming datagrams received from our outside interface instead.
#!/bin/bash ########################################################################## # IPTABLES VERSION # This sample configuration is for a single host firewall configuration # with no services supported by the firewall machine itself. ########################################################################## # USER CONFIGURABLE SECTION # The name and location of the ipchains utility. IPTABLES=iptables # The path to the ipchains executable. PATH="/sbin" # Our internal network address space and its supporting network device. OURNET="172.29.16.0/24" OURBCAST="172.29.16.255" OURDEV="eth0" # The outside address and the network device that supports it. ANYADDR="0/0" ANYDEV="eth1" # The TCP services we wish to allow to pass - "" empty means all ports # note: comma separated TCPIN="smtp,www" TCPOUT="smtp,www,ftp,ftp-data,irc" # The UDP services we wish to allow to pass - "" empty means all ports # note: comma separated UDPIN="domain" UDPOUT="domain" # The ICMP services we wish to allow to pass - "" empty means all types # ref: /usr/include/netinet/ip_icmp.h for type numbers # note: comma separated ICMPIN="0,3,11" ICMPOUT="8,3,11" # Logging; uncomment the following line to enable logging of datagrams # that are blocked by the firewall. # LOGGING=1 # END USER CONFIGURABLE SECTION ########################################################################### # Flush the Input table rules $IPTABLES -F FORWARD # We want to deny incoming access by default. $IPTABLES -P FORWARD deny # Drop all datagrams destined for this host received from outside. $IPTABLES -A INPUT -i $ANYDEV -j DROP # SPOOFING # We should not accept any datagrams with a source address matching ours # from the outside, so we deny them. $IPTABLES -A FORWARD -s $OURNET -i $ANYDEV -j DROP # SMURF # Disallow ICMP to our broadcast address to prevent "Smurf" style attack. $IPTABLES -A FORWARD -m multiport -p icmp -i $ANYDEV -d $OURNET -j DENY # We should accept fragments, in iptables we must do this explicitly. $IPTABLES -A FORWARD -f -j ACCEPT # TCP # We will accept all TCP datagrams belonging to an existing connection # (i.e. having the ACK bit set) for the TCP ports we're allowing through. # This should catch more than 95 % of all valid TCP packets. $IPTABLES -A FORWARD -m multiport -p tcp -d $OURNET --dports $TCPIN / ! --tcp-flags SYN,ACK ACK -j ACCEPT $IPTABLES -A FORWARD -m multiport -p tcp -s $OURNET --sports $TCPIN / ! --tcp-flags SYN,ACK ACK -j ACCEPT # TCP - INCOMING CONNECTIONS # We will accept connection requests from the outside only on the # allowed TCP ports. $IPTABLES -A FORWARD -m multiport -p tcp -i $ANYDEV -d $OURNET $TCPIN / --syn -j ACCEPT # TCP - OUTGOING CONNECTIONS # We will accept all outgoing tcp connection requests on the allowed / TCP ports. $IPTABLES -A FORWARD -m multiport -p tcp -i $OURDEV -d $ANYADDR / --dports $TCPOUT --syn -j ACCEPT # UDP - INCOMING # We will allow UDP datagrams in on the allowed ports and back. $IPTABLES -A FORWARD -m multiport -p udp -i $ANYDEV -d $OURNET / --dports $UDPIN -j ACCEPT $IPTABLES -A FORWARD -m multiport -p udp -i $ANYDEV -s $OURNET / --sports $UDPIN -j ACCEPT # UDP - OUTGOING # We will allow UDP datagrams out to the allowed ports and back. $IPTABLES -A FORWARD -m multiport -p udp -i $OURDEV -d $ANYADDR / --dports $UDPOUT -j ACCEPT $IPTABLES -A FORWARD -m multiport -p udp -i $OURDEV -s $ANYADDR / --sports $UDPOUT -j ACCEPT # ICMP - INCOMING # We will allow ICMP datagrams in of the allowed types. $IPTABLES -A FORWARD -m multiport -p icmp -i $ANYDEV -d $OURNET / --dports $ICMPIN -j ACCEPT # ICMP - OUTGOING # We will allow ICMP datagrams out of the allowed types. $IPTABLES -A FORWARD -m multiport -p icmp -i $OURDEV -d $ANYADDR / --dports $ICMPOUT -j ACCEPT # DEFAULT and LOGGING # All remaining datagrams fall through to the default # rule and are dropped. They will be logged if you've # configured the LOGGING variable above. # if [ "$LOGGING" ] then # Log barred TCP $IPTABLES -A FORWARD -m tcp -p tcp -j LOG # Log barred UDP $IPTABLES -A FORWARD -m udp -p udp -j LOG # Log barred ICMP $IPTABLES -A FORWARD -m udp -p icmp -j LOG fi # # end.
In many simple situations, to use the sample all you have to do is edit the top section of the file labeled "USER CONFIGURABLE section" to specify which protocols and datagrams type you wish to allow in and out. For more complex configurations, you will need to edit the section at the bottom, as well. Remember, this is a simple example, so scrutinize it very carefully to ensure it does what you want while implementing it.