Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This

Kernel Port Forwarding—High Wizardry

We're about to come full circle on TCP/IP stack tricks. Some clever kernel folks decided that the functionality being performed by the user-level processes we've discussed could also be implemented completely in the kernel. In review of the previous two sections, IP transparent proxying could have been named firewall port redirection. Its purpose is to redirect traffic to a local port, regardless of its destination. In contrast, the user-space redirectors take traffic bound for a local port and forward it to a predetermined destination. This section covers extensions to the IP masquerading code in the kernel that can perform a mixture of these functions. But before we dive in, there are a few things you should know about kernel port forwarding:

  • This functionality is available only in the 2.2 kernel or later. (Well, this isn't entirely true. Patches are available for the 2.0 kernel that support IPPORTFW, one of the functionalities discussed here. If you want to use this on the 2.0 kernel, retrieve the Debian packages ipportfw and kernel-patch-ipportfw to get started. You may also want to refer to the documentation at http://www.monmouth.demon.co.uk/ipsubs/portforwarding.html. This section won't cover the 2.0 kernel.)

  • You'll need the ipmasqadm package if your distribution doesn't include this binary. The source is http://juanjox.linuxhq.com/. Debian users already have it; it's included in the netbase package.

  • This code is still considered experimental. This means that YMMV—and in some places the documentation—is still a little spotty. The 2.3 kernel coders are working on an entirely new functionality called netfilter,3 which will replace this code and ipchains. I mention this because you may not see a lot of additional development for these modules.

Compiling Support for Kernel Port Forwarding into the 2.2.x Kernel

To use kernel port forwarding, you must compile support for it into your kernel. Each of the IP masquerading special modules may be compiled as a module or directly into the kernel. The options required are described in the following listing:

Code maturity level options --->
    [*] Prompt for development and/or incomplete code/drivers

Networking options --->
    <*>Packet socket
    [*]Network firewalls
    [*]TCP/IP networking
    [*]IP: advanced router
    [*]IP: firewalling
    [*]IP: always defragment (required for masquerading)
    [*]IP: masquerading
    [*]IP: masquerading special modules support
    <*>IP: ipautofw masq support (EXPERIMENTAL)
    <*>IP: ipportfw masq support (EXPERIMENTAL)
    <*>IP: ip fwmark masq-forwarding support (EXPERIMENTAL)

Filesystems --->
    [*] /proc filesystem support

The last three options are the ones of interest—they're actually "special modules." To differentiate among them through the end of this section, I will refer to them as AUTOFW, PORTFW, and FWMARK, respectively.

Kernel Port Forwarding with AUTOFW

AUTOFW allows for the masquerading of protocols that don't have their own protocol helpers. The following list shows the masquerading protocol helpers (that is, protocols that already have support in the kernel):

  • CuSeeMe with the module ip_masq_cuseeme.o

  • FTP with the module ip_masq_ftp.o

  • IRC with the module ip_masq_irc.o

  • Quake with the module ip_masq_quake.o

  • RealAudio and RealVideo with the module ip_masq_raudio.o

  • VDO Live with the module ip_masq_vdolive.o

The idea is that sometimes an internal (masqueraded) client will connect to an external resource via a control connection (typically TCP), but the external resource returns data on a range of ports, possibly UDP ports. This is often the case for streaming media protocols, such as RealAudio and NetMeeting. When the router masquerades the outgoing connection, it expects traffic to return only from the server port to which the client sent (see Figure 4).

Figure 4

An application for AUTOFW.

AUTOFW attempts to mend this situation by allowing a range of ports to be forwarded to the internal system, also known as the hidden system. There are two ways to specify which internal system should receive the packets:

  • Explicitly define the IP address of this system (using the -h hiddenhost option).

  • Use an auto-detection technique that watches for traffic to traverse a specified control port. The (internal) sender of that traffic is then noted as the correct recipient of the inbound data destined for the range of ports.

If you take a moment to consider either of these two options, you'll notice (at least) one serious problem: The functionality is not designed for use by multiple internal clients connecting to a single external server simultaneously. Any single client can use the service, and as soon as it's finished, a different client (assuming that you're using the auto-detection mechanism) will be able to use the service. By specifying the hidden host explicitly, only one client can ever use the service (until you reconfigure the AUTOFW rule). When it does its thing, port forwarding looks like Figure 5.

Figure 5

AUTOFW at work.

Its limitations aside, the AUTOFW functionality may be useful, and it's a handy thing to have in your bag o' tricks. To use it, follow these steps:

    1. Make sure that you have support for it in your kernel, and that you've loaded the ip masq autofw module, if you compiled it as a module.

    2. Masquerade the outgoing (control) connection as you normally would with ipchains.

    3. Add your auto-forwarding rule with ipmasqadm autofw -A. Documentation on this is a little sparse. If you invoke ipmasqadm autofw (with no arguments), you'll evoke a usage statement, as shown in the following listing. (Note that the option syntax is the same as for the ipautofw, which was used for the AUTOFW patches running on the 2.0 kernel.)

hafnium:/root> ipmasqadm autofw

Usage:
    ipautofw <command> <options>

Valid commands:
    -A                           add new autoforward entry
    -D                           delete an autoforward entry
    -F                           flush the autoforward table
     .
     .
     .

When in AUTOFW mode, ipmasqadm supports three basic commands, similar to ipchains, plus options that specify how you want the auto-forwarding to work. Remember that there are two ways to use auto-forwarding; the first specifies the hidden host explicitly, and the second infers it from activity on the control connection. This AUTOFW rule always forwards to the "hidden host":

ipmasqadm autofw -A -r proto lport hport -h ipaddr -u

The first syntax always names the hidden host with -h. -A indicates that a rule should be added. -r specifies the protocol (either udp or tcp) and the range of ports to be auto-forwarded to the hidden host. -u tells the kernel to allow timeouts longer than the default of 15 seconds. This AUTOFW rule tracks the protocol to determine the hidden host:

ipmasqadm autofw -A -r proto lport hport -c proto port -u

The second command is the same as the first, except that instead of specifying a hidden host, -c indicates the control connection of protocol proto and port port. Once you establish rules, look at /proc/net/ip masq/autofw to get an idea of what's happening.

A Better Way to AUTOFW—NAT

Another way to handle the auto-forwarding situation is to use a Network Address Translator (NAT). The idea is to allocate a set of Internet-valid IP addresses to the router for use when masquerading these special (or all) types of protocols. The router then binds one of these addresses on the external interface before it sends (masquerades) the outgoing packet. This is the method used by most commercial NATs; unfortunately, Linux doesn't have this sort of functionality in the kernel yet, nor am I aware of a user-space daemon that does this.

Kernel Port Forwarding with PORTFW

The PORTFW feature has a different focus (and is less complicated!) than AUTOFW. Its aim is to replace user-space redirectors by performing the same task in kernel space. If done correctly, it should have lower resource requirements than the user-space equivalents. The drawback is that some features, such as configurable logging formats and access control lists,4 are not implemented to prevent bloating the kernel code. (The developers did manage to include support for preferences and load balancing.) There is much less to discuss about using this option; you should already be familiar with the concepts from the discussion of user-space redirectors. PORTFW has the added feature of preserving the original sender's IP address when forwarding the connection (like redir using the --transproxy option).

There are a couple of details you should keep in mind when using PORTFW:

  • Because this code is an extension to the masquerading code in the kernel, it can occur only during the forwarding of a packet. This means that you can't use PORTFW on a firewall to redirect an internal connection to a local port on that firewall. Because the packet remains on the "inside" of the firewall, no forwarding occurs. In practice, this isn't the sort of thing you would want to do with PORTFW anyway, but it might cause some confusion when you test your port forwarding from an internal address. (You can achieve the desired effect with transparent proxying anyway.)
  • By themselves, the PORTFW rules don't masquerade the outgoing (internal) server (external) client replies. This means that if you port forward inbound requests (from an external client to an internal server), you may want to masquerade the outbound reply. Otherwise, the client will see the reply from a different server (the internal address) than the one it sent the request to (the external firewall address). This may or may not pose a problem. If it does, add a masquerading rule for these packets, similar to one you would use for connections in the other direction.

To make use of PORTFW in production, you advertise the IP address of your Web server to the world via DNS as the IP address of the external interface on the firewall. If internal users are to use the same resource, you can overload this name on the internal DNS server with the internal IP address. Then configure the PORTFW rule to redirect inbound connections to the IP address(es) of the Web server. You set up your forwarding rules using the following syntax:

hafnium:/root> 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)

Notice that the -a (add), -d (delete), and -f (flush) options are in lowercase, unlike for AUTOFW, and that you always precede these options ipmasqadm portfw. The usage is straightforward, but Table 1 shows a few additional tips.

Table 1

ipmasqadm PORTFW Options

Option

Description

-l

Lists not only the rules but also the pcnt and pref fields, which are explained along with the -p option.

-n

Suppresses name resolution, as it normally does. It makes sense to specify this is in conjunction with -l.

-p preference

Load balancing is implemented via a simple counter. The rules are stored in the kernel as a linked list, and by default each rule is initialized with a preference count (pcnt) of 10. Each time the rule is used, the preference count is decremented. When the counter reaches 0, the rule is moved to the end of the list. In the degenerate case of a single rule, this doesn't change anything. But if there are multiple rules for a given LADDR:LPORT pair, shuffling the list will result in the next entry (with a different RADDR:RPORT value) being used on the next request. Use -p 1 to implement a simple round-robin scheme. If one server is more capable than another, you can weight your preference values accordingly.

The following sequence of commands is a simple example of usage:

# kernel PORTFW for inbound requests

### set up the port forwarding
# the .27 system gets the bulk of the requests because it
# has the new UltraPANTHEON 4692 HTTP co-processor chip
ipmasqadm portfw -a -P tcp -L extip 80 -R 192.168.16.27 80 -p 15
ipmasqadm portfw -a -P tcp -L extip 80 -R 192.168.16.28 80 -p 5

### need masquerading rules too!
ipchains -A -p tcp -s 192.168.16.27/32 80 -j MASQ
ipchains -A -p tcp -s 192.168.16.28/32 80 -j MASQ

Remember that you can perform a sort of load balancing by specifying preferences for your rules. Test your setup by Telnetting to an external machine and then trying to Telnet to the firewall at port 80. You should connect to the internal system. Issue the command quit to disconnect. As with most things in the kernel, you don't have to use the commands provided to get an idea of what's going on. In this case, you can view the contents of /proc/net/ip masq/portfw.

Kernel Port Forwarding with FWMARK

FWMARK basically accomplishes the same goal as PORTFW—redirecting traffic to an internal host using private address space—but adds a more powerful way to specify which inbound connections are to be forwarded. It does this by operating in conjunction with ipchains, which is used to mark packets with a label (actually, an integer). A FWMARK rule can then act on a packet bearing a certain mark, with different rules operating on each type of mark.

Consider the case where you want a certain set of users to be redirected to one Web server (perhaps with privileged information) while the rest always use another server. With PORTFW, there's no way to specify any sort of source criteria; this also goes for transparent proxying. So you would have to publish a second IP address (and therefore DNS record, etc.) and use PORTFW or a redirector bound to the second interface and then perform some sort of filtering to make sure that unprivileged machines couldn't connect to the restricted redirector. As long as you can differentiate between clients based on IP address, FWMARK allows you to do this sort of selection without leaving clues as to the different forms of access.

The command syntax is similar to that for PORTFW (except that most of the options have changed from lowercase to uppercase and vice versa). There's no need to specify the local address or port because ipchains syntax takes care of that with the criteria it uses to mark the packet.

hafnium:/root> ipmasqadm mfw

Usage: mfw -A -m FWMARK -r RADDR RPORT [-p PREF] add entry
mfw -D -m FWMARK [-r RADDR RPORT]                delete entry
mfw -E -m FWMARK [-r RADDR RPORT]                edit entry
mfw -S -m FWMARK                                 force scheduling
mfw -F                                           clear table
mfw -L                                           list table
mfw <args> -n                                    no names

The syntax is straightforward, but the option -S bears explanation. The round-robin scheduling mechanism used in PORTFW is also available for FWMARK, but with an extension. If a rule's preference is set to 0, no scheduling is performed, and that rule retains its position in the linked list of rules. If other rules have non-zero preferences, the zero-preference rule eventually becomes the first rule in the list for that mark, and stays there. This remains so until you force scheduling to occur by invoking ipmasqadm mfw -S. At this time, the rule at the head of the linked list is moved to the back, promoting the next rule. An application of this is to perform failover from one RADDR to another. Set all preferences to 0; if the primary server is detected to be down, force scheduling of the rules to select the next in line.

Marking packets with ipchains isn't difficult, either. You mark them with an integer value using -m markvalue. Following is a sequence of commands that enforce a policy like the one described at the beginning of this section:

# kernel firewall mark forwarding for Web access
#
# use these symbolic names to keep everything straight
MARK_FRIEND=1
MARK_NEUTRAL=3
FRIEND=209.81.8.0/24
FRIEND_SVR=192.168.17.3/32
NEUTRAL_SVR=192.168.15.46/32

# mark packets as they enter the system
ipchains -I input -s ${FRIEND} -m ${MARK_FRIEND}
ipchains -I input -s ! ${FRIEND} -m ${MARK_NEUTRAL}

# establish forward/redir rules based on marks
ipmasqadm mfw -I -m ${MARK_NEUTRAL} -r ${NEUTRAL_SVR}
ipmasqadm mfw -I -m ${MARK_FRIEND} -r ${FRIEND_SVR}

# make sure that the replies are masqueraded too
ipchains -I forward -d ${FRIEND} -s ${FRIEND_SVR} -j MASQ
ipchains -I forward -s ${NEUTRAL_SVR} -j MASQ

The script is a pretty simple case, but not so trivial that it can't have interesting uses. Note the lack of -p protocol and port specifications in the ipchains commands and the lack of a rport in the ipmasqadm statements. Because they're not specified, the commands will forward traffic for all ports (TCP, UDP, and ICMP) to the corresponding internal server. The same is true for the masquerading rules on the return trip. You could have just as easily added specific ports—it's up to you.

That concludes our tour of some of the redirection facilities available for Linux. You'll undoubtedly find other methods to perform no end of TCP/IP acrobatics. The change in the amount of capability between Linux 2.0 and 2.2 is significant, primarily due to the addition of ipchains. You can expect that much change (again) with the 2.4 kernel, which uses a new firewalling and masquerading code known as netfilter. netfilter is a complete rewrite and rethink of how to provide the range of features found in the current Linux kernel in a consistent manner, plus making it easy to add more features. Part of this is making it easy (and quick) to pass packets from kernel space into user space and back down. This should give birth to a whole new breed of network management daemons that can perform complex and arbitrary manipulations of packet headers, and that potentially have the ability to detect network-based attacks and take defensive measures in real-time. Visit http://netfilter.kernelnotes.org/ to get the full story.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.