Linux Firewalls Using iptables

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

In This Chapter

Chapter 2

Linux Firewalls Using iptables

What Is iptables?

Download And Install The Iptables Package

How To Get iptables Started

Determining The Status of iptables

Fedora Core Status Messages

RedHat 9 Status Messages

Packet Processing In iptables

Iptables Packet Flow Diagram

Processing For Packets Routed By The Firewall

Packet Processing For Data Received By The Firewall

Packet Processing For Data Sent By The Firewall

Targets And Jumps

Descriptions Of The Most Commonly Used Targets

Important Iptables Command Switch Operations

General Iptables Match Criteria

Common TCP and UDP Match Criteria

Common ICMP (Ping) Match Criteria

Common Match Extensions Criteria

Using User Defined Chains

Sample iptables Scripts

Basic Operating System Defense

Basic iptables Initialization

Advanced iptables Initialization

Allowing DNS Access To Your Firewall

Allowing WWW And SSH Access To Your Firewall

Allowing Your Firewall To Access The Internet

Allow Your Home Network To Access The Firewall

Masquerading (Many to One NAT)

Port Forwarding Type NAT (DHCP DSL)

Static NAT

Logging & Troubleshooting

 

(c) Peter Harrison, www.linuxhomenetworking.com

 

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =


You can convert your Linux box into a firewall using the IPtables package. This page shows how to convert your Linux box into:

>        A firewall while simultaneously being your home website's mail, web and DNS server.

>        A router that will use NAT and port forwarding to both protect your home network and have another web server on your home network while sharing the public IP address of your firewall

What Is iptables?

Originally, the most popular firewall / NAT package running on Linux was ipchains. It had a number of limitations, the primary one being that it ran as a separate program and not as part of the kernel. The Netfilter organization decided to create a new product called iptables in order to rectify this shortcoming. As a result of this, iptables is considered a faster and more secure alternative.  iptables has now become the default firewall package installed under RedHat and Fedora Linux.

Download And Install The Iptables Package

Most RedHat and Fedora Linux software products are available in the RPM format. Downloading and installing RPMs isn't hard. If you need a refresher, the chapter on RPMs covers how to do this in detail. The latest version of the RPM for Fedora Core 1 is iptables-1.2.9-1.0.i386.rpm. Install the package using the following command:

 

[root@bigboy tmp]# rpm -Uvh iptables-1.2.9-1.0.i386.rpm
Preparing...    ########################################### [100%]
1:iptables      ########################################### [100%]

[root@bigboy tmp]#

How To Get iptables Started

You can start/stop/restart iptables after booting by using the following commands:

 

[root@bigboy tmp]# /etc/init.d/iptables start
[root@bigboy tmp]# /etc/init.d/iptables stop
[root@bigboy tmp]# /etc/init.d/iptables restart

 

To get iptables configured to start at boot:

 

[root@bigboy tmp]# chkconfig --level 345 iptables on

Determining The Status of iptables

You can determine whether iptables is running or not by running the init.d script with the "status" argument. Fedora Core will give a simple status message. RedHat 9 and older will give a short rule list in which all the firewall policies are set to "accept".


 

Fedora Core Status Messages

[root@bigboy tmp]# /etc/init.d/iptables status

Firewall is stopped.

[root@bigboy tmp]#

RedHat 9 Status Messages

[root@bigboy sysconfig]# /etc/init.d/iptables status

Table: filter

Chain INPUT (policy ACCEPT)

target     prot opt source               destination

 

Chain FORWARD (policy ACCEPT)

target     prot opt source               destination

 

Chain OUTPUT (policy ACCEPT)

target     prot opt source               destination

[root@bigboy sysconfig]#

Packet Processing In iptables

All packets inspected by iptables pass through a sequence of built-in tables (queues) for processing. Each of these queue is dedicated to a particular type of packet activity and is controlled by an associated packet transformation / filtering chain. Don't worry if this all seems confusing, there'll be tables and examples of how the concepts are all interlinked.

For example, the chart and graphic below describe the steps taken by iptables when a packet traverses the firewall.


Iptables Packet Flow Diagram

 

 

 


 

Processing For Packets Routed By The Firewall

 

Packet flow

Intercepted by iptables chain (Queue)

Packet transformation table associated with this queue

Description of possible modifications by iptables using this transformation table

Packet enters the NIC and is passed to iptables

Mangle

PREROUTING

Modification of the TCP packet quality of service bits.

(Rarely used)

 

Nat

PREROUTING

Destination network address translation (DNAT). Frequently used to NAT connections from the Internet to your home network

Packet passed to the Linux routing engine

N/A

N/A

N/A

Determines whether the packet is destined to a local application or should be sent out another NIC interface

Packet passed back to iptables

Filter

FORWARD

Packet filtering:

Packets destined for servers accessible by another NIC on the firewall.

 

Nat

POSTROUTING

Source network address translation (SNAT). Frequently used to NAT connections from your home network to the Internet

Packet transmitted out the other NIC

N/A

N/A

N/A

 


 

Packet Processing For Data Received By The Firewall

 

Packet flow

Actions by Operating System

Packet intercepted by iptables table (Queue)

Packet transformation chain associated with this queue

Description of possible modifications by iptables using this transformation table

Packet

destined for firewall

 

Packet enters the NIC from remote server.

The packet is intercepted by the iptables mangle, then nat queues

mangle

PREROUTING

Modification of the TCP packet quality of service bits.

(Rarely used)

 

 

nat

PREROUTING

Destination network address translation (DNAT)

 

The packet is then passed from iptables to the Linux routing engine.

 

The routing engine passes the packet to the target application via the iptables filter queue

filter

INPUT

Packet filtering:

Packets destined for the firewall.

The application receives the packet from iptables then processes it.

 


 

 

Packet Processing For Data Sent By The Firewall

 

Packet flow

Actions by Operating System

Packet intercepted by iptables table (Queue)

Packet transformation chain associated with this queue

Description of possible modifications by iptables using this transformation table

The application sends data to a remote server

Packet

originating from firewall

 

The packet is intercepted by iptables which then processes it in the mangle, nat and filter tables

mangle

OUTPUT

Modification of the TCP packet quality of service bits.

(Rarely used)

 

 

nat

OUTPUT

Source network address translation

(Rarely used)

 

 

filter

OUTPUT

Packet filtering:

Packets destined for other servers / devices.

 

The packet is then passed to the Linux routing engine which forwards the packet out the correct NIC


The packet is intercepted by the iptables nat table

nat

POSTROUTING

Source network address translation (SNAT)

Packet transmitted out a NIC

 


 

Targets And Jumps

You don't have to rely solely on the built-in chains provided by iptables, you can create your own chains. These can be accessed by making them the targets of "jumps" in the built-in chains. So in summary, the targets/jumps tell the rule what to do with a packet that matches the rule perfectly.

There are a number of built-in targets that most rules may use.

 

Descriptions Of The Most Commonly Used Targets

Target

Description

Most common options

ACCEPT

>        iptables stops further processing.

>        The packet is handed over to the end application or the operating system for processing

N/A

DROP

>        iptables stops further processing.

>        The packet is blocked

N/A

 

LOG

>        The packet information is sent to the syslog daemon for logging

>        iptables continues processing with the next rule in the table

>        As you can't LOG and DROP at the same time, it is common to have two similar rules in sequence. The first will LOG the packet, the second will DROP it.

--log-prefix "string"

 

Tells iptables to prefix all log messages with a user defined string. Frequently used to tell why the logged packet was dropped

REJECT

>        Works like the DROP target, but will also return an error message to the host sending the packet that was blocked

--reject-with qualifier

 

The qualifier tells what type of reject message is returned. These include:

 

icmp-port-unreachable (default)

icmp-net-unreachable

icmp-host-unreachable

icmp-proto-unreachable

icmp-net-prohibited

icmp-host-prohibited

tcp-reset

echo-reply

DNAT

>        Used to do Destination Network Address Translation. ie.rewriting the destination IP address of the packet

--to-destination ipaddress

 

Tells iptables what the destination IP address should be

SNAT

>        Used to do Source Network Address Translation. ie.rewriting the source IP address of the packet

>        The source IP address is user defined

--to-source <address>[-<address>][:<port>-<port>]

 

Specifies the source IP address and ports to be used by SNAT.

MASQUERADE

 

>        Used to do Source Network Address Translation. ie.rewriting the source IP address of the packet

>        By default the source IP address is the same as that used by the firewall's interface

[--to-ports <port>[-<port>]]

 

Specifies the range of source ports the original source port can be mapped to.

 

 


 

Important Iptables Command Switch Operations

We'll now explore how to use iptables command switches used to create your firewall.

General Iptables Match Criteria

iptables

command

Switch

Description

-t <table>

If you don't specify a table, then the filter table is assumed. As discussed before, the possible built-in tables include: filter, nat, mangle

-A

Append rule to end of a chain

-F

Flush. Deletes all the rules in the selected table

-p <protocol-type>

Match protocol. Types include, icmp, tcp, udp, all

-s <ip-address>

Match source IP address

-d <ip-address>

Match destination IP address

-i <interface-name>

Match "input" interface on which the packet enters.

-o <interface-name>

Match "output" interface on which the packet exits

 

Example:

 

iptables -A INPUT -s 0/0 -i eth0 -d 192.168.1.1  -p TCP -j ACCEPT

 

In this example iptables is being configured to allow the firewall to accept TCP packets coming in on interface eth0 from any IP address destined for the firewall's IP address of 192.168.1.1


 

Common TCP and UDP Match Criteria 

switches used with

 

-p tcp

Description

 

switches used with

 

-p udp

Description

 

--sport <port>

TCP source port

Can be a single value or a range in the format:

start-port-number:end-port-number

 

--sport <port>

TCP source port

Can be a single value or a range in the format:

starting-port:ending-port

--dport <port>

TCP destination port

Can be a single value or a range in the format:

starting-port:ending-port

 

--dport <port>

TCP destination port

Can be a single value or a range in the format:

starting-port:ending-port

--syn

Used to identify a new connection request

 

! --syn means, not a new connection request

 

 

 

 

Example:

 

iptables -A FORWARD -s 0/0 -i eth0 -d 192.168.1.58 -o eth1 -p TCP \

         --sport 1024:65535 --dport 80 -j ACCEPT

 

In this example iptables is being configured to allow the firewall to accept TCP packets to be routed when they enter on interface eth0 from any IP address destined for IP address of 192.168.1.58 that is reachable via interface eth1. The source port is in the range 1024 to 65535 and the destination port is port 80 (www/http)


 

Common ICMP (Ping) Match Criteria 

Matches

used with

 

---icmp-type

Description

--icmp-type <type>

The most commonly used types are

echo-reply and echo-request

 

Example:

 

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT  -p icmp --icmp-type echo-reply   -j ACCEPT

 

In this example iptables is being configured to allow the firewall send ICMP echo-requests (pings) and in turn, accept the expected ICMP echo-replies.

 

 

Common Match Extensions Criteria 

TCP/UDP match

extensions used with

 

-m multiport

Description

--sport <port, port>

A variety of TCP/UDP source ports separated by commas

--dport <port, port>

A variety of TCP/UDP destination  ports separated by commas

--dport <port, port>

A variety of TCP/UDP ports separated by commas. Source and destination ports are assumed to be the same.

 

 

 


 

Match extensions

used with

 

-m state

Description

--state <state>

The most frequently tested states are:

 

ESTABLISHED

The packet is part of a connection which has seen packets in both directions

 

NEW

The packet is the start of a new connection

 

RELATED

The packet is starting a new secondary connection. This is a common feature of protocols such as an FTP data transfer, or an ICMP error.

 

Example:

 

iptables -A FORWARD -s 0/0 -i eth0 -d 192.168.1.58 -o eth1 -p TCP \

         --sport 1024:65535 -m multiport --dport 80,443 -j ACCEPT

 

iptables -A FORWARD -d 0/0 -o eth0 -s 192.168.1.58 -i eth1 -p TCP \

         -m state --state ESTABLISHED -j ACCEPT

 

This is an expansion on the previous example. Here iptables is being configured to allow the firewall to accept TCP packets to be routed when they enter on interface eth0 from any IP address destined for IP address of 192.168.1.58 that is reachable via interface eth1. The source port is in the range 1024 to 65535 and the destination ports are port 80 (www/http) and 443 (https).

We are also allowing the return packets from 192.168.1.58 to be accepted too. Instead of stating the source and destination ports, it is sufficient to allow packets related to established connections using the -m state and --state ESTABLISHED options.


 

Using User Defined Chains

As stated in the introduction, iptables can be configured to have user-defined chains. This feature is frequently used to help streamline the processing of packets. For example, instead of having a single chain for all protocols, it is possible to have a chain that determines the protocol type for the packet and then hands off the actual final processing to a protocol specific chain. In other words, you can replace a long chain with a main stubby chain pointing to multiple stubby chains thereby shortening the total length of all chains the packet has to pass through.

 

Example:

 

iptables -A INPUT -i eth0  -d 206.229.110.2 -j fast-input-queue
iptables -A OUTPUT -o eth0 -s 206.229.110.2 -j fast-output-queue

iptables -A fast-input-queue  -p icmp -j icmp-queue-in
iptables -A fast-output-queue -p icmp -j icmp-queue-out

iptables -A icmp-queue-out -p icmp --icmp-type echo-request \
         -m state --state NEW -j ACCEPT

iptables -A icmp-queue-in -p icmp --icmp-type echo-reply -j ACCEPT

 

In this example we have six queues with the following characteristics to help assist in processing speed:

 

 

Chain

Description

INPUT

The regular built-in INPUT chain in iptables

OUTPUT

The regular built-in OUTPUT chain in iptables

fast-input-queue

Input chain dedicated to specific protocols

fast-output-queue

Output chain dedicated to specific protocols

icmp-queue-out

Output queue dedicated to ICMP

icmp-queue-in

Intput queue dedicated to ICMP

 

 

 


 

Sample iptables Scripts

Here are some sample scripts you can use to get iptables working for you. It is best to invoke these from your /etc/rc.d/rc.local file so that the firewall script is run every time you boot up. Pay special attention to the logging example at the end.

The "basic initialization" script snippet should also be included in all your scripts to ensure the correct initialization of your chains should you decide to restart your script after startup. This chapter also includes other snippets that will help you get basic functionality. It should be a good guide to get you started.

You then can use the Appendix to find a detailed script once you feel more confident. It shows you how to allow your firewall to:

>        Be used as a Linux Web / Mail / DNS server

>        Be the NAT router for your home network

>        Prevent various types of attacks using corrupted TCP, UDP and ICMP packets.

>        Outbound passive FTP access from the firewall

There are also simpler code snippets in the Appendix for:

>        Inbound and outbound FTP connections to / from your firewall

Basic Operating System Defense

There are a number of things you can do at the very beginning of your firewall script to improve the resilience of your firewall to attack. Here are some sample commands you can use:

 

#!/bin/bash

 

#---------------------------------------------------------------

# Disable routing triangulation. Respond to queries out

# the same interface, not another. Helps to maintain state

# Also protects against IP spoofing

#---------------------------------------------------------------

 

echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter

 

 

#---------------------------------------------------------------

# Enable logging of packets with malformed IP addresses

#---------------------------------------------------------------

 

echo 1 > /proc/sys/net/ipv4/conf/all/log_martians

 

 

#---------------------------------------------------------------

# Disable redirects

#---------------------------------------------------------------

 

echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects

 

 

#---------------------------------------------------------------

# Disable source routed packets

#---------------------------------------------------------------

 

echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

 

 

#---------------------------------------------------------------

# Disable acceptance of ICMP redirects

#---------------------------------------------------------------

 

echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects

 

 

#---------------------------------------------------------------

# Turn on protection from Denial of Service (DOS) attacks

#---------------------------------------------------------------

 

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

 

 

#---------------------------------------------------------------

# Disable responding to ping broadcasts

#---------------------------------------------------------------

 

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

 

Basic iptables Initialization

It is a good policy, in any iptables script you write, to initialize your chain and table settings with known values. The "filter" table's INPUT, FORWARD and OUTPUT chains should DROP packets by default for the best security. However, it is not good policy to make your "nat" and "mangle" tables DROP packets by default. This is because these tables are queried before the "filter" table, and if all packets that don't match the "nat" and "mangle" rules  are DROP-ped, then they will not reach the the INPUT, FORWARD and OUTPUT chains and won't be processed.

 

Additional ALLOW rules should be added to the end of this script snippet.

 

#---------------------------------------------------------------
# Load modules for FTP connection tracking and NAT - You may need

# them later
#---------------------------------------------------------------

modprobe ip_conntrack_ftp

modprobe iptable_nat


#---------------------------------------------------------------
# Initialize all the chains by removing all the rules
# tied to them
#---------------------------------------------------------------

iptables --flush
iptables -t nat --flush
iptables -t mangle --flush

#---------------------------------------------------------------
# Now that the chains have been initialized, the user defined
# chains should be deleted. We'll recreate them in the next step
#---------------------------------------------------------------

iptables --delete-chain
iptables -t nat --delete-chain
iptables -t mangle --delete-chain

#---------------------------------------------------------------
# If a packet doesn't match one of the built in chains, then
# The policy should be to drop it
#---------------------------------------------------------------

iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP

 

#---------------------------------------------------------------
# The loopback interface should accept all traffic

# Necessary for X-Windows and other socket based services
#---------------------------------------------------------------

iptables -A INPUT  -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

Advanced iptables Initialization

There are more advanced initialization steps you may also want to add to your script. These include checks for invalid TCP flags and Internet traffic from RFC1918 private addresses. The sample script snippets below outline how to do this.

The script also uses multiple user defined chains can make the script shorter and faster as the chains can be repeatedly accessed. This removes the need to repeat the same statements over and over again.

You can take even more precautions to further protect your network. The complete firewall script in the appendix outlines most of them.

 

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=

#

# Define networks: NOTE!! You may want to put these four "EXTERNAL"

# definitions at the top of your script.

#

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=

 

EXTERNAL_INT="eth0"                             # Internet-connected

                                                # interface

EXTERNAL_IP="97.158.253.25"                     # your IP address

EXTERNAL_SUBNET_BASE="97.158.253.24"            # ISP network segment

                                                # base address

EXTERNAL_SUBNET_BROADCAST="97.158.253.31"       # network segment

                                                # broadcast address

 

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=

#

# The variables below should not normally be changed as they

# are not site specific

#

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=

 

LOOPBACK="127.0.0.0/8"                    # reserved for

                                          # loopback address

RESERVED_IP_172_SPACE="172.16.0.0/12"     # RFC1918 172 space

                                          # class B private networks

RESERVED_IP_192_SPACE="192.168.0.0/16"    # RFC1918 192 space

                                          # class C private networks

RESERVED_IP_10_SPACE="10.0.0.0/8"         # RFC1918 10 space

                                          # class A private networks

RESERVED_IP_MULTICAST="224.0.0.0/4"       # Multicast addresses

RESERVED_IP_FUTURE="240.0.0.0/5"          # IP addresses reserved

                                          # for future use

 

#---------------------------------------------------------------

# Check TCP packets for invalid state flag combinations

#---------------------------------------------------------------

 

iptables -A INPUT   -p tcp -j valid-tcp-flags

iptables -A OUTPUT  -p tcp -j valid-tcp-flags

iptables -A FORWARD -p tcp -j valid-tcp-flags

 

#---------------------------------------------------------------

# Verify valid source and destination addresses for all packets

#---------------------------------------------------------------

 

iptables -A INPUT   -i $EXTERNAL_INT -p ! tcp     \

            -j valid-source-address

iptables -A INPUT   -i $EXTERNAL_INT -p tcp --syn \

            -j valid-source-address

iptables -A FORWARD -i $EXTERNAL_INT -p ! tcp     \

            -j valid-source-address

iptables -A FORWARD -i $EXTERNAL_INT -p tcp --syn \

            -j valid-source-address

iptables -A OUTPUT  -o $EXTERNAL_INT              \

            -j valid-destination-address

iptables -A FORWARD -o $EXTERNAL_INT              \

            -j valid-destination-address

 

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

#

# Check for incorrect TCP state flags

#

# All state bits zeroed

# FIN set ACK cleared

# PSH set ACK cleared

# URG set ACK cleared

# SYN and FIN set

# SYN and RST set

# FIN and RST set

#

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

 

iptables -A valid-tcp-flags -p tcp --tcp-flags ALL NONE \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags ACK,FIN FIN \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags ACK,PSH PSH \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags ACK,URG URG \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags SYN,FIN SYN,FIN \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags SYN,RST SYN,RST \

            -j LOG-and-drop

iptables -A valid-tcp-flags -p tcp --tcp-flags FIN,RST FIN,RST \

            -j LOG-and-drop

 

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

#

# Source and Destination Address Sanity Checks

#

# Drop packets from networks covered in RFC 1918 (private nets)

# Drop packets from external interface IP

# Drop directed broadcast packets

#

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

 

iptables -A valid-source-address -s $RESERVED_IP_10_SPACE  -j DROP

iptables -A valid-source-address -s $RESERVED_IP_172_SPACE -j DROP

iptables -A valid-source-address -s $RESERVED_IP_192_SPACE -j DROP

iptables -A valid-source-address -s $RESERVED_IP_MULTICAST -j DROP

iptables -A valid-source-address -s $RESERVED_IP_FUTURE    -j DROP

iptables -A valid-source-address -s $LOOPBACK              -j DROP

iptables -A valid-source-address -s 0.0.0.0/8              -j DROP

iptables -A valid-source-address -d 255.255.255.255        -j DROP

iptables -A valid-source-address -s 169.254.0.0/16         -j DROP

iptables -A valid-source-address -s 192.0.2.0/24           -j DROP

iptables -A valid-source-address -s $EXTERNAL_IP           -j DROP

 

iptables -A valid-destination-address -d $EXTERNAL_SUBNET_BASE \

            -j DROP

iptables -A valid-destination-address -d $EXTERNAL_SUBNET_BROADCAST \

            -j DROP

iptables -A valid-destination-address -d $RESERVED_IP_MULTICAST \

            -j DROP

 

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

#

# Log and drop chain

#

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

 

iptables -A LOG-and-drop -j LOG --log-ip-options --log-tcp-options \

            --log-level debug

iptables -A LOG-and-drop -j DROP


Allowing DNS Access To Your Firewall

You'll almost certainly want your firewall to make DNS queries to the Internet. The following statements will apply not only for firewalls acting as DNS clients but also for firewalls working in a caching or regular DNS server role.

 

#---------------------------------------------------------------

# Allow outbound DNS queries from the FW and the replies too

#

# - Interface eth0 is the internet interface

#

# Zone transfers use TCP and not UDP. Most home networks

# / websites using a single DNS server won't require TCP statements

#

#---------------------------------------------------------------

 

iptables -A OUTPUT -p udp -o eth0 --dport 53 --sport 1024:65535 \

         -j ACCEPT

 

iptables -A INPUT -p udp -i eth0 --sport 53 --dport 1024:65535 \

         -j ACCEPT

Allowing WWW And SSH Access To Your Firewall

This sample snippet is for a web server that is managed remotely by its system administrator via secure shell (SSH) sessions. Inbound packets destined for ports 80 and 22 are allowed thereby making the first steps in establishing a connection. It isn't necessary to specify these ports for the return leg as outbound packets for all established connections are allowed. Connections initiated by persons logged into the webserver will be denied as outbound NEW connection packets aren't allowed.

 

#---------------------------------------------------------------
# Allow previously established connections

# - Interface eth0 is the internet interface

#---------------------------------------------------------------

iptables -A OUTPUT -o eth0 -m state --state ESTABLISHED,RELATED \

  -j ACCEPT

#---------------------------------------------------------------
# Allow port 80 (www) and 22 (SSH) connections to the firewall

#---------------------------------------------------------------

iptables -A INPUT -p tcp -i eth0 --dport 22 --sport 1024:65535 \

  -m state -state NEW -j ACCEPT

iptables -A INPUT -p tcp -i eth0 --dport 80 --sport 1024:65535 \

  -m state -state NEW -j ACCEPT

 


Allowing Your Firewall To Access The Internet

The following iptables sample script allows a user on the firewall to use a web browser to surf the Internet. TCP port 80 is used for HTTP traffic and port 443 is used for HTTPS (secure HTTP frequently used for credit card transactions). HTTPS is also used by RedHat Linux servers using up2date.

 

#---------------------------------------------------------------
# Allow port 80 (www) and 443 (https) connections to the firewall

#---------------------------------------------------------------

iptables -A OUTPUT -j ACCEPT -m state --state NEW \

  -o eth0 -p tcp -m multiport --dport 80,443 --sport 1024:65535

 

#---------------------------------------------------------------
# Allow previously established connections

# - Interface eth0 is the internet interface

#---------------------------------------------------------------
iptables -A INPUT -j ACCEPT -m state --state ESTABLISHED,RELATED  \

-i eth0 -p tcp

 

 

If you want all TCP traffic originating from the firewall to be accepted then you can remove the following section from the snippet above:

 

-m multiport --dport 80,443 --sport 1024:65535

 

Allow Your Home Network To Access The Firewall

In this example, eth1 is directly connected to a home network using IP addresses from the 192.168.1.0 network. All traffic between this network and the firewall is simplistically assumed to be trusted and allowed.

Further rules will be needed for the interface connected to the Internet to allow only specific ports, types of connections and possibly even remote servers to have access to your firewall and home network.

 

#---------------------------------------------------------------
# Allow all bidirectional traffic from your firewall to the

# protected network

# - Interface eth1 is the private network interface

#---------------------------------------------------------------


iptables -A INPUT   -j ACCEPT -p all -s 192.168.1.0/24 -i eth1
iptables -A OUTPUT  -j ACCEPT -p all -d 192.168.1.0/24 -o eth1




Masquerading (Many to One NAT)

As explained in the Introduction to Networking chapter, masquerading is another word for what many call "many to one" NAT. In other words, traffic from all devices on one or more protected networks will appear as if it originated from a single IP address on the Internet side of the firewall.

Note: You can force your firewall to use a pre-defined IP address for many to one NAT by using an IP alias together with iptable's POSTROUTING queue. This can come in handy when you want machines from one network to all NAT to one alias address, and those from another network to all NAT to a second alias. The advantage of masquerading is that you never have to specify the NAT IP address as it always uses the firewall's interface's main IP address. This makes it much easier to configure NAT with DHCP. There is an example using the POSTROUTING statement for NAT using fixed IP addresses in the static NAT section below. Though it may be tempting, configuring IP aliases with DHCP is not a good idea as it may cause conflicts with other DHCP client computers.

iptables requires the iptables_nat module to be loaded with the "modprobe" command for the masquerade feature to work. Masquerading also depends on the Linux operating system being configured to support routing between the internet and private network interfaces of the firewall. This is done by enabling "IP forwarding" or routing by giving the file /proc/sys/net/ipv4/ip_forward the value "1" as opposed to the default disabled value of "0".

Once masquerading has been achieved using the POSTROUTING chain of the "nat" table, iptables will have to be configured to allow packets to flow between the two interfaces. This is done using the FORWARD chain of the "filter" table. More specifically, packets related to NEW and ESTABLISHED connections will be allowed outbound to the Internet, while only packets related to ESTABLISHED connections will be allowed inbound. This helps to protect the home network from persons trying to initiate connections from the Internet. An example follows:

 

#---------------------------------------------------------------
# Load the NAT module

#---------------------------------------------------------------

 

modprobe iptable_nat

 

#---------------------------------------------------------------
# Allow masquerading

# Enable routing by modifying the ip_forward /proc filesystem file

# - Interface eth0 is the internet interface

# - Interface eth1 is the private network interface

#---------------------------------------------------------------

 

iptables -A POSTROUTING -t nat -o eth0 -s 192.168.1.0/24 -d 0/0 \

         -j MASQUERADE


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

#---------------------------------------------------------------
# Prior to masquerading, the packets are routed via the filter

# table's FORWARD chain.

# Allowed outbound: New, established and related connections

# Allowed inbound : Established and related connections

#---------------------------------------------------------------

 

iptables -A FORWARD -t filter -i eth1 -m state \

         --state NEW,ESTABLISHED,RELATED -j ACCEPT


iptables -A FORWARD -t filter -i eth0 -m state \

         --state ESTABLISHED,RELATED     -j ACCEPT

 

Note: If you configure your firewall to do masquerading, then if should be the used as the default gateway for all your servers on the network.

 

Port Forwarding Type NAT (DHCP DSL)

In many cases home users may get a single DHCP public IP address from their ISP. If their Linux firewall is their interface to the Internet and they want to host a website on one of the NAT protected home servers then they will have to use the "port forwarding" technique.

Here the combination of the firewall's single IP address, the remote server's IP address and the source/destination port of the traffic can be used to uniquely identify a traffic flow. All traffic that matches a particular combination of these factors may then be forwarded to a single server on the private network.

Port forwarding is handled by the PREROUTING chain of the "nat" table. As in masquerading, the iptables_nat module will have to be loaded and routing enabled for port forwarding to work.  Routing too will have to be allowed in iptables with the FORWARD chain, this would include all NEW inbound connections from the Internet matching the port forwarding port plus all future packets related to the ESTABLISHED connection in both directions. An example follows:

 

#---------------------------------------------------------------
# Load the NAT module

#---------------------------------------------------------------

 

modprobe iptable_nat

#---------------------------------------------------------------
# Get the IP address of the Internet interface eth0 (linux only)

#

# You'll have to use a different expression to get the IP address

# for other operating systems which have a different ifconfig output

# or enter the IP address manually in the PREROUTING statement

#

# This is best when your firewall gets its IP address using DHCP.

# The external IP address could just be hard coded ("typed in

# normally")

#---------------------------------------------------------------

 

external_int="eth0"
external_ip="`ifconfig $external_int | grep 'inet addr' | \

                       awk '{print $2}' | sed -e 's/.*://'`"

 

#---------------------------------------------------------------
# Allow port forwarding for traffic destined to port 80 of the

# firewall's IP address to be forwarded to port 8080 on server

# 192.168.1.200

#

# Enable routing by modifying the ip_forward /proc filesystem file

# - Interface eth0 is the internet interface

# - Interface eth1 is the private network interface

#---------------------------------------------------------------

 

iptables -t nat -A PREROUTING -p tcp -i eth0 -d $external_ip \

     --dport 80 --sport 1024:65535 -j DNAT --to 192.168.1.200:8080


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

#---------------------------------------------------------------
# After DNAT, the packets are routed via the filter table's

# FORWARD chain.

# Connections on port 80 to the target machine on the private

# network must be allowed.

#---------------------------------------------------------------

 

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.200 \

    --dport 8080 --sport 1024:65535 -m state --state NEW -j ACCEPT

 

iptables -A FORWARD -t filter -i eth1 -m state \

         --state NEW,ESTABLISHED,RELATED -j ACCEPT

 

iptables -A FORWARD -t filter -i eth0 -m state \

         --state ESTABLISHED,RELATED -j ACCEPT


Static NAT

In this example, all traffic to a particular public IP address, not just to a particular port, is NAT-ted to a single server on the protected subnet. As the firewall has more than one IP address, MASQUERADE isn't recommended to be used as it will force masquerading as the IP address of the primary interface and not any of the alias IP addresses the firewall may have. SNAT is therefore used to specify the alias IP address to be used for connections initiated by all other servers in the protected net.

Note: Though the "nat" table NATs all traffic to the target servers (192.168.1.100 to 102), only connections on ports 80,443 and 22 are allowed through by the FORWARD chain. Also notice how you have to specify a separate "-m multiport" option whenever you need to match multiple non-sequential ports for both source and destination.

Note: In this example, the firewall uses 1:1 NAT to make the servers 192.168.1.100 to 102 on your home network appear on the Internet as IP addresses 97.158.253.26 to 28. You will have to create alias IP addresses for each of these Internet IPs for 1:1 NAT to work.

 

#---------------------------------------------------------------
# Load the NAT module

#---------------------------------------------------------------

 

modprobe iptable_nat

 

#---------------------------------------------------------------
# Enable routing by modifying the ip_forward /proc filesystem file

#---------------------------------------------------------------

 

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

 

#---------------------------------------------------------------
# NAT ALL traffic:

#

# TO:             FROM:        MAP TO SERVER:

# 97.158.253.26  Anywhere      192.168.1.100

# 97.158.253.27  Anywhere      192.168.1.101

# 97.158.253.28  Anywhere      192.168.1.102

#

# SNAT is used to NAT all other outbound connections initiated

# from the protected network to appear to come from

# IP address 97.158.253.29

#

# POSTROUTING:

#   NATs source IP addresses. Frequently used to NAT connections from

#   your home network to the Internet

#

# PREROUTING:

#   NATs destination IP addresses. Frequently used to NAT

#   connections from the Internet to your home network

#

# - Interface eth0 is the internet interface

# - Interface eth1 is the private network interface

#---------------------------------------------------------------

 

# PREROUTING statements for 1:1 NAT

# (Connections originating from the Internet)


iptables -t nat -A PREROUTING -d 97.158.253.26 -i eth0 \
         -j DNAT --to-destination 192.168.1.100
iptables -t nat -A PREROUTING -d 97.158.253.27 -i eth0 \
         -j DNAT --to-destination 192.168.1.101
iptables -t nat -A PREROUTING -d 97.158.253.28 -i eth0 \
         -j DNAT --to-destination 192.168.1.102

# POSTROUTING statements for 1:1 NAT

# (Connections originating from the home network servers)


iptables -t nat -A POSTROUTING -s 97.158.253.26 -o eth0 \

         -j SNAT --to-source 192.168.1.100

iptables -t nat -A POSTROUTING -s 97.158.253.27 -o eth0 \

         -j SNAT --to-source 192.168.1.101

iptables -t nat -A POSTROUTING -s 97.158.253.28 -o eth0 \

         -j SNAT --to-source 192.168.1.102

 

# POSTROUTING statements for Many:1 NAT

# (Connections originating from the entire home network)


iptables -t nat -A POSTROUTING -s 192.168.1.0/24 \
         -j SNAT -o eth1 --to-source 97.158.253.29

# Allow forwarding to each of the servers configured for 1:1 NAT

# (For connections originating from the Internet. Notice how you

# use the real IP addresses here)

 

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.100 \

    -m multiport --dport 80,443,22 -m multiport --sport 1024:65535 \

    -m state --state NEW -j ACCEPT

 

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.101 \

    -m multiport --dport 80,443,22 -m multiport --sport 1024:65535 \

    -m state --state NEW -j ACCEPT

 

iptables -A FORWARD -p tcp -i eth0 -o eth1 -d 192.168.1.102 \

    -m multiport --dport 80,443,22 -m multiport --sport 1024:65535 \

    -m state --state NEW -j ACCEPT

 

# Allow forwarding for all New and Established SNAT connections

# originating on the home network AND already established

# DNAT connections

 

iptables -A FORWARD -t filter -i eth1 -m state \

         --state NEW,ESTABLISHED,RELATED -j ACCEPT

 

# Allow forwarding for all 1:1 NAT connections originating on

# the Internet that have already passed through the NEW forwarding

# statements above

 

iptables -A FORWARD -t filter -i eth0 -m state \

         --state ESTABLISHED,RELATED -j ACCEPT

 

Logging & Troubleshooting

You track packets passing through the iptables list of rules using the LOG target. You should be aware that the LOG target:

o        will log all traffic that matches the iptables rule in which it is located.

o        automatically writes an entry to the /var/log/messages file and then executes the next rule.

Therefore if you want to log only unwanted traffic then you have to add a matching rule with a DROP target immediately after the LOG rule. If you don't, you'll find yourself logging both desired and unwanted traffic with no way of discerning between the two as by default iptables doesn't state why the packet was logged in its log message.

This example logs a summary of failed packets to the file /var/log/messages. You can use the contents of this file to determine what TCP/UDP ports you need to open to provide access to specific traffic that is currently stopped.

 

#---------------------------------------------------------------

# Log and drop all other packets to file /var/log/messages

# Without this we could be crawling around in the dark

#---------------------------------------------------------------

 

iptables -A OUTPUT -j LOG

iptables -A INPUT -j LOG

iptables -A FORWARD -j LOG

 

iptables -A OUTPUT -j DROP

iptables -A INPUT -j DROP

iptables -A FORWARD -j DROP

 

Here are some examples of the output of this file:

 

o        Firewall denying replies to DNS queries (UDP port 53) destined to server 192.168.1.102 on the home network.

 

Feb 23 20:33:50 bigboy kernel: IN=wlan0 OUT= MAC=00:06:25:09:69:80:00:a0:c5:e1:3e:88:08:00 SRC=192.42.93.30 DST=192.168.1.102 LEN=220 TOS=0x00 PREC=0x00 TTL=54 ID=30485 PROTO=UDP SPT=53 DPT=32820 LEN=200

 

o        Firewall denying Windows NetBIOS traffic (UDP port 138)

 

Feb 23 20:43:08 bigboy kernel: IN=wlan0 OUT= MAC=ff:ff:ff:ff:ff:ff:00:06:25:09:6a:b5:08:00 SRC=192.168.1.100 DST=192.168.1.255 LEN=241 TOS=0x00 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=138 DPT=138 LEN=221

 

o        Firewall denying Network Time Protocol (NTP UDP port 123)

 

Feb 23 20:58:48 bigboy kernel: IN= OUT=wlan0 SRC=192.168.1.102 DST=207.200.81.113 LEN=76 TOS=0x10 PREC=0x00 TTL=64 ID=0 DF PROTO=UDP SPT=123 DPT=123 LEN=56

 

 

Note: The traffic in all these examples isn't destined for the firewall. Therefore you should check your INPUT, OUTPUT, FORWARD and NAT related statements. If the firewall's IP address is involved, then you should focus on the INPUT, OUTPUT statements

If nothing shows up in the logs, then follow the steps in the Network Troubleshooting chapter to determine whether the data is reaching your firewall at all, and if it is not, the location your network that could be causing the problem.

Troubleshooting NAT: As a general rule, you won't be able to access the public NAT IP addresses from servers on your home network. Basic NAT testing will require you to ask a friend to try to connect to your home network from the Internet.

You can then use the logging output in /var/log/messages to make sure that:

o        the translations are occurring correctly and

o        iptables isn't dropping the packets after translation occurs