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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020