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

IP Masquerading Concepts Under LINUX 2.2

System administrator Tony Mancill explains some of the intricacies of the IP masquerading facility available in version 2.2 of the Linux kernel. This feature enables a private network (or collection of private networks) to access the Internet via a single masquerading router.

IP Masquerading Concepts

IP masquerading is a facility in the Linux kernel that can manipulate packets so that they appear to originate from addresses other than the original source. Before you think that this is some hacker tool, the masquerading is performed only during the forwarding of a packet. (It would make no sense if the router itself originates the packet or if the router were the destination of the packet.) The kernel performs some acrobatics to make the process transparent to both the sender and the receiver. It does a good job in all but a few rare cases.

Before we talk about configuring IP masquerading, let's start with an example of why one might need it, and what happens to a packet when it's masqueraded. The primary function of masquerading is to obscure the IP address of a client from a server located on a separate network. The reasons for doing this vary. The most common one is that the client has an address such that the server either would not or could not respond to a connection request originating from that client. This situation is depicted in Figure 1, where the client can contact the server, but the server response will never reach the client.

Figure 1

A scenario for IP masquerading.

Remember that the private address space may be used by any private net, and as such may be routed internally at B's network to some other machine with the address To remedy the situation, the router alters the packet so that it appears to have originated from its external interface RB, which is an Internet-valid address. When the server sends a response, it's routed to R, which then forwards the packet to client A. The topology, of course, is usually much more complex than that depicted in Figure 1; there may be many hops between the router and the server. The result, however, is the same. The packet appears to have an Internet-valid source address and will find its way back to the router to be unmasqueraded.

IP Masquerading Under the Hood

Now that we're motivated to use masquerading, we can talk about what's really happening to the packet when it's masqueraded. As an example, let's say that client A would like to connect to server B using either TCP or UDP.1 The client is going to send from port x to port y on the server. In order to reach B, A first sends the packet to its gateway, which has address RA. The gateway interface on the B side is RB.

Taking a close look at such a transaction, you'll see that three different types of addresses are involved. First, each machine has an Ethernet address, useful only for transmission of frames to other machines on its local subnet. The next layer includes the IP address of the source and the destination. Finally, for the TCP and UDP protocols, there is a specific port on both the client and the server. Normally, the client port is not significant and is a value between 1024 and 65534, arbitrarily chosen by the operating system.2 However, the server response must arrive on the port where the client expects it—otherwise, the client doesn't know that the packet is a response to its send.

Forwarding Without Masquerading

Let's list the sequence of a send/respond transaction when no masquerading occurs, and then follow the values of the three addresses in Table 1:

    1. Client A wants to send to the service running on port y on server B, so it builds a packet with B's IP address as the destination. Because B is part of a different subnet, client A knows to forward the packet to its gateway, R. It does this by setting the destination in the Ethernet frame to R.

    2. R receives the packet and notes that its destination is a remote IP address. Because R is configured to forward, it accepts the packet and determines which interface to use to forward the packet. It then places B's Ethernet address as the destination address in the Ethernet frame and sends the packet. (In the general case where B is still several hops away, it determines which gateway is the next hop and sends to it, where the same procedure takes place.)

    3. Server B receives the Ethernet frame and notes that the destination address for the packet is its own. Therefore, it accepts the packet and sends it to the process that has a socket bound and listening to the destination port y in the TCP packet header.

    4. The same procedure is executed in reverse for the response. This time, the TCP header destination port is x, and the source port is y. The IP packet header has B as the source and A as the destination. The Ethernet frame headers take on the appropriate values as the packet makes its way back to client A.

Table 1

Protocol Headers During Normal Forwarding

Forwarding with Masquerading

Now take the same situation and configure the router to masquerade traffic from subnetA or traffic to subnetB. The following steps will occur during a transaction between client A and server B:

    1. Client send/router receive. A sends a packet to B via its gateway R.

    2. Router masquerade. The packet pattern-matching on the router R notices that this connection should be masqueraded. It builds a new set of IP headers for the packet payload in which the source IP address of the packet is replaced by the IP address of the forwarding interface on R. R opens a free port, z, and fixes up the packet so that it now originates from R:z.

    3. Router forward/server receive. The newly massaged packet is forwarded to B.

    4. Server reply/router receive. B's server process receives the packet and builds a packet to reply to it. The reply is to R at port z, because these are the source values B sees in the packet headers. B puts this packet on the wire to R.

    5. Router unmasquerade. The kernel on R recognizes the packet as a response to a previously masqueraded send by the destination IP and port tuple (R, z). When it opened the socket corresponding to port z, it left special instructions there to forward responses to that port to A at port x. Therefore, it unmasquerades the packet by fixing up the headers and then forwarding it to client A. The fixup includes replacing the source IP address to be that of B, and the sending port to be y.

    6. Router forward/client receive. R puts the packet on the wire. A receives the server response, which automagically appears to have come directly from the server at B. Neither A nor B is the wiser.

In summary, forwarding involves fixing up the Link Layer headers, while masquerading is the act of fixing up Network Layer headers (IP address) and Transport Protocol Layer headers (port). Table 2 and Figure 2 illustrate the step-by-step exchange explained above. The items in the table that are changed by the masquerading router are marked with an asterisk (*).

Table 2

Protocol Headers While Masquerading

Figure 2

IP forwarding and masquerading over Ethernet.

The values reported in the tables are the same values you would see in the output of a packet sniffer if you traced such a transaction. In this case, there are four different points where you could monitor the packet flow (at A, RA, RB, and B). If you watched all four, you would see that both interfaces on subnetA see the same traffic, as do both interfaces on subnetB. I point this out to show that the kernel modifies the packets between the interfaces—that is, while it internally forwards the packet from one interface to another. The upshot is that you can perform your monitoring directly on any interface on the masquerading router.

Protocol-Specific Masquerading

You can fool some of the packets some of the time, but you can't fool all of the packets all of the time. The example presented in the preceding section represents one class of TCP/IP connection: a TCP stream. What about masquerading UDP and ICMP? As long as they are well-mannered, the IP masquerading code in ./net/ipv4/ip masq.c handles all three without any additional configuration. What do I mean by well-mannered? IP masquerading works "out of the box" for all TCP– and UDP–based applications based on a single fixed server port and arbitrarily chosen client port, where the machine being masqueraded (the client) is the initiator of the connection.

How far does this get you? It handles Telnet, ssh, rlogin, HTTP, pings (ICMP) and traceroutes (a combination of ICMP and UDP), DNS (often UDP, but can be TCP), NNTP, and many others. But, as you already know, it's what doesn't work that people notice. The first notable exception is FTP. FTP likes to open connections from the server back to the client, contrary to the direction you're trying masquerade (and/or firewall).

To handle a case like this, the masquerading code needs to understand something about the application protocol so that it can watch for the beginning of a transfer and know to connect the inbound socket connection to the client, not to the router. Remember, the process running on the client is expecting that inbound connection, not the router. To make things even more complicated, the FTP protocol also has a passive mode in which this inbound connection doesn't occur. The client and server negotiate a new pair of ports and use these to build a stream connection for the data transmission.

The Linux kernel developers weren't satisfied with IP masquerading without FTP, so they added protocol-specific masquerading support. Code, in the form of modules, can be loaded into the running kernel to provide masquerading for the less well-behaved protocols. These modules are automatically built when you select IP: masquerading during kernel configuration—all you have to do is load them. Pretty spiffy, eh? The list of modules and protocols supported includes, but is not limited to, the following:

  • 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.o3

  • RealAudio and RealVideo with the module ip masq raudio.o

  • VDO Live with the module ip masq vdolive.o

To use one of the protocol modules, simply load it with insmod modulename. Because they need to be loaded to be useful, I add them to my /etc/init.d/network file so that they're loaded during the startup sequence. Although you may rarely need to use it, several of the modules support the ability to listen to more than just the well-known port for their respective protocol. This is useful if you want to provide FTP services on more ports than just port 21 by adding the argument to ports=x1,x2,x3… to the command line by using insmod to load the module. If you want to specify more than MAX MASQ APP PORTS different ports, you have to modify the value in /usr/src/linux/include/net/ip masq.h and recompile the kernel and the modules.

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.


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.


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.


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.


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


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


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.


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.


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