Firewall

Published on May 2016 | Categories: Types, Instruction manuals | Downloads: 41 | Comments: 0 | Views: 624
of 79
Download PDF   Embed   Report

Comments

Content

Contents

Presented by:

Linux Firewalls
Third Edition

STEVE SUEHRING ROBERT ZIEGLER

Published by Pearson Education, Inc. 800 East 96th Street, Indianapolis, Indiana 46240 USA

Linux Firewalls, Third Edition
Copyright © 2006 by Pearson Education, Inc. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32771-6 Library of Congress Catalog Card Number: 2004098792 Printed in the United States of America First Printing: September 2005 08 07 06 05 4 3 2 1 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Novell Press cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Novell is a registered trademark, and Novell Press and the Novell Press logo are trademarks of Novell, Inc. in the United States and other countries. All brand names and product names used in this book are trade names, service marks, trademarks, or registered trademarks of their respective owners. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author(s) and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book. Special and Bulk Sales Pearson offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside of the U.S., please contact International Sales [email protected]

ACQUISITIONS EDITOR Linda Bump Harrison DEVELOPMENT EDITOR Scott Meyers MANAGING EDITOR Charlotte Clapp PROJECT EDITOR Mandie Frank COPY EDITOR Cheri Clark INDEXER Erika Millen PROOFREADER Kathy Bidwell TECHNICAL EDITOR A.J. Prowant PUBLISHING COORDINATOR Vanessa Evans BOOK DESIGNER Gary Adair PAGE LAYOUT Julie Parks

Novell Press is the exclusive publisher of trade computer technology books that have been authorized by Novell, Inc. Novell Press books are written and reviewed by the world’s leading authorities on Novell and related technologies, and are edited, produced, and distributed by the Que/Sams Publishing group of Pearson Education, the worldwide leader in integrated education and computer technology publishing. For more information on Novell Press and Novell Press books, please go to www.novellpress.com. Associate Publisher Mark Taber Program Manager, Novell, Inc. Darrin Vandenbos Marketing Manager Doug Ingersoll

ii

CHAPTER 4

Building and Installing a Standalone Firewall
Chapter 2, “Packet-Filtering Concepts,” covered the background ideas and
concepts behind a packet-filtering firewall. Each firewall rule chain has its own default policy. Each rule not only applies to an individual INPUT or OUTPUT chain, but also can apply to a specific network interface, message protocol type (such as TCP, UDP, or ICMP), and service port number. Individual acceptance, denial, and rejection rules are defined for the INPUT chain and the OUTPUT chain, as well as for the FORWARD chain, which you’ll learn about at the end of this chapter and in Chapter 6, “Packet Forwarding.” This chapter pulls together those ideas to demonstrate how to build a simple, single-system firewall for your site. The firewall that you’ll build in this chapter is based on a deny-everythingby-default policy. All network traffic is blocked by default. Services are individually enabled as exceptions to the policy. After the single-system firewall is built, Chapter 6 and Chapter 7, “NAT— Network Address Translation,” move on to demonstrate how to extend the standalone firewall to a dual-homed firewall. A multihomed firewall has at least two network interfaces. It insulates an internal LAN from direct communication with the Internet. It protects your internal LAN by applying packet-filtering rules at the two forwarding interfaces and, with the addition of Network Address Translation (NAT), by acting as a proxying gateway between the LAN and the Internet. NAT is not a proxy service, in the sense that it does not provide an intermediate termination point for the connection. NAT is proxy-like in the sense that the local hosts are hidden from the public Internet.

C H A P T E R 4 : Building and Installing a Standalone Firewall

The single-system and dual-homed firewalls are the least-secure forms of firewall architectures. If the firewall host were compromised, any local machines would be open to attack. As a standalone firewall, it’s an all-or-nothing proposition. A single-homed host is found most often in a DMZ hosting a public Internet service or in a residential setting. In the case of the single-system home or small-business setting, the assumption is that the majority of users have a single computer connected to the Internet or a single firewall machine protecting a small, private LAN. The assumption is that these sites simply don’t have the resources to extend the model to an architecture with additional levels of firewalls. The term “least secure” does not necessarily imply an insecure firewall, however. These firewalls are less secure than more complicated architectures involving multiple machines. Security is a compromise between available resources and diminishing returns on the next dollar spent. Chapter 6 introduces more secure configurations that allow for additional internal security protecting more complicated LAN and server configurations than a single-system firewall can.

iptables: The Linux Firewall Administration Program
This book is based on the 2.6 Linux kernel series, though much of it is applicable to the 2.4 kernel series as well. Most distributions of Linux come supplied with the Netfilter firewall mechanism introduced in Chapter 3, “iptables: The Linux Firewall Administration Program.” This mechanism is usually referred to as iptables, its administration program’s name. Older Linux distributions used the earlier IPFW mechanism. That firewall mechanism is usually referred to as ipfwadm or ipchains, the earlier version’s administration program names. iptables includes compatibility modules for both ipchains and ipfwadm. Some people might want to use one of these modules until their conversion to iptables is tested. As a firewall administration program, iptables creates the individual packet-filter rules for the INPUT and OUTPUT chains composing the firewall. One of the most important aspects of defining firewall rules is the order in which the rules are defined. Packet-filtering rules are stored in kernel tables, in an INPUT, OUTPUT, or FORWARD chain, in the order in which they are defined. Individual rules are inserted at the beginning of the chain or are appended to the end of the chain. All rules are appended in the examples in this chapter (with one exception at the end of the chapter). The order in which you define the rules is the order in which they’ll be added to the kernel tables and, thereby, the order in which the rules will be compared against each packet.

102

iptables: The Linux Firewall Administration Program

As each externally originating packet arrives at the network interface, its header fields are compared against each rule in the interface’s INPUT chain until a match is found. Conversely, as each locally generated packet is sent out, its header fields are compared against each rule in the interface’s OUTPUT chain until a match is found. In either direction, when a match is found, the comparison stops and the rule’s packet disposition is applied: ACCEPT, DROP, or, optionally, REJECT. If the packet doesn’t match any rule on the chain, the default policy for that chain is applied. The bottom line is that the first matching rule wins. The numeric service port numbers, rather than their symbolic names, as listed in /etc/ services, are used in all the filter examples in this chapter. iptables supports the symbolic service port names. The examples in this chapter use the numeric values because the symbolic names are not consistent across Linux distributions—or even from one release to the next. You could use the symbolic names for clarity in your own rules, but remember that your firewall could break with the next system upgrade. I’ve found it much more reliable to use the port numbers themselves. The last thing you want in a firewall is ambiguity, which is just what is introduced by using names instead of numbers for ports. Most Linux distributions implement iptables as a set of loadable program modules. Most or all of the modules are dynamically and automatically loaded on first use. If you choose to build your own kernel, which I nearly always do, you’ll need to compile in support for Netfilter, either as modules or directly into the kernel. The iptables command must be invoked once for each individual firewall rule you define. This is initially done from a shell script. This chapter will use a script called rc.firewall. The location of the script is dependent on the flavor of Linux where the script will be used. For example, on Red Hat and SUSE systems, the script should likely be within the /etc/rc.d/ directory whereas on Debian, /etc/init.d/ is the correct location. In cases in which shell semantics differ, the examples are written in Bourne (sh) or Bourne Again (bash) shell semantics. The shell script sets a number of variables. Chief among these is the location of the iptables command itself. It’s important to set this in a variable so that it is explicitly located. There’s no excuse for ambiguity with a firewall script. The variable used to represent the iptables command in this chapter is $IPT. If you see $IPT, it is a substitute for the iptables command. You could just as easily execute the commands from the shell by typing iptables instead of $IPT. However, for use in a script (which is the intention in this chapter), setting this variable is a good idea. The script should begin with the “shebang” line invoking the shell as the interpreter for the script. In other words, put this as the first line of the script:
#!/bin/sh

The examples are not optimized. They are spelled out for clarity. Firewall optimization and user-defined chains are discussed separately in Chapter 5, “Firewall Optimization.”
103

C H A P T E R 4 : Building and Installing a Standalone Firewall

Build Versus Buy: The Linux Kernel
There is great debate over whether it is advisable to compile a custom kernel or stick with the “stock” kernel that comes with a given Linux distribution. The debate also includes whether it is inherently better to compile a monolithic kernel (in which everything is compiled into the kernel) or use a modular kernel. As with any debate, there are pros and cons to each method. On the one hand there are those who always (or almost always) build their own kernel, sometimes called “rolling their own.” On the other hand, there are those who rarely or never roll their own kernel. There are those who always build monolithic kernels and others who use modular kernels. Building a custom kernel has a few advantages. First is the capability to compile in only the exact drivers and options necessary for the computer to run. This is great for a server such as a firewall because the hardware rarely, if ever, changes. Another advantage to compiling a custom kernel, if you choose a monolithic kernel, is the capability to completely prevent some types of attacks against the computer. Although attacks against monolithic kernels are possible, they are less common than attacks against modular kernels. Further, when you roll your own kernel you’re not confined to the kernel version used by the distribution. This enables you to use the latest and greatest kernel, which may include bug fixes for your hardware. Finally, with a custom kernel you can apply additional security enhancements to the kernel itself. One such enhancement is covered in Chapter 13, “Kernel Enhancements.” Building a custom kernel is not without its own set of pitfalls. After you roll your own kernel, you can no longer use the distribution’s kernel updates. Actually, you can revert to the distribution’s kernel and use the updates, but it’s likely that the distribution uses an earlier version of the kernel that may reintroduce bugs that were fixed in your custom version. Using a stock kernel also makes it easier to obtain support from the vendor for kernel issues. As alluded to earlier, I nearly always roll my own kernel for production server machines. The situations in which direct support is an absolute requirement are the only exceptions. These are few and far between. I believe the capability to customize the kernel to the computer and add greater security through additional patches far outweighs the need to use official kernel updates from the distribution.

Source and Destination Addressing Options
A packet’s source address and destination address can both be specified in a firewall rule. Only packets with that specific source or destination address match the rule. Addresses may be a specific IP address, a fully qualified hostname, a network (domain) name or address, a limited range of addresses, or all-inclusive.

104

iptables: The Linux Firewall Administration Program

IP ADDRESSES EXPRESSED AS SYMBOLIC NAMES Remote hosts and networks may be specified as fully qualified hostnames or network names. Using a hostname is especially convenient for firewall rules that apply to an individual remote host. This is particularly true for hosts whose IP address can change or that invisibly represent multiple IP addresses, such as ISP mail servers sometimes do. In general, however, remote addresses are better expressed in dotted quad notation because of the possibility of DNS host hostname spoofing. Symbolic hostnames can’t be resolved until DNS traffic is enabled in the firewall rules. If hostnames are used in the firewall rules, those rules must follow the rules enabling DNS traffic, unless /etc/hosts contains entries for the hostnames. Furthermore, some distributions such as Red Hat use a boot environment that installs the firewall rules before starting the network or any other services, including BIND. If symbolic host and network names are used in the firewall script, those names must have entries in /etc/hosts to be resolved.

iptables allows the address to be suffixed with a bit mask specifier. The mask’s value can range from 0 through 32, indicating the number of bits to mask. As discussed in Chapter 1, “Preliminary Concepts Underlying Packet-Filtering Firewalls,” bits are counted from the left, or most significant, bit. This mask specifier indicates how many of the leading bits in the address must exactly match the IP address specified. A mask of 32, /32, means that all the bits must match. The address must exactly match what you’ve defined in the rule. Specifying an address as 192.168.10.30 is the same as specifying the address as 192.168.10.30/32. The /32 mask is implied by default; you don’t need to specify it. An example using masking is to allow connections to a particular service to be made only between your machine and your ISP’s server machines. Let’s say that your ISP uses addresses in the range of 192.168.24.0 through 192.168.27.255 for its server address space. In this case, the address/mask pair would be 192.168.24/22. As shown in Figure 4.1, the first 22 bits of all addresses in this range are identical, so any address matching on the first 22 bits will match. Effectively, you are saying that you will allow connections to the service only when offered from machines in the address range 192.168.24.0 through 192.168.27.255. A mask of 0, /0, means that no bits in the address are required to match. In other words, because no bits need to match, using /0 is the same as not specifying an address. Any unicast address matches. iptables has a built-in alias for 0.0.0.0/0, any/0. Note that any/0, whether implied or stated, does not include broadcast addresses.

105

C H A P T E R 4 : Building and Installing a Standalone Firewall

FIGURE 4.1

The matching first 22 bits in the masked IP address range 192.168.24.0/22.
Decimal
192.168.24.0 192.168.27.255

Binary
11000000.10101000.00011000.00000000 11000000.10101000.00011011.11111111

Bit

31

24

21

16

10 8

0

Initializing the Firewall
A firewall is implemented as a series of packet-filtering rules defined by options on the iptables command line. iptables is executed once for each individual rule. (Different firewalls can range from a dozen rules to hundreds.) The iptables invocations should be made from an executable shell script, not directly from the command line. You should invoke the complete firewall shell script. Do not attempt to invoke specific iptables rules from the command line because this could cause your firewall to accept or drop packets inappropriately. When the chains are initialized and the default drop policy is enabled, all network services are blocked until acceptance filters are defined to allow the individual service. Ideally, you should execute the shell script from the console. Only the brave execute the firewall shell script from either a remote machine or an X Window xterm session. Not only is remote network traffic blocked, but access to the local loopback interface used by X Windows is blocked until access to the interface is explicitly reenabled. Ideally, X Windows should not be running nor even installed on a firewall. It is a typical example of software that is not necessary and has been used as a means to exploit servers in the past. As someone who manages Linux computers that are geographically hundreds to thousands of miles away, I can activate a firewall script only from a remote location. In these instances, it’s advisable to do two things. First, change the default policy to ACCEPT for the first or first few executions of the firewall script. Do this to debug the syntax of the script itself, not the rules. After the script is syntactically correct, change that policy back to DROP. A second and just as important tip for working with firewall scripts from remote locations is to create a cron job to stop the firewall at some point in the near future. Doing so will effectively allow you to enable the firewall and perform some testing but also enable you to get back into the computer if you lock yourself out through misplaced (or missing) rules. For example, when debugging a firewall script, I’ll create a cron entry to disable the firewall every 2 minutes. I can then safely run the firewall script and find out whether I’ve locked out my

106

Initializing the Firewall

SSH session. If indeed I have locked myself out, I merely wait a few minutes for the firewall script to run and shut the firewall down, giving me the opportunity to fix the script and try again. Furthermore, remember that firewall filters are applied in the order in which you’ve defined them on the INPUT or OUTPUT chain. The rules are appended to the end of their chain in the order in which you define them. The first matching rule wins. Because of this, firewall rules must be defined in a hierarchical order from most specific to more general rules. Firewall initialization is used to cover a lot of ground, including defining global constants used in the shell script, enabling kernel support services (when necessary), clearing out any existing rules in the firewall chains, defining default policies for the INPUT and OUTPUT chains, reenabling the loopback interface for normal system operation, denying access from any specific hosts or networks you’ve decided to block, and defining some basic rules to protect against bad addresses and to protect certain services running on unprivileged ports.

Symbolic Constants Used in the Firewall Examples
A firewall shell script is easiest to read and maintain if symbolic constants are used for recurring names and addresses. The following constants either are used throughout the examples in this chapter or are universal constants defined in the networking standards. This example also includes the “shebang” interpreter line from above as a friendly reminder:
#!/bin/sh IPT=”/sbin/iptables” INTERNET=”eth0” LOOPBACK_INTERFACE=”lo” IPADDR=”my.ip.address” MY_ISP=”my.isp.address.range” SUBNET_BASE=”my.subnet.network” SUBNET_BROADCAST=”my.subnet.bcast” LOOPBACK=”127.0.0.0/8” CLASS_A=”10.0.0.0/8” CLASS_B=”172.16.0.0/12” CLASS_C=”192.168.0.0/16” CLASS_D_MULTICAST=”224.0.0.0/4” CLASS_E_RESERVED_NET=”240.0.0.0/5” BROADCAST_SRC=”0.0.0.0” BROADCAST_DEST=”255.255.255.255” PRIVPORTS=”0:1023” UNPRIVPORTS=”1024:65535” # # # # # # # # # # # # # # # # # Location of iptables on your system Internet-connected interface however your system names it your IP address ISP server & NOC address range Your subnet’s network address Your subnet’s broadcast address reserved loopback address range class A private networks class B private networks class C private networks class D multicast addresses class E reserved addresses broadcast source address broadcast destination address well-known, privileged port range unprivileged port range

Constants not listed here are defined in the context of the specific rules they are used with.

107

C H A P T E R 4 : Building and Installing a Standalone Firewall

Enabling Kernel-Monitoring Support
Operating system support for various types of packet checking often overlaps with what the firewall can test for. When in doubt, aim for redundancy or defense in depth. From the commands shown in the following lines, icmp_echo_ignore_broadcasts instructs the kernel to drop ICMP echo-request messages directed to broadcast or multicast addresses. (Another facility, icmp_echo_ignore_all, drops any incoming echo-request message. It should be noted that ISPs often rely on ping to help diagnose local network problems, and DHCP sometimes relies on echo-request to avoid address collision.)
# Enable broadcast echo Protection echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

Source routing is rarely used legitimately today. Firewalls commonly drop all source-routed packets. These commands disable source routed packets:
# Disable Source Routed Packets for f in /proc/sys/net/ipv4/conf/*/accept_source_route; do echo 0 > $f done

TCP SYN cookies are a mechanism to attempt speedier detection of and recovery from SYN floods. This command enables SYN cookies:
# Enable TCP SYN Cookie Protection echo 1 > /proc/sys/net/ipv4/tcp_syncookies

ICMP redirect messages are sent to hosts by their adjacent routers. Their purpose is to inform the host that a shorter path is available. That is, the host and both routers are on the same network, and the new router is the router to which the original would send the packet as its next hop. Routers generate redirect messages for hosts; hosts do not. Hosts are required to honor and add the new gateway to their route cache, except in the cases indicated in RFC 1122, “Requirements for Internet Hosts—Communication Layers,” Section 3.2.2.2: “A Redirect message SHOULD be silently discarded if the new gateway address it specifies is not on the same connected (sub-) net through which the Redirect arrived [INTRO:2, Appendix A], or if the source of the Redirect is not the current first-hop gateway for the specified destination (see Section 3.3.1).” These commands enable redirects:
redirects
# Disable ICMP Redirect Acceptance for f in /proc/sys/net/ipv4/conf/*/accept_redirects; do echo 0 > $f done

108

Initializing the Firewall

# Don’t send Redirect Messages for f in /proc/sys/net/ipv4/conf/*/send_redirects; do echo 0 > $f done

attempts to implement source address validation as described in RFC 1812, “Requirements for IP Version 4 Routers,” Section 5.3.8. In short, packets are silently dropped if their source address is such that the host’s forwarding table would not route a packet with that destination address out the same interface on which the packet was received. According to RFC 1812, if implemented, routers should enable this feature by default. This form of address validation is often not enabled on routers, so these commands disable it:
rp_filter
# Drop Spoofed Packets coming in on an interface, which if replied to, # would result in the reply going out a different interface. for f in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 1 > $f done

log_martians

logs packets received with impossible addresses, as defined in RFC 1812, Section 5.3.7. Impossible source addresses include multicast or broadcast addresses, addresses in the 0 and 127 networks, and the Class E reserved space. Impossible destination addresses include address 0.0.0.0, host 0 on any network, any host on the 127 network, and Class E addresses.

Currently, the Linux network code checks for the previously mentioned addresses. It does not check for private class addresses (nor could it do so without knowledge of the network a given interface was connected to). log_martians does not affect packet validity checking; it merely affects logging, which is set here:
# Log packets with impossible addresses. for f in /proc/sys/net/ipv4/conf/*/log_martians; do echo 1 > $f done

Removing Any Preexisting Rules
The first thing to do when defining a set of filtering rules is to remove any existing rules from their chains. Otherwise, any new rules that you define will be added to the end of existing rules. Packets could easily match a preexisting rule before reaching the point in the chain that you are defining from this point on. Removal is called flushing the chain. Without an argument referring to a specific chain, the following command flushes all rules from all chains at once:

109

C H A P T E R 4 : Building and Installing a Standalone Firewall

# Remove any existing rules from all chains $IPT --flush $IPT -t nat --flush $IPT -t mangle --flush

The chains are empty, but any user-defined chains still exist. Flushing the chains does not affect the default policy state currently in effect. The next step would be to delete any user-defined chains. They can be deleted with the following commands:
$IPT -X $IPT -t nat -X $IPT -t mangle -X

Resetting Default Policies and Stopping the Firewall
So far, the firewall has set some defaults that can be used regardless of the state of the Netfilter firewall. Before setting the default policies to DROP, I’ll first reset the default policies to ACCEPT. This is useful for stopping the firewall completely, as you’ll see shortly. These lines set the default policy:
# Reset the default policy $IPT --policy INPUT ACCEPT $IPT --policy OUTPUT ACCEPT $IPT --policy FORWARD ACCEPT $IPT -t nat --policy PREROUTING ACCEPT $IPT -t nat --policy OUTPUT ACCEPT $IPT -t nat --policy POSTROUTING ACCEPT $IPT -t mangle --policy PREROUTING ACCEPT $IPT -t mangle --policy OUTPUT ACCEPT

Here’s a final addition to what I term to be the beginning of the firewall script, namely the code to enable the firewall to be stopped easily. With this code placed below the previous code, when you call the script with an argument of “stop” the script will flush, clear, and reset the default policies and the firewall will effectively stop:
if [ “$1” = “stop” ] then echo “Firewall completely stopped! exit 0 fi

WARNING: THIS HOST HAS NO FIREWALL RUNNING.”

110

Initializing the Firewall

Enabling the loopback Interface
You need to enable unrestricted loopback traffic. This enables you to run any local networkbased services that you choose—or that the system depends on—without having to worry about getting all the firewall rules specified. Local services rely on the loopback network interface. After the system boots, the system’s default policy is to accept all packets. Flushing any preexisting chains has no effect. However, if the firewall is being reinitialized and had previously used a deny-by-default policy, the drop policy would still be in effect. Without any acceptance firewall rules, the loopback interface would still be inaccessible. Because the loopback interface is a local, internal interface, the firewall can allow loopback traffic immediately:
# Unlimited traffic on the loopback interface $IPT -A INPUT -i lo -j ACCEPT $IPT -A OUTPUT -o lo -j ACCEPT

Defining the Default Policy
By default, you want the firewall to drop everything. The two available options for the built-in chains are ACCEPT and DROP. REJECT is not a legal policy in iptables. User-defined chains cannot be assigned default policies. Using a default policy of DROP, unless a rule is defined to either explicitly allow or reject a matching packet, packets are silently dropped. What you more likely want is to silently drop unwanted incoming packets, but to reject outgoing packets and return an ICMP error message to the local sender. The difference for the end user is that, for example, if someone at a remote site attempts to connect to your web server, that person’s browser hangs until his system returns a TCP timeout condition. There is no indication whether your site or your web server exists. On the other hand, if you attempt to connect to a remote web server, your browser receives an immediate error condition indicating that the operation isn’t allowed:
# Set the default policy to drop $IPT --policy INPUT DROP $IPT --policy OUTPUT DROP $IPT --policy FORWARD DROP

At this point, all network traffic other than local loopback traffic is blocked. This firewall host has only one network interface. The FORWARD policy isn’t necessary. Defining the FORWARD policy is a precaution for the future. For that reason, the following definitions should be added as well:

111

C H A P T E R 4 : Building and Installing a Standalone Firewall

$IPT -t nat --policy PREROUTING DROP $IPT -t nat --policy OUTPUT DROP $IPT -t nat --policy POSTROUTING DROP $IPT -t mangle --policy PREROUTING DROP $IPT -t mangle --policy OUTPUT DROP

DEFAULT POLICY RULES AND THE FIRST MATCHING RULE WINS The default policies appear to be exceptions to the first-matching-rule-wins scenario. The default policy commands are not position dependent. They aren’t rules, per se. A chain’s default policy is applied after a packet has been compared to each rule on the chain without a match. The default policies are defined first in the script to define the default packet disposition before any rules to the contrary are defined. If the policy commands were executed at the end of the script, and if the firewall script contained a syntax error causing it to exit prematurely, the default accept-everything policy could be in effect. If a packet didn’t match a rule (and rules are usually accept rules in a deny-everything-by-default firewall), the packet would fall off the end of the chain and be accepted by default. The firewall rules would not be accomplishing anything useful.

Stealth Scans and TCP State Flags
Testing for common forms of TCP stealth scans is possible because iptables gives access to all the TCP state flags. The following rules block common stealth scan probes. None of the TCP state combinations tested for are legal combinations. In addition, the unclean match is used first in order to match packets with bad headers and other problems. This module has been experimental for a while, so use with caution. Should you see an error when attempting to load this module, it may not be available with your kernel version. In such an event, comment out the unclean match line by using a single pound sign “#” in front of the line loading the unclean module. To reiterate statements made in Chapter 3, the first list of state flags lists the bits to be tested. Out of those bits, the second list of state flags lists the bits that must be set to match the test:
# Unclean $IPT -A INPUT -m unclean -j DROP # All of the bits are cleared $IPT -A INPUT -p tcp --tcp-flags ALL NONE -j DROP # SYN and FIN are both set $IPT -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP # SYN and RST are both set $IPT -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP # FIN and RST are both set

112

Initializing the Firewall

$IPT -A INPUT -p tcp --tcp-flags FIN,RST FIN,RST -j DROP # FIN is the only bit set, without the expected accompanying ACK $IPT -A INPUT -p tcp --tcp-flags ACK,FIN FIN -j DROP # PSH is the only bit set, without the expected accompanying ACK $IPT -A INPUT -p tcp --tcp-flags ACK,PSH PSH -j DROP # URG is the only bit set, without the expected accompanying ACK $IPT -A INPUT -p tcp --tcp-flags ACK,URG URG -j DROP

The ACK,FIN FIN test implicitly includes xmastree packets that contain FIN-PSH, FIN-URG, and FIN-PSH-URG as well.

Using Connection State to Bypass Rule Checking
Specifying the state match for previously initiated and accepted exchanges enables you to bypass the firewall tests for the ongoing exchange. The initial client request remains controlled by the service’s specific filters, however. Notice that both the INPUT and the OUTPUT filters are necessary to bypass the rules in both directions. A connection isn’t treated as a two-way exchange by the state module, and a symmetric dynamic rule is not generated. Because the state module can require more RAM than some Linux firewall machines have, the firewall example developed in this chapter provides the rules for both alternatives, with and without the state module. Remember that use of the state module allows you to bypass the standard firewall rules for ongoing exchanges under normal operation. The standard rules must be included, however, if the state table entry for a connection is recycled or times out.
INCLUDING BOTH STATIC AND DYNAMIC FIREWALL RULES Resource limits in terms of scalability and state table timeouts can require that both the static and the dynamic rules be used. The top limit is a selling point with large commercial firewalls. The scalability issue comes up in large firewalls designed to handle 50,000–100,000 simultaneous connections—that’s a lot of state. System resources run out at some point, and connection tracking can’t be done. Either the new connection has to be dropped or the software has to fall back to stateless mode. There’s also the issue of timeouts. Connection state isn’t kept forever. Slow and quiescent connections can have their state information easily cleaned out to make room for other more active connections. When a packet comes along later, the state information has to be rebuilt. In the meantime, the packet flow has to fall back to stateless mode while the transport stack looks up the connection information and informs the state module that the packet is indeed part of an established exchange:

113

C H A P T E R 4 : Building and Installing a Standalone Firewall

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT $IPT -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Using the state module alone, INVALID will break protocols that use # bi-directional connections or multiple connections or exchanges, # unless an ALG is provided for the protocol. At this time, FTP and # IRC are the only protocols with ALG support. $IPT -A INPUT -m state --state INVALID -j LOG \ --log-prefix “INVALID input: “ $IPT -A INPUT -m state --state INVALID -j DROP $IPT -A OUTPUT -m state --state INVALID -j LOG \ --log-prefix “INVALID output: “ $IPT -A OUTPUT -m state --state INVALID -j DROP fi

Source Address Spoofing and Other Bad Addresses
This section establishes some INPUT chain filters based on source and destination addresses. These addresses will never be seen in a legitimate incoming packet from the Internet. At the packet-filtering level, one of the few cases of source address spoofing that you can identify with certainty as a forgery is your own IP address. This rule drops incoming packets claiming to be from you:
# Refuse spoofed packets pretending to be from # the external interface’s IP address $IPT -A INPUT -i $INTERNET -s $IPADDR -j DROP

There is no need to block outgoing packets destined to yourself. They won’t return, claiming to be from you and appearing to be spoofed. Remember, if you send packets to your own external interface, those packets arrive on the loopback interface’s input queue, not on the external interface’s input queue. Packets containing your address as the source address never arrive on the external interface, even if you send packets to the external interface.
FIREWALL LOGGING The -j LOG target enables logging for packets matching the rule. When a packet matches the rule, the event is logged in /var/log/messages, or wherever you’ve defined messages of the specified priority to be logged.

114

Initializing the Firewall

As explained in Chapter 1 and Chapter 2, private IP addresses are set aside in each of the Class A, B, and C address ranges for use in private LANs. They are not intended for use on the Internet. Routers are not supposed to route packets with private source addresses. Nevertheless, some routers do forward packets containing private source addresses. Additionally, if someone on your ISP’s subnet (that is, on your side of the router that you share) is leaking packets with private IP addresses, you’ll see them even if the router doesn’t forward them. Machines on your own LAN could also leak private addresses if your NAT or proxy configuration is set up incorrectly. The next three sets of rules disallow incoming packets containing source addresses from any of the Class A, B, or C private network addresses. None of these packets should be seen on a public network:
# Refuse packets claiming to be from a Class A private network $IPT -A INPUT -i $INTERNET -s $CLASS_A -j DROP # Refuse packets claiming to be from a Class B private network $IPT -A INPUT -i $INTERNET -s $CLASS_B -j DROP # Refuse packets claiming to be from a Class C private network $IPT -A INPUT -i $INTERNET -s $CLASS_C -j DROP

The next rule disallows packets with a source address in the loopback network:
# Refuse packets claiming to be from the loopback interface $IPT -A INPUT -i $INTERNET -s $LOOPBACK -j DROP

Because loopback addresses are assigned to an internal, local software interface, any packet claiming to be from such an address is intentionally forged. As with addresses set aside for use in private LANs, routers are not supposed to forward packets originating from the loopback address range. A router cannot forward a packet with a loopback destination address. The next two rules primarily serve to log matching packets. The firewall’s default policy is to deny everything. As such, broadcast addresses are dropped by default and must be explicitly enabled if they are wanted:
# Refuse malformed broadcast packets $IPT -A INPUT -i $INTERNET -s $BROADCAST_DEST -j LOG $IPT -A INPUT -i $INTERNET -s $BROADCAST_DEST -j DROP $IPT -A INPUT $IPT -A INPUT -i $INTERNET -d $BROADCAST_SRC -i $INTERNET -d $BROADCAST_SRC -j LOG -j DROP

115

C H A P T E R 4 : Building and Installing a Standalone Firewall

The first pair of rules logs and denies any packet claiming to come from 255.255.255.255, the address reserved as the broadcast destination address. A packet will never legitimately originate from address 255.255.255.255. The second pair of rules logs and denies any packet directed to destination address 0.0.0.0, the address reserved as a broadcast source address. Such a packet is not a mistake; it is a specific probe intended to identify a UNIX machine running network software derived from BSD. Because most UNIX operating system network code is derived from BSD, this probe is effectively intended to identify machines running UNIX.
CLARIFICATION ON THE MEANING OF IP ADDRESS 0.0.0.0 Address 0.0.0.0 is reserved for use as a broadcast source address. The Netfilter convention of specifying a match on any address, any/0, 0.0.0.0/0, or 0.0.0.0/0.0.0.0, doesn’t match the broadcast source address. The reason is that a broadcast packet has a bit set in the Layer 2 frame header indicating that it’s a broadcast packet destined for all interfaces on the network, rather than a point-to-point, unicast packet destined for a particular destination. Broadcast packets are handled differently than nonbroadcast packets. There is no legitimate nonbroadcast IP address 0.0.0.0.

The next two rules block two forms of directed broadcasts:
# Refuse directed broadcasts # Used to map networks and in Denial of Service attacks $IPT -A INPUT -i $INTERNET -d $SUBNET_BASE -j DROP $IPT -A INPUT -i $INTERNET -d $SUBNET_BROADCAST -j DROP

With the deny-by-default policy and the firewall rules explicitly accepting packets based in part by matching on destination address, neither of these directed broadcast messages will be accepted by the firewall. These rules become more critical in larger setups in which the LAN uses real-world addresses. With the use of variable-length network prefixes, a site’s network and host fields may or may not fall on a byte boundary. For the sake of simplicity, the SUBNET_BASE is your network address, such as 192.168.1.0. The SUBNET_BROADCAST is your network’s broadcast address, as in 192.168.1.255. Just as with directed broadcast messages, limited broadcasts, confined to your local network segment, are likewise not accepted with the deny-by-default policy and the firewall rules explicitly accepting packets based in part by matching on destination address. Again, the following rule becomes more critical in larger setups in which the LAN uses real-world addresses:

116

Initializing the Firewall

# Refuse limited broadcasts $IPT -A INPUT -i $INTERNET -d $BROADCAST_DEST -j DROP

It should be noted that an exception must be made in later chapters for DHCP clients. Broadcast source and destination addresses are used between the DHCP client and server ports initially. Multicast addresses are legal only as destination addresses. The next rule drops spoofed multicast network packets:
# Refuse Class D multicast addresses # illegal as a source address $IPT -A INPUT -i $INTERNET -s $CLASS_D_MULTICAST -j DROP

Legitimate multicast packets are always UDP packets. As such, multicast messages are sent point-to-point, just as any other UDP message is. The difference between unicast and multicast packets is the class of destination address used (and the protocol flag carried in the Ethernet header). The next rule denies multicast packets carrying a non-UDP protocol:
$IPT -A INPUT -i $INTERNET -p ! udp -d $CLASS_D_MULTICAST -j DROP

Multicast functionality is a configurable option when you compile the kernel, and your network interface card can be initialized to recognize multicast addresses. The functionality is enabled by default in the default kernel from many newer distributions of Linux. You might want to enable these addresses if you subscribe to a network conferencing service that provides multicast audio and video broadcasts. (Multicast is also sometimes used on the local network for global resource discovery, such as with DHCP or routing.) You won’t generally see multicast destination addresses unless you’ve registered yourself as a recipient. Multicast packets are sent to multiple, but specific, targets by prior arrangement. I have seen multicast packets sent out from machines on my ISP’s local subnet, however. The default policy drops multicast packets, even if you have registered as a recipient. You have to define a rule to accept the multicast address. The next rule allows incoming multicast packets for the sake of completeness:
$IPT -A INPUT -i $INTERNET -p udp -d $CLASS_D_MULTICAST -j ACCEPT

Multicast registration and routing is a complicated process managed by its own IP layercontrol protocol, the Internet Group Management Protocol (IGMP, protocol 2). For more information on multicast communication, refer to the “Multicast over TCP/IP HOWTO” at http://www.tldp.org/HOWTO/Multicast-HOWTO.html. Additional resources include RFC 1458, “Requirements for Multicast Protocols”; RFC 1112, “Host Extensions for IP Multicasting” (updated by RFC 2236, “Internet Group Management Protocol Version 2”); and RFC 2588, “IP Multicast and Firewalls.”

117

C H A P T E R 4 : Building and Installing a Standalone Firewall

Class D IP addresses range from 224.0.0.0 to 239.255.255.255. The CLASS_D_MULTICAST constant, 224.0.0.0/4, is defined to match on the first 4 bits of the address. As shown in Figure 4.2, in binary, the decimal values 224 (11100000B) to 239 (11101111B) are identical through the first 4 bits (1110B).
FIGURE 4.2

The matching first 4 bits in the masked Class D multicast address range 224.0.0.0/4.
Decimal
224.0.0.0 239.255.255.255

Binary
11100000.00000000.00000000.00000000 11101111.11111111.11111111.11111111

Bit

31

28 24

16

8

0

The next rule in this section drops packets claiming to be from a Class E reserved network:
# Refuse Class E reserved IP addresses $IPT -A INPUT -i $INTERNET -s $CLASS_E_RESERVED_NET -j DROP

Class E IP addresses range from 240.0.0.0 to 247.255.255.255. The CLASS_E_RESERVED_NET constant, 240.0.0.0/5, is defined to match on the first 5 bits of the address. As shown in Figure 4.3, in binary, the decimal values 240 (11110000B) to 247 (11110111B) are identical through the first 5 bits (11110B).
FIGURE 4.3

The matching first 5 bits in the masked Class E reserved address range 240.0.0.0/5.
Decimal
224.0.0.0 247.255.255.255

Binary
11100000.00000000.00000000.00000000 11110111.11111111.11111111.11111111

Bit

31

27 24

16

8

4

0

The IANA ultimately manages the allocation and registration of the world’s IP address space. For more information on IP address assignments, see http://www.iana.org/_assignments/ ipv4-address-space. Some blocks of addresses are defined as reserved by the IANA. These addresses should not appear on the public Internet. Out of the entire set of the IANA’s reserved address blocks, the 0.0.0.0/8, Link Local Network, and Test Net spaces are blocks that will not be assigned as public addresses. The remaining reserved blocks are not routable until assigned. In the meantime, they can be used

118

Protecting Services on Assigned Unprivileged Ports

as source addresses in denial-of-service attacks. The firewall could block the remaining reserved blocks as source addresses, but it turns out to be impractical for most sites because the IANA has been actively allocating these blocks since year 2000. The following lines drop packets from those sources:
# # # # Refuse addresses 0.*.*.* 169.254.0.0/16 192.0.2.0/24 defined as reserved by the IANA - Can’t be blocked unilaterally with DHCP - Link Local Networks - TEST-NET

$IPT -A INPUT -i $INTERNET -s 0.0.0.0/8 -j DROP $IPT -A INPUT -i $INTERNET -s 169.254.0.0/16 -j DROP $IPT -A INPUT -i $INTERNET -s 192.0.2.0/24 -j DROP

Protecting Services on Assigned Unprivileged Ports
Services intended for local or private use, in particular, often run on unprivileged ports. For TCP-based services, a connection attempt to one of these services can be distinguished from an ongoing connection with a client using one of these unprivileged ports through the state of the SYN and ACK bits. Blocking connection requests is sufficient. UDP-based services must simply be blocked unless the state module is used. You should block incoming connection attempts to these ports for your own security protection. You want to block outgoing connection attempts to protect yourself and others from mistakes on your end and to log potential internal security problems. It’s safer to block these ports across the board and route related traffic on an exceptional, case-by-case basis.
OFFICIAL SERVICE PORT NUMBER ASSIGNMENTS Port numbers are assigned and registered by the IANA. The information was originally maintained as RFC 1700,“Assigned Numbers.” That RFC is now obsolete. The official information is dynamically maintained by the IANA at http://www.iana.org/assignments/port-numbers.

What kinds of mistakes might you need protection from? The worst mistake is offering dangerous services to the world, whether inadvertently or intentionally. A common mistake is running local network services that leak out to the Internet and bother other people. Another is allowing questionable outgoing traffic, such as port scans, whether this traffic is generated by accident or intentionally is sent out by someone on your machine. A deny-everything-bydefault firewall policy protects you from many mistakes of these types.
119

C H A P T E R 4 : Building and Installing a Standalone Firewall

THE PROBLEM WITH PORT SCANS Port scans are not harmful in themselves. They’re generated by network-analysis tools. The problem with port scans today is that they are usually generated by people with less-thanhonorable intentions. They are “analyzing” your network, not their own. Unfortunately, this leaves the merely curious looking guilty as well.

A deny-everything-by-default firewall policy enables you to run many private services behind the firewall without undue risk. These services must explicitly be allowed through the firewall to be accessible to remote hosts. This generalization is only an approximation of reality, however. Although TCP services on privileged ports are reasonably safe from all but a skilled and determined hacker, UDP services are inherently less secure, and some services are assigned to run on unprivileged ports. RPC services, usually run over UDP, are even more problematic. RPC-based services are bound to some port, often an unprivileged port. The portmap daemon maps between the RPC service number and the actual port number. A port scan can show where these RPC-based services are bound without going through the portmap daemon. Luckily, the use of portmap is becoming less and less common, so this isn’t as much of a concern as it was a number of years ago.

Common Local TCP Services Assigned to Unprivileged Ports
Some services, usually LAN services, are offered through an officially registered, well-known unprivileged port. Additionally, some services, such as FTP and IRC, use more complex communication protocols that don’t lend themselves well to packet filtering. The rules described in the following sections disallow local or remote client programs from initiating a connection to one of these ports. FTP is a good example of how the deny-by-default policy isn’t always enough to cover all the possible cases. The FTP protocol is covered later in this chapter. For now, the important idea is that FTP allows connections between two unprivileged ports. Because some services listen on registered unprivileged ports, and because the incoming connection request to these services is originating from an unprivileged client port, the rules allowing FTP can inadvertently allow incoming connections to these other local services as well. This situation is also an example of how firewall rules are logically hierarchical and order-dependent. The rules explicitly protecting a private, local service running on an unprivileged port must precede the FTP rules allowing access to the entire unprivileged port range. As a result, some of these rules appear to be redundant and will be redundant for some people. For other people running other services, the following rules are necessary to protect private services running on local unprivileged ports.

120

Protecting Services on Assigned Unprivileged Ports

DISALLOWING CONNECTIONS TO COMMON TCP UNPRIVILEGED SERVER PORTS Connections to remote X Window servers should be made over SSH, which automatically supports X Window connections. By specifying the --syn flag, indicating the SYN bit, only connection establishment to the server port is blocked. Other connections initiated using the port as a client port are not affected. X Window port assignment begins at port 6000 with the first running server. If additional servers are run, each is assigned to the next incremental port. As a small site, you’ll probably run a single X server, so your server will listen only on port 6000. Port 6063 is typically the highest assigned port, allowing 64 separate X Window managers running on a single machine, although ranges up to 6255 and 6999 are also seen sometimes:
XWINDOW_PORTS=”6000:6063” # (TCP) X Window

The first rule ensures that no outgoing connection attempts to remote X Window managers are made from your machine:
# X Window connection establishment $IPT -A OUTPUT -o $INTERNET -p tcp --syn \ --destination-port $XWINDOW_PORTS -j REJECT

The next rule blocks incoming connection attempts to your X Window manager. Local connections are not affected because local connections are made over the loopback interface:
# X Window: incoming connection attempt $IPT -A INPUT -i $INTERNET -p tcp --syn \ --destination-port $XWINDOW_PORTS -j DROP

The remaining TCP-based services can be blocked with a single rule by use of the multiport match extension. Blocking incoming connections isn’t necessary if the machine isn’t running the service, but it’s safer in the long run, in case you later decide to run the service locally. NFS usually binds to UDP port 2049 but can use TCP. You shouldn’t be running NFS on a firewall machine, but if you are, external access is denied. Connections to Open Window managers should not be allowed. Linux is not distributed with the Open Window manager. Incoming connections to port 2000 don’t need to be blocked. (This will not be the case later, when the firewall’s FORWARD rules are protecting other local hosts.) Attempts to connect to remote SOCKS servers are fairly common and often involve intrusion exploits. SOCKS uses port 1080.
squid

is a web cache and proxy server. squid uses port 3128 by default but can be configured to use a different port.

121

C H A P T E R 4 : Building and Installing a Standalone Firewall

The following rule blocks local clients from initiating a connection request to a remote NFS server, Open Window manager, SOCKS proxy server, or squid web cache server:
NFS_PORT=”2049” SOCKS_PORT=”1080” OPENWINDOWS_PORT=”2000” SQUID_PORT=”3128” # # # # (TCP) (TCP) (TCP) (TCP) NFS socks OpenWindows squid

# Establishing a connection over TCP to NFS, OpenWindows, SOCKS or squid $IPT -A OUTPUT -o $INTERNET -p tcp \ -m multiport --destination-port \ $NFS_PORT,$OPENWINDWS_PORT,$SOCKS_PORT,$SQUID_PORT \ --syn -j REJECT $IPT -A INPUT -i $INTERNET -p tcp \ -m multiport --destination-port \ $NFS_PORT,$OPENWINDWS_PORT,$SOCKS_PORT,$SQUID_PORT \ --syn -j DROP

Common Local UDP Services Assigned to Unprivileged Ports
TCP protocol rules can be handled more precisely than UDP protocol rules because of TCP’s connection establishment protocol. As a datagram service, UDP doesn’t have a connection state associated with it. Unless the state module is used, access to UDP services should simply be blocked. Explicit exceptions are made to accommodate DNS and any of the few other UDP-based Internet services you might use. Fortunately, the common UDP Internet services are often the type used between a client and a specific server. The filtering rules can often allow exchanges with one specific remote host. NFS is the main UNIX UDP service to be concerned with and also is one of the most frequently exploited. NFS runs on unprivileged port 2049. Unlike the previous TCP-based services, NFS is primarily a UDP-based service. It can be configured to run as a TCP-based service, but usually it isn’t. Associated with NFS is the RPC lock daemon, lockd, for NFS. lockd runs on UDP port 4045:
NFS_PORT=”2049” LOCKD_PORT=”4045” # NFS # RPC lockd for NFS

# NFS and lockd if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p udp \ -m multiport --destination-port $NFS_PORT,$LOCKD_PORT \ -m state --state NEW -j REJECT

122

Protecting Services on Assigned Unprivileged Ports

$IPT -A INPUT -i $INTERNET -p udp \ -m multiport --destination-port $NFS_PORT,$LOCKD_PORT \ -m state --state NEW -j DROP else $IPT -A OUTPUT -o $INTERNET -p udp \ -m multiport --destination-port $NFS_PORT,$LOCKD_PORT \ -j REJECT $IPT -A INPUT -i $INTERNET -p udp \ -m multiport --destination-port $NFS_PORT,$LOCKD_PORT \ -j DROP fi

THE TCP AND UDP SERVICE PROTOCOL TABLES The remainder of this chapter is devoted to defining rules to allow access to specific services. Client/server communication, for both TCP- and UDP-based services, involves some kind of twoway communication using a protocol specific to the service. As such, access rules are always represented as an I/O pair. The client program makes a query, and the server sends a response. Rules for a given service are categorized as client rules or server rules. The client category represents the communication required for your local clients to access remote servers. The server category represents the communication required for remote clients to access the services hosted from your machines. The application messages are encapsulated in either TCP or UDP transport protocol messages. Because each service uses an application protocol specific to itself, the particular characteristics of the TCP or UDP exchange are, to some extent, unique to the given service. The exchange between client and server is explicitly described by the firewall rules. Part of the purpose of firewall rules is to ensure protocol integrity at the packet level. Firewall rules, expressed in iptables syntax, are not especially human-readable, however. In each of the following sections, the service protocol at the packet-filtering level is presented as a table of state information, followed by the iptables rules expressing those states. Each row in the table lists a packet type involved in the service exchange. A firewall rule is defined for each individual packet type. The table is divided into columns:


Description contains a brief description of whether the packet is originating from the client or the server, and the packet’s purpose. Protocol is the transport protocol in use, TCP or UDP, or the IP protocol’s control messages, ICMP. Remote Address is the legal address, or range of addresses, that the packet can contain in the remote address field. Remote Port is the legal port, or range of ports, that the packet can contain in the remote port field.







123

C H A P T E R 4 : Building and Installing a Standalone Firewall



In/Out describes the packet’s direction—that is, whether it is coming into the system from a remote location or whether it is going out from the system to a remote location. Local Address is the legal address, or range of addresses, that the packet can contain in the local address field. Local Port is the legal port, or range of ports, that the packet can contain in the local port field. TCP protocol packets contain a final column, TCP Flag, defining the legal SYN-ACK states that the packet may have.







The table describes packets as either incoming or outgoing. Addresses and ports are described as either remote or local, relative to your machine’s network interface. Notice that, for incoming packets, Remote Address and Port refer to the source fields in the IP packet header; Local Address and Port refer to the destination fields in the IP packet header. For outgoing packets, Remote Address and Port refer to the destination fields in the IP packet header; Local Address and Port refer to the source fields in the IP packet header. Finally, in the few instances when the service protocol involves ICMP messages, notice that the IP Network-layer ICMP packets are not associated with the concept of a source or destination port, as is the case for Transport-layer TCP or UDP packets. Instead, ICMP packets use the concept of a control or status message type. ICMP messages are not sent to programs bound to particular service ports. Instead, ICMP messages are sent from one computer to another. (The ICMP packet contains a copy of at least some of the original packet that resulted in the error message. The receiving host identifies the process that the error refers to by examining the packet carried in the ICMP packet’s data area.) Consequently, the few ICMP packet entries presented in the tables use the source port column to contain the message type. For incoming ICMP packets, the source port column is the Remote Port column. For outgoing ICMP packets, the source port column is the Local Port column.

Enabling Basic, Required Internet Services
Only one service is truly required: the domain name service (DNS). DNS translates between hostnames and their associated IP addresses. You generally can’t locate a remote host without DNS unless the host is defined locally.

Allowing DNS (UDP/TCP Port 53)
DNS uses a communication protocol that relies on both UDP and TCP. Connection modes include regular client-to-server connections, peer-to-peer traffic between forwarding servers and full servers, and primary and secondary name server connections.

124

Enabling Basic, Required Internet Services

Query lookup requests are normally done over UDP, both for client-to-server lookups and for peer-to-peer server lookups. The UDP communication can fail for a lookup if the information being returned is too large to fit in a single UDP DNS packet. The server sets a flag bit in the DNS message header indicating that the data is truncated. In this case, the protocol allows for a retry over TCP. Figure 4.4 shows the relationship between UDP and TCP during a DNS lookup. In practice, TCP isn’t normally needed for queries. TCP is conventionally used for administrative zone transfers between primary and secondary name servers.
FIGURE 4.4

DNS client-to-server lookup.

DNS Client Port 14000 UDP Lookup Request UDP Server Response

DNS Server Port 53

UDP Lookup Request UDP Truncated Server Response

TCP Lookup Request TCP Server Response Time

Zone transfers are the transfer of a name server’s complete information about a network, or the piece (zone) of a network, that the server is authoritative for (that is, the official server). The authoritative name server is referred to as the primary name server. Secondary, or backup, name servers can periodically request zone transfers from their primary to keep their DNS caches up-to-date.

125

C H A P T E R 4 : Building and Installing a Standalone Firewall

For example, one of your ISP’s name servers is the primary, authoritative server for the ISP’s address space. ISPs often have multiple DNS servers to balance the load, as well as for backup redundancy. The other name servers are secondary name servers, refreshing their information from the master copy on the primary server. Zone transfers require careful access control between the primary and the secondary servers. A small system isn’t likely to be an authoritative name server for a public domain’s name space, nor is it likely to be a public backup server for that information. Larger sites could easily host both primary and secondary servers. Care must be taken that zone transfers are allowed only between these hosts. Numerous attacks have been successful because the attacker was able to grab a copy of an entire DNS zone and learn about the network topology in order to direct the attack at the most valuable assets. Table 4.1 lists the complete DNS protocol the firewall rules account for.
TABLE 4.1

DNS Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
53 53

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535

TCP FLAG

Local client query Remote server response Local client query Remote server response Local server query Remote server response Local zone transfer request Remote zone transfer request

UDP UDP

NAMESERVER NAMESERVER

Out In

IPADDR IPADDR

— —

TCP TCP

NAMESERVER NAMESERVER

53 53

Out In

IPADDR IPADDR

1024:65535 1024:65535

Any
ACK

UDP UDP

NAMESERVER NAMESERVER

53 53

Out In

IPADDR IPADDR

53 53

— —

TCP

Primary

53

Out

IPADDR

1024:65535

Any

TCP

Primary

53

In

IPADDR

1024:65535

ACK

126

Enabling Basic, Required Internet Services

TABLE 4.1

DNS Protocol (continued)
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
1024:65535 1024:65535 1024:65535 53 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
53 53 53 53 53

TCP FLAG

Remote client query Local server response Remote client query Local server response Remote zone transfer request Local zone transfer response

UDP UDP TCP UDP TCP

DNS client DNS client DNS client DNS client Secondary

In Out In Out In

IPADDR IPADDR IPADDR IPADDR IPADDR

— — Any — Any

TCP

Secondary

1024:65535

Out

IPADDR

53

ACK

ALLOWING DNS LOOKUPS AS A CLIENT The DNS resolver client isn’t a specific program. The client is incorporated into the network library code used by network programs. When a hostname requires a lookup, the resolver requests the lookup from a DNS server. Most computers are configured only as a DNS client. The server runs on a remote machine. For a home user, the name server is usually a machine owned by your ISP. As a client, the assumption is that your machine is not running a local DNS server; if it is, you should ensure that you need to actually run the name server. There’s no need to run extra services! Each client lookup goes through the resolver and is then sent to one of the remote name servers configured in /etc/resolv.conf. In general, it’s better to install the client rules even if a local server is used. You’ll avoid some confusing problems that could otherwise crop up at some point. These rules must be installed in the firewall tables before any other rules could successfully specify a remote host by name, rather than by IP address, unless the remote host had an entry in the local /etc/hosts file. DNS sends a lookup request as a UDP datagram:
NAMESERVER =”my.name.server” # (TCP/UDP) DNS

if [ “$CONNECTION_TRACKING” = “1” ]; then

127

C H A P T E R 4 : Building and Installing a Standalone Firewall

$IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NAMESERVER --dport 53 \ -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NAMESERVER --dport 53 -j ACCEPT $IPT -A INPUT -i $INTERNET -p udp \ -s $NAMESERVER --sport 53 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

If an error occurs because the returned data is too large to fit in a UDP datagram, the DNS client retries using a TCP connection. The next two rules are included for the rare occasion when the lookup response won’t fit in a DNS UDP datagram. They won’t be used in normal, day-to-day operations. You could run your system without problems for months on end without the TCP rules. Unfortunately, every so often your DNS lookups hang without these rules. More typically, these rules are used by a secondary name server requesting a zone transfer from its primary name server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NAMESERVER --dport 53 \ -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NAMESERVER --dport 53 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $NAMESERVER --sport 53 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

ALLOWING YOUR DNS LOOKUPS AS A FORWARDING SERVER Configuring a local forwarding name server can be a big performance gain. As shown in Figure 4.5, when BIND is configured as a caching and forwarding name server, it functions both as a local server and as a client to a remote DNS server. The difference between a direct client-to-server exchange and a forwarded server-to-server exchange is in the source and destination ports used. Instead of initiating an exchange from an unprivileged port, BIND initiates

128

Enabling Basic, Required Internet Services

the exchange from its own DNS port 53. (The query source port is now configurable. In newer versions of BIND, the local server makes its request from an unprivileged port, by default.) A second difference is that forwarding server lookups of this type are always done over UDP. (If the response is too large to fit in a UDP DNS packet, the local server must revert to standard client/server behavior to initiate the TCP request.)
FIGURE 4.5

A DNS forwarding server lookup.

DNS Client Port 14000

Local Forwarding DNS Server Port 53 UDP Lookup Request

Remote DNS Server Port 53

Cache Miss UDP Lookup Request

UDP Server Response UDP Server Response Cache the Response

UDP Lookup Request

Cache Hit UDP Server Response Time

DNS BIND PORT USAGE Historically, DNS servers used UDP port 53 as their source port when talking to other servers. This distinguished client traffic from server-initiated traffic because the client always uses a high, unprivileged port as its source. Later versions of BIND allow the server-to-server source port to be configurable and use the unprivileged ports by default. All examples in this book assume that BIND has been configured to use UDP port 53, rather than an unprivileged port, for server-to-server queries.

129

C H A P T E R 4 : Building and Installing a Standalone Firewall

Local client requests are sent to the local DNS server. The first time, BIND won’t have the lookup information, so it forwards the request to a remote name server. BIND caches the returned information and passes it on to the client. The next time the same information is requested, BIND finds it in its local cache (according to the record’s time to live [TTL]) and doesn’t do a remote request:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport 53 \ -d $NAMESERVER --dport 53 \ -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport 53 \ -d $NAMESERVER --dport 53 -j ACCEPT $IPT -A INPUT -i $INTERNET -p udp \ -s $NAMESERVER --sport 53 \ -d $IPADDR --dport 53 -j ACCEPT

If the lookup fails because of UDP packet size, the server will fall back to a TCP client-mode lookup. If the lookup fails because the remote server doesn’t have the information, the local server will query the root cache server. Because of this, the client rules would need to allow DNS traffic to any server, rather than to the specific servers listed in the local configuration. The alternative BIND configuration is to configure it not only as a forwarding server, but also as a slave to the remote servers specified in the BIND configuration file, named.conf. As a slave, the general client UDP rules aren’t required.

Filtering the AUTH User Identification Service (TCP Port 113)
The AUTH, or identd, user identification service is sometimes used when sending mail or posting a Usenet article. Some FTP sites are also configured to require a resolvable AUTH lookup. For logging purposes, the server initiates an AUTH request back to your machine to get the account name of the user who initiated the mail or news connection. Table 4.2 lists the complete client/server connection protocol for the AUTH service. It’s becoming much less common for this service to be required though, and therefore I wouldn’t recommend running it on your servers.

130

Enabling Basic, Required Internet Services

TABLE 4.2

identd Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
113 113 1024:65535 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 113 113

TCP FLAG

Local client query Remote server response Remote client query Local server response

TCP TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE ANYWHERE

Out In In Out

IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

ALLOWING YOUR OUTGOING AUTH REQUESTS AS A CLIENT Your machine would act as an AUTH client if you ran a mail or FTP server. Here are rules to allow your server to act as an AUTH client, should you choose to do so:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 113 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 113 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 113 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

FILTERING INCOMING AUTH REQUESTS TO YOUR SERVER Whether or not you decide to offer the service, you will likely receive incoming requests for the service when you send mail. If you run the identd server, the following rules enable incoming identd connection requests:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 113 \ -m state --state NEW -j ACCEPT fi

131

C H A P T E R 4 : Building and Installing a Standalone Firewall

$IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 113 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 113 \ --dport $UNPRIVPORTS -j ACCEPT

If you decide not to offer the service, it’s a good practice to reject the connection request to avoid waiting for the TCP connection timeout. This is the case only when an incoming packet is rejected rather than dropped, in these examples:
$IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 113 -j REJECT --reject-with tcp-reset

Alternatively, you could use the accept rules but not run the identd server. The result would be the same: The TCP layer would return a TCP RST message to the sender.

Enabling Common TCP Services
It’s likely that no one will want to enable all the services listed in this section, but most everyone will want to enable some subset of them. These are the services most often used over the Internet today. As such, this section is more of a reference section than anything else. This section provides rules for the following:
■ ■ ■ ■ ■ ■ ■ ■

Email Usenet Telnet SSH FTP Web services Whois RealAudio, RealVideo, and QuickTime

Many other services are available that aren’t covered here. Some of them are used on specialized servers, some are used by large businesses and organizations, and some are designed for use in local, private networks. Additional LAN and DMZ services are covered in Chapter 6.

132

Enabling Common TCP Services

Email (TCP SMTP Port 25, POP Port 110, IMAP Port 143)
Email is a service that almost everyone wants. How mail is set up depends on your ISP, your connection type, and your own choices. Email is sent across the network using the SMTP protocol assigned to TCP service port 25. Email is commonly received locally through one of three different protocols—SMTP, POP, or IMAP—depending on the services your ISP provides and on your local configuration. SMTP is the general mail protocol. Mail is delivered to the destination host machine, as defined most commonly by the MX record in the DNS for the given domain. The endpoint mail server determines whether the mail is deliverable (addressed to a valid user account on the machine) and then delivers it to the user’s local mailbox. POP and IMAP are mail-retrieval services. POP runs on TCP port 110. IMAP runs on TCP port 143. ISPs commonly make incoming mail available to their customers using one or both of these two services. Both services are usually authenticated by username and password. As far as mail retrieval is concerned, the difference between SMTP and POP or IMAP is that SMTP receives incoming mail and queues it in the user’s local mailbox. POP and IMAP retrieve mail into the user’s local mail program from the user’s ISP, where the mail had been queued remotely in the user’s SMTP mailbox at the ISP. Table 4.3 lists the complete client/server connection protocols for SMTP, POP, and IMAP. SMTP also uses specialized delivery mechanisms that your local network might use, such as ETRN, that effectively transfer all mail for a given domain for local processing.
TABLE 4.3

SMTP, POP, and IMAP Mail Protocols
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
25 25 1024:65535 1024:65536 110 110

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 25 25 1024:65535 1024:65535

TCP FLAG

Send outgoing mail Remote server response Receive incoming mail Local server response Local client query Remote server response

TCP TCP TCP TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE ANYWHERE POP SERVER POP SERVER

Out In In Out Out In

IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

Any
ACK

133

C H A P T E R 4 : Building and Installing a Standalone Firewall

TABLE 4.3

SMTP, POP, and IMAP Mail Protocols (continued)
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
1024:65535 1024:65535 143 143 1024:65535 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
110 110 1024:65535 1024:65535 143 143

TCP FLAG

Remote client query Local server response Local client query Remote server response Remote client query Local server response

TCP TCP TCP TCP TCP TCP

POP CLIENT POP CLIENT IMAP SERVER IMAP SERVER IMAP CLIENT IMAP CLIENT

In Out Out In In Out

IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

Any
ACK

SENDING MAIL OVER SMTP (TCP PORT 25) Mail is sent over SMTP. But whose SMTP server do you use to collect your mail and send it onward? ISPs offer SMTP mail service to their customers. The ISP’s mail server acts as the mail gateway. It knows how to collect your mail, find the recipient host, and relay the mail. With UNIX, you can host your own local mail server, if you want. Your server will be responsible for routing the mail to its destination.
RELAYING OUTGOING MAIL THROUGH AN EXTERNAL (ISP) GATEWAY SMTP SERVER

When you relay outgoing mail through an external mail gateway server, your client mail program sends all outgoing mail to your ISP’s mail server. Your ISP acts as your mail gateway to the rest of the world. Your system doesn’t need to know how to locate your mail destinations or the routes to them. The ISP mail gateway serves as your relay. The following two rules enable you to relay mail through your ISP’s SMTP gateway:
SMTP_GATEWAY=”my.isp.server” # external mail server or relay

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \

134

Enabling Common TCP Services

-d $SMTP_GATEWAY --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $SMTP_GATEWAY --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

SENDING MAIL TO ANY EXTERNAL MAIL SERVER

Alternatively, you can bypass your ISP’s mail server and host your own. Your local server is responsible for collecting your outgoing mail, doing the DNS lookup on the destination hostname, and sending the mail to its destination. Your client mail program points to your local SMTP server rather than to the ISP’s server. The following two rules enable you to send mail directly to the remote destinations:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 25 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

RECEIVING MAIL How you receive mail depends on your situation. If you run your own local mail server, you can collect incoming mail directly on your Linux machine. If you retrieve your mail from your ISP account, you may or may not retrieve mail as a POP or IMAP client, depending on how you’ve configured your ISP email account, and depending on the mail delivery services the ISP offers.
RECEIVING MAIL AS A LOCAL SMTP SERVER (TCP PORT 25)

If you want to receive mail sent directly to your local machines from anywhere in the world, you need to run sendmail, qmail, or some other mail server program. These are the local server rules:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 \ -m state --state NEW -j ACCEPT

135

C H A P T E R 4 : Building and Installing a Standalone Firewall

fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 25 \ --dport $UNPRIVPORTS -j ACCEPT

Alternatively, if you’d rather keep your local email account relatively private and use your work or ISP email account as your public address, you can configure your work and ISP mail accounts to forward mail to your local server. In this case, you could replace the previous single rule pair, accepting connections from anywhere, with separate, specific rules for each mail forwarder.
RETRIEVING MAIL AS A POP CLIENT (TCP PORT 110)

Connecting to a POP server is a very common means of retrieving mail from a remote ISP or work account. If your ISP uses a POP server for customer mail retrieval, you need to allow outgoing client-to-server connections. The server’s address will be a specific hostname or address rather than the global, implied ANYWHERE specifier. POP accounts are user accounts associated with a specific user and password:
POP_SERVER=”my.isp.pop.server” # external pop server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $POP_SERVER --dport 110 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $POP_SERVER --dport 110 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $POP_SERVER --sport 110 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

RECEIVING MAIL AS AN IMAP CLIENT (TCP PORT 143)

Connecting to an IMAP server is another common means of retrieving mail from a remote ISP or work account. If your ISP uses an IMAP server for customer mail retrieval, you need to allow outgoing client-to-server connections.

136

Enabling Common TCP Services

The server’s address will be a specific hostname or address rather than the global, implied $ANYWHERE specifier. IMAP accounts are user accounts associated with a specific user and password:
IMAP_SERVER=”my.isp.imap.server” # external imap server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $IMAP_SERVER --dport 143 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $IMAP_SERVER --dport 143 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $IMAP_SERVER --sport 143 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

EXAMPLES OF REAL-WORLD CLIENT AND SERVER EMAIL COMBINATIONS Four common approaches to client and server email combinations are described in this section:
■ ■ ■ ■

Sending mail as an SMTP client and receiving mail as a POP client Sending mail as an SMTP client and receiving mail as an IMAP client Sending mail as an SMTP client and receiving mail as an SMTP server Sending mail as an SMTP server and receiving mail as an SMTP server

The first two are useful if you rely completely on your ISP’s SMTP and POP or IMAP email services. The third example is a mixed approach, relaying outgoing mail through your ISP’s SMTP mail server, but receiving mail directly through your local SMTP server. The fourth approach supports running your own complete, independent mail server for both outgoing and incoming mail.
SENDING MAIL AS AN SMTP CLIENT AND RECEIVING MAIL AS A POP CLIENT

If you are sending mail as an SMTP client and are receiving mail as a POP client, you are relying completely on a remote site for your mail services. The remote site hosts both an SMTP server for relaying your outgoing mail and a POP server for local mail retrieval:

137

C H A P T E R 4 : Building and Installing a Standalone Firewall

SMTP_GATEWAY=”my.isp.server”

# external mail server or relay

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $SMTP_GATEWAY --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT POP_SERVER=”my.isp.pop.server” # external pop server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $POP_SERVER --dport 110 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $POP_SERVER --dport 110 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $POP_SERVER --sport 110 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

SENDING MAIL AS AN SMTP CLIENT AND RECEIVING MAIL AS AN IMAP CLIENT

If you are sending mail as an SMTP client and are receiving mail as an IMAP client, you are relying completely on a remote site for your mail services. The remote site hosts both an SMTP server for relaying outgoing mail and an IMAP server for local mail retrieval:
SMTP_GATEWAY=”my.isp.server” # external mail server or relay

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -m state --state NEW -j ACCEPT fi

138

Enabling Common TCP Services

$IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $SMTP_GATEWAY --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT IMAP_SERVER=”my.isp.imap.server” # external imap server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $IMAP_SERVER --dport 143 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $IMAP_SERVER --dport 143 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $IMAP_SERVER --sport 143 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

SENDING MAIL AS AN SMTP CLIENT AND RECEIVING MAIL AS AN SMTP SERVER

If you are sending mail as an SMTP client and are receiving mail as an SMTP server, you are relying on a remote site to offer SMTP service to relay your outgoing mail to remote destinations. You run sendmail locally as a local SMTP server, allowing remote hosts to send mail to your machine directly. Outgoing mail is relayed through your ISP, but the local sendmail daemon knows how to deliver incoming mail to local user accounts:
SMTP_GATEWAY=”my.isp.server” # external mail server or relay

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $SMTP_GATEWAY --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $SMTP_GATEWAY --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

139

C H A P T E R 4 : Building and Installing a Standalone Firewall

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 25 \ --dport $UNPRIVPORTS -j ACCEPT

SENDING MAIL AS AN SMTP SERVER AND RECEIVING MAIL AS AN SMTP SERVER

If you are sending mail as an SMTP server and are receiving mail as an SMTP server, you provide all your own mail services. Your local sendmail daemon is configured to relay outgoing mail to the destination hosts itself, as well as collect and deliver incoming mail:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 25 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 25 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 25 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 25 -j ACCEPT

140

Enabling Common TCP Services

$IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 25 \ --dport $UNPRIVPORTS -j ACCEPT

HOSTING A MAIL SERVER FOR REMOTE CLIENTS Hosting public POP or IMAP services is unusual for a small system. You might do this if you offer remote mail services to a few friends, for example, or if their ISP mail service is temporarily unavailable. In any case, it’s important to limit the clients your system will accept connections from, both on the packet-filtering level and on the server configuration level.
HOSTING A POP SERVER FOR REMOTE CLIENTS

POP servers are one of the most common and successful points of entry for hacking exploits. Firewall rules can offer some amount of protection, in many cases. Of course, you would limit access at the server configuration level as well. As always, and perhaps particularly so with mail server software, it is crucial to keep up-to-date with security updates for the software. If you use a local system as a central mail server and run a local POP3 server to provide mail access to local machines on a LAN, you don’t need the server rules in this example. Incoming connections from the Internet should be dropped. If you do need to host POP service for a limited number of remote individuals, the next two rules allow incoming connections to your POP server. Connections are limited to your specific clients’ IP addresses:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ -s <my.pop.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 110 \ -m state --state NEW -j ACCEPT fi

$IPT -A INPUT -i $INTERNET -p tcp \ -s <my.pop.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 110 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 110 \ -d <my.pop.clients> --dport $UNPRIVPORTS -j ACCEPT

If your site were an ISP, you could use network address masking to limit which source addresses you would accept POP connection requests from:
POP_CLIENTS=”192.168.24.0/24”

If yours is a residential site with a handful of remote POP clients, the client addresses would need to be stated explicitly, with a separate rule pair for each client address.
141

C H A P T E R 4 : Building and Installing a Standalone Firewall

HOSTING AN IMAP SERVER FOR REMOTE CLIENTS

IMAP servers are one of the most common and successful points of entry for hacking exploits. Firewall rules can offer some amount of protection, in many cases. Of course, you would limit access at the server configuration level as well. As always, and perhaps particularly so with mail server software, it is crucial to keep up-to-date with security updates for the software. If you use a local system as a central mail server and run a local imapd server to provide mail access to local machines on a LAN, you don’t need a server rule. Incoming connections from the Internet should be dropped. If you do need to host IMAP service for a limited number of remote individuals, the next two rules allow incoming connections to your IMAP server. Connections are limited to your specific clients’ IP addresses:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ -s <my.imap.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 143 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ -s <my.imap.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 143 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 143 \ -d <my.imap.clients> --dport $UNPRIVPORTS -j ACCEPT

If your site were an ISP, you could use network address masking to limit which source addresses you would accept IMAP connection requests from:
IMAP_CLIENTS=”192.168.24.0/24”

If yours is a residential site with a handful of remote IMAP clients, the client addresses would need to be stated explicitly, with a separate rule pair for each client address.

Accessing Usenet News Services (TCP NNTP Port 119)
Usenet news is accessed over NNTP running on top of TCP through service port 119. Reading news and posting articles are handled by your local news client. Few systems require the server rules. Table 4.4 lists the complete client/server connection protocol for the NNTP Usenet news service.

142

Enabling Common TCP Services

TABLE 4.4

NNTP Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
119 119 1024:65535 1024:65535 119 119

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 119 119 1024:65535 1024:65535

TCP FLAG

Local client query Remote server response Remote client query Local server response Local server query Remote server response

TCP TCP TCP TCP TCP TCP

NEWS SERVER NEWS SERVER NNTP clients NNTP clients News feed News feed

Out In In Out Out In

IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

Any
ACK

READING AND POSTING NEWS AS A USENET CLIENT The client rules allow connections to your ISP’s news server. Both reading news and posting articles are handled by these rules:
NEWS_SERVER=”my.news.server” # external news server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NEWS_SERVER --dport 119 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $NEWS_SERVER --dport 119 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $NEWS_SERVER --sport 119 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

HOSTING A USENET NEWS SERVER FOR REMOTE CLIENTS A small site is very unlikely to host a news server for the outside world. Even hosting a local news server is unlikely. For the rare exception, the server rules should be configured to allow incoming connections from only a select set of clients:

143

C H A P T E R 4 : Building and Installing a Standalone Firewall

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ -s <my.news.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 119 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ -s <my.news.clients> --sport $UNPRIVPORTS \ -d $IPADDR --dport 119 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 119 \ -d <my.news.clients> --dport $UNPRIVPORTS -j ACCEPT

ALLOWING PEER NEWS FEEDS FOR A LOCAL USENET SERVER A small, home-based site is unlikely to have a peer-to-peer news-feed server relationship with an ISP. Although news servers used to be fairly accessible to the general Internet, few open news servers are available anymore because of SPAM and server load issues. If your site is large enough or rich enough to host a general Usenet server, you have to get your news feed from somewhere. The next two rules allow your local news server to receive its news feed from a remote server. The local server contacts the remote server as a client. The only difference between the peer-to-peer news-feed rules and the regular client rules is the name or address of the remote host:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d <my.news.feed> --dport 119 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d <my.news.feed> --dport 119 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s <my.news.feed> --sport 119 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

Telnet (TCP Port 23)
Telnet had been the de facto standard means of remote login over the Internet for many years. As the nature of the Internet community has changed, telnet has come to be viewed more as

144

Enabling Common TCP Services

an insecure service because it communicates in ASCII clear text. If you have the option, you should always use an encrypted service, such as SSH, rather than telnet. However, Microsoft Windows does not offer an SSH service and only offers telnet—so much for that security commitment! The client and server rules here allow access to and from anywhere. If you use telnet, you can probably limit the external addresses to a very select subset at the packet-filtering level. Table 4.5 lists the complete client/server connection protocol for the telnet service.
TABLE 4.5

Telnet Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
23 23 1024:65535 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 23 23

TCP FLAG

Local client request Remote server response

TCP TCP

ANYWHERE ANYWHERE Telnet clients Telnet clients

Out In In Out

IPADDR IPADDR IPADDR IPADDR

Any
ACK

Remote client TCP request Local server response TCP

Any
ACK

ALLOWING OUTGOING CLIENT ACCESS TO REMOTE SITES If you need to use telnet to access remote systems (SSH servers are very prevalent today), the next two rules allow outgoing connections to remote sites. If your site has multiple users, you should limit outgoing connections to the specific sites your users have accounts on, if at all possible, rather than allowing outgoing connections to anywhere:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 23 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 23 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 23 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

145

C H A P T E R 4 : Building and Installing a Standalone Firewall

ALLOWING INCOMING ACCESS TO YOUR LOCAL SERVER Even if you need client access to remote servers, you may not need to allow incoming connections to your telnet server. If you do, the next two rules allow incoming connections to your server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 23 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 23 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 23 \ --dport $UNPRIVPORTS -j ACCEPT

Rather than allowing connections from anywhere, it is far preferable to define server rules for each specific host or network that an incoming connection can legitimately originate from. SSH clients are freely available for almost all systems in use today.

SSH (TCP Port 22)
With the expiration of the RSA patent in year 2000, OpenSSH, secure shell, is included in Linux distributions. It is also freely available from software sites on the Internet. SSH is considered far preferable to using telnet for remote login access because both ends of the connection use authentication keys for both hosts and users, and because data is encrypted. Additionally, SSH is more than a remote login service. It can automatically direct X Window connections between remote sites, and FTP and other TCP-based connections can be directed over the more secure SSH connection. Provided that the other end of the connection allows SSH connections, it’s possible to route all TCP connections through the firewall using SSH. As such, SSH is something of a poor man’s virtual private network (VPN). The ports used by SSH are highly configurable. By default, connections are initiated between a client’s unprivileged port and the server’s assigned service port 22. The SSH client uses the unprivileged ports exclusively. The rules in this example apply to the default SSH port usage:
SSH_PORTS=”1024:65535” # RSA authentication

or
SSH_PORTS=”1020:65535” # Rhost authentication

146

Enabling Common TCP Services

The client and server rules here allow access to and from anywhere. In practice, you would limit the external addresses to a select subset, particularly because both ends of the connection must be configured to recognize each individual user account for authentication. Table 4.6 lists the complete client/server connection protocol for the SSH service.
TABLE 4.6

SSH Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
22 22 22 22 1024:65535 1024:65535 513:1023 513:1023

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 513:1023 513:1023 22 22 22 22

TCP FLAG

Local client request Remote server response Local client request Remote server response Remote client request Local server response Remote client request Local server response

TCP TCP TCP TCP TCP TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE ANYWHERE SSH clients SSH clients SSH clients SSH clients

Out In Out In In Out In Out

IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

Any
ACK

Any
ACK

ALLOWING CLIENT ACCESS TO REMOTE SSH SERVERS These rules allow you to connect to remote sites using SSH:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $SSH_PORTS \ --dport 22 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $SSH_PORTS \ --dport 22 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 22 \ -d $IPADDR --dport $SSH_PORTS -j ACCEPT

147

C H A P T E R 4 : Building and Installing a Standalone Firewall

ALLOWING REMOTE CLIENT ACCESS TO YOUR LOCAL SSH SERVER These rules allow incoming connections to your SSH server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $SSH_PORTS \ -d $IPADDR --dport 22 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $SSH_PORTS \ -d $IPADDR --dport 22 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 22 \ --dport $SSH_PORTS -j ACCEPT

FTP (TCP Ports 21, 20)
FTP remains one of the most common means of transferring files between two networked machines. Web-based browser interfaces to FTP have become common as well. Like telnet, FTP sends both authentication credentials and data communication in plain text over the network. Therefore, FTP is also considered to be an inherently insecure protocol. SFTP and SCP offer improvements to FTP in this regard. FTP is used as the classic example of a protocol that isn’t firewall- or NAT-friendly. Traditional client/server applications that communicate over TCP all work the same way. The client initiates the request to connect to the server. Table 4.7 lists the complete client/server connection protocol for the FTP service.
TABLE 4.7

FTP Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
21 21 20

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 1024:65535

TCP FLAG

Local client query Remote server response

TCP TCP

ANYWHERE ANYWHERE ANYWHERE

Out In In

IPADDR IPADDR IPADDR

Any
ACK

Remote server TCP port data channel request

Any

148

Enabling Common TCP Services

TABLE 4.7

FTP Protocol (continued)
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
20

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535

TCP FLAG
ACK

Local client port data channel response

TCP

ANYWHERE

Out

IPADDR

Local client TCP passive data channel request Remote server passive data channel response Remote client request Local server response Local server port data channel response Remote client port data channel response TCP

ANYWHERE

1024:65535

Out

IPADDR

1024:65535

Any

ANYWHERE

1024:65535

In

IPADDR

1024:65535

ACK

TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE

1024:65535 1024:65535 1024:65535

In Out Out

IPADDR IPADDR IPADDR

21 21 20

Any
ACK

Any

TCP

ANYWHERE

1024:65535

In

IPADDR

20

ACK

Remote client TCP passive data channel request Local server passive data channel response TCP

ANYWHERE

1024:65535

In

IPADDR

1024:65535

Any

ANYWHERE

1024:65535

Out

IPADDR

1024:65535

ACK

FTP deviates from this standard TCP, client/server communication model. FTP relies on two separate connections, one for the control or command stream, and one for passing the data files and other information, such as directory listings. The control stream is carried over a traditional TCP connection. The client binds to a high, unprivileged port, and sends a connection request to the FTP server, which is bound to port 21. This connection is used to pass commands.

149

C H A P T E R 4 : Building and Installing a Standalone Firewall

In terms of the second data stream connection, FTP has two alternate modes for exchanging data between a client and server: port mode and passive mode. Port mode is the original, default mechanism. The client tells the server which secondary, unprivileged port it will listen on. The server initiates the data connection from port 20 to the unprivileged port the client specified. This is the deviation from the standard client/server model. The server is initiating the secondary connection back to the client. This is why FTP is a protocol that requires ALG support for both the firewall and NAT. The firewall must account for an incoming connection from port 20 to a local unprivileged port. NAT must account for the destination address used for the secondary data stream connection. (The client has no knowledge that its network traffic is being NATed. The port and address it sent the server were its local, pre-NATed port and address.) Passive mode is similar to the traditional client/server model in that the client initiates the secondary connection for the data stream. Again, the client initiates the connection from a high, unprivileged port. The server isn’t bound to port 20 for the data connection, however. Instead, the server has told the client which high, unprivileged port the client should address the connection request to. The data stream is carried between unprivileged ports on both the client and the server. In terms of traditional packet filtering, the firewall must allow TCP traffic between all unprivileged ports. Connection state tracking and ALG support allow the firewall to associate the secondary connection with a particular FTP control stream. NAT isn’t an issue on the client side because the client is initiating both connections. ALLOWING OUTGOING CLIENT ACCESS TO REMOTE FTP SERVERS It’s almost a given that most sites will want FTP client access to remote file repositories. Most people will want to enable outgoing client connections to a remote server.
OUTGOING FTP REQUESTS OVER THE CONTROL CHANNEL

The next two rules allow an outgoing control connection to a remote FTP server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 21 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 21 -j ACCEPT

150

Enabling Common TCP Services

$IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 21 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

PORT-MODE FTP DATA CHANNELS

The next two rules allow the standard data channel connection, in which the remote server calls back to establish the data connection from server port 20 to a client-specified unprivileged port:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport 20 \ -d $IPADDR --dport $UNPRIVPORTS \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport 20 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 20 -j ACCEPT

This unusual callback behavior, with the remote server establishing the secondary connection with your client, is part of what makes FTP difficult to secure at the packet-filtering level.
PASSIVE-MODE FTP DATA CHANNELS

The next two rules allow the newer passive data channel mode used by most web browsers:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport $UNPRIVPORTS -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport $UNPRIVPORTS -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport $UNPRIVPORTS \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

Passive mode is considered more secure than port mode because the FTP client initiates both the control and the data connections, even though the connection is made between two

151

C H A P T E R 4 : Building and Installing a Standalone Firewall

unprivileged ports. And, as stated earlier, passive mode doesn’t have the problems with NAT that port mode does on the client side. ALLOWING INCOMING ACCESS TO YOUR LOCAL FTP SERVER Whether to offer FTP services to the world is a difficult decision. Although FTP sites abound on the Internet, FTP server configuration requires great care. Numerous FTP security exploits are possible. If your goal is to offer general read-only access to some set of files on your machine, you might consider making these files available through a web server. If your goal is to allow file uploads to your machine from the outside, FTP server access should be severely limited on the firewall level, on the xinetd configuration level, on the tcp_wrappers level, and on the FTP configuration level. In any case, if you decide to offer FTP services, and if you decide to allow incoming file transfers, write access should not be allowed via anonymous FTP. Remote write access to your file systems should be allowed only from specific, authenticated FTP user accounts, from specific remote sites, and to carefully controlled and limited FTP areas reserved in your file system. Hosting the FTP area from a chroot environment would be even better.
INCOMING FTP REQUESTS

The next two rules allow incoming control connections to your FTP server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 21 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 21 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 21 \ --dport $UNPRIVPORTS -j ACCEPT

PORT-MODE FTP DATA CHANNEL RESPONSES

The next two rules allow the FTP server to call back the remote client and establish the secondary data channel connection:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \

152

Enabling Common TCP Services

-s $IPADDR --sport 20\ --dport $UNPRIVPORTS -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport 20 \ --dport $UNPRIVPORTS -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 20 -j ACCEPT

PASSIVE-MODE FTP DATA CHANNEL RESPONSES

The next two rules allow the remote FTP client to establish the secondary data channel connection with the local server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport $UNPRIVPORTS \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport $UNPRIVPORTS \ --dport $UNPRIVPORTS -j ACCEPT

CAUTION Don’t use TFTP on the Internet! TFTP offers a simplified, unauthenticated, UDP version of the FTP service. It is intended for loading boot software into routers and diskless workstations over a local network from trusted hosts. Some people confuse TFTP as an alternative to FTP. Don’t use it over the Internet, period. Preferably, don’t install TFTP on your system at all.

Web Services
Web services are based on the Hypertext Transfer Protocol (HTTP). Client and server connections use the standard TCP conventions. Several higher-level, special-purpose communication protocols are available in addition to the standard general HTTP access, including secure

153

C H A P T E R 4 : Building and Installing a Standalone Firewall

access over SSL or TLS, and access via an ISP-provided web server proxy. These different access protocols use different service ports. STANDARD HTTP ACCESS (TCP PORT 80) In normal use, web services are available over http service port 80. Table 4.8 lists the complete client/server connection protocol for the HTTP web service.
TABLE 4.8

HTTP Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
80 80 1024:65535 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 80 80

TCP FLAG

Local client request Remote server response Remote client request Local server response

TCP TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE ANYWHERE

Out In In Out

IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

ACCESSING REMOTE WEBSITES AS A CLIENT

It’s almost inconceivable in today’s world that a home-based site would not want to access the World Wide Web from a web browser. The next two rules allow access to remote web servers:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 80 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 80 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 80 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

ALLOWING REMOTE ACCESS TO A LOCAL WEB SERVER

If you decide to run a web server of your own and host a public website, the following general server rules allow all typical incoming access to your site. This is all that most people need in order to host a website:
154

Enabling Common TCP Services

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 80 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 80 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 80 \ --dport $UNPRIVPORTS -j ACCEPT

SECURE WEB ACCESS (SSL AND TLS) (TCP PORT 443) Secure Sockets Layer (SSL) and Transport Layer Security (TLS) are used for secure, encrypted web access. The protocols use TCP port 443. You will most often encounter this if you go to a commercial website to purchase something, use online banking services, or enter a protected web area where you’ll be prompted for personal information. The Apache web server shipped with Red Hat Linux 7.1 includes OpenSSL support. Table 4.9 lists the complete client/server connection protocol for the service.
TABLE 4.9

SSL and TLS Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
443 443 1024:65535 1024:65535

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535 1024:65535 443 443

TCP FLAG

Local client request Remote server response Remote client request Local server response

TCP TCP TCP TCP

ANYWHERE ANYWHERE ANYWHERE ANYWHERE

Out In In Out

IPADDR IPADDR IPADDR IPADDR

Any
ACK

Any
ACK

ACCESSING REMOTE WEBSITES OVER SSL OR TLS AS A CLIENT

Most people will want client access to secure websites at some point:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \

155

C H A P T E R 4 : Building and Installing a Standalone Firewall

--dport 443 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 443 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 443 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

ALLOWING REMOTE ACCESS TO A LOCAL SSL OR TLS WEB SERVER

If you conduct some form of e-commerce or have a user-authenticated web area, you’ll most likely want to allow incoming connections to encryption-protected areas of your website. Otherwise, you won’t need local server rules. Both the OpenSSL included with Linux and commercial SSL support packages are available for the Apache web server. See http://www.apache.org for more information. The next two rules allow incoming access to your web server using the SSL or TLS protocols:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 443 \ -m state --state NEW -j ACCEPT fi $IPT -A INPUT -i $INTERNET -p tcp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 443 -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p tcp ! --syn \ -s $IPADDR --sport 443 \ --dport $UNPRIVPORTS -j ACCEPT

WEB PROXY ACCESS (TCP PORTS 8008, 8080) Publicly accessible web server proxies are most common at ISPs. As a customer, you configure your browser to use a remote proxy service. Web proxies are often accessed through one of two unprivileged ports assigned for this purpose, ports 8008 or 8080, as defined by the ISP. In return, you get faster web page access when the pages are already cached locally at your ISP’s server and the relative anonymity of proxied access to remote sites. Your connections are not direct, but instead they are done on your behalf by your ISP’s proxy. Table 4.10 lists the complete client/server connection protocol for the web proxy service.

156

Enabling Common TCP Services

TABLE 4.10

Web Proxy Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT LOCAL IN/OUT ADDRESS LOCAL PORT
1024:65535 1024:65535

TCP FLAG

Local client request Remote server response

TCP TCP

WEB PROXY SERVER WEB PROXY SERVER

WEB PROXY PORT WEB PROXY PORT

Out In

IPADDR IPADDR

Any
ACK

If you use a web proxy service offered by your ISP, the specific server address and port number will be defined by your ISP. The client rules are as shown here:
# ISP Web proxy server, if any # ISP Web proxy port, if any # typically 8008 or 8080 if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $WEB_PROXY_SERVER --dport $WEB_PROXY_PORT \ -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $WEB_PROXY_SERVER --dport $WEB_PROXY_PORT -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ -s $WEB_PROXY_SERVER --sport $WEB_PROXY_PORT \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT WEB_PROXY_SERVER=”my.www.proxy” WEB_PROXY_PORT=”www.proxy.port”

Whois (TCP Port 43)
The whois program accesses the InterNIC Registration Services database. Table 4.11 lists the complete client/server connection protocol for the whois service.
TABLE 4.11

Whois Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS
ANYWHERE ANYWHERE

REMOTE PORT
43 43

IN/OUT

LOCAL ADDRESS
IPADDR IPADDR

LOCAL PORT
1024:65535 1024:65535

TCP FLAG

Local client request Remote server response

TCP TCP

Out In

Any
ACK

157

C H A P T E R 4 : Building and Installing a Standalone Firewall

The next two rules enable you to query an official remote server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 43 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 43 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 43 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

RealAudio, RealVideo, and QuickTime (TCP Ports 554 and 7070)
RealAudio, RealVideo, and QuickTime use the same ports. The control connection to the server is built on top of the Real-Time Streaming Protocol (RTSP). See RFC 2326, “Real Time Streaming Protocol (RTSP),” for more information on the protocol. The incoming data stream is built on top of the Real-Time Transport Protocol (RTP). See RFC 3550, “RTP: A Transport Protocol for Real-Time Applications,” for more information on the RTP protocol. See http://www.realnetworks.com for more information on RealAudio and RealVideo firewall requirements. The client programs can be configured to use TCP solely, to use TCP for the control connection and UDP for the data stream (the UDP port can be configured to be a single port or one from a range of ports), or to use the HTTP application protocol solely. The TCP server ports, 554 or 7070 and 7071, depend on the client and server versions. The UDP client ports range between 6970 and 7170 for newer clients. If your site uses the older RealAudio version 3.0 player, the UDP client port range is 6770 to 7170. The actual port range supported can vary by application and platform. Typically, the client program uses the most efficient transport combination available. The client determines this by attempting the different methods. Because bidirectional protocols usually have problems getting through a firewall without ALG support, the data stream will usually arrive over the TCP or HTTP protocols. In other words, without a firewall support module for RealAudio, your options are to use HTTP for the incoming stream, to open the specific TCP or UDP ports and not use the state module (or, at least, not use the INVALID match), or to open the required ports and place the rules for the data stream before the state match rules.
158

Enabling Common TCP Services

Table 4.12 lists the control and data streams for a local client.
TABLE 4.12

RealAudio Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
554,7070

LOCAL IN/OUT ADDRESS

LOCAL PORT
1024:65535

TCP FLAG

Local client control request Remote server control response Local client TCP data request Remote server TCP data response Remote server UDP data stream

TCP

ANYWHERE

Out

IPADDR

Any

TCP

ANYWHERE

554,7070

In

IPADDR

1024:65535

ACK

TCP

ANYWHERE

7071

Out

IPADDR

1024:65535

Any

TCP

ANYWHERE

7071

In

IPADDR

1024:65535

ACK

UDP

ANYWHERE

1024:65535

In

IPADDR

6970:71709



The next rule pair establishes the control connection with the server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -m multiport --source-port 554,7070 \ --syn -s $IPADDR --sport $UNPRIVPORTS \ -m state--state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -m multiport --destination-port 554,7070 \ --syn -s $IPADDR --dport $UNPRIVPORTS -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp \ -m multiport --destination-port 554,7070 \ ! --syn -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

The next rule allows the preferred incoming UDP data stream from the server:
$IPT -A INPUT -i $INTERNET -p udp \ --sport $UNPRIVPORTS \ -d $IPADDR --dport 6970:7170 -j ACCEPT

159

C H A P T E R 4 : Building and Installing a Standalone Firewall

The next rule pair establishes the TCP data stream connection with the server:
if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 7071 -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p tcp \ -s $IPADDR --sport $UNPRIVPORTS \ --dport 7071 -j ACCEPT $IPT -A INPUT -i $INTERNET -p tcp ! --syn \ --sport 7071 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

Enabling Common UDP Services
The stateless UDP protocol is inherently less secure than the connection-based TCP protocol. Because of this, many security-conscious sites completely disable, or else limit as much as possible, all access to UDP services. Obviously, UDP-based DNS exchanges are necessary, but the remote name servers can be explicitly specified in the firewall rules. As such, this section provides rules for only three services:
■ ■ ■

traceroute

Dynamic Host Configuration Protocol (DHCP) Network Time Protocol (NTP)

traceroute (UDP Port 33434)
On Unix and Linux systems, traceroute is a UDP service that causes intermediate systems to generate ICMP Time Exceeded messages to gather hop count information, and that causes the target system to return a Destination Unreachable message, indicating the endpoint of the route to the host. By the default deny policy, the firewall being developed in this chapter blocks incoming UDP traceroute packets because traceroute default ports are not explicitly enabled. As a result, outgoing ICMP responses to incoming traceroute requests won’t be sent. Table 4.13 lists the complete client/server connection protocol for the traceroute service.

160

Enabling Common UDP Services

TABLE 4.13

traceroute Protocol
REMOTE ADDRESS REMOTE PORT / ICMP TYPE LOCAL ADDRESS LOCAL PORT / ICMP TYPE

DESCRIPTION

PROTOCOL

IN/OUT

Outgoing
traceroute

probe Time exceeded (intermediate hop) Port not found (termination) Incoming
traceroute

UDP ICMP

ANYWHERE ANYWHERE

33434:33523 11

Out In

IPADDR IPADDR

32769:66535



UDP

ANYWHERE

3

In

IPADDR



probe Time exceeded (intermediate hop) Port not found (termination)
traceroute

UDP

ISP

32769:65535

In

IPADDR

33434:33523

ICMP

ISP



Out

IPADDR

11

ICMP

ISP



Out

IPADDR

3

can be configured to use any port or port range. As such, it’s difficult to block all incoming traceroute packets by listing specific ports. However, it often uses source ports in the range from 32,769 to 65,535 and destination ports in the range from 33,434 to 33,523. Because traceroute can be configured to use any source and destination port, the most effective way to block incoming traceroute is to block the outgoing ICMP messages generated in response. Symbolic constants are defined for traceroute’s default source and destination ports:
TRACEROUTE_SRC_PORTS=”32769:65535” TRACEROUTE_DEST_PORTS=”33434:33523”

ENABLING OUTGOING traceroute REQUESTS If you intend to use traceroute yourself, you must enable the UDP client ports. Note that you must allow incoming ICMP Time Exceeded and Destination Unreachable messages from anywhere for outgoing traceroute to work:

161

C H A P T E R 4 : Building and Installing a Standalone Firewall

$IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport $TRACEROUTE_SRC_PORTS \ --dport $TRACEROUTE_DEST_PORTS -j ACCEPT

Because traceroute is a less secure UDP service and can be used to identify your edge router, map your LAN, or attack other UDP services, allowing incoming traceroute isn’t recommended.

Accessing Your ISP’s DHCP Server (UDP Ports 67, 68)
DHCP exchanges, if any, between your site and your ISP’s server will necessarily be local client-to-remote server exchanges. Most often, DHCP clients receive temporary, or semipermanent, dynamically allocated IP addresses from a central server that manages the ISP’s customer IP address space. The server also typically provides your local host with other configuration information, such as the network subnet mask; the network MTU; the default, first-hop router addresses; the domain name; and the default TTL. If you have a dynamically allocated IP address from your ISP, you need to run a DHCP client daemon on your machine. It’s not uncommon for bogus DHCP server messages to fly around your ISP’s local subnet if someone runs the server by accident. For this reason, it’s especially important to filter DHCP messages to limit traffic between your client and your specific ISP DHCP server as much as possible. Table 4.14 lists the DHCP message type descriptions, as quoted from RFC 2131, “Dynamic Host Configuration Protocol.”
TABLE 4.14

DHCP Message Types
DHCP MESSAGE
DHCPDISCOVER DHCPOFFER DHCPREQUEST

DESCRIPTION

Client broadcast to locate available servers Server to client in response to DHCPDISCOVER with offer of configuration parameters Client message to servers either (a) requesting offered parameters from one server and implicitly declining offers from all others; (b) confirming correctness of previously allocated address after, for example, system reboot; or (c) extending the lease on a particular network address Server to client with configuration parameters, including committed network address Server to client indicating that client’s notion of network address is incorrect (for example, client has moved to new subnet) or client’s lease has expired

DHCPACK DHCPNAK

162

Enabling Common UDP Services

TABLE 4.14

DHCP Message Types (continued)
DHCP MESSAGE
DHCPDECLINE DHCPRELEASE DHCPINFORM

DESCRIPTION

Client to server indicating that network address is already in use Client to server relinquishing network address and canceling remaining lease Client to server, asking only for local configuration parameters; client already has externally configured address

In essence, when the DHCP client initializes, it broadcasts a DHCPDISCOVER query to discover whether any DHCP servers are available. Any servers receiving the query may respond with a DHCPOFFER message indicating their willingness to function as server to this client; they include the configuration parameters that they have to offer. The client broadcasts a DHCPREQUEST message to accept one of the servers and to inform any remaining servers that it has chosen to decline their offers. The chosen server responds with a broadcast DHCPACK message, indicating confirmation of the parameters that it originally offered. Address assignment is complete at this point. Periodically, the client sends the server a DHCPREQUEST message requesting a renewal on the IP address lease. If the lease is renewed, the server responds with a unicast DHCPACK message. Otherwise, the client falls back to the initialization process. Table 4.15 lists the complete client/server exchange protocol for the DHCP service.
TABLE 4.15

DHCP Protocol
DESCRIPTION
DHCPDISCOVER; DHCPREQUEST DHCPOFFER DHCPOFFER DHCPREQUEST; DHCPDECLINE DHCPACK; DHCPNACK DHCPACK DHCPREQUEST; DHCPRELEASE

PROTOCOL

REMOTE ADDRESS
255.255.255.255 0.0.0.0 DHCP SERVER DHCP SERVER DHCP SERVER DHCP SERVER DHCP SERVER

REMOTE PORT
67 67 67 67 67 67 67

IN/OUT

LOCAL ADDRESS
0.0.0.0 255.255.255.255 255.255.255.255 0.0.0.0 ISP/NETMASK IPADDR IPADDR

LOCAL PORT
68 68 68 68 68 68 68

UDP UDP UDP UDP UDP UDP UDP

Out In In Out In In Out

163

C H A P T E R 4 : Building and Installing a Standalone Firewall

The DHCP protocol is far more complicated than this brief summary, but the summary describes the essentials of the typical client and server exchange. For more information, refer to the section “Choke as a Local DHCP Server (UDP Ports 67 and 68),” in Chapter 6. The following firewall rules allow communication between your DHCP client and a remote server:
DHCP_SERVER=”my.dhcp.server” # if you use one

# Initialization or rebinding: No lease or Lease time expired. $IPT -A OUTPUT -o $INTERNET -p udp \ -s $BROADCAST_SRC --sport 68 \ -d $BROADCAST_DEST --dport 67 -j ACCEPT # Incoming DHCPOFFER from available DHCP servers $IPT -A INPUT -i $INTERNET -p udp \ -s $BROADCAST_SRC --sport 67 \ -d $BROADCAST_DEST --dport 68 -j ACCEPT # Fall back to initialization # The client knows its server, but has either lost its lease, # or else needs to reconfirm the IP address after rebooting. $IPT -A OUTPUT -o $INTERNET -p udp \ -s $BROADCAST_SRC --sport 68 \ -d $DHCP_SERVER --dport 67 -j ACCEPT $IPT -A INPUT -i $INTERNET -p udp \ -s $DHCP_SERVER --sport 67 \ -d $BROADCAST_DEST --dport 68 -j ACCEPT # # # # # # # # # # As a result of the above, we’re supposed to change our IP address with this message, which is addressed to our new address before the dhcp client has received the update. Depending on the server implementation, the destination address can be the new IP address, the subnet address, or the limited broadcast address. If the network subnet address is used as the destination, the next rule must allow incoming packets destined to the subnet address, and the rule must precede any general rules that block such incoming broadcast packets. -i $INTERNET -p udp \

$IPT -A INPUT

164

Enabling Common UDP Services

-s $DHCP_SERVER --sport 67 \ --dport 68 -j ACCEPT # Lease renewal $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport 68 \ -d $DHCP_SERVER --dport 67 -j ACCEPT $IPT -A INPUT -i $INTERNET -p udp \ -s $DHCP_SERVER --sport 67 \ -d $IPADDR --dport 68 -j ACCEPT

Notice that DHCP traffic cannot be completely limited to your DHCP server. During initialization sequences, when your client doesn’t yet have an assigned IP address or even the server’s IP address, packets are broadcast rather than sent point-to-point. At the Layer 2 level, the packets may be addressed to your network card’s hardware address.

Accessing Remote Network Time Servers (UDP Port 123)
Network time services such as NTP allow access to one or more public Internet time providers. This is useful to maintain an accurate system clock, particularly if your internal clock tends to drift, and to establish the correct time and date at bootup or after a power loss. A small-system user should use the service only as an Internet client. Few small sites have a satellite link to Greenwich, England; a radio link to an atomic clock; or an atomic clock of their own lying around.
ntpd is the server daemon. In addition to providing time service to clients, ntpd uses a peerto-peer relationship among servers. Few small sites require the extra precision ntpd provides. ntpdate is the client program and uses a client-to-server relationship. The client program is all that a small site will need. Table 4.16 lists only the client/server exchange protocol for the NTP service. There is rarely, if ever, a reason to run ntpd itself because that’s the server component. If you must run the NTP server (as opposed to the client), do so in a chroot environment. TABLE 4.16

NTP Protocol
DESCRIPTION PROTOCOL REMOTE ADDRESS REMOTE PORT
123 123

IN/OUT

LOCAL ADDRESS
IPADDR IPADDR

LOCAL PORT
1024:65535 1024:65535

Local client query Remote server response

UDP UDP

TIMESERVER TIMESERVER

Out In

165

C H A P T E R 4 : Building and Installing a Standalone Firewall

The ntpd startup script that is run at boot time uses ntpdate to query a series of public time service providers. The ntpd daemon is started after the server’s reply. These hosts would be individually specified in a series of firewall rules:
TIME_SERVER=”my.time.server” # external time server, if any

if [ “$CONNECTION_TRACKING” = “1” ]; then $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $TIME_SERVER --dport 123 \ -m state --state NEW -j ACCEPT fi $IPT -A OUTPUT -o $INTERNET -p udp \ -s $IPADDR --sport $UNPRIVPORTS \ -d $TIME_SERVER --dport 123 -j ACCEPT $IPT -A INPUT -i $INTERNET -p udp \ -s $TIME_SERVER --sport 123 \ -d $IPADDR --dport $UNPRIVPORTS -j ACCEPT

Note that the previous rules are written for a standard client/server UDP communication. Depending on your particular client and server software, it’s possible that one or both of them will use the NTP server-to-server communication model, with both the client and the server using UDP port 123.

Filtering ICMP Control and Status Messages
ICMP control messages are generated in response to a number of error conditions, and they are produced by network analysis programs such as ping and traceroute.
ICMP MESSAGE TYPES AND IPTABLES iptables supports the use of either the ICMP numeric message type or the alphabetic symbolic name. iptables also supports use of the message subtypes, or codes. This is especially useful for finer filtering control over type 3 Destination Unreachable messages. For example, you could specifically disallow outgoing Port Unreachable messages to disable an incoming traceroute, or you could specifically allow only outgoing Fragmentation Needed messages. To see a list of all supported ICMP symbolic names in iptables, run iptables -p icmp -h. To see the official RFC assignments, go to http://www.iana.org/assignments/icmp-parameters.

166

Filtering ICMP Control and Status Messages

Error Status and Control Messages
Four ICMP control and status messages need to pass through the firewall: Source Quench, Parameter Problem, incoming Destination Unreachable, and outgoing Destination Unreachable of subtype Fragmentation Needed. Four other ICMP message types are optional: Echo Request, Echo Reply, other outgoing Destination Unreachable subtypes, and Time Exceeded. Other message types can be ignored, to be filtered out by the default policy. Of the message types that can—or should—be ignored, only redirect is considered dangerous because of its role in denial-of-service attacks as a redirect bomb. (See Chapter 2 for more information on redirect bombs.) As with redirect, the remaining ICMP message types are specialized control and status messages intended for use between routers. The following sections describe the message types important to an endpoint host machine, as opposed to an intermediate router, in more detail. FRAGMENTED ICMP MESSAGES An ICMP message will never be fragmented under normal circumstances. An ICMP message should fit entirely within a Layer 2 frame. It’s safe to drop fragmented ICMP messages. Such packets are usually used in denial-of-service attacks:
$IPT -A INPUT -i $INTERNET --fragment -p icmp -j LOG \ --log-prefix “Fragmented ICMP: “ $IPT -A INPUT -i $INTERNET --fragment -p icmp -j DROP

SOURCE QUENCH CONTROL (TYPE 4) MESSAGES ICMP message type 4, Source Quench, can be sent when a connection source, usually a router, is sending data faster than the next destination router can handle it. Source Quench is used as a primitive form of flow control at the IP Network layer, usually between two adjacent, point-to-point machines:
$IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type source-quench -d $IPADDR -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type source-quench -j ACCEPT

The router’s next hop or destination machine sends a Source Quench command. The originating router responds by sending packets at a slower rate, gradually increasing the rate until it receives another Source Quench message. In practice, Source Quench is not much used within the Internet anymore. Flow control is left to the higher-level protocols. The message type is seen on LANs, however.

167

C H A P T E R 4 : Building and Installing a Standalone Firewall

PARAMETER PROBLEM STATUS (TYPE 12) MESSAGES ICMP message type 12, Parameter Problem, is sent when a packet is received containing illegal or unexpected data in the header, or when the header checksum doesn’t match the checksum generated by the receiving machine:
$IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type parameter-problem -d $IPADDR -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type parameter-problem -j ACCEPT

DESTINATION UNREACHABLE ERROR (TYPE 3) MESSAGES ICMP message type 3, Destination Unreachable, is a general error status message:
$IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type destination-unreachable -d $IPADDR -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type fragmentation-needed -j ACCEPT # Don’t log dropped outgoing ICMP error messages $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type destination-unreachable -j DROP

The ICMP packet header for type 3 messages, Destination Unreachable, contains an error code field identifying the particular kind of error. Ideally, you’d want to drop outgoing type 3 messages. This message type is what is sent in response to a port scan used to map your service ports or address space. An attacker can create a denial-of-service condition by forcing your system to generate large numbers of these messages by bombarding your unused ports. Worse, an attacker can spoof the source address, forcing your system to send them to the spoofed hosts. Unfortunately, the Destination Unreachable message creates a Catch-22 situation. One of the message subtypes, Fragmentation Needed, is used to negotiate packet fragment size. Your network performance can be seriously degraded without this negotiation. TIME EXCEEDED STATUS (TYPE 11) MESSAGES ICMP message type 11, Time Exceeded, indicates a timeout condition—or, more accurately, that a packet’s maximum hop count has been exceeded. On networks today, incoming Time Exceeded is mostly seen as the ICMP response to an outgoing UDP traceroute request:
$IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type time-exceeded -d $IPADDR -j ACCEPT

168

Filtering ICMP Control and Status Messages

If you want to use traceroute, you must allow incoming ICMP Time Exceeded messages. Because your machine is not an intermediate router, you have no other use for Time Exceeded messages.

ping Echo Request (Type 8) and Echo Reply (Type 0) Control

Messages
uses two ICMP message types. The request message, Echo Request, is message type 8. The reply message, Echo Reply, is message type 0. ping is a simple network-analysis tool dating back to the original DARPANet. The name ping was taken from the idea of the audible ping played back by sonar systems. (DARPA is the Defense Advanced Research Projects Agency, after all.) Similar to sonar, an Echo Request message broadcast to all machines in a network address space generates Echo Reply messages, in return, from all hosts responding on the network.
ping smurf ATTACKS

Don’t broadcast anything out unto the Internet. The ping broadcast mentioned previously is the basis of the smurf IP denial-of-service attack. See CERT Advisory CA-98.01.smurf at http://www.cert.org for more information on smurf attacks.

OUTGOING ping TO REMOTE HOSTS The following rule pair enables you to ping any host on the Internet:
if [ “$CONNECTION_TRACKING” = “1” ]; then # allow outgoing pings to anywhere $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type echo-request \ -m state --state NEW -j ACCEPT fi # allow outgoing pings to anywhere $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type echo-request -j ACCEPT $IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type echo-reply -d $IPADDR -j ACCEPT

INCOMING ping FROM REMOTE HOSTS The approach shown here allows only selected external hosts to ping you:

169

C H A P T E R 4 : Building and Installing a Standalone Firewall

if [ “$CONNECTION_TRACKING” = “1” ]; then # allow incoming pings from trusted hosts $IPT -A INPUT -i $INTERNET -p icmp \ -s $MY_ISP --icmp-type echo-request -d $IPADDR \ -m state --state NEW -j ACCEPT fi # allow incoming pings from trusted hosts $IPT -A INPUT -i $INTERNET -p icmp \ -s $MY_ISP --icmp-type echo-request -d $IPADDR -j ACCEPT $IPT -A OUTPUT -o $INTERNET -p icmp \ -s $IPADDR --icmp-type echo-reply -d $MY_ISP -j ACCEPT

For the purposes of the example you’ve been building in this chapter, external hosts allowed to ping your machine are machines belonging to your ISP. Chances are good that your network operations center or customer support will want to ping your external interface. If your machine is a DHCP client, it’s possible that the DHCP implementation depends on ping as well. Except for those from your local network neighbors, other incoming Echo Requests are denied. ping has been used in several types of denial-of-service attacks.

Logging Dropped Incoming Packets
Any packet matching a rule can be logged by using the -j LOG target. Logging a packet has no effect on the packet’s disposition, however. The packet must match an accept or drop rule. Some of the rules presented previously had logging enabled, before matching the packet a second time to drop it. Some of the IP address spoofing rules are examples. Rules can be defined for the explicit purpose of logging certain kinds of packets. Most typically, packets of interest are suspicious packets indicating some sort of probe or scan. Because all packets are denied by default, if logging is desired for certain packet types, explicit rules must be defined before the packet falls off the end of the chain and the default policy takes effect. Essentially, out of all the denied packets, you might be interested in logging some of them, using rate-limited logging for some, and silently dropping others. Which packets are logged is an individual matter. Some people want to log all dropped packets. For other people, logging all dropped packets could soon overflow their system logs. Some people, secure in the knowledge that the packets are dropped, don’t care about them and don’t want to know about them. Other people are interested in the obvious port scans or in some particular packet type.

170

Logging Dropped Incoming Packets

Because of the first-matching-rule-wins behavior, you could log all dropped incoming packets with a single rule. The assumption here is that all packet-matching acceptance rules have been tested, and the packet is about to drop off the end of the chain and be thrown away:
$IPT -A INPUT -i $INTERNET -j LOG

For some people, this will produce too many log entries—or too many uninteresting log entries. For example, you might want to log all dropped incoming ICMP traffic with the exception of ping because it is a common service, regardless of whether your site responds to ping requests:
$IPT -A INPUT -i $INTERNET -p icmp \ --icmp-type ! 8 -d $IPADDR -j LOG

You might want to log dropped incoming TCP traffic to all ports and log dropped incoming UDP traffic to your privileged ports:
$IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR -j LOG $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport $PRIVPORTS -j LOG

Then again, you might want to log all dropped privileged port access, with the exception of commonly probed ports that you don’t offer service on anyway:
$IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 0:19 -j LOG # skip ftp, telnet, ssh $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 24 -j LOG # skip smtp $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 26:78 -j LOG # skip finger, www $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 81:109 -j LOG # skip pop-3, sunrpc $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 112:136 -j LOG # skip NetBIOS $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 140:142 -j LOG # skip imap $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 144:442 -j LOG

171

C H A P T E R 4 : Building and Installing a Standalone Firewall

# skip secure_web/SSL $IPT -A INPUT -i $INTERNET -p tcp \ -d $IPADDR --dport 444:65535 -j LOG #UDP rules $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 0:110 -j LOG # skip sunrpc $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 112:160 -j LOG # skip snmp $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 163:634 -j LOG # skip NFS mountd $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 636:5631 -j LOG # skip pcAnywhere $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 5633:31336 -j LOG # skip traceroute’s default ports $IPT -A INPUT -i $INTERNET -p udp \ --sport $TRACEROUTE_SRC \ -d $IPADDR --dport $TRACEROUTE_DEST -j LOG # skip the rest $IPT -A INPUT -i $INTERNET -p udp \ -d $IPADDR --dport 33434:65535 -j LOG

Logging Dropped Outgoing Packets
Logging outgoing traffic blocked by the firewall rules is necessary for debugging the firewall rules and to be alerted to local software problems. With the exception of outgoing ICMP type 3 errors, which were dropped previously, possibly all traffic about to be dropped by the default policy could be logged:
$IPT -A OUTPUT -o $INTERNET -j LOG

Denying Access to Problem Sites Up Front
If some site is making a habit of scanning your machine or otherwise being a nuisance, you might decide to deny it access to everything, at least until the problem behavior is corrected.

172

Installing the Firewall

One way to do this without editing the rc.firewall script each time is to include a separate file of specific drop rules. By inserting the rules into the INPUT chain rather than appending them, the site will be blocked even if subsequent rules would otherwise allow them access to some service. The file is named /etc/rc.d/rc.firewall.blocked. To avoid a possible runtime error, check for the file’s existence before trying to include it:
# Refuse packets claiming to be from the banned list if [ -f /etc/rc.d/rc.firewall.blocked ]; then . /etc/rc.d/rc.firewall.blocked fi

An example of a global drop rule in the rc.firewall.blocked file is this:
$IPT -I INPUT -i $INTERNET -s <address/mask> -j DROP

As an alternative to inserting the rules at the very beginning of the chains, which would precede state checking, the rules could be append rules, and the file could be included in the spoofed source address section of the ruleset. Any packet from this source address range is dropped, regardless of message protocol type or source or destination port.

Installing the Firewall
This section assumes that the firewall script is called rc.firewall. There’s no reason that the script couldn’t be called simply fwscript or something else either. In fact, on Debian systems the standard is closer to the single name, fwscript, rather than a name prefixed with an rc. as is the case on Red Hat. This section covers the commands as if the script was installed in either /etc/rc.d/ for a Red Hat or SUSE system and /etc/init.d/ for a Debian system. As a shell script, initial installation is simple. The script should be owned by root. On Red Hat and SUSE:
chown root.root /etc/rc.d/rc.firewall

On Debian:
chown root.root /etc/init.d/rc.firewall

The script should be writable and executable by root alone. Ideally, the general user should not have read access. On Red Hat and SUSE:
chmod u=rwx /etc/rc.d/rc.firewall

On Debian:
chmod u=rwx /etc/init.d/rc.firewall

173

C H A P T E R 4 : Building and Installing a Standalone Firewall

To initialize the firewall at any time, execute the script from the command line. There is no need to reboot:
/etc/rc.d/rc.firewall start

Technically, the start argument isn’t required there, but it’s a good habit anyway—again, I’d rather err on the side of completeness than have ambiguity with a firewall. The script includes a stop action that flushes the firewall entirely. Therefore, if you want to stop the firewall, call the same command with the stop argument:
/etc/rc.d/rc.firewall stop

Be forewarned: If you stop the firewall in this way, you are running with no protection. The attorneys tell me that I should tell you, “Always leave the firewall enabled!” On Debian, change the path for the command to /etc/init.d. Start the firewall:
/etc/init.d/rc.firewall start

Stop the firewall on Debian:
/etc/init.d/rc.firewall stop

Tips for Debugging the Firewall Script
When you’re debugging a new firewall script through an SSH or another remote connection, it’s quite possible that you might lock yourself out of the system. Granted, this isn’t a concern when you’re installing the firewall from the console, but as someone who manages remote Linux servers, I find that access to the console is rarely possible. Therefore, a method is necessary for stopping the firewall automatically after it gets started, just in case the firewall locks out my connection. Cron to the rescue. Using a cron entry, you can stop the firewall by running the script with a stop argument at some predefined interval. I find that every 2 minutes works well during initial debugging. If you’d like to use this method, set a cron entry with the following command as root (on Debian):
crontab -e */2 * * * * /etc/init.d/rc.firewall stop

On Red Hat and SUSE:
crontab -e */2 * * * * /etc/rc.d/rc.firewall stop

With this cron entry in place, you can start the firewall and have it stop every 2 minutes. Using such a mechanism is somewhat of a trade-off though, because you have to do your

174

Installing the Firewall

initial debugging before the clock hits a minute divisible by two! Additionally, it’s up to you to remember to remove this cron entry when you’ve debugged the firewall. If you forget to remove this entry the firewall will stop and you’ll be running with no firewall again!

Starting the Firewall on Boot with Red Hat and SUSE
On Red Hat and SUSE, the simplest way to initialize the firewall is to edit /etc/rc.d/rc.local and add the following line to the end of the file:
/etc/rc.d/rc.firewall start

After the firewall rules are debugged and stable, Red Hat Linux provides a more standard way to start and stop the firewall. If you chose iptables while using one of the runlevel managers, the default runlevel directory contains a link to /etc/rc.d/init.d/_iptables. As with the other startup scripts in this directory, the system will start and stop the firewall automatically when booting or changing runlevels. One additional step is required to use the standard runlevel system, however. You must first manually install the firewall rules:
/etc/rc.d/rc.firewall

Then execute the command:
/etc/init.d/iptables save

The rules will be saved in a file, /etc/sysconfig/iptables. After this, the startup script will find this file and load the saved rules automatically. A word of caution is in order about saving and loading the firewall rules using this method. The iptables save and load features are not fully debugged at this point. If your particular firewall configuration results in a syntax error when saving or loading the rules, you must continue using some other startup mechanism, such as executing the firewall script from /etc/rc.d/rc.local.

Starting the Firewall on Boot with Debian
As with many other things, configuring the firewall script to start on boot is simpler on Debian than on other distributions. You can make the firewall start and stop on boot with the update-rc.d command. Run update-rc.d with the firewall script in /etc/init.d, and set your current directory to /etc/init.d/ as well:
cd /etc/init.d update-rc.d rc.firewall defaults

See the man page for update-rc.d for more information on its usage beyond that shown here.

175

C H A P T E R 4 : Building and Installing a Standalone Firewall

Other aspects of the firewall script depend on whether you have a registered, static IP address or a dynamic, DHCP-assigned IP address. The firewall script as presented in this chapter is set up for a site with a statically assigned, permanent IP address.

Installing a Firewall with a Dynamic IP Address
If you have a dynamically assigned IP address, the standard firewall installation method won’t work without modification. The firewall rules would be installed before the network interfaces are brought up, before the system is assigned an IP address, and possibly before being assigned a default gateway router or name servers. The firewall script itself needs the IPADDR and NAMESERVER values defined. Both the DHCP server and the local /etc/resolv.conf file can define up to three name servers. Also, any given site may or may not know the addresses of their name servers, default gateway router, or DHCP server ahead of time. Furthermore, it’s not uncommon for your network mask, subnet, and broadcast addresses to change over time as the ISP renumbers its network. Some ISPs assign a different IP address on a frequent basis, with the result that your IP address can change numerous times during the course of an ongoing connection. Your site must provide some means of dynamically updating the installed firewall rules as these changes occur. Appendix B, “Firewall Examples and Support Scripts,” provides sample scripts designed to handle these changes automatically. In addition, if you’re using a DSL connection, there’s a chance that the MTU might cause problems. If this is the case, here’s a firewall rule to fix the problem:
$IPT -A OUTPUT -o $INTERNET -p tcp --tcp-flags SYN,RST \ SYN -j TCPMSS --clamp-mss-to-pmtu

The firewall script could read these shell variables directly from the environment or could read them from a file. In any case, the variables would not be hard-coded into the firewall script, as they are in the example in this chapter.

Summary
This chapter led you through the processes involved in developing a standalone firewall using iptables. The deny-by-default policy was established. Some commonly used attack vectors were fixed at the beginning of the script, including source address spoofing, protecting services running on unprivileged ports, and DNS. Examples of rules for popular network services were shown. ICMP messages, the control and status messages used by the underlying IP Network layer, were handled as well. Examples of controlling the level of logging produced

176

Summary

were demonstrated. Finally, the issues involved in firewall installation were described, both for sites with a static IP address and for sites with a dynamically assigned IP address. Chapter 5 uses the standalone firewall as the basis for building an optimized firewall. Chapter 6 uses it as the basis for a more complicated firewall architecture. A screened subnet architecture using two firewalls separating a DMZ perimeter network is described in Chapter 6. A small business could easily have the need and the resources for this more elaborate configuration. Chapter 7 uses the standalone firewall as the basis for its examples but does not build on this example directly.

177

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close