Chapter 12.  System Security (212)

Revision: $Revision: 1158 $ ($Date: 2013-04-25 16:05:02 +0200 (Thu, 25 Apr 2013) $)

This topic has a total weight of 13 points and contains the following objectives:

Objective 212.1; Configuring a router (3 points)

Candidates should be able to configure a system to perform network address translation (NAT, IP masquerading) and state its significance in protecting a network. This objective includes configuring port redirection, managing filter rules and averting attacks.

Objective 212.2; Securing FTP servers (2 points)

Candidates should be able to configure an FTP server for anonymous downloads and uploads. This objective includes precautions to be taken if anonymous uploads are permitted and configuring user access.

Objective 212.3; Secure shell (SSH) (4 points)

Candidates should be able to configure and secure an SSH daemon. This objective includes managing keys and configuring SSH for users. Candidates should also be able to forward an application protocol over SSH and manage the SSH login.

Objective 212.4; TCP wrapper (1 point)

Candidates should be able to configure TCP Wrapper to allow connections to specified servers only from certain hosts or subnets.

Objective 212.5; Security tasks (3 points)

Candidates should be able to receive security alerts from various sources, install, configure and run intrusion detection systems and apply security patches and bugfixes.

Sources of information: RFC1918

Configuring a router (212.1)

Candidates should be able to configure a system to perform network address translation (NAT, IP masquerading) and state its significance in protecting a network. This objective includes configuring port redirection, managing filter rules and averting attacks.

Key Knowledge Areas

iptables configuration files, tools and utilities

Tools, commands and utilities to manage routing tables

Private address ranges

Port redirection and IP forwarding

List and write filtering and rules that accept or block datagrams based on source or destination protocol, port and address

Save and reload filtering configurations

The following is a partial list of the used files, terms and utilities:

/proc/sys/net/ipv4
/etc/services
iptables
routed

Private Network Addresses

Why do Private Network Addresses exist? It has been common practice to assign globally-unique addresses to all hosts that use TCP/IP. In order to extend the life of the IPv4 address space, address registries are requiring more justification concerning the need for extra address space than ever before, which makes it harder for organizations to acquire additional address space.

Hosts within enterprises that use IP can be partitioned into three categories:

Category 1

These hosts do not require access to the hosts of other enterprises or on the Internet itself; hosts within this category may use IP addresses that are unambiguous within an enterprise, but may be ambiguous between enterprises.

Category 2

These are hosts that need access to a limited set of outside services (e.g., E-mail, FTP, netnews, remote login), which can be handled by mediating gateways (e.g., application layer gateways). For many hosts in this category, unrestricted external access (provided via IP connectivity) may be unnecessary and even undesirable (for privacy/security reasons). These hosts, the same as category 1 hosts, may use IP addresses that are unambiguous within an enterprise, but may be ambiguous between enterprises.

Category 3

These hosts need network-layer access outside the enterprise (provided via IP connectivity); hosts in the last category require IP addresses that are globally unambiguous.

We will refer to the hosts in the first and second categories as private and to hosts in the third category as public.

Many applications require connectivity only within one enterprise and do not need external (outside the enterprise) connectivity for the majority of internal hosts. In larger enterprises it is often easy to identify a substantial number of hosts using TCP/IP that do not need network-layer connectivity outside the enterprise.

The Internet Assigned Numbers Authority (IANA) has reserved the following three blocks of the IP address space for private internets:

10.0.0.0        -   10.255.255.255  (10/8 prefix)
172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
192.168.0.0     -   192.168.255.255 (192.168/16 prefix)

We will refer to the first block as 24-bit block, the second as 20-bit block, and to the third as 16-bit block. Note that (in pre-CIDR notation) the first block is nothing but a single class A network number, while the second block is a set of 16 contiguous class B network numbers and third block is a set of 256 contiguous class C network numbers.

Network Address Translation (NAT)

The figure above displays a hypothetical situation which will serve as an example in the following explanation.

The Firm has four machines, 1 to 4, which are connected via a HUB and have private IP-Addresses in the 192.168.x.x range. Machine 4 serves as a router to the Internet and has two network interfaces. One connects the router to The Firm's internal network via the hub and has a private IP-address of 192.168.0.1, while the other connects the router to the Internet and has a valid (dynamic) IP-Address of 101.102.103.104.

Let's say that the user at Machine 2 wishes to look at a web page on Some Host (http://SomeHost.example) with an IP-address of 201.202.203.204. To be able to see the web page, Machine 2 must be able to get information from the Internet and thus must be, in some way, connected to the Internet. And indeed, Machine 2 has an indirect connection to the Internet via Machine 4, but how can this work? Machine 2 has a private IP-address which is not supported on the Internet!

This is where NAT kicks in. Machine 4, the router, replaces the private IP-address of Machine 2 (and also of Machine 1 and 3 if needed) with its own IP-Address before sending the request to Some Host. Some Host thinks that a machine with IP-Address 101.102.103.104 asked for the web page and responds by sending the web page to Machine 4.

Machine 4 knows that it has replaced the IP-address of Machine 2 with its own before sending the request to Some Host so it also knows that the answer it got to the request has to go to Machine 2. Machine 4 accomplishes this by replacing its own IP-address in the answer by the IP-address of Machine 2.

This is, in a nutshell, what NAT does. For more detailed information consult RFC1631.

The Linux firewall, an overview

Implementation

The Linux firewall is implemented in the kernel (as of version 2.3.15). The NETFILTER modules implement the packet filtering rules. The user space application iptables is used to configure these rules.

Netfilter hooks

As the figure above shows, netfilter supports five different hooks in the protocol stack. These hooks enable us to examine and change (if needed) every packet passing through the kernel.

There are five possible actions:

NF_ACCEPT

Continue traversal as normal.

NF_DROP

Drop the packet and do not continue traversal.

NF_QUEUE

Queue the packet for userspace handling.

NF_REPEAT

Call this hook again.

NF_STOLEN

I've taken over the packet, do not continue traversal.

Tables and Chains

By default five chains and three tables are supported. As the figure below shows, certain chains are only valid for certain tables.

Table 12.1.  Valid chains per table

  CHAIN
  PREROUTINGINPUTFORWARDOUTPUTPOSTROUTING
TABLEMANGLEV  V 
NATV  VV
FILTER VVV 


The filter table

The filter table is used for filtering packets. The filter table contains three chains. The INPUT chain is used for all packets that are for the firewall. The FORWARD chain is used for all packets that come from outside the firewall and are destined for another machine. The OUTPUT chain is used for all packets generated by the firewall.

The nat table

The nat table is used for Network Address Translation. The nat table contains three chains. The PREROUTING chain is the first used to alter packets. The OUTPUT chain is used to alter packets generated by the firewall. The POSTROUTING chain is the last chain where packets can be altered as they leave the firewall.

The mangle table

The mangle table is used to mangle packets. We can change several things but we can't do masquerading or network address translation here. The mangle table contains two chains. The PREROUTING chain is the first chain alter packets. The OUTPUT chain is used to alter packets generated by the firewall.

Connection tracking: Stateful Firewalling

Firewalls that are able to do connection tracking are called Stateful Firewalls. What it comes down to is that connections are tracked by remembering what (type of) packets have been received and sent.

Incoming packets in response to a ping, for instance, can be accepted by the firewall because the firewall knows that we've caused this ourselves by doing the ping in the first place.

The iptables option used for connection tracking is the --state option.

The manual page describes this as follows:

state

This module, when combined with connection tracking, allows access to the connection tracking state for this packet.

--state state

Where state is a comma-separated list of the connection states to match. Possible states are: NEW, ESTABLISHED, RELATED, INVALID.

There are two modules for connection tracking:

ip_conntrack

The main connection-tracking code.

ip_conntrack_ftp

Additional code needed to track ftp connections, both active and passive.

Conntrack hooks in at PREROUTING, FORWARD, OUTPUT and POSTROUTING.

Hooks, Tables and Chains put together

Putting what we've discussed so far into one picture:

Adding extra functionality

Adding targets

Each rule specifies what to do with a packet matching the rule. The what-to-do part is called the target. Standard targets always present are:

ACCEPT means let the packet through.

DROP means throw the packet on the floor.

QUEUE means pass the packet to user space.

RETURN means stop traversing this chain and resume at the next rule in the previous calling chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN matches the packet, the target specified in the chain policy determines the fate of the packet.

Included in the standard distribution are a number of target extensions for which support in the kernel must be enabled if you wish to use them. Consult the man page of iptables for further details. Most of these targets have options. The extension LOG for instance, has the following five options: --log-level, --log-prefix, --log-tcp-sequence, --log-tcp-options, --log-ip-options. Please consult the man page for details on options per target.

The extended target modules included in the distribution are:

LOG

Turn on kernel logging of matching packets. When this option is set for a rule, the Linux kernel will print some information on all matching packets (such as most IP header fields) via printk().

MARK

This is used to set the netfilter mark value associated with the packet. It is only valid in the mangle table.

REJECT

This is used to send back an error packet in response to the matched packet; otherwise, it is equivalent to DROP. This target is only valid in the INPUT, FORWARD and OUTPUT chains and user-defined chains which are only called by those chains.

TOS

This is used to set the 8-bit Type of Service field in the IP header. It is only valid in the mangle table.

MIRROR

This is an experimental demonstration target which inverts the source and destination fields in the IP header and retransmits the packet. It is only valid in the INPUT, FORWARD and OUTPUT chains and user-defined chains which are only called by those chains.

SNAT

This target is only valid in the POSTROUTING chain of the nat table. It specifies that the source address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined.

DNAT

This target is only valid in the PREROUTING, OUTPUT and user-defined chains (which are only called by those chains) of the nat table. It specifies that the destination address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined.

MASQUERADE

This target is only valid in the POSTROUTING chain of the nat table. It should only be used with dynamically assigned IP (dialup) connections: if you have a static IP address, you should use the SNAT target. Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is going out, but also has the effect that connections are forgotten when the interface goes down. This is the correct behaviour when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway).

REDIRECT

This target is only valid in the PREROUTING, OUTPUT and user-defined chains (which are only called by those chains) of the nat table. It alters the destination IP address to send the packet to the machine itself (locally-generated packets are mapped to the 127.0.0.1 address).

Adding matching modules

Each rule specifies what to do with a packet matching that rule. The match part is implemented by packet matching modules. Most of these modules support options. Please consult the man page for detailed information on the options.

The following modules are included in the distribution:

tcp

These extensions are loaded if --protocol tcp is specified, and no other match is specified.

udp

These extensions are loaded if --protocol udp is specified, and no other match is specified.

icmp

This extension is loaded if --protocol icmp is specified, and no other match is specified.

mac

Match source MAC address. It must be of the form XX:XX:XX:XX:XX:XX. Note that this only makes sense for packets entering the PREROUTING, FORWARD or INPUT chains for packets coming from an ethernet device.

limit

This module matches at a limited rate using a token bucket filter: it can be used in combination with the LOG target to give limited logging. A rule using this extension will match until this limit is reached (unless the ! flag is used).

multiport

This module matches a set of source or destination ports. Up to 15 ports can be specified. It can only be used in conjunction with -p tcp or -p udp.

mark

This module matches the netfilter mark field associated with a packet (which can be set using the MARK target).

owner

This module attempts to match various characteristics of the packet creator for locally-generated packets. It is only valid in the OUTPUT chain, and even then some packets (such as ICMP responses) may have no owner and hence, never match.

state

This module, when combined with connection tracking, allows access to the connection tracking state for this packet.

unclean

This module takes no options, but attempts to match packets which seem malformed or unusual. This is regarded as experimental.

tos

This module matches the 8 bits of Type of Service field in the IP header (ie. including the precedence bits).

The Firm's network with IPTABLES

The picture below shows The Firm's network and the possible combinations of traffic initiation/destination.

(1) Traffic initiated by the Firewall that is destined for the Internet

We are running a DNS on the Firewall that needs to be able to consult other DNSes on the Internet (which use the UDP protocol and listen to PORT 53). We want to be able to use ssh (which uses the TCP protocol and port 22) to connect to other systems on the Internet. We are participating in a distributed.net project RC564 cracking and are running a proxy server on the Firewall (which uses the TCP protocol and PORT 2064 to communicate with the keyserver). We want to be able to ping hosts on the Internet (ping uses the ICMP protocol and message type ping). The Firewall communicates with the Internet through interface eth1. Taking all this into consideration, the iptables commands needed are:

iptables -t filter -A OUTPUT -o eth1 -p udp  --destination-port dns        \
-m state --state NEW -j ACCEPT  
iptables -t filter -A OUTPUT -o eth1 -p tcp  --destination-port ssh        \
-m state --state NEW -j ACCEPT
iptables -t filter -A OUTPUT -o eth1 -p tcp  --destination-port 2064       \
-m state --state NEW -j ACCEPT
iptables -t filter -A OUTPUT -o eth1 -p icmp --icmp-type echo-request      \
-m state --state NEW -j ACCEPT
          

These four iptables commands tell the firewall to allow outgoing connection-initialization packets for dns, ssh, RC564 cracking and ping.

(2) Traffic initiated by the Internet that is destined for the Firewall

We want to be able to use ssh, which uses the TCP protocol and port 22, to connect to our Firewall from other systems on the Internet. The iptables command needed is:

iptables -t filter -A INPUT  -i eth1 -p tcp --destination-port ssh         \
-m state --state NEW -j ACCEPT
          

This iptables command tells the firewall to allow incoming connection initialization packets for ssh.

(3) Traffic initiated by the Firewall that is destined for the internal network

We want to be able to use ssh, which uses the TCP protocol and port 22, to connect to one of our internal machines from our Firewall. The iptables commands needed is:

iptables -t filter -A OUTPUT -o eth0 -p tcp --destination-port ssh         \
-m state --state NEW -j ACCEPT
          

This iptables command tells the Firewall to allow outgoing SSH connection initialization packets destined for a machine on the Internal Network.

(4) Traffic initiated by the internal network that is destined for the firewall

The machines on the internal network, using the dns of the firewall, must be able to connect to the firewall using ssh, are processing RC564 keys, must be able to talk to the proxy on the firewall using port 2064 and must be able to ping the Firewall for system administrative purposes. The iptables commands needed are:

iptables -t filter -A INPUT  -i eth0 -p udp --destination-port dns         \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p tcp --destination-port ssh         \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p tcp --destination-port 2064        \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p icmp --icmp-type echo-request      \
-m state --state NEW -j ACCEPT
          

These four iptables commands tell the Firewall to allow incoming connection-initialization packets for dns, ssh, RC564 cracking and ping.

(5) Traffic initiated by the Internal Network that is destined for the Internet

Every connection from a machine on the internal network to a machine on the Internet is allowed. The iptables commands needed is:

iptables -t filter -A FORWARD -i eth0 -o eth1 -m state --state NEW -j ACCEPT
          

This iptables command tells the Firewall to allow ALL outgoing connection initialization packets.

(6) Traffic initiated by the Internet that is destined for the Internal Network

This does not occur because our local network uses private IP addresses that can't be used on the Internet. Our local machines aren't visible from the Internet.

What we could do to make one of our machines available on the Internet is to let people connect to a certain port on the firewall and use NAT to redirect them to a port on one of the machines on the Internal Network.

Suppose Machine 2 has a web-server (or some other program) running which listens to port 2345 and people from the outside must be able to connect to that program. Since The Firm is using private IP addresses for their Internal Network, Machine 2 is not visible on the Internet. The solution here is to tell Machine 4 that all data from the outside that is aimed at port 80 should be routed to port 2345 on Machine 2. The iptables commands needed are:

iptables -t nat -A PREROUTING -i eth1 -p tcp --destination-port 80         \
-j DNAT --to-destination 192.168.0.11:2345
iptables -t filter -A FORWARD -i eth1 -p tcp --destination-port 2345       \
-m state --state NEW -j ACCEPT
          

The first line changes the destination address and port. Since this then becomes traffic aimed at another machine, the traffic must pass the FORWARD filter. The second line sees to it that that happens.

(!) Traffic as a result of initiated traffic

So far, we've only specified that connection initiation traffic is allowed, but that is not enough. We also must allow ESTABLISHED and RELATED traffic.

Let's tell the firewall that all ESTABLISHED and RELATED traffic, regardless of type, interface etc. is allowed. We must also allow the initiation of traffic on the firewalls lo interface because otherwise some services, such a a caching DNS server, will not work. We need the following iptables commands to realize this:

iptables -t filter -A INPUT   -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A OUTPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A INPUT   -m state --state NEW -i lo           -j ACCEPT
          

Remember that this can't be a problem because the packets are a result of the fact that we've accepted the initiation of the connection in the first place.

All iptables commands put together

Adding stuff to start with a clean sheet and telling the firewall to masquerade packets from the internal network aimed at the Internet can be accomplished with the following commands:

################################################################################
# FLUSH ALL RULES IN THE MANGLE, NAT AND FILTER TABLES
################################################################################
iptables -t mangle -F
iptables -t nat    -F
iptables -t filter -F

################################################################################
# DELETE ALL USER-DEFINED (NOT BUILT-IN) CHAINS IN THE TABLES
################################################################################
iptables -t mangle -X
iptables -t nat    -X
iptables -t filter -X

################################################################################
# SET ALL POLICIES FOR ALL BUIL-IN CHAINS TO DROP
################################################################################
iptables -P INPUT   DROP
iptables -P FORWARD DROP
iptables -P OUTPUT  DROP

################################################################################
# (1) TRAFFIC INITIATED BY THE FIREWALL DESTINED FOR THE INTERNET
#     DNS, SSH, RC564, PING
################################################################################
# ALLOW INITIATION BY THE FIREWALL
iptables -t filter -A OUTPUT -o eth1 -p udp  --destination-port dns        \
-m state --state NEW -j ACCEPT
iptables -t filter -A OUTPUT -o eth1 -p tcp  --destination-port ssh        \
-m state --state NEW -j ACCEPT
iptables -t filter -A OUTPUT -o eth1 -p tcp  --destination-port 2064       \
-m state --state NEW -j ACCEPT
iptables -t filter -A OUTPUT -o eth1 -p icmp --icmp-type echo-request      \
-m state --state NEW -j ACCEPT
# ALLOW INCOMING RESPONSES 
iptables -t filter -A INPUT  -i eth1                                       \
-m state --state ESTABLISHED,RELATED -j ACCEPT

################################################################################
# (2) TRAFFIC INITIATED BY THE OUTSIDE DESTINED FOR THE FIREWALL
#     SSH
################################################################################
# ALLOW INITIATION
iptables -t filter -A INPUT  -i eth1 -p tcp  --destination-port ssh        \
-m state --state NEW -j ACCEPT
# ALLOW RESPONSE
iptables -t filter -A OUTPUT -o eth1 -p tcp  --destination-port ssh                     \
-m state --state ESTABLISHED,RELATED -j ACCEPT

################################################################################
# (3) TRAFFIC INITIATED BY THE FIREWALL DESTINED FOR THE INTERNAL NETWORK
#     SSH
################################################################################
# ALLOW INITIATION
iptables -t filter -A OUTPUT -o eth0 -p tcp  --destination-port ssh        \
-m state --state NEW -j ACCEPT
# ALLOW RESPONSE
iptables -t filter -A INPUT  -i eth0 -p tcp  --destination-port ssh        \
-m state --state ESTABLISHED,RELATED -j ACCEPT

################################################################################
# (4) TRAFFIC INITIATED BY THE INTERNAL NETWORK DESTINED FOR THE FIREWALL
#     DNS, SSH, RC564, PING
################################################################################
# ALLOW INITIATION
iptables -t filter -A INPUT  -i eth0 -p udp  --destination-port dns        \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p tcp  --destination-port ssh        \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p tcp  --destination-port 2064       \
-m state --state NEW -j ACCEPT
iptables -t filter -A INPUT  -i eth0 -p icmp --icmp-type echo-request      \
-m state --state NEW -j ACCEPT
# ALLOW RESPONSE 
iptables -t filter -A OUTPUT -o eth0                                       \
-m state --state ESTABLISHED,RELATED -j ACCEPT

################################################################################
# (5) TRAFFIC INITIATED BY THE INTERNAL NETWORK DESTINED FOR THE OUTSIDE
#     EVERYTHING WE CAN INITIATE IS ALLOWED
################################################################################
# ALLOW INITIATION OF EVERYTHING
iptables -t filter -A FORWARD -i eth0 -o eth1                              \
-m state --state NEW -j ACCEPT
# ALLOW RECEPTION
iptables -t filter -A FORWARD -i eth1 -o eth0                              \
-m state --state ESTABLISHED,RELATED -j ACCEPT

################################################################################
# (6) TRAFFIC INITIATED BY THE OUTSIDE DESTINED FOR THE INTERNAL NETWORK
#     ALL FORBIDDEN, EXCEPT WEBSERVER FORWARDING TO INTERNAL MACHINE
################################################################################
# ALLOW DESTINATION NAT FROM FIREWALL:80 TO INTERNAL MACHINE:2345
iptables -t nat -A PREROUTING -i eth1 -p tcp --destination-port 80         \
-j DNAT --to-destination 192.168.0.11:2345
iptables -t filter -A FORWARD -i eth1 -p tcp --destination-port 2345       \
-m state --state NEW -j ACCEPT

################################################################################
# (!) TRAFFIC AS A RESULT OF INITIATED TRAFFIC
#     ALL ALLOWED
################################################################################
# ALLOW ALL PACKETS RESULTING FROM ALLOWED CONNECTIONS
iptables -t filter -A INPUT   -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A OUTPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A INPUT   -m state --state NEW -i lo           -j ACCEPT

################################################################################
# MASQUERADE PACKAGES FROM OUR INTERNAL NETWORK DESTINED FOR THE INTERNET
# THIS IS SNAT (SOURCE NAT)
################################################################################
iptables -t nat    -A POSTROUTING -i eth0 -o eth1 -s 192.168.0.0/24 -j MASQUERADE

################################################################################
# ENABLE FORWARDING
################################################################################
echo 1 > /proc/sys/net/ipv4/ip_forward
          

Saving And Restoring Firewall Rules

Firewall rules can be saved and restored easily by using the commands iptables-save, which writes to stdout and iptables-restore, which reads from stdin. Assuming that we use the file fwrules.saved to save and/or restore the rules, the two commands are:

iptables-save > fwrules.saved
iptables-restore < fwrules.saved
        

Port and/or IP forwarding

In the first example of this chapter the client thinks it's connecting directly to the external server and the router in between transparently routes all traffic and performs SOURCE NAT to masquerade the internal (private) addresses. Keyword in this example is transparency.

Besides packet filtering firewalls can also perform Port and IP forwarding. With port forwarding a client will connect to a port on the firewall. To the client the connection will terminate on the firewall, but the firewall knows to what internal server tthe connections on the receiving fic port. The firwewall will apply DESTINATION NAT to the packets and pass them on.

Forwarded traffic can also have SOURCE NAT applied but in most cases this would be unwanted because this would seriously hamper auditing the connections on the receiving server(s).

Situations in which port forwarding is used are (amongst others):

  • Transparency is unwanted (security or other considerations):

    • example: One specific service available through the firewall is running on multiple internal servers, for instance one for each customer of our organization. Based on the source address a decision can be made to which server the traffic has to be forwarded.

    Transparency is impossible (private IP addresses aren't routed on the internet):

    • example: If an organisation has only one external IP address but several services that have to be accessible from the internet running on different servers these services will need to be made available to the outside as seemingly originating from one single IP address.

    • Example: One internal server is serving a single service but listening on different port numbers (for instance to seperate between customer). Clients will connect to the IANA assigned service port and based on source IP address the firewall will forward the traffic to the assigned destination port for that source address.

    Scaling considerations:

    • example: If an organisation has only one external IP address but several services that have to be accessible from the internet running on different servers these services will need to be made available to the outside as seemingly originating from one single IP address.

Most often Port and/or IP forwarding is used to enable incoming connections from the internet to servers with a private IP address.

Port forwarding examples:

Denial of Service (DoS) attacks

Description

DoS attackers abuse the fact that resources on the Internet are limited and that services can be disrupted by taking away (one of) their resources: storage-capacity, bandwith or processor-capacity. This is often done by packet flooding.

Packet flooding can be done with TCP, ICMP and UDP.

When using TCP mostly the SYN, ACK and RST flags are used.

When using ICMP, the message types echo request and echo reply are used. This is called ping-flooding.

When using UDP, the chargen and echo UDP services are used.

Also, two systems (A and B) can be played out against each other by a third system (C). System C sends packets to system A but changes the source IP-address of the packages it sends to the IP address of system B. System A then thinks the packets came from system B and starts sending replies to system B. This method is called DoS with IP address spoofing.

Check the site http://www.cert.org/ for a complete history of DoS and DDoS (Distributed DoS) attacks. And have a look at RFC2827 which describes Network Ingress Filtering, a method to prevent IP address spoofing. This doesn't prevent DoS attacks but makes it possible to trace the real IP address of the offender.

Prevention

It is not possible to fully prevent DoS attacks without disconnecting from the Internet. What can be done to minimize the effects of DoS and DDoS attacks is to apply some packet filtering and rate limiting rules to the firewall.

Using /proc/sys/net/ipv4 (sysctl) to prevent simple DOS attacks

Kernel documentation describes the following sysctl options to prevent simple DoS attacks:

  • tcp_max_orphans - INTEGER:

    • Maximal number of TCP sockets not attached to any user file handle, held by system. If this number is exceeded orphaned connections are reset immediately and warning is printed.

  • tcp_max_tw_buckets - INTEGER:

    • Maximal number of timewait sockets held by system simultaneously. If this number is exceeded time-wait socket is immediately destroyed and warning is printed.

  • rp_filter - INTEGER:

    • 0 - No source validation.

    • 1 - Strict mode as defined in RFC3704 Strict Reverse Path: Each incoming packet is tested against the FIB and if the interface is not the best reverse path the packet check will fail. By default failed packets are discarded.

    • 2 - Loose mode as defined in RFC3704 Loose Reverse Path: Each incoming packet's source address is also tested against the FIB and if the source address is not reachable via any interface the packet check will fail.

Routed

In an environment that uses dynamic routing, the routed daemon may be used. The routed daemon manages the routing tables in the kernel. The routed daemon only implements the RIP (Routing Information Protocol) protocol. When you wish to dynamically route other types of protocols gated can be used instead. Gated is a vintage routing daemon which supports RIPv2, RIPng, OSPF, OSPF6, BGP4+ and BGP4-.

The routed daemon finds interfaces to directly connected hosts and networks that are configured into the system and marked as up. (Mark networks as up using the ifconfig command.) If multiple interfaces are present, the routed daemon assumes that the local host forwards packets between networks. The routed daemon transmits a RIP request packet on each interface, using a broadcast message when the interface supports it.

The routed daemon then listens for RIP routing requests and response packets from other hosts. When the routed daemon supplies RIP information to other hosts, it sends RIP update packets every 30 seconds (containing copies of its routing tables) to all directly connected hosts and networks.

When the routed daemon receives a Routing Information Protocol (RIP) request packet to supply RIP routing information, the routed daemon generates a reply in the form of a response packet. The response packet is based on the information maintained in the kernel routing tables and contains a list of known routes. Each route is marked with a hop-count metric, which is the number of gateway hops between the source network and the destination network. The metric for each route is relative to the sending host. A metric of 16 or greater is considered infinite or beyond reach.

When to use routed

If there are multiple possible paths to a certain destination, and you want an alternate route to that destination to be selected automatically (in case the default route to that destination for some reason is unusable) the routed program can do this for you automatically.

IPCHAINS

Note

IPCHAINS is not mentioned in the LPIC objectives anymore. For historical reasons the info about IPCHAINS is left in these pages.

IPCHAINS, an overview

This figure shows the stages of the ipchains process.

IPCHAINS, nomen est omen, hence there are chains, a minimum of three to be precise. We've always got an INPUT, FORWARD and OUTPUT chain and, optionally, one or more user-defined chains.

A chain contains rules that determine the fate of a packet based on its source address, destination address, source port, destination port, protocol-type or any combination of these.

If a packet matches a rule, the packet is sent to the chain specified in the target. This can be ACCEPT, DENY, MASQ, REDIRECT or RETURN or a user-defined chain.

ACCEPT means that the packet will pass through. DENY means that the packet is not accepted and is thrown away without any form of notification to the sender. MASQ means that the packet will be masqueraded if it came from the localhost or demasqueraded if it is a response to an earlier sent masqueraded packet. MASQ is only allowed for the forward chain and the user-defined chains. REDIRECT will redirect packets to a local port. REDIRECT is only allowed for the input chain and for user-defined chains. REJECT means that the packet is not accepted and that the sender will be notified of this fact by means of an ICMP message. RETURN has the same effect as a packet reaching the end of a user-defined chain without match, i.e., the next rule in the previous chain will be checked. If the end of a built-in chain is reached, or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet.

IP Masquerading with IPCHAINS

IP Masquerading is a form of NAT. To get IP Masquerading up and running on your Linux computer, your kernel must support this.

For more detailed information on compiling a kernel and modules, see Chapter 1, Linux Kernel (201).

Let's go back to The Firm's network. The IP masquerading rules on machine 4 can be set using the following ipchains commands:

# ipchains -P forward DENY
# ipchains -A forward -i eth0 -s 192.168.0.0/24 -j MASQ
        

The first line defines a policy (-P) that states that all packets that have a destination address in the outside world will not be forwarded (DENY) by the forward chain (forward). This is done because it is good practice to forbid all traffic by default except traffic that you explicitly want.

The second line adds (-A) a rule to the forward chain (forward) that states that all packages arriving (-i) at interface eth0 and coming from (-s) an ip-address in the range 192.168.0.0-192.168.0.255 will be masqueraded (-j MASQ) and forwarded to the outside world. The /24 states that the first 24 bits always have the same value, in this case 192.168.0, and that the last 8 bits can have any value.

Machine 4 now knows WHAT to do with IP packets that come from Machines 1 to 4, but not WHERE to send them. To complete Machine 4's instructions, we add the following commands:

# route add -net 192.168.0.0 netmask 255.255.255.0 eth0
# route add default gw 101.102.103.104 eth1
        

The first line adds a route to the 192.168.x.x network via eth0.

The second line adds a default route via eth1, which is used if the destination is not in the 192.168.x.x range.

IP forwarding with IPCHAINS

IP forwarding is the relaying of IP packets from one network to another. Let's go back to The Firm's network. We want Machine 4 to forward the IP packets to the Internet. This means that all of the Firms machines must use real IP addresses, as explained earlier, and that Machine 4 must know that certain IP addresses should go to the outside world, i.e., the Internet.

To enable forwarding, support must be enabled in the kernel (see Chapter 1, Linux Kernel (201) for more details) and forwarding itself must be enabled by issuing the command echo 1 > /proc/sys/net/ipv4/ip_forward.

Machine 4 now knows WHAT to do with IP packets that come from the Machines 1 to 4, but not WHERE to send them. To tell Machine 4 this, we use the following commands:

# route add -net 192.168.0.0 netmask 255.255.255.0 eth0
# route add default gw 101.102.103.104 eth1
        

The first line adds a route to the 192.168.x.x network via eth0. With kernel versions of 2.2 or higher this is done automatically.

The second line adds a default route via eth1 which is used if the destination is not in the 192.168.x.x range.

Port Redirection with IPCHAINS

Port redirection is a mechanism which enables the redirection of IP packets based on destination port number to another port. To enable port redirection, support must be enabled in the kernel.

Since it worked so well the last time, let's go back to The Firm's network again for an example.

Suppose Machine 2 has a web-server (or some other program) running which listens to port 2345, and people from the outside must be able to connect to that program. Since The Firm is using private IP addresses for their internal network, Machine 2 is not visible on the Internet. The solution here is to tell Machine 4 to route all data from the outside that is aimed at port 80 to port 2345 on Machine 2.

Now we've got a problem: with the command ipchains -j REDIR, the port must be on the same host and here this is not the case. So, what to do now ?

The solution lies in the ipmasqadm portfw command. Typing ipmasqadm portfw -h gives the following information:

# ipmasqadm portfw -h
Usage: portfw -a -P PROTO -L LADDR LPORT -R RADDR RPORT [-p PREF] add entry
       portfw -d -P PROTO -L LADDR LPORT [-R RADDR RPORT]         delete entry
       portfw -f                                                  clear table
       portfw -l                                                  list table
       portfw <args> -n                                           no names

PROTO is the protocol, can be "tcp" or "udp"
LADDR is the local interface receiving packets to be forwarded.
LPORT is the port being redirected.
RADDR is the remote address.
RPORT is the port being redirected to.
PREF  is the preference level (load balancing, default=10)
        

Executing the following commands on Machine 4 will achieve our goal:

# ipmasqadm portfw -f
# ipmasqadm portfw -a -P tcp -L 101.102.103.104 80 -R 192.168.0.11 2345
        

The first line empties the portfw table, the second line adds a portfw rule (portfw -a) for the tcp packets (-P tcp) arriving at port 80 on the external interface of Machine 4 (-L 101.102.103.104 80), which states that those packets must be sent to port 2345 on Machine 2 (-R 192.168.0.11 2345).

And what about the replies from Machine 2 in response to the requests? Shouldn't there be a rule for that too? The answer is no, because this works similarly to masquerading. Machine 2 has no idea whatsoever that the request came from the outside. To Machine 2, it looks like the request came from Machine 4, so the answer goes to Machine 4. Machine 4 knows that this is in answer to a request from the outside that has been rerouted to Machine 2, so it sends the answer to the same machine the request came from.

The Firm's network with IPCHAINS

The best way to secure things is to define what is allowed, consider everything else to be not allowed and see to it that such traffic is unable to pass through the network.

How does this reflect on the usage of IPCHAINS ? Before explaining things, let's make a few functional assumptions in relation to the Firm's network:

  • We are running a nameserver on Machine 4

  • Packets from Machines 1-3 aimed at the outside world are masqueraded by Machine 4 and forwarded.

  • We can ping machines on our local net as well as machines in the outside world, but we ourselves do not respond to any pings from the outside world, i.e., arriving at our eth1 interface.

  • We are participating in a distributed.net project: rc564 cracking. We are running a proxy on Machine 4 that communicates with a server on the Internet. Machines 1-3 get their data from the proxy server and send their computed results to the proxy server.

  • Of course we also want to be able to view web-pages with http and https.

First, we delete all rules for all built-in chains:

# ipchains -F input
# ipchains -F forward
# ipchains -F output
        

Then we delete all user-defined chains:

# ipchains -X
        

The we tell ipchains to DENY all traffic:

# ipchains -P input DENY
# ipchains -P forward DENY
# ipchains -P output DENY
        

The next thing to do is allow traffic on a need basis. Let's start with forwarding:

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

We trust everything coming from the local Machines 1-3. Machine 4 receives this on its eth0 interface (192.168.0.1) and thus the ipchains commands needed are:

# ipchains -A input -i eth0 -j ACCEPT
# ipchains -A output -i eth0 -j ACCEPT      
        

The same goes for the lo interface. Without this definition, certain services, such as a caching DNS Server, will not function correctly:

# ipchains -A input -i lo -j ACCEPT
# ipchains -A output -i lo -j ACCEPT      
        

We want to be able to view web-pages. This is done via either the http or the https protocol which use port 80 and port 443 respectively:

# ipchains -A output -i eth1 -p tcp --dport 80  -j ACCEPT
# ipchains -A input  -i eth1 -p tcp --sport 80  -j ACCEPT ! -y
# ipchains -A output -i eth1 -p tcp --dport 443 -j ACCEPT
# ipchains -A input  -i eth1 -p tcp --sport 443 -j ACCEPT ! -y
# ipchains -A forward -p tcp -i eth1 -s 192.168.0.0/24 --dport 80 -j MASQ
# ipchains -A forward -p tcp -i eth1 -s 192.168.0.0/24 --dport 443 -j MASQ
        

We also want to enable our DNS, running on Machine 4, to do requests on other nameservers, DNS uses port 53 for sending the queries and for receiving the answers to the queries:

# ipchains -A output -i eth1 -p udp --dport 53 -j ACCEPT
# ipchains -A input  -i eth1 -p udp --sport 53 -j ACCEPT
        

For the rc564 proxyserver running on Machine 4 which uses port 2064 to receive new and send computed keys, we need the following two lines:

# ipchains -A output -i eth1 -p tcp --dport 2064 -j ACCEPT
# ipchains -A input  -i eth1 -p tcp --sport 2064 -j ACCEPT ! -y
        

We want to be able to ping hosts on the Internet. This is done with so-called ICMP packets. ICMP stands for Internet Control Message Protocol. ICMP messages are sent in several situations: for example, when a datagram cannot reach its destination, when the gateway does not have the buffering capacity to forward a datagram or when the gateway can direct the host to send traffic on a shorter route. There are several ICMP types. Typing ipchains -h icmp will show you which types are valid:

Type Code Description
0    0     echo-reply (pong)
3          destination-unreachable
     0       network-unreachable
     1       host-unreachable
     2       protocol-unreachable
     3       port-unreachable
     4       fragmentation-needed
     5       source-route-failed
     6       network-unknown
     7       host-unknown
     9       network-prohibited
     10      host-prohibited
     11      TOS-network-unreachable
     12      TOS-host-unreachable
     13      communication-prohibited
     14      host-precedence-violation
     15      precedence-cutoff
4    0     source-quench
5          redirect
     0       network-redirect
     1       host-redirect
     2       TOS-network-redirect
     3       TOS-host-redirect
8    0     echo-request (ping)
9    0     router-advertisement
10   0     router-solicitation
11         time-exceeded (ttl-exceeded)
     0       ttl-zero-during-transit
     1       ttl-zero-during-reassembly
12         parameter-problem
     0       ip-header-bad
     1       required-option-missing
13   0     timestamp-request
14   0     timestamp-reply
17   0     address-mask-request
18   0     address-mask-reply
        

Because we want to be able to ping hosts on the Internet, we need to allow outgoing echo-request or ping. Since we also want to be able to receive the answers to a ping, we must allow incoming echo-reply or pong:

# ipchains -A output -i eth1 -p icmp --icmp-type ping -j ACCEPT
# ipchains -A input  -i eth1 -p icmp --icmp-type pong -j ACCEPT
        

We also allow incoming and outgoing destination-unreachable ICMP messages on both the internal (eth0) interface and the external (eth1) interface. These occur if a datagram can't be delivered to its destination.

# ipchains -A input  -p icmp --icmp-type destination-unreachable -j ACCEPT
# ipchains -A output -p icmp --icmp-type destination-unreachable -j ACCEPT
        

If a gateway hasn't got the buffer space needed to queue the datagrams for output to the next network on the route to the destination network, it discards Internet datagrams and sends source-squench messages. On receipt of a source-quench message, the source host should cut back the rate at which it is sending traffic to the specified destination until it no longer receives source-quench messages from the gateway.

So we must also allow incoming and outgoing source-quench messages on both the internal (eth0) interface and the external (eth1) interface.

# ipchains -A input  -p icmp --icmp-type source-quench -j ACCEPT
# ipchains -A output -p icmp --icmp-type source-quench -j ACCEPT
        

We do not allow redirect messages because this is not applicable in our situation. This kind of message is used to tell a host that there is a shorter route to a network via another gateway. We only have one gateway, Machine 4, so there is no need for it.

We do not allow router-advertisement and router-solicitation messages. These messages enable hosts attached to multicast or broadcast networks to discover the IP addresses of their neighboring routers. For more information, consult RFC1256.

Datagrams contain a field called TTL, which stands for Time To Live. This field is decremented by each gateway the datagram passes through. If a gateway sees that the value of the TTL field is zero, it will discard the datagram and notify the source of this situation by means of an ICMP time-exceeded message. We allow both incoming and outgoing ICMP time-exceeded messages on all interfaces:

# ipchains -A input  -p icmp --icmp-type time-exeeded -j ACCEPT
# ipchains -A output -p icmp --icmp-type time-exeeded -j ACCEPT
      

If a datagram is discarded by a host or gateway because it can't be processed due to a problem with the header parameters, the host or gateway will send an ICMP parameter-problem message. We allow both incoming and outgoing ICMP parameter-problem messages on all interfaces:

# ipchains -A input  -p icmp --icmp-type parameter-problem -j ACCEPT
# ipchains -A output -p icmp --icmp-type parameter-problem -j ACCEPT
      

We are also not interested in timestamp-request and timestamp-reply messages. For more information, consult RFC792.

A host can use ICMP address-mask-request messages to ask for the address mask of a certain machine. ICMP address-mask-reply messages are used to transmit the answer to the request. See RFC950 for more information if you're interested. We don't allow these types of messages because we don't need them.

Finally, we must allow for the masquerading of any ICMP packet. As a result of the rules mentioned above, any ICMP packet can only be one of the packets we have previously permitted:

# ipchains -A forward -p icmp -i eth1 -s 192.168.0.0/24 -j MASQ
        

You don't have to know all icmp-types by heart. Some of them have been described here to point out that there's more going on than meets the eye. These topics are described in-depth in the RFC's 792, 950, and 1256, which are available from multiple sources on the Internet.

Copyright Snow B.V. The Netherlands