Sei sulla pagina 1di 38

Network Address Translation Technion - Israel Institute of Technology Computer Networks Laboratory

Spring 2002 semester


By: Caliv Nir (shanir@techst.technion.ac.il) Project# cn19s02

Page 1 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Content:

1. 2.

NAT Abstract....................................................................................................... 3 Network Address Translation ................................................................................. 4 2.1 IP Addresses.................................................................................................... 4 2.2 Security Considerations .................................................................................. 5 2.3 Administrative Considerations........................................................................ 6 2.4 NAT and Proxies............................................................................................. 7 2.5 NAT Operation ............................................................................................... 8 3. Software ................................................................................................................ 10 3.1 Block Diagram .............................................................................................. 10 3.2 Building a Sniffer.......................................................................................... 11 3.3 Building a Manipulator ................................................................................. 12 3.4 Building a Transmitter .................................................................................. 13 4. Setup & Installation .............................................................................................. 15 5. References............................................................................................................. 16 Appendix A Header files ........................................................................................... 17

Page 2 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

1. NAT Abstract
In this project I have implemented NAT-Network Address Translate Server. In short NAT Server allows one to share its internet connection with multiple computers. The project implement the NAT Server in software under Microsoft Windows 2000 server. The machine running the NAT Server has network connection through one network card (or modem) and allows computers connected to a network visible through the second server network card to share its internet connection. The project is completed and function with the TCP, UDP and ICMP internet protocols. For projects presentations and source files you can reference: http://comnet.technion.ac.il/~cn19s02/

Page 3 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

2. Network Address Translation


The Internet is expanding at an exponential rate. As the amount of information and resources increases, it is becoming a requirement for even the smallest businesses and homes to connect to the Internet. Network Address Translation (NAT) is a method of connecting multiple computers to the Internet (or any other IP network) using one IP address. This allows home users and small businesses to connect their network to the Internet cheaply and efficiently. The impetus towards increasing use of NAT comes from a number of factors: A world shortage of IP addresses Security needs Ease and flexibility of network administration

2.1

IP Addresses

In an IP network, each computer is allocated a unique IP address. In the current version of IP protocol, IP version 4, an IP address is 4 bytes. The addresses are usually written as x1.x2.x3.x4, with x1, x2, x3 and x4 each describing one byte of the address. For example, address 16843009 (hex 1010101) is written as 1.1.1.1, since each byte of this address has a value of 1. Since an address is 4 bytes, the total number of available addresses is 2 to the power of 32 = 4,294,967,296. This represents the TOTAL theoretical number of computers that can be directly connected to the Internet. In practice, the real limit is much smaller for several reasons. Each physical network has to have a unique Network Number, comprising some of the bits of the IP address. The rest of the bits are used as a Host Number to uniquely identify each computer on that network. The number of unique Network Numbers that can be assigned in the Internet is therefore much smaller than 4 billion, and it is very unlikely that all of the possible Host Numbers in each Network Number are fully assigned. An address is divided into two parts: a network number and a host number. The idea is that all computers on one physical network will have the same network number - a bit like the street name, the rest of the address defines an individual computer - a bit like house numbers within a street. The size of the network and host parts depends on the class of the address, and is determined by address' network mask. The network mask is a binary mask with 1s in the network part of the address, and 0 in the host part. To allow for a range from big networks, with a lot of computers, to small networks, with a few hosts, the IP address space is divided into 4 classes, called class A, B, C and D. The first byte of the address determines which class an address belongs to: Network addresses with first byte between 1 and 126 are class A, and can have about 17 million hosts each. Network addresses with first byte between 128 and 191 are class B, and can have about 65000 hosts each. Network addresses with first byte between 192 and 223 are class C, and can have 256 hosts. All other networks are class D, used for special functions or class E which is reserved.

Page 4 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Most class A and B addresses have already been allocated, leaving only class C available. This means that total number of available addresses on the Internet is 2,147,483,774. Each major world region has an authority which is given a share of the addresses and is responsible for allocating them to Internet Service Providers (ISPs) and other large customers. Because of routing requirements, a whole class C network (256 addresses) has to be assigned to a client at a time; the clients (e.g.. ISPs) are then responsible for distributing these addresses to their customers. While the number of available addresses seems large, the Internet is growing at such a pace that it will soon be exhausted. While the next generation IP protocol, IP version 6, allows for larger addresses, it will take years before the existing network infrastructure migrates to the new protocol. Because IP addresses are a scarce resource, most Internet Service Providers (ISPs) will only allocate one address to a single customer. In majority of cases this address is assigned dynamically, so every time a client connects to the ISP a different address will be provided. Big companies can buy more addresses, but for small businesses and home users the cost of doing so is prohibitive. Because such users are given only one IP address, they can have only one computer connected to the Internet at one time. With an NAT gateway running on this single computer, it is possible to share that single address between multiple local computers and connect them all at the same time. The outside world is unaware of this division and thinks that only one computer is connected.

2.2

Security Considerations

Many people view the Internet as a "one-way street"; they forget that while their computer is connected to the Internet, the Internet is also connected to their computer. That means that anybody with Net access can potentially access resources on their computers (such as files, email, company network etc). Most personal computer operating systems are not designed with security in mind, leaving them wide open to attacks from the Net. To make matters worse, many new software technologies such as Java or Active X have actually reduced security since it is now possible for a Java applet or Active X control to take control of a computer it is running on. Many times it is not even possible to detect that such applets are running; it is only necessary to go to a Web site and the browser will automatically load and run any applets specified on that page. The security implications of this are very serious. For home users, this means that sensitive personal information, such as emails, correspondence or financial details (such as credit card or cheque numbers) can be stolen. For business users the consequences can be disastrous; should confidential company information such as product plans or marketing strategies be stolen, this can lead to major financial losses or even cause the company to fold. To combat the security problem, a number of firewall products are available. They are placed between the user and the Internet and verify all traffic before allowing it to pass through. This means, for example, that no unauthorized user would be allowed to access the company's file or email server. The problem with firewall solutions is that they are expensive and difficult to set up and maintain, putting them out of reach for home and small business users. NAT automatically provides firewall-style protection without any special set-up. That is because it only allows connections that are originated on the inside network. This means, for example, that an internal client can connect to an outside FTP server, but an outside client will not be able to connect to an internal FTP server because it would have to originate the connection, and NAT will not allow that. It is still possible to make some internal servers available to the outside world via

Page 5 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

inbound mapping, which maps certain well know TCP ports (e.g.. 21 for FTP) to specific internal addresses, thus making services such as FTP or Web available in a controlled way. Many TCP/IP stacks are susceptible to low-level protocol attacks such as the recently-publicized "SYN flood" or "Ping of Death". These attacks do not compromise the security of the computer, but can cause the servers to crash, resulting in potentially damaging "denials of service". Such attacks can cause abnormal network events that can be used as a precursor or cloak for further security breaches. NATs that do not use the host machine protocol stack but supply their own can provide protection from such attacks:

2.3

Administrative Considerations

IP networks are more difficult to set up than local desktop LANs; each computer requires an IP address, a subnet mask, DNS address, domain name, and a default router. This information has to be entered on every computer on the network; if only one piece of information is wrong, the network connection will not function and there is usually no indication of what is wrong. In bigger networks the task of co-ordinating the distribution of addresses and dividing the network into subnets is so complicated that it requires a dedicated network administrator. NAT can help network administration in several ways: It can divide a large network into several smaller ones. The smaller parts expose only one IP address to the outside, which means that computers can be added or removed, or their addresses changed, without impacting external networks. With inbound mapping, it is even possible to move services (such as Web servers) to a different computer without having to do any changes on external clients.

Some modern NAT gateways contain a dynamic host configuration protocol (DHCP) server. DHCP allows client computers to be configured automatically; when a computer is switched on, it searches for a DHCP server and obtains TCP/IP setup information. Changes to network configuration are done centrally at the server and affect all the clients; the administrator does not need to apply the change to every computer in the network. For example, if the DNS server address changes, all clients will automatically start using the new address the next time they contact the DHCP server.

Page 6 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Many NAT gateways provide for a way to restrict access to the Internet. For example, CyberPatrol filtering, that allows administrators to prohibit access to dubious material. Another useful feature is traffic logging; since all the traffic to and from the Internet has to pass through a NAT gateway, it can record all the traffic to a log file. This file can be used to generate various traffic reports, such as traffic breakdown by user, by site, by network connection etc. Since NAT gateways operate on IP packet-level, most of them have built-in internetwork routing capability. The internetwork they are serving can be divided into several separate sub networks (either using different backbones or sharing the same backbone) which further simplifies network administration and allows more computers to be connected to the network:

To summarize, a NAT gateway can provide the following benefits: Firewall protection for the internal network; only servers specifically designated with "inbound mapping" will be accessible from the Internet Protocol-level protection Automatic client computer configuration control Packet level filtering and routing

2.4

NAT and Proxies

A proxy is any device that acts on behalf of another. The term is most often used to denote Web proxying. A Web proxy acts as a "half-way" Web server: network clients make requests to the proxy, which then makes requests on their behalf to the appropriate Web server. Proxy technology is often seen as an alternative way to provide shared access to a single Internet connection. The main benefits of Web proxying are: Local caching: a proxy can store frequently-accessed pages on its local hard disk; when these pages are requested, it can serve them from its local files instead of having to download the data from a remote Web server. Proxies that perform caching are often called caching proxy servers. Network bandwidth conservation: if more than one client requests the same page, the proxy can make one request only to a remote server and distribute the received data to all waiting clients.

Both these benefits only become apparent in situations where multiple clients are very likely to access the same sites and so share the same data. Unlike NAT, Web proxying is not a transparent operation: it must be explicitly supported by its clients. Due to early adoption of Web proxying, most browsers, including Internet Explorer and Netscape Communicator, have built-in support for proxies, but this must normally be configured on each client machine, and may be changed by the naive or malicious user. Web proxying has the following disadvantages: Web content is becoming more and more dynamic, with new developments such as streaming video & audio being widely used. Most of the new data formats are not cacheable, eliminating one of the main benefits of proxying. Clients have to be explicitly set to use Web proxying; whenever there is a change (e.g. proxy is moved to a new IP address) each and every client has to be set up again.

Page 7 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

A proxy server operates above the TCP level and uses the machine's built-in protocol stack. For each Web request from a client, a TCP connection has to be established between the client and the proxy machine, and another connection between the proxy machine and the remote Web server. This puts lot of strain on the proxy server machine; in fact, since Web pages are becoming more and more complicated the proxy itself may become bottleneck on the network. This contrasts with a NAT which operates on packet level and requires much less processing for each connection.

2.5

NAT Operation

The basic purpose of NAT is to multiplex traffic from the internal network and present it to the Internet as if it was coming from a single computer having only one IP address. The TCP/IP protocols include a multiplexing facility so that any computer can maintain multiple simultaneous connections with a remote computer. It is this multiplexing facility that is the key to single address NAT. To multiplex several connections to a single destination, client computers label all packets with unique "port numbers". Each IP packet starts with a header containing the source and destination addresses and port numbers: Source address Source port Destination address Destination port This combination of numbers completely defines a single TCP/IP connection. The addresses specify the two machines at each end, and the two port numbers ensure that each connection between this pair of machines can be uniquely identified. Each separate connection is originated from a unique source port number in the client, and all reply packets from the remote server for this connection contain the same number as their destination port, so that the client can relate them back to its correct connection. In this way, for example, it is possible for a web browser to ask a web server for several images at once and to know how to put all the parts of all the responses back together. A modern NAT gateway must change the Source address on every outgoing packet to be its single public address. It therefore also renumbers the Source Ports to be unique, so that it can keep track of each client connection. The NAT gateway uses a port mapping table to remember how it renumbered the ports for each client's outgoing packets. The port mapping table relates the client's real local IP address and source port plus its translated source port number to a destination address and port. The NAT gateway can therefore reverse the process for returning packets and route them back to the correct clients. When any remote server responds to an NAT client, incoming packets arriving at the NAT gateway will all have the same Destination address, but the destination Port number will be the unique Source Port number that was assigned by the NAT. The NAT gateway looks in its port mapping table to determine which "real" client address and port number a packet is destined for, and replaces these numbers before passing the packet on to the local client. This process is completely dynamic. When a packet is received from an internal client, NAT looks for the matching source address and port in the port mapping table. If the entry is not found, a new one is created, and a new mapping port allocated to the client: Incoming packet received on non-NAT port

Page 8 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Look for source address, port in the mapping table If found, replace source port with previously allocated mapping port If not found, allocate a new mapping port Replace source address with NAT address, source port with mapping port

Packets received on the NAT port undergo a reverse translation process: Incoming packet received on NAT port Look up destination port number in port mapping table If found, replace destination address and port with entries from the mapping table If not found, the packet is not for us and should be rejected

Each client has an idle time-out associated with it. Whenever new traffic is received for a client, its time-out is reset. When the time-out expires, the client is removed from the table. This ensures that the table is kept to a reasonable size. The length of the time-out varies, but taking into account traffic variations on the Internet should not go below 2-3 minutes. Most NAT implementations can also track TCP clients on a per-connection basis and remove them from the table as soon as the connection is closed. This is not possible for UDP traffic since it is not connection based. Many higher-level TCP/IP protocols embed client addressing information in the packets. For example, during an "active" FTP transfer the client informs the server of its IP address & port number, and then waits for the server to open a connection to that address. NAT has to monitor these packets and modify them on the fly to replace the client's IP address (which is on the internal network) with the NAT address. Since this changes the length of the packet, the TCP sequence/acknowledge numbers must be modified as well. Most protocols can be supported within the NAT; some protocols, however, may require that the clients themselves are made aware of the NAT and that they participate in the address translation process. [Or the NAT must be protocol-sensitive so that it can monitor or modify the embedded address or port data] Because the port mapping table relates complete connection information - source and destination address and port numbers - it is possible to validate any or all of this information before passing incoming packets back to the client. This checking helps to provide effective firewall protection against Internet-launched attacks on the private LAN. Each IP packet also contain checksums that are calculated by the originator. They are recalculated and compared by the recipient to see if the packet has been corrupted in transit. The checksums depend on the contents of the packet. Since the NAT must modify the packet addresses and port numbers, it must also recalculate and replace the checksums. Careful design in the NAT software can ensure that this extra processing has a minimal effect on the gateway's throughput. Before doing so it must check for, and discard, any corrupt packets to avoid converting a bad packet into a good one.

Page 9 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

3. Software
3.1

Block Diagram

Local Network Sniffer Protocol Detector Transmitter Manipulator Address Translator

Internet
NAT server reside between two networks, lets call it Private (Local Network) and Public (Internet for example). The NAT server is build from these following components: Sniffer listen to both of the networks and capture incoming (Public Private) and outgoing (Private Public) network packets. It is implemented as a C++ class encapsulating all of its functionality. Protocol detector examine the incoming/outgoing packets and find their protocol, it discard unsupported protocol and pass forward supported protocols (currently TCP, UDP & ICMP). In the program it is implemented in the connecting layer between the NAT and the Sniffer. Address translator Responsible for, two way translation, of IP/Port pair and unique integer number. Upon receiving outgoing packet we need to alter its IP and Port data, but we need to remember the original data (as explained in the NAT explanation) so the translator assigns this pair a unique integer. When receiving an incoming packet we take this unique integer and find by it the original IP and Port. It is implemented as a C++ class encapsulating all of its functionality. Manipulator - Responsible for packet examination and manipulation. It is implemented as a C++ interface encapsulating all of its functionality, and a collection of C++ classes implementing several network protocols (TCP, UDP and ICMP)

Page 10 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Transmitter - Responsible for transmitting the NAT manipulated network packets back to the appropriate network (private or public). It is implemented as a C++ class encapsulating all of its functionality.

3.2

Building a Sniffer

In order to implement Network Sniffer I have used Microsoft Network monitor API. This is COM based API available for use from Win2000 an on, giving access to the network traffic. Network Monitor Purpose Network Monitor captures network traffic for display and analysis. It allows you to perform tasks such as analyzing previously captured data in user-defined methods, extracting data from defined protocol parsers, and analyzing real-time traffic on your network. Developer Audience All API sets provided by Network Monitor can be accessed using C/C++. Those developers also working with network packet providers must also be familiar with COM. Runtime Requirements To call the Network Monitor API sets, you must be running on Microsoft Windows NT Server version 4.0 or Microsoft Windows 2000 Server, or have Microsoft Systems Management Server installed. The NPP driver and supported functionality ship with all versions of Windows NT version 4.0 and Microsoft Windows 2000 Server.

NPP Interfaces Network packet providers (NPPs) provide COM interfaces that are called by monitors, NPP applications, and Network Monitor. When you call CreateNPPInterface, remember that each NPP is represented as a single in-process COM object. Applications can instantiate any number of NPP objects. However, each instantiated object must use one and only oneof the five NPP interfaces. Note also that different NPP interfaces provide network data in various forms. For example, Network Monitor uses the IDelaydC interface to capture network traffic and save it to a capture file; while monitors use the IRTC interface to capture real time network traffic. The following table describes Network Monitor NPP interfaces. Interface Description IDelaydC IESP IRTC IStats Captures network traffic that is stored in a capture file. This interface is used by Network Monitor and NPP applications. Captures network traffic that is stored in a capture file and provides enhanced statistics in a special ESP file format. This interface is used by NPP applications Captures real time network traffic and triggers events when they occur. This interface is used by monitors and NPP applications. Retrieves statistics as raw data rather than frames. This interface is used by NPP applications such as Perfmon.

Page 11 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

IRTC The IRTC interface provides the methods used to connect the NPP to the network, capture network traffic to a capture file, retrieve statistics, and disconnect the NPP from the network. IRTC gets an interface to local-only entry points, which are necessary to engage in real-time capture. This interface includes a method that hands off a callback to the NPP. Methods in Vtable Order The IRTC interface inherits the methods of the standard COM interface IUnknown. In addition, IRTC defines the following methods. Method Connect Disconnect QueryStatus Configure Start Pause Resume Stop GetControlState GetTotalStatistics GetConversationStatistics QueryStations Description Connects the NPP to the network. Disconnects the NPP from the network. Retrieves the status of the NPP. Sets the trigger, pattern match, and buffer size of the capture file. Starts a capture. Temporarily stops the current capture. Restarts a paused capture. Stops the current capture. Retrieves the state of the capture, which indicates if the capture is running or paused. Extracts time, buffer, driver, and other network statistics from the currently running capture. Retrieves session and station information for the current capture. Retrieves a list of all computers on a subnet that are using Network Monitor to capture network data.

Requirements Windows NT/2000/XP: Included in Windows NT 4.0, Windows 2000, Windows XP, and Windows .NET Server 2003 family. Header: Declared in Netmon.h.

3.3

Building a Manipulator
The manipulator is responsible for packet examination and manipulation. Upon receiving an outgoing packet (from private network to public network) it must find the protocol used by examining the content of the packet and manipulating (according to the protocol used) the IP and optionally Port data from the internal IP to the NAT server public IP. Upon receiving an incoming packet (from public network into private network), it must find the protocol used by examining the content of the packet and manipulating (according to the protocol used) the IP and optionally Port data from the public NAT servers IP to on of the private IPs in the internal network. The manipulator is also responsible for fixing the Packet checksums that need to be updated because of the packets data manipulation.

Page 12 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

It is implemented as a C++ interface encapsulating all of its functionality, and a collection of C++ classes implementing several network protocols (TCP, UDP and ICMP)

3.4

Building a Transmitter
In order to implement network transmitter I have used Microsoft WinSock2 API and its Raw Sockets. A raw socket is one that allows access to the underlying transport protocol. Raw sockets can also be used to manipulate IP header information. The first step in using raw sockets is creating the socket. You can use either socket or WSASocket. Note that for Windows 95, Windows 98, and Windows Me, no catalog entry in Winsock for IP has the SOCK_RAW socket type. However, this does not prevent you from creating this type of socket. It just means that you cannot create a raw socket using a WSAPROTOCOL_INFO structure. Refer back to Chapter 2 for information about enumerating protocol entries with the WSAEnumProtocols function and the WSAPROTOCOL_INFO structure. You must specify the SOCK_RAW flag yourself in socket creation. The following code snippet illustrates the creation of a raw socket using ICMP as the underlying IP protocol: SOCKET s; s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); // Or s = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED); if (s == INVALID_SOCKET) { // Socket creation failed } When creating a raw socket, the protocol parameter of the socket call becomes the protocol value in the IP header. That is, if a raw AF_INET6 socket is created with the protocol value 66, the IPv6 header for outgoing packets will contain the value 66 in the next header field. Because raw sockets offer the capability to manipulate the underlying transport, they can be used for malicious purposes and are a security issue in Windows NT. Therefore, only members of the Administrators group can create sockets of type SOCK_RAW. Anyone can create a raw socket on Windows NT, but non-Administrators will not be able to do anything with it because the bind API will fail with WSAEACCES. Windows 95, Windows 98, and Windows Me do not impose any kind of limitation. To work around this limitation on Windows NT, you can disable the security check on raw sockets by creating the following registry variable and setting its value to the integer 1 as a DWORD type. HKEY_LOCAL_MACHINE\System\CurrentControlSet \Services\Afd\Parameters\DisableRawSecurity After the registry change, you need to reboot the machine. Once the raw socket is created with the appropriate protocol flags, you can use the socket handle in send and receive calls. When creating raw sockets, the IP header will be included in the data returned upon any receive, regardless of whether the IP_HDRINCL option is set. Applications will have to know the layout of the IP header and have to determine the length of the IP header to find the payload data within the received buffer. The one limitation of raw sockets is that you can work only with certain protocols that are already defined, such as ICMP and IGMP. You cannot create a raw socket with

Page 13 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

IPPROTO_UDP and manipulate the UDP header; likewise with TCP. To manipulate the IP header as well as either the TCP or UDP header (or any other protocol encapsulated in IP), you must use the IP_HDRINCL socket option with a raw socket. For IPv6, the option is IPV6_HDRINCL. This option allows you to build your own IP header as well as other protocols' headers. In addition to manipulating well-known protocols such as UDP, using raw sockets with the header include option allows you to implement your own protocol scheme that is encapsulated in IP. This is done by creating a raw socket and using the IPPROTO_RAW value as the protocol. This allows you to set the protocol field in the IP header manually and build your own custom protocol header. You need to know one important difference between using this option with IPv4 and IPv6. For IPv4, the stack still verifies some fields within the supplied IPv4 header. For example, the IPv4 identification field is set by the stack and the stack will fragment the packet if necessary. That is, if you create a raw IPv4 packet and set IP_HDRINCL and send a packet larger than the MTU size, the stack will fragment the data into multiple packets for you. For IPv6, if the IPV6_HDRINCL option is set, it is your responsibility to compute all the headers and fields necessary. If you submit a send larger than the MTU size, your application must create the IPv6 fragment headers and compute the offsets correctly; otherwise, the IPv6 stack will drop the packet without sending it. When you use the header include option, you are required to fill in the IP header yourself for every send call, as well as the headers of any other protocols wrapped within.

Page 14 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

4. Setup & Installation


How to install & configure NAT Server and clients. 1. Setup a machine running Win2k or above OS. 2. Install two network cards (NICs) on the machine 3. Connect one NIC to the external network (Internet or Corporate LAN). 4. Connect the second NIC to the internal network. 5. Assign your private internal network appropriate IP addresses. (These addresses must not collide with real internet addresses or you corporate LAN addresses). The following IP address ranges are private i.e. never assigned on the global internet: 10.0.0.0 to 10.255.255.255 172.16.0.0 to 172.31.255.255 192.168.0.0 to 192.168.255.255 6. Copy the NAT binaries to the designated server and execute it according to its parameters (described in the next section). Nat.exe parameters Usage: nat.exe l:[index] w:[index] p:[private IP] i:[public IP] index of the WAN adapter (connected to the public network) index of the LAN adapter (connected to the private network) the IP of the private network NIC the IP of the public network NIC

-l:[index] -w:[index] -p:[IP] -i:[IP]

The WAN and LAN adapters indexes can be found by the IPConfig.exe Windows system utility.

Page 15 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

5. References
Microsoft Developer Network (MSDN) RFC 791 - Internet Protocol RFC 1011 - Official Internet Protocols RFC 1055 - A Non-standard for Transmission of IP Datagrams over Serial Lines: Slip RFC 1542 - Clarifications and Extensions for the Bootstrap Protocol RFC 1631 - The IP Network Address Translator (NAT) RFC 1661 - The Point-to-Point Protocol (PPP) RFC 1700 - Assigned Numbers RFC 1883 - Internet Protocol, Version 6 (IPv6) Specification RFC 1884 - IP Version 6 Addressing Architecture RFC 2068 - Hypertext Transfer Protocol -- HTTP/1.1 RFC 2131 - Dynamic Host Configuration Protocol Well Known Port Numbers DHCP Q&A Microsoft Proxy Server Description Egevang K., Francis P., "The IP Network Address Translator (NAT)" RFC 1631, Cray Communications, NTT, May 1994 Droms, R., "Dynamic Host Configuration Protocol", RFC 2131, Bucknell University, March 1997

Page 16 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Appendix A Header files


List of header files: NAT\NAT.h NAT\NATExcept.h NAT\Packet.h NAT\DebugPrint\Debug.h NAT\DebugPrint\Registry.h NAT\DebugPrint\tstring.h NAT\DebugPrint\util.h NAT\Manipulator\ICMPHeader.h NAT\Manipulator\ICMPHeaderManipulator.h NAT\Manipulator\IPHeader.h NAT\Manipulator\Manipulator.h NAT\Manipulator\PacketManipulator.h NAT\Manipulator\TCPHeader.h NAT\Manipulator\TCPHeaderManipulator.h NAT\Manipulator\TCPIPUtils.h NAT\Manipulator\UDPHeader.h NAT\Manipulator\UDPHeaderManipulator.h NAT\Sniffer\NetInterface.h NAT\Sniffer\parser.h NAT\Sniffer\Sniffer.h NAT\Translator\translator.h NAT\Transmitter\Transmitter.h

Page 17 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// NAT.h // // NAT class. // Wrap NAT functionality - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __NAT_H__ #define __NAT_H__ #include <memory> #include "NATExcept.h" #include "Sniffer\Sniffer.h"

class NAT{ public: NAT(int idxLANInterface, unsigned LANip, int idxWANInterface, unsigned WANip ) throw (NATInitializationException) :m_idxLANInterface(idxLANInterface), m_idxWANInterface(idxWANInterface), m_pLANSniffer(new Sniffer(idxLANInterface)), m_pWANSniffer(new Sniffer(idxWANInterface)), m_hCompletionPort(NULL) { localIPAddresses[0] = LANip; localIPAddresses[1] = WANip; init(); }

~NAT() throw(); static const unsigned* getLocalIPAddresses(){return localIPAddresses;} void go(); private: static bool initiated; // = false std::auto_ptr<Sniffer> m_pLANSniffer; std::auto_ptr<Sniffer> m_pWANSniffer; static unsigned localIPAddresses[2]; int m_idxLANInterface; int m_idxWANInterface; HANDLE m_hCompletionPort; void DWORD }; init(); WorketThreadFunc(LPVOID pData);

#endif //__NAT_H__// NATExcept.h

Page 18 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// // // // // // // //

NAT exception classes hierarchy - Network Addresses Translation (NAT) Project. Writen By: Created: Caliv Nir Apr - 2002 -

Last Modified : 12-Jun-2002

#ifndef __NATEXCEPT_H__ #define __NATEXCEPT_H__ // C++ exception specification ignored #pragma warning( disable : 4290 ) #include <stdexcept> typedef unsigned long DWORD; class NATException : public std::exception { public: NATException(const char* msg, DWORD ec):std::exception(msg),ec_(ec){} virtual const char *what( ) const throw( ); private: DWORD };

ec_;

// error code

class NATInitializationException : public NATException{ public: NATInitializationException(const char* msg, DWORD ec):NATException(msg,ec){} }; #endif //__NATEXCEPT_H__

Page 19 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

#ifndef __PACKET_H__ #define __PACKET_H__ #include <windows.h> #include <vector> struct Packet { OVERLAPPED std::vector<BYTE>

m_Overlapped; m_vecFrame;

Packet(BYTE* start,BYTE* end):m_vecFrame(start,end) { ZeroMemory(&m_Overlapped,sizeof OVERLAPPED); } }; #endif //__PACKET_H__

Page 20 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// Debug.h // // Debug utilities - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __DEBUG_H__ #define __DEBUG_H__ #include <windows.h> #include "tstring.h" class Debug { public: enum level_t {MSG, WRN, ERR, LAST_LEVEL}; Debug(const tstring& functionName):functionName_(functionName),line_(0){} void SetLine (int line){line_ = line;} void DebugPrint (level_t level,LPCTSTR msg, ...); static void private: void DebugPrint_ InitDebug();

(level_t level,LPCTSTR msg, va_list argptr);

static const tstring levelTxt[LAST_LEVEL]; static level_t DebugLevel; static HANDLE hLogFile; static level_t GetDebugLevel(); static HANDLE GetLogFileHandle(); const tstring functionName_; int line_; };

class DebugInitiator{ public: DebugInitiator(){Debug::InitDebug();} }; #ifdef _DEBUG #define FUNCTION(functionName) #else #define FUNCTION (void)(0) #endif #ifdef _DEBUG #define DEBUG_PRINT #else #define DEBUG_PRINT #endif #ifdef _DEBUG #define MSG #define WRN #define ERR #else #define MSG #define WRN #define ERR #endif #endif //__DEBUG_H__

Debug _DebugObject(functionName);

_DebugObject.SetLine(__LINE__); \ _DebugObject.DebugPrint (void)(0)

Debug::MSG Debug::WRN Debug::ERR 0 0 0

Page 21 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// registry.h // // registry defines - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __REGISTRY_H__ #define __REGISTRY_H__

// // //

Application - Registry keys and values

#define NAT #define NAT_REGKEY

TEXT("NAT") TEXT("SOFTWARE\\Shanir\\") NAT

#define NAT_DEBUG_REGKEY NAT_REGKEY TEXT("\\Debug") #define NAT_REGVAL_DEBUGLEVEL TEXT("DebugLevel") #define NAT_REGVAL_LOGFILE TEXT("LogFile") #endif //__REGISTRY_H__

Page 22 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// tstring.h // // string defines for ANSI and UNICODE support - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __TSTRING_H__ #define __TSTRING_H__ #include <string> #include <sstream> #include <iostream> #ifdef _UNICODE typedef std::wstring typedef std::wstringstream #define tcout std::wcout #define tcin std::wcin #define tcerr std::wcerr #else typedef std::string typedef std::stringstream #define tcout std::cout #define tcin std::cin #define tcerr std::cerr #endif #endif //__TSTRING_H__

tstring; tstringstream;

tstring; tstringstream;

Page 23 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// util.h // // general utilities - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __UTIL_H__ #define __UTIL_H__

#define ARR_SIZE(arr) ((sizeof arr)/(sizeof arr[0])) #endif //__UTIL_H__// ICMPHeader.h

Page 24 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// // // // // // // //

ICMP Header class - Network Addresses Translation (NAT) Project. Writen By: Created: Caliv Nir Apr - 2002 -

Last Modified : 12-Jun-2002

#ifndef __ICMPHEADER_H__ #define __ICMPHEADER_H__ // // Define the ICMP header // typedef struct ICMP_hdr { BYTE icmp_type; BYTE icmp_code; // Type sub code USHORT icmp_cksum; USHORT icmp_id; USHORT icmp_seq; // This is not the standard header, but we use this for NAT internals unsigned short port; } ICMP_HDR, *PICMP_HDR; #endif //__ICMPHEADER_H__

Page 25 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// ICMPHeaderManipulator.h // // ICMPHeaderManipulator class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __ICMPHeaderManipulator_H__ #define __ICMPHeaderManipulator_H__ #include "TCPIPUtils.h" #include "Manipulator.h" class ICMPHeaderManipulator : public BaseManipulator { public: // // change source IP & PORT of a given packet // virtual void manipulateOutgoingPacket( BYTE* packet, ip_t newSourceIP, port_t newSourcePort); // // change destination IP & PORT of a given packet // virtual void manipulateIncommingPacket( BYTE* packet, ip_t newDestIP, port_t newDestPort); private: // // Adjust checksum after the change // static void reCalculateICMPIPChecksums( BYTE* packet, ip_t originalSourceIP, port_t originalSourcePort, ip_t originalDestIP );

}; // class ICMPHeaderManipulator

#endif //__ICMPHeaderManipulator_H__

Page 26 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// IPHeader.h // // IP Header class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __IPHEADER_H__ #define __IPHEADER_H__ // // Define the IP header. Make the version and length field one // character since we can't declare two 4 bit fields without // the compiler aligning them on at least a 1 byte boundary. // typedef struct ip_hdr { unsigned char ip_verlen; // IP version & length unsigned char ip_tos; // IP type of service unsigned short ip_totallength; // Total length unsigned short ip_id; // Unique identifier unsigned short ip_offset; // Fragment offset field unsigned char ip_ttl; // Time to live unsigned char ip_protocol; // Protocol(TCP,UDP etc) unsigned short ip_checksum; // IP checksum unsigned int ip_srcaddr; // Source address unsigned int ip_destaddr; // Destination address } IP_HDR, *PIP_HDR;

#endif //__IPHEADER_H__

Page 27 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// Manipulator.h // // Manipulator class - Network Addresses Translation (NAT) Project. // BaseManipulator class for Socket based (IP+Port) Protocols manipulators // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __MANIPULATOR_H__ #define __MANIPULATOR_H__ #include "TCPIPUtils.h" class BaseManipulator { public: // // change source IP & PORT of a given packet // virtual void manipulateOutgoingPacket( BYTE* packet, ip_t newSourceIP, port_t newSourcePort) = 0; // // change destination IP & PORT of a given packet // virtual void manipulateIncommingPacket( BYTE* packet, ip_t newDestIP, port_t newDestPort) = 0; virtual ~BaseManipulator() = 0 { } }; #endif //__MANIPULATOR_H__

Page 28 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// PacketManipulator.h // // PacketManipulator class - Network Addresses Translation (NAT) Project. // Do NAT manipulation on a given packet // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __PACKETMANIPULATOR_H__ #define __PACKETMANIPULATOR_H__

#include "manipulator.h" #include <vector> class PacketManipulator { public: PacketManipulator(); void manipulateIncommingPacket( BYTE* packet, ip_t newDestIP, port_t newDestPort); void manipulateOutgoingPacket ( BYTE* packet, ip_t newSourceIP, port_t newSourcePort);

private: enum Protocol { TCP, UDP, ICMP }; std::vector<BaseManipulator*> manipulatorTable; }; #endif //__PACKETMANIPULATOR_H__

Page 29 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// TCPHeader.h // // TCP Header class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __TCPHEADER_H__ #define __TCPHEADER_H__ // // Define the TCP header. // typedef struct tcp_hdr { unsigned short tcp_SourcePort; unsigned short tcp_DestPort; unsigned int tcp_SeqNum; unsigned int tcp_AckNum; unsigned short tcp_ctrl; Bits: 6 bits unsigned short tcp_window; unsigned short tcp_Checksum; unsigned short tcp_UrgentPtr; } TCP_HDR, *PTCP_HDR; #endif //__TCPHEADER_H__

// Source Port // Destination Port // Sequence Number // Acknowledgment Number // Data Offset: 4 bits + Reserved: 6 bits + Control // Window // Checksum // Urgent Pointer

Page 30 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// TCPHeaderManipulator.h // // TCPHeaderManipulator class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __TCPHEADERMANIPULATOR_H__ #define __TCPHEADERMANIPULATOR_H__ #include "TCPIPUtils.h" #include "Manipulator.h" class TCPHeaderManipulator : public BaseManipulator { public: // // change source IP & PORT of a given packet // virtual void manipulateOutgoingPacket( BYTE* packet, ip_t newSourceIP, port_t newSourcePort); // // change destination IP & PORT of a given packet // virtual void manipulateIncommingPacket( BYTE* packet, ip_t newDestIP, port_t newDestPort); private: // // Adjust checksum after the change // static void reCalculateTCPIPChecksums( BYTE* packet, ip_t originalSourceIP, port_t originalSourcePort, ip_t originalDestIP, port_t originalDestPort );

}; // class TCPHeaderManipulator

#endif //__TCPHEADERMANIPULATOR_H__

Page 31 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// TCPIPUtils.h // // TCP/IP utility functions - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __TCPIPUTILS_H__ #define __TCPIPUTILS_H__ #include #include #include #include <winsock2.h> <windows.h> "IPHeader.h" "TCPHeader.h" (((byte) >> 4) & 0x0F) ((byte) & 0x0F) 65535 1 17 6

#define HI_WORD(byte) #define LO_WORD(byte) #define MAX_IP_SIZE #define ICMP_PROTO #define UDP_PROTO #define TCP_PROTO

extern char *szProto[]; typedef unsigned char typedef unsigned long typedef unsigned short BYTE; ip_t; port_t;

void PrintRawBytes ( BYTE *ptr, DWORD len); //int //int // // // int DecodeIGMPHeader(WSABUF *wsabuf, DWORD iphdrlen); DecodeUDPHeader (WSABUF *wsabuf, DWORD iphdrlen);

Dump TCP header to the consol DecodeTCPHeader ( WSABUF *wsabuf, DWORD iphdrlenz);

// // // int

Dump IP header to the consol

DecodeIPHeader ( WSABUF *wasbuf);

// // Caluculates a given buffer checksum // USHORT checksum( USHORT *buffer, int size); // // Adjust checksum for a given buffer // void checksumAdjust( unsigned char *chksum, unsigned char *optr, int olen, unsigned char *nptr, int nlen);

Page 32 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// // Extract source IP from IP header // inline ip_t getSourceIPFromIPHeader( BYTE* packet) { return reinterpret_cast<PIP_HDR>(packet)->ip_srcaddr; }

// // Extract destination IP from IP header // inline ip_t getDestinationIPFromIPHeader( BYTE* packet) { return reinterpret_cast<PIP_HDR>(packet)->ip_destaddr; } // // Extract source port from TCP header // inline port_t getSourcePortFromTCPHeader( BYTE* packet) { PIP_HDR pIPHeader = reinterpret_cast<PIP_HDR>(packet); return reinterpret_cast<PTCP_HDR>(packet + LO_WORD(pIPHeader->ip_verlen) * 4)>tcp_SourcePort; } // // Extract destination port from TCP header // inline port_t getDestinationPortFromTCPHeader( BYTE* packet) { PIP_HDR pIPHeader = reinterpret_cast<PIP_HDR>(packet); return reinterpret_cast<PTCP_HDR>(packet + LO_WORD(pIPHeader->ip_verlen) * 4)>tcp_DestPort; } #endif //__TCPIPUTILS_H__

Page 33 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// UDPHeader.h // // UDP Header class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __UDPHEADER_H__ #define __UDPHEADER_H__ // // Define the UDP header // typedef struct udp_hdr { unsigned short udp_SourcePort; unsigned short udp_DestPort; unsigned short udp_length; unsigned short udp_Checksum; } UDP_HDR, *PUDP_HDR; #endif //__UDPHEADER_H__

// Source port number // Destination port number // UDP packet length // UDP checksum (optional)

Page 34 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// UDPHeaderManipulator.h // // UDPHeaderManipulator class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __UDPHEADERMANIPULATOR_H__ #define __UDPHEADERMANIPULATOR_H__ #include "TCPIPUtils.h" #include "Manipulator.h" class UDPHeaderManipulator : public BaseManipulator { public: // // change source IP & PORT of a given packet // virtual void manipulateOutgoingPacket( BYTE* packet, ip_t newSourceIP, port_t newSourcePort); // // change destination IP & PORT of a given packet // virtual void manipulateIncommingPacket( BYTE* packet, ip_t newDestIP, port_t newDestPort); private: // // Adjust checksum after the change // static void reCalculateUDPIPChecksums( BYTE* packet, ip_t originalSourceIP, port_t originalSourcePort, ip_t originalDestIP, port_t originalDestPort );

}; // class UDPHeaderManipulator

Page 35 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// NetInterface.h // // NetInterfaces class - Network Addresses Translation (NAT) Project. // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 #ifndef __NETINTERFACE_H__ #define __NETINTERFACE_H__ #include <winsock2.h> // // Warper class to incapsulate network Interface utility function // class NetInterfaces { public: NetInterfaces(){initializeInterfaceList();} ~NetInterfaces(){destroyInterfaceList();} SOCKADDR_IN operator [](int idxInterface){return getInterface(idxInterface);} // // Get the interfaces list // static const SOCKET_ADDRESS_LIST*

getInterfaceList(){ return interfaceList;}

private: // // Get a interface which index is idxInterface // static SOCKADDR_IN getInterface(int idxInterface) ; static SOCKET_ADDRESS_LIST* interfaceList; static bool interfaceListinitialized; static void initializeInterfaceList(); static void destroyInterfaceList(); }; #endif //__NETINTERFACE_H__

// = false

Page 36 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// // // // // // // //

Sniffer class - Network Addresses Translation (NAT) Project. Writen By: Created: Caliv Nir Apr - 2002 -

Last Modified : 12-Jun-2002

#ifndef __SNIFFER_H__ #define __SNIFFER_H__ #include <windows.h> class Sniffer { public: Sniffer(int idxInterface); static void static HANDLE void listen(); private: static HANDLE int }; #define FRAME_OFFSET 14 #define SRC_IP_OFFSET 12 #endif //__SNIFFER_H__ // translator.cpp // // translator class definition - Network Addresses Translation (NAT) Project. // Do the port:ip <-> key (port) translation // // Writen By: Caliv Nir // // Created: Apr - 2002 // // Last Modified : 12-Jun-2002 // #ifndef __TRANSLATOR_H__ #define __TRANSLATOR_H__ #include <map> typedef unsigned long typedef unsigned short ip_t; port_t; set_hIoCompletionPort(HANDLE hIoCompletionPort); get_hIoCompletionPort();

hIoCompletionPort; m_idxInterface;

class Translator { public: static const port_t INVALID_KEY = 0; static const std::pair<ip_t,port_t> BAD_ADDRESS; Translator(); port_t getKey (const std::pair<ip_t,port_t>& std::pair<ip_t,port_t> getAddress(port_t key); private: port_t allocateNewKey (const std::pair<ip_t,port_t>& void removeAddress (const std::pair<ip_t,port_t>& // // address); address); address);

Translation address table:

Page 37 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

// IP:Port -> Key // typedef std::map<std::pair<ip_t,port_t>,port_t> tTable_t; tTable_t translationTable_; // // Reverse translation address table: // Key -> IP:Port // typedef std::map< port_t,std::pair<ip_t,port_t> > rtTable_t; rtTable_t revTranslationTable_; port_t keyCounter_; }; #endif //__TRANSLATOR_H__#ifndef __TRANSMITTER_H__ #define __TRANSMITTER_H__ #include <winsock2.h> class Transmitter { public: Transmitter(int idxInterface); ~Transmitter(); void send(char *buf, int iTotalSize); private: SOCKET rawSocket_; }; #endif //__TRANSMITTER_H__

Page 38 of 38 PDF created with FinePrint pdfFactory Pro trial version http://www.fineprint.com

Potrebbero piacerti anche