Сценарий nat что такое

NAT в роутере. Что такое трансляция сетевых адресов, примеры использования, типы, как включить и настроить на маршрутизаторе

Всем привет! Сегодня мы поговорим про то, что же такое NAT в роутере. Как вы, наверное, все знаете, большинство адресов в интернете использует IPv4 версию. Эти адреса имеют диапазон от 0.0.0.0 до 255.255.255.255. Если подсчитать, то у нас есть больше 4-х миллиардов айпишников. Вроде бы достаточно много, но на деле с ростом клиентов интернета свободных адресов почти уже не осталось. Приплюсуем сюда тот факт, что многие IP зарезервированы, а на планете активно развивается мобильный интернет, который забирает львиную долю IPv4.

Но как получается всем подключаться к интернету и не оставаться в стороне? – Для этих целей и используется NAT (Network Address Translation – трансляция сетевых адресов). А теперь о самой сетевой технологии более подробно в статье.

Содержание

  1. Что такое NAT и как работает и зачем он нужен
  2. Термины NAT
  3. Типы NAT
  4. Статический (Static) NAT
  5. Динамический (Dynamic) NAT
  6. PAT (Port Address Translation)
  7. Плюсы и минусы IP NAT
  8. Видео
  9. Как настроить и включить NAT на роутере
  10. Задать вопрос автору статьи

Если у вас есть дома роутер, то вы уже используете технологию NAT. Чтобы вам было понятнее для чего она нужна, давайте рассмотрим простой пример. Представим, что вам нужно в квартиру провести интернет. Вы звоните провайдеру, он приходит и прокидывает вам кабель. Помимо всего, чтобы работать в глобальной сети вам нужен внешний айпишник, его также предоставляет только провайдер.

Конечно вы можете воткнуть кабель в ноутбук или компьютер, тогда никакого NAT (в вашей квартире) не будет, так как ваш комп будет напрямую подключен к интернету сети. Но если помимо вас, интернетом хотят пользоваться и другие жильцы квартиры, то вам нужно установить Wi-Fi роутер. Не будете же вы каждому жителю проводить интернет-кабель и отдельно платить за каждого.

Кабель подключается к выделенному WAN порту. Далее к роутеру уже можно подключить телефоны, планшеты, ноутбуки, компьютеры, телевизоры и многое другое. Маршрутизатор выступает неким шлюзом между вашей домашней и глобальной интернет сетью.

Роутер каждому устройству дома выдает свой локальный IP. Например:

  • 192.168.1.10 – Компьютер папы.
  • 192.168.1.11 – Телефон сына.
  • 192.168.1.12 – Планшет жены.
  • 192.168.1.13 – ноутбук дочери.

Шлюз, он же роутер, имеет сразу два адреса:

  • Внутренний – 192.168.1.1
  • Внешний – его выдает провайдер и он может иметь любой вид. Например, 175.67.87.223.

Все жители квартиры сразу могут иметь доступ к интернету с одного внешнего адреса за счет роутера. Как я уже и говорил, таких внешних айпишников в интернете очень мало – всего 4 294 967 296.

NAT – это технология, которая позволяет переводить вот такие вот локальные адреса во внешние и получать ответ из интернета. В итоге каждый житель квартиры, находясь внутри локальной сети, и используя за счет роутера внешний IP – может выходить в интернет.

Если говорить грубо, то NAT – это как дверь в квартире, каждый может её использовать, чтобы выйти в открытый мир. В итоге пользователей в интернете становится куда больше чем 4 миллиарда, но количество самих адресов остается всегда одним и тем же.

NAT позволяет скрывать внутренние айпишники от интернета, и их никто не сможет увидеть. Это мы рассмотрели случай, когда подключена небольшая семья. А представим, что нужно подключить офис из сотни или даже тысячи человек. Для организации просто не целесообразно подключать каждому пользователю свой интернет с внешним IP. Да и это не нужно. Достаточно использовать маршрутизатор, в котором уже по умолчанию будет работать NAT.

Схема достаточно простая, давайте рассмотрим пример.

  1. Компьютер из домашней сети с ИП 192.168.1.10 отправил запрос на какой-то сайт.
  2. Запрос пришел на роутер (192.168.1.1).
  3. Роутер не может использовать свой локальный адрес, поэтому переводит запрос и использует внешний адрес.
  4. Сайт получает запрос с внешним IP и на него отсылает ответ.
  5. Роутер принимает ответ от сайта, и уже отправляет его на компьютер, но уже используя внутренний айпишник.

Как видите, NAT постоянно переводит внутренний адрес во внешний и обратно. Если локальная сеть имеет только один выходной маршрутизатор, который может быть связан с внешней сетью, то такую сеть называют Stub сетью.

Что такое NAT в роутере: определение, примеры, как включить и настроить

Термины NAT

В сфере NAT есть различная терминология, которую вы можете встретить в настройках маршрутизатора или на схемах подключения.

Есть 4 вида NAT адресов:

  • Insidelocal – внутренний локальный адрес, который прописывается в первичном запросе от клиента.
  • Insideglobal – внешний айпишник роутера.
  • Outsidelocal – внутренний глобальный адрес сервера в интернете. Внутренний он, потому что он прописывается в первичном запросе от компьютера во внутренней сети.
  • Outsideglobal – внешний глобальный. IP запроса на конечный сервер, который записан во внешнем запросе от роутера.

Пока ничего не понятно? Сейчас постараюсь рассказать на примере. Давайте рассмотрим пример NAT адресации. Смотрим на картинку ниже.

Что такое NAT в роутере: определение, примеры, как включить и настроить

  1. У нас есть компьютер с (Inside Local) адресом 192.168.0.30, который находится с домашней сети.
  2. Он посылает запрос на сервер с (Outside Local) адресом 246.10.79.235.
  3. Маршрутизатор принимает ответ и переводит запрос:

(Inside Local) 192.168.0.30 -> (Outside Local) 246.10.79.235

В

(Inside Global) 135.87.99.202 -> (Outside Global) 246.10.79.235

  1. Когда сервер получает запрос, он отсылает ответ и все запросы переделываются в обратном порядке. Чтобы роутеру было понятно от кого пришел ответ и кому отправить запрос, он все данные записывает в свою таблицу маршрутизации.

Типы NAT

Статический (Static) NAT

Статический NAT – это когда у каждого локального внутреннего адреса, есть свой глобальный адрес. Часто используется для Web-серверов. Весь трафик при этом проходит аналогично через один узел, и у каждого устройства есть свой как локальный, так и глобальный IP.

Что такое NAT в роутере: определение, примеры, как включить и настроить

Динамический (Dynamic) NAT

У нас есть пул внутренних айпишников, который постоянно присваивается разные глобальные внешние адреса. Внешние IP присваиваются по принципу, какой есть свободный, тот и назначается маршрутизатором. Очень часто используется в городских сетях провайдерами, именно поэтому ваши глобальные IP постоянно меняются. Чтобы немного расширить эту тему, советую более подробно почитать про белые и серые IP.

Что такое NAT в роутере: определение, примеры, как включить и настроить

PAT (Port Address Translation)

Самая популярная форма NAT. Про неё я в самом начале и говорил. Когда нескольким локальным адресам назначается один глобальный. То есть когда вся семья, грубо говоря, использует один внешний IP. Чтобы маршрутизатор понял, кому именно посылать ответ от сервера, на который ранее был запрос, он использует в своем запросе номер порта. И по нему отсылает ответ нужному локальному пользователю.

Что такое NAT в роутере: определение, примеры, как включить и настроить

Посмотрите на картинку выше. Как видите при запросе на выделенный сервер, помимо того, что роутер переводит адреса, он еще в запросе добавляет номер порта. То есть ответ от сервера также имеет этот порт, который потом уже используется для того, чтобы ответ получил нужный компьютер.

Плюсы и минусы IP NAT

  • Офисы, а также домашние сети при большом количестве клиентов могут использовать всего один или несколько внешних интернет-адресов.
  • Повышается надежность локальной сети, где контроль за пропускной способностью и трафиком отслеживает роутер.
  • Снижает стоимость, которая нужна для приобретения внешних IP.
  • Контроль внешнего и внутреннего доступа к обоим сетям.
  • Увеличивается задержка запроса, так как маршрутизатору нужно постоянно делать NAT перевод адресов.
  • В больших сетях, где идет многоуровневая NAT адресация, сложно найти место поломки, так как IP постоянно изменяется.

Видео

Если вам что-то было не понятно, или вам лень читать, то советую посмотреть это полезное видео.

Как настроить и включить NAT на роутере

Стандартный NAT уже работает в режиме PAT и его настраивать не нужно. То есть вы просто настраиваете интернет и Wi-Fi на маршрутизаторе. Другой вопрос, если дома вы решили организовать Web, игровой или почтовый сервер. А быть может вы хотите подключить камеры видеонаблюдения и следить за домом или квартирой, отдыхая на Бали. Вот тут нам понадобится проброс портов – об смотрите статью про порты. Там коротко рассказано, что такое порты, для чего они нужны и как их пробросить.

Network address translation between a private network and the Internet

Network address translation (NAT) is a method of mapping an IP address space into another by modifying network address information in the IP header of packets while they are in transit across a traffic routing device.[1] The technique was originally used to bypass the need to assign a new address to every host when a network was moved, or when the upstream Internet service provider was replaced, but could not route the network’s address space. It has become a popular and essential tool in conserving global address space in the face of IPv4 address exhaustion. One Internet-routable IP address of a NAT gateway can be used for an entire private network.[2]

As network address translation modifies the IP address information in packets, NAT implementations may vary in their specific behavior in various addressing cases and their effect on network traffic. The specifics of NAT behavior are not commonly documented by vendors of equipment containing NAT implementations.[2]

Basic NAT[edit]

The simplest type of NAT provides a one-to-one translation of IP addresses. RFC 2663 refers to this type of NAT as basic NAT; it is also called a one-to-one NAT. In this type of NAT, only the IP addresses, IP header checksum, and any higher-level checksums that include the IP address are changed. Basic NAT can be used to interconnect two IP networks that have incompatible addressing.[2]

One-to-many NAT[edit]

The majority of network address translators map multiple private hosts to one publicly exposed IP address.

Here is a typical configuration:

  1. A local network uses one of the designated private IP address subnets (RFC 1918[3]).
  2. The network has a router having both a private and a public address. The private address is used by the router for communicating with other devices in the private local network. The public address (typically assigned by an Internet service provider) is used by the router for communicating with the rest of the Internet.
  3. As traffic passes from the network to the Internet, the router translates the source address in each packet from a private address to the router’s own public address. The router tracks basic data about each active connection (particularly the destination address and port). When the router receives inbound traffic from the Internet, it uses the connection tracking data it stored during the outbound phase to determine to which private address (if any) it should forward the reply.[2]

All IP packets have a source IP address and a destination IP address. Typically packets passing from the private network to the public network will have their source address modified, while packets passing from the public network back to the private network will have their destination address modified. To avoid ambiguity in how replies are translated, further modifications to the packets are required. The vast bulk of Internet traffic uses Transmission Control Protocol (TCP) or User Datagram Protocol (UDP). For these protocols, the port numbers are changed so that the combination of IP address (within the IP header) and port number (within the Transport Layer header) on the returned packet can be unambiguously mapped to the corresponding private network destination. RFC 2663 uses the term network address and port translation (NAPT) for this type of NAT.[3] Other names include port address translation (PAT), IP masquerading, NAT overload and many-to-one NAT. This is the most common type of NAT and has become synonymous with the term «NAT» in common usage.

This method allows communication through the router only when the conversation originates in the private network, since the initial originating transmission is what establishes the required information in the translation tables. Thus a web browser within the private network would be able to browse websites that are outside the network, whereas web browsers outside the network would be unable to browse a website hosted within.[a] Protocols not based on TCP and UDP require other translation techniques.

An additional benefit of one-to-many NAT is that it mitigates IPv4 address exhaustion by allowing entire networks to be connected to the Internet using a single public IP address.[b]

Methods of translation[edit]

Network address and port translation may be implemented in several ways. Some applications that use IP address information may need to determine the external address of a network address translator. This is the address that its communication peers in the external network detect. Furthermore, it may be necessary to examine and categorize the type of mapping in use, for example when it is desired to set up a direct communication path between two clients both of which are behind separate NAT gateways.

For this purpose, RFC 3489 specified a protocol called Simple Traversal of UDP over NATs (STUN) in 2003. It classified NAT implementations as full-cone NAT, (address) restricted-cone NAT, port-restricted cone NAT or symmetric NAT, and proposed a methodology for testing a device accordingly. However, these procedures have since been deprecated from standards status, as the methods are inadequate to correctly assess many devices. RFC 5389 standardized new methods in 2008 and the acronym STUN now represents the new title of the specification: Session Traversal Utilities for NAT.

NAT implementation classifications

Full-cone NAT, also known as one-to-one NAT

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • Any external host can send packets to iAddr:iPort by sending packets to eAddr:ePort.

Full Cone NAT.svg

(Address)-restricted-cone NAT

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • An external host (hAddr:any) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:any. «Any» means the port number doesn’t matter.

Restricted Cone NAT.svg

Port-restricted cone NAT Like an address restricted cone NAT, but the restriction includes port numbers.

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • An external host (hAddr:hPort) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:hPort.

Port Restricted Cone NAT.svg

Symmetric NAT

  • The combination of one internal IP address plus a destination IP address and port is mapped to a single unique external source IP address and port; if the same internal host sends a packet even with the same source address and port but to a different destination, a different mapping is used.
  • Only an external host that receives a packet from an internal host can send a packet back.

Symmetric NAT.svg

Many NAT implementations combine these types, so it is better to refer to specific individual NAT behavior instead of using the Cone/Symmetric terminology. RFC 4787 attempts to alleviate confusion by introducing standardized terminology for observed behaviors. For the first bullet in each row of the above table, the RFC would characterize Full-Cone, Restricted-Cone, and Port-Restricted Cone NATs as having an Endpoint-Independent Mapping, whereas it would characterize a Symmetric NAT as having an Address- and Port-Dependent Mapping. For the second bullet in each row of the above table, RFC 4787 would also label Full-Cone NAT as having an Endpoint-Independent Filtering, Restricted-Cone NAT as having an Address-Dependent Filtering, Port-Restricted Cone NAT as having an Address and Port-Dependent Filtering, and Symmetric NAT as having either an Address-Dependent Filtering or Address and Port-Dependent Filtering. Other classifications of NAT behavior mentioned in the RFC include whether they preserve ports, when and how mappings are refreshed, whether external mappings can be used by internal hosts (i.e., its hairpinning behavior), and the level of determinism NATs exhibit when applying all these rules.[2] Specifically, most NATs combine symmetric NAT for outgoing connections with static port mapping, where incoming packets addressed to the external address and port are redirected to a specific internal address and port.

Type of NAT and NAT traversal, role of port preservation for TCP[edit]

The NAT traversal problem arises when peers behind different NATs try to communicate. One way to solve this problem is to use port forwarding. Another way is to use various NAT traversal techniques. The most popular technique for TCP NAT traversal is TCP hole punching.

TCP hole punching requires the NAT to follow the port preservation design for TCP. For a given outgoing TCP communication, the same port numbers are used on both sides of the NAT. NAT port preservation for outgoing TCP connections is crucial for TCP NAT traversal because, under TCP, one port can only be used for one communication at a time, so programs bind distinct TCP sockets to ephemeral ports for each TCP communication, rendering NAT port prediction impossible for TCP.[2]

On the other hand, for UDP, NATs do not need port preservation. Indeed, multiple UDP communications (each with a distinct endpoint) can occur on the same source port, and applications usually reuse the same UDP socket to send packets to distinct hosts. This makes port prediction straightforward, as it is the same source port for each packet.

Furthermore, port preservation in NAT for TCP allows P2P protocols to offer less complexity and less latency because there is no need to use a third party (like STUN) to discover the NAT port since the application itself already knows the NAT port.[2][4]

However, if two internal hosts attempt to communicate with the same external host using the same port number, the NAT may attempt to use a different external IP address for the second connection or may need to forgo port preservation and remap the port.[2]: 9 

As of 2006, roughly 70% of the clients in P2P networks employed some form of NAT.[5]

Implementation[edit]

Establishing two-way communication[edit]

In bidirectional NAT the session can be established both from inside and outside realms.

Every TCP and UDP packet contains a source port number and a destination port number. Each of those packets is encapsulated in an IP packet, whose IP header contains a source IP address and a destination IP address. The IP address/protocol/port number triple defines an association with a network socket.

For publicly accessible services such as web and mail servers the port number is important. For example, port 80 connects through a socket to the web server software and port 25 to a mail server’s SMTP daemon. The IP address of a public server is also important, similar in global uniqueness to a postal address or telephone number. Both IP address and port number must be correctly known by all hosts wishing to successfully communicate.

Private IP addresses as described in RFC 1918 are usable only on private networks not directly connected to the internet. Ports are endpoints of communication unique to that host, so a connection through the NAT device is maintained by the combined mapping of port and IP address. A private address on the inside of the NAT is mapped to an external public address. Port address translation (PAT) resolves conflicts that arise when multiple hosts happen to use the same source port number to establish different external connections at the same time.

Telephone number extension analogy[edit]

A NAT device is similar to a phone system at an office that has one public telephone number and multiple extensions. Outbound phone calls made from the office all appear to come from the same telephone number. However, an incoming call that does not specify an extension cannot be automatically transferred to an individual inside the office. In this scenario, the office is a private LAN, the main phone number is the public IP address, and the individual extensions are unique port numbers.[6]

Translation process[edit]

With NAT, all communications sent to external hosts actually contain the external IP address and port information of the NAT device instead of internal host IP addresses or port numbers. NAT only translates IP addresses and ports of its internal hosts, hiding the true endpoint of an internal host on a private network.

When a computer on the private (internal) network sends an IP packet to the external network, the NAT device replaces the internal source IP address in the packet header with the external IP address of the NAT device. PAT may then assign the connection a port number from a pool of available ports, inserting this port number in the source port field. The packet is then forwarded to the external network. The NAT device then makes an entry in a translation table containing the internal IP address, original source port, and the translated source port. Subsequent packets from the same internal source IP address and port number are translated to the same external source IP address and port number. The computer receiving a packet that has undergone NAT establishes a connection to the port and IP address specified in the altered packet, oblivious to the fact that the supplied address is being translated.

Upon receiving a packet from the external network, the NAT device searches the translation table based on the destination port in the packet header. If a match is found, the destination IP address and port number is replaced with the values found in the table and the packet is forwarded to the inside network. Otherwise, if the destination port number of the incoming packet is not found in the translation table, the packet is dropped or rejected because the PAT device doesn’t know where to send it.

Visibility of operation[edit]

NAT operation is typically transparent to both the internal and external hosts. The NAT device may function as the default gateway for the internal host which is typically aware of the true IP address and TCP or UDP port of the external host. However, the external host is only aware of the public IP address for the NAT device and the particular port being used to communicate on behalf of a specific internal host.

Applications[edit]

Routing
Network address translation can be used to mitigate IP address overlap.[7][8] Address overlap occurs when hosts in different networks with the same IP address space try to reach the same destination host. This is most often a misconfiguration and may result from the merger of two networks or subnets, especially when using RFC 1918 private network addressing. The destination host experiences traffic apparently arriving from the same network, and intermediate routers have no way to determine where reply traffic should be sent to. The solution is either renumbering to eliminate overlap or network address translation.
Load balancing
In client–server applications, load balancers forward client requests to a set of server computers to manage the workload of each server. Network address translation may be used to map a representative IP address of the server cluster to specific hosts that service the request.[9][10][11][12]

[edit]

IEEE Reverse Address and Port Translation (RAPT or RAT) allows a host whose real IP address changes from time to time to remain reachable as a server via a fixed home IP address.[13] Cisco’s RAPT implementation is PAT or NAT overloading and maps multiple private IP addresses to a single public IP address. Multiple addresses can be mapped to a single address because each private address is tracked by a port number. PAT uses unique source port numbers on the inside global IP address to distinguish between translations.[c] PAT attempts to preserve the original source port. If this source port is already used, PAT assigns the first available port number starting from the beginning of the appropriate port group 0–511, 512–1023, or 1024–65535. When there are no more ports available and there is more than one external IP address configured, PAT moves to the next IP address to try to allocate the original source port again. This process continues until it runs out of available ports and external IP addresses.

Mapping of Address and Port is a Cisco proposal that combines Address plus Port translation with tunneling of the IPv4 packets over an ISP provider’s internal IPv6 network. In effect, it is an (almost) stateless alternative to carrier-grade NAT and DS-Lite that pushes the IPv4 address/port translation function (and the maintenance of NAT state) entirely into the existing customer premises equipment NAT implementation. Thus avoiding the NAT444 and statefulness problems of carrier-grade NAT, and also provides a transition mechanism for the deployment of native IPv6 at the same time with very little added complexity.

Issues and limitations[edit]

Hosts behind NAT-enabled routers do not have end-to-end connectivity and cannot participate in some internet protocols. Services that require the initiation of TCP connections from the outside network, or that use stateless protocols such as those using UDP, can be disrupted. Unless the NAT router makes a specific effort to support such protocols, incoming packets cannot reach their destination. Some protocols can accommodate one instance of NAT between participating hosts («passive mode» FTP, for example), sometimes with the assistance of an application-level gateway (see § Applications affected by NAT), but fail when both systems are separated from the internet by NAT. The use of NAT also complicates tunneling protocols such as IPsec because NAT modifies values in the headers which interfere with the integrity checks done by IPsec and other tunneling protocols.

End-to-end connectivity has been a core principle of the Internet, supported, for example, by the Internet Architecture Board. Current Internet architectural documents observe that NAT is a violation of the end-to-end principle, but that NAT does have a valid role in careful design.[14] There is considerably more concern with the use of IPv6 NAT, and many IPv6 architects believe IPv6 was intended to remove the need for NAT.[15]

An implementation that only tracks ports can be quickly depleted by internal applications that use multiple simultaneous connections such as an HTTP request for a web page with many embedded objects. This problem can be mitigated by tracking the destination IP address in addition to the port thus sharing a single local port with many remote hosts. This additional tracking increases implementation complexity and computing resources at the translation device.

Because the internal addresses are all disguised behind one publicly accessible address, it is impossible for external hosts to directly initiate a connection to a particular internal host. Applications such as VOIP, videoconferencing, and other peer-to-peer applications must use NAT traversal techniques to function.

Fragmentation and checksums[edit]

Pure NAT, operating on IP alone, may or may not correctly parse protocols with payloads containing information about IP, such as ICMP. This depends on whether the payload is interpreted by a host on the inside or outside of the translation. Basic protocols as TCP and UDP cannot function properly unless NAT takes action beyond the network layer.

IP packets have a checksum in each packet header, which provides error detection only for the header. IP datagrams may become fragmented and it is necessary for a NAT to reassemble these fragments to allow correct recalculation of higher-level checksums and correct tracking of which packets belong to which connection.

TCP and UDP, have a checksum that covers all the data they carry, as well as the TCP or UDP header, plus a pseudo-header that contains the source and destination IP addresses of the packet carrying the TCP or UDP header. For an originating NAT to pass TCP or UDP successfully, it must recompute the TCP or UDP header checksum based on the translated IP addresses, not the original ones, and put that checksum into the TCP or UDP header of the first packet of the fragmented set of packets.

Alternatively, the originating host may perform path MTU Discovery to determine the packet size that can be transmitted without fragmentation and then set the don’t fragment (DF) bit in the appropriate packet header field. This is only a one-way solution, because the responding host can send packets of any size, which may be fragmented before reaching the NAT.

DNAT[edit]

Destination network address translation (DNAT) is a technique for transparently changing the destination IP address of a routed packet and performing the inverse function for any replies. Any router situated between two endpoints can perform this transformation of the packet.

DNAT is commonly used to publish a service located in a private network on a publicly accessible IP address. This use of DNAT is also called port forwarding, or DMZ when used on an entire server, which becomes exposed to the WAN, becoming analogous to an undefended military demilitarized zone (DMZ).

SNAT[edit]

The meaning of the term SNAT varies by vendor:[16][17][18]

  • source NAT is a common expansion and is the counterpart of destination NAT (DNAT). This is used to describe one-to-many NAT; NAT for outgoing connections to public services.
  • stateful NAT is used by Cisco Systems[19]
  • static NAT is used by WatchGuard[20]
  • secure NAT is used by F5 Networks[21] and by Microsoft (in regard to the ISA Server)

Secure network address translation (SNAT) is part of Microsoft’s Internet Security and Acceleration Server and is an extension to the NAT driver built into Microsoft Windows Server. It provides connection tracking and filtering for the additional network connections needed for the FTP, ICMP, H.323, and PPTP protocols as well as the ability to configure a transparent HTTP proxy server.

Dynamic network address translation[edit]

Dynamic NAT, just like static NAT, is not common in smaller networks but is found within larger corporations with complex networks. Where static NAT provides a one-to-one internal to public static IP address mapping, dynamic NAT uses a group of public IP addresses.[22][23]

NAT hairpinning[edit]

NAT hairpinning, also known as NAT loopback or NAT reflection,[24] is a feature in many consumer routers[25] where a machine on the LAN is able to access another machine on the LAN via the external IP address of the LAN/router (with port forwarding set up on the router to direct requests to the appropriate machine on the LAN). This notion is officially described in 2008, RFC 5128.

The following describes an example network:

  • Public address: 203.0.113.1. This is the address of the WAN interface on the router.
  • Internal address of router: 192.168.1.1
  • Address of the server: 192.168.1.2
  • Address of a local computer: 192.168.1.100

If a packet is sent to 203.0.113.1 by a computer at 192.168.1.100, the packet would normally be routed to the default gateway (the router)[d] A router with the NAT loopback feature detects that 203.0.113.1 is the address of its WAN interface, and treats the packet as if coming from that interface. It determines the destination for that packet, based on DNAT (port forwarding) rules for the destination. If the data were sent to port 80 and a DNAT rule exists for port 80 directed to 192.168.1.2, then the host at that address receives the packet.

If no applicable DNAT rule is available, the router drops the packet. An ICMP Destination Unreachable reply may be sent. If any DNAT rules were present, address translation is still in effect; the router still rewrites the source IP address in the packet. The local computer (192.168.1.100) sends the packet as coming from 192.168.1.100, but the server (192.168.1.2) receives it as coming from 203.0.113.1. When the server replies, the process is identical to an external sender. Thus, two-way communication is possible between hosts inside the LAN network via the public IP address.

NAT in IPv6[edit]

Network address translation is not commonly used in IPv6 because one of the design goals of IPv6 is to restore end-to-end network connectivity.[26] The large addressing space of IPv6 obviates the need to conserve addresses and every device can be given a unique globally routable address. Use of unique local addresses in combination with network prefix translation can achieve results similar to NAT.

Applications affected by NAT[edit]

Some application layer protocols, such as File Transfer Protocol (FTP) and Session Initiation Protocol (SIP), send explicit network addresses within their application data. FTP in active mode, for example, uses separate connections for control traffic (commands) and for data traffic (file contents). When requesting a file transfer, the host making the request identifies the corresponding data connection by its network layer and transport layer addresses. If the host making the request lies behind a simple NAT firewall, the translation of the IP address or TCP port number makes the information received by the server invalid. SIP commonly controls voice over IP calls, and suffer the same problem. SIP and its accompanying Session Description Protocol may use multiple ports to set up a connection and transmit voice stream via Real-time Transport Protocol. IP addresses and port numbers are encoded in the payload data and must be known before the traversal of NATs. Without special techniques, such as STUN, NAT behavior is unpredictable and communications may fail. Application Layer Gateway (ALG) software or hardware may correct these problems. An ALG software module running on a NAT firewall device updates any payload data made invalid by address translation. ALGs need to understand the higher-layer protocol that they need to fix, and so each protocol with this problem requires a separate ALG. For example, on many Linux systems, there are kernel modules called connection trackers that serve to implement ALGs. However, ALG cannot work if the protocol data is encrypted.

Another possible solution to this problem is to use NAT traversal techniques using protocols such as STUN or Interactive Connectivity Establishment (ICE), or proprietary approaches in a session border controller. NAT traversal is possible in both TCP- and UDP-based applications, but the UDP-based technique is simpler, more widely understood, and more compatible with legacy NATs.[citation needed] In either case, the high-level protocol must be designed with NAT traversal in mind, and it does not work reliably across symmetric NATs or other poorly behaved legacy NATs.

Other possibilities are Internet Gateway Device Protocol, NAT Port Mapping Protocol (NAT-PMP), or Port Control Protocol (PCP),[27] but these require the NAT device to implement that protocol.

Most client–server protocols (FTP being the main exception[e]), however, do not send layer 3 contact information and do not require any special treatment by NATs. In fact, avoiding NAT complications is practically a requirement when designing new higher-layer protocols today.

NATs can also cause problems where IPsec encryption is applied and in cases where multiple devices such as SIP phones are located behind a NAT. Phones that encrypt their signaling with IPsec encapsulate the port information within an encrypted packet, meaning that NAT devices cannot access and translate the port. In these cases, the NAT devices revert to simple NAT operations. This means that all traffic returning to the NAT is mapped onto one client, causing service to more than one client behind the NAT to fail. There are a couple of solutions to this problem: one is to use TLS, which operates at layer 4 and does not mask the port number; another is to encapsulate the IPsec within UDP – the latter being the solution chosen by TISPAN to achieve secure NAT traversal, or a NAT with «IPsec Passthru» support; another is to use a session border controller to help traverse the NAT.

Interactive Connectivity Establishment is a NAT traversal technique that does not rely on ALG support.

The DNS protocol vulnerability announced by Dan Kaminsky on July 8, 2008,[28] is indirectly affected by NAT port mapping. To avoid DNS cache poisoning, it is highly desirable not to translate UDP source port numbers of outgoing DNS requests from a DNS server behind a firewall that implements NAT. The recommended workaround for the DNS vulnerability is to make all caching DNS servers use randomized UDP source ports. If the NAT function de-randomizes the UDP source ports, the DNS server becomes vulnerable.

Examples of NAT software[edit]

  • Internet Connection Sharing (ICS): NAT & DHCP implementation included with Windows desktop operating systems
  • IPFilter: included with (Open)Solaris, FreeBSD and NetBSD, available for many other Unix-like operating systems
  • ipfirewall (ipfw): FreeBSD-native packet filter
  • Netfilter with iptables/nftables: the Linux packet filter
  • NPF: NetBSD-native Packet Filter
  • PF: OpenBSD-native Packet Filter
  • Routing and Remote Access Service: routing implementation included with Windows Server operating systems
  • WinGate: third-party routing implementation for Windows

See also[edit]

  • Anything In Anything (AYIYA) – IPv6 over IPv4 UDP, thus working IPv6 tunneling over most NATs
  • Gateway (telecommunications) – Connection between two network systems
  • Internet Gateway Device Protocol (IGD) – UPnP NAT-traversal method
  • Middlebox – Intermediary box on the data path between a source host and destination host
  • Port triggering – NAT traversal mechanism
  • Hairpinning
  • Subnetwork – Logical subdivision of an IP network
  • Teredo tunneling – NAT traversal using IPv6
  • Carrier-grade NAT – NAT behind NAT within ISP.

Notes[edit]

  1. ^ Most NAT devices today allow the network administrator to configure static translation table entries for connections from the external network to the internal masqueraded network. This feature is often referred to as static NAT. It may be implemented in two types: port forwarding which forwards traffic from a specific external port to an internal host on a specified port, and designation of a DMZ host which passes all traffic received on the external interface (on any port number) to an internal IP address while preserving the destination port. Both types may be available in the same NAT device.
  2. ^ The more common arrangement is having computers that require end-to-end connectivity supplied with a routable IP address, while having others that do not provide services to outside users behind NAT with only a few IP addresses used to enable Internet access.
  3. ^ The port numbers are 16-bit integers. The total number of internal addresses that can be translated to one external address could theoretically be as high as 65,536 per IP address. Realistically, the number of ports that can be assigned a single IP address is around 4000.
  4. ^ Unless an explicit route is set in the computer’s routing tables.
  5. ^ This issue can be avoided by using SFTP instead of FTP

References[edit]

  1. ^ Network Protocols Handbook (2 ed.). Javvin Technologies Inc. 2005. p. 27. ISBN 9780974094526. Retrieved 2014-09-16.
  2. ^ a b c d e f g h François Audet; Cullen Jennings (January 2007). Network Address Translation (NAT) Behavioral Requirements for Unicast UDP. IETF. doi:10.17487/RFC4787. RFC 4787.
  3. ^ a b Wing, Dan (2010-07-01). «Network Address Translation: Extending the Internet Address Space». IEEE Internet Computing. 14 (4): 66–70. doi:10.1109/MIC.2010.96. ISSN 1089-7801. S2CID 31082389.
  4. ^ «Characterization and Measurement of TCP Traversal through NATs and Firewalls». December 2006.
  5. ^ «Illuminating the shadows: Opportunistic network and web measurement». December 2006. Archived from the original on 2010-07-24.
  6. ^ «The Audio over IP Instant Expert Guide» (PDF). Tieline. January 2010. Archived from the original (PDF) on 2011-10-08. Retrieved 2011-08-19.
  7. ^ «Using NAT in Overlapping Networks». August 2005.
  8. ^ «VPNs with Overlapping Subnets Problem Scenario». September 2017.
  9. ^ Srisuresh, Pyda; Gan, Der-Hwa (August 1998). «Load Sharing using IP Network Address Translation». doi:10.17487/RFC2391.
  10. ^ «What Is Layer 4 Load Balancing?». June 2020.
  11. ^ «What is load balancing?». November 2018.
  12. ^ «Configure Server Load Balancing Using Dynamic NAT». June 2018.
  13. ^ Singh, R.; Tay, Y.C.; Teo, W.T.; Yeow, S.W. (1999). «RAT: A quick (and dirty?) push for mobility support». Proceedings WMCSA’99. Second IEEE Workshop on Mobile Computing Systems and Applications. pp. 32–40. CiteSeerX 10.1.1.40.461. doi:10.1109/MCSA.1999.749275. ISBN 978-0-7695-0025-6. S2CID 7657883.
  14. ^ Bush, R.; Meyer, D. (2002). Some Internet Architectural Guidelines and Philosophy. IETF. doi:10.17487/RFC3439. RFC 3439.
  15. ^ Velde, G. Van de; Hain, T.; Droms, R.; Carpenter, B.; Klein, E. (2007). Local Network Protection for IPv6. IETF. doi:10.17487/RFC4864. RFC 4864.
  16. ^ «Enhanced IP Resiliency Using Cisco Stateful NAT». Cisco.
  17. ^ «Use NAT for Public Accessto Servers with Private IP Addresses on the Private Network (WatchGuard configuration example)» (PDF). www.watchguard.com.
  18. ^ «K7820: Overview of SNAT features». AskF5. August 28, 2007. Retrieved February 24, 2019.
  19. ^ «Enhanced IP Resiliency Using Cisco Stateful NAT». Cisco.
  20. ^ «Use NAT for Public Accessto Servers with Private IP Addresses on the Private Network (WatchGuard configuration example)» (PDF). www.watchguard.com.
  21. ^ «K7820: Overview of SNAT features». AskF5. August 28, 2007. Retrieved February 24, 2019.
  22. ^ «Dynamic NAT». 26 January 2016. Retrieved 2022-04-19.
  23. ^ «Dynamic NAT». Retrieved 2022-04-19.
  24. ^ «What is NAT Reflection/NAT Loopback/NAT Hairpinning?». NYC Networkers. 2014-11-09. Retrieved 2017-04-27.
  25. ^ «NAT Loopback Routers – OpenSim» (MediaWiki). OpenSimulator. 2013-10-21. Retrieved 2014-02-21.
  26. ^ Iljitsch van Beijnum (2008-07-23). «After staunch resistance, NAT may come to IPv6 after all». Ars Technica. Retrieved 2014-04-24.
  27. ^ D. Wing, Ed; Cheshire, S.; Boucadair, M.; Penno, R.; Selkirk, P. (2013). Port Control Protocol (PCP). IETF. doi:10.17487/RFC6887. RFC 6887.
  28. ^ Messmer, Ellen (2008-07-08). «Major DNS flaw could disrupt the Internet». Network World. Archived from the original on 2009-02-13. Retrieved 14 June 2021.

External links[edit]

  • NAT-Traversal Test and results
  • Characterization of different TCP NATs – Paper discussing the different types of NAT
  • Anatomy: A Look Inside Network Address Translators – Volume 7, Issue 3, September 2004
  • Jeff Tyson, HowStuffWorks: How Network Address Translation Works
  • Routing with NAT (Part of the documentation for the IBM iSeries)
  • Network Address Translation (NAT) FAQ – Cisco Systems

Network address translation between a private network and the Internet

Network address translation (NAT) is a method of mapping an IP address space into another by modifying network address information in the IP header of packets while they are in transit across a traffic routing device.[1] The technique was originally used to bypass the need to assign a new address to every host when a network was moved, or when the upstream Internet service provider was replaced, but could not route the network’s address space. It has become a popular and essential tool in conserving global address space in the face of IPv4 address exhaustion. One Internet-routable IP address of a NAT gateway can be used for an entire private network.[2]

As network address translation modifies the IP address information in packets, NAT implementations may vary in their specific behavior in various addressing cases and their effect on network traffic. The specifics of NAT behavior are not commonly documented by vendors of equipment containing NAT implementations.[2]

Basic NAT[edit]

The simplest type of NAT provides a one-to-one translation of IP addresses. RFC 2663 refers to this type of NAT as basic NAT; it is also called a one-to-one NAT. In this type of NAT, only the IP addresses, IP header checksum, and any higher-level checksums that include the IP address are changed. Basic NAT can be used to interconnect two IP networks that have incompatible addressing.[2]

One-to-many NAT[edit]

The majority of network address translators map multiple private hosts to one publicly exposed IP address.

Here is a typical configuration:

  1. A local network uses one of the designated private IP address subnets (RFC 1918[3]).
  2. The network has a router having both a private and a public address. The private address is used by the router for communicating with other devices in the private local network. The public address (typically assigned by an Internet service provider) is used by the router for communicating with the rest of the Internet.
  3. As traffic passes from the network to the Internet, the router translates the source address in each packet from a private address to the router’s own public address. The router tracks basic data about each active connection (particularly the destination address and port). When the router receives inbound traffic from the Internet, it uses the connection tracking data it stored during the outbound phase to determine to which private address (if any) it should forward the reply.[2]

All IP packets have a source IP address and a destination IP address. Typically packets passing from the private network to the public network will have their source address modified, while packets passing from the public network back to the private network will have their destination address modified. To avoid ambiguity in how replies are translated, further modifications to the packets are required. The vast bulk of Internet traffic uses Transmission Control Protocol (TCP) or User Datagram Protocol (UDP). For these protocols, the port numbers are changed so that the combination of IP address (within the IP header) and port number (within the Transport Layer header) on the returned packet can be unambiguously mapped to the corresponding private network destination. RFC 2663 uses the term network address and port translation (NAPT) for this type of NAT.[3] Other names include port address translation (PAT), IP masquerading, NAT overload and many-to-one NAT. This is the most common type of NAT and has become synonymous with the term «NAT» in common usage.

This method allows communication through the router only when the conversation originates in the private network, since the initial originating transmission is what establishes the required information in the translation tables. Thus a web browser within the private network would be able to browse websites that are outside the network, whereas web browsers outside the network would be unable to browse a website hosted within.[a] Protocols not based on TCP and UDP require other translation techniques.

An additional benefit of one-to-many NAT is that it mitigates IPv4 address exhaustion by allowing entire networks to be connected to the Internet using a single public IP address.[b]

Methods of translation[edit]

Network address and port translation may be implemented in several ways. Some applications that use IP address information may need to determine the external address of a network address translator. This is the address that its communication peers in the external network detect. Furthermore, it may be necessary to examine and categorize the type of mapping in use, for example when it is desired to set up a direct communication path between two clients both of which are behind separate NAT gateways.

For this purpose, RFC 3489 specified a protocol called Simple Traversal of UDP over NATs (STUN) in 2003. It classified NAT implementations as full-cone NAT, (address) restricted-cone NAT, port-restricted cone NAT or symmetric NAT, and proposed a methodology for testing a device accordingly. However, these procedures have since been deprecated from standards status, as the methods are inadequate to correctly assess many devices. RFC 5389 standardized new methods in 2008 and the acronym STUN now represents the new title of the specification: Session Traversal Utilities for NAT.

NAT implementation classifications

Full-cone NAT, also known as one-to-one NAT

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • Any external host can send packets to iAddr:iPort by sending packets to eAddr:ePort.

Full Cone NAT.svg

(Address)-restricted-cone NAT

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • An external host (hAddr:any) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:any. «Any» means the port number doesn’t matter.

Restricted Cone NAT.svg

Port-restricted cone NAT Like an address restricted cone NAT, but the restriction includes port numbers.

  • Once an internal address (iAddr:iPort) is mapped to an external address (eAddr:ePort), any packets from iAddr:iPort are sent through eAddr:ePort.
  • An external host (hAddr:hPort) can send packets to iAddr:iPort by sending packets to eAddr:ePort only if iAddr:iPort has previously sent a packet to hAddr:hPort.

Port Restricted Cone NAT.svg

Symmetric NAT

  • The combination of one internal IP address plus a destination IP address and port is mapped to a single unique external source IP address and port; if the same internal host sends a packet even with the same source address and port but to a different destination, a different mapping is used.
  • Only an external host that receives a packet from an internal host can send a packet back.

Symmetric NAT.svg

Many NAT implementations combine these types, so it is better to refer to specific individual NAT behavior instead of using the Cone/Symmetric terminology. RFC 4787 attempts to alleviate confusion by introducing standardized terminology for observed behaviors. For the first bullet in each row of the above table, the RFC would characterize Full-Cone, Restricted-Cone, and Port-Restricted Cone NATs as having an Endpoint-Independent Mapping, whereas it would characterize a Symmetric NAT as having an Address- and Port-Dependent Mapping. For the second bullet in each row of the above table, RFC 4787 would also label Full-Cone NAT as having an Endpoint-Independent Filtering, Restricted-Cone NAT as having an Address-Dependent Filtering, Port-Restricted Cone NAT as having an Address and Port-Dependent Filtering, and Symmetric NAT as having either an Address-Dependent Filtering or Address and Port-Dependent Filtering. Other classifications of NAT behavior mentioned in the RFC include whether they preserve ports, when and how mappings are refreshed, whether external mappings can be used by internal hosts (i.e., its hairpinning behavior), and the level of determinism NATs exhibit when applying all these rules.[2] Specifically, most NATs combine symmetric NAT for outgoing connections with static port mapping, where incoming packets addressed to the external address and port are redirected to a specific internal address and port.

Type of NAT and NAT traversal, role of port preservation for TCP[edit]

The NAT traversal problem arises when peers behind different NATs try to communicate. One way to solve this problem is to use port forwarding. Another way is to use various NAT traversal techniques. The most popular technique for TCP NAT traversal is TCP hole punching.

TCP hole punching requires the NAT to follow the port preservation design for TCP. For a given outgoing TCP communication, the same port numbers are used on both sides of the NAT. NAT port preservation for outgoing TCP connections is crucial for TCP NAT traversal because, under TCP, one port can only be used for one communication at a time, so programs bind distinct TCP sockets to ephemeral ports for each TCP communication, rendering NAT port prediction impossible for TCP.[2]

On the other hand, for UDP, NATs do not need port preservation. Indeed, multiple UDP communications (each with a distinct endpoint) can occur on the same source port, and applications usually reuse the same UDP socket to send packets to distinct hosts. This makes port prediction straightforward, as it is the same source port for each packet.

Furthermore, port preservation in NAT for TCP allows P2P protocols to offer less complexity and less latency because there is no need to use a third party (like STUN) to discover the NAT port since the application itself already knows the NAT port.[2][4]

However, if two internal hosts attempt to communicate with the same external host using the same port number, the NAT may attempt to use a different external IP address for the second connection or may need to forgo port preservation and remap the port.[2]: 9 

As of 2006, roughly 70% of the clients in P2P networks employed some form of NAT.[5]

Implementation[edit]

Establishing two-way communication[edit]

In bidirectional NAT the session can be established both from inside and outside realms.

Every TCP and UDP packet contains a source port number and a destination port number. Each of those packets is encapsulated in an IP packet, whose IP header contains a source IP address and a destination IP address. The IP address/protocol/port number triple defines an association with a network socket.

For publicly accessible services such as web and mail servers the port number is important. For example, port 80 connects through a socket to the web server software and port 25 to a mail server’s SMTP daemon. The IP address of a public server is also important, similar in global uniqueness to a postal address or telephone number. Both IP address and port number must be correctly known by all hosts wishing to successfully communicate.

Private IP addresses as described in RFC 1918 are usable only on private networks not directly connected to the internet. Ports are endpoints of communication unique to that host, so a connection through the NAT device is maintained by the combined mapping of port and IP address. A private address on the inside of the NAT is mapped to an external public address. Port address translation (PAT) resolves conflicts that arise when multiple hosts happen to use the same source port number to establish different external connections at the same time.

Telephone number extension analogy[edit]

A NAT device is similar to a phone system at an office that has one public telephone number and multiple extensions. Outbound phone calls made from the office all appear to come from the same telephone number. However, an incoming call that does not specify an extension cannot be automatically transferred to an individual inside the office. In this scenario, the office is a private LAN, the main phone number is the public IP address, and the individual extensions are unique port numbers.[6]

Translation process[edit]

With NAT, all communications sent to external hosts actually contain the external IP address and port information of the NAT device instead of internal host IP addresses or port numbers. NAT only translates IP addresses and ports of its internal hosts, hiding the true endpoint of an internal host on a private network.

When a computer on the private (internal) network sends an IP packet to the external network, the NAT device replaces the internal source IP address in the packet header with the external IP address of the NAT device. PAT may then assign the connection a port number from a pool of available ports, inserting this port number in the source port field. The packet is then forwarded to the external network. The NAT device then makes an entry in a translation table containing the internal IP address, original source port, and the translated source port. Subsequent packets from the same internal source IP address and port number are translated to the same external source IP address and port number. The computer receiving a packet that has undergone NAT establishes a connection to the port and IP address specified in the altered packet, oblivious to the fact that the supplied address is being translated.

Upon receiving a packet from the external network, the NAT device searches the translation table based on the destination port in the packet header. If a match is found, the destination IP address and port number is replaced with the values found in the table and the packet is forwarded to the inside network. Otherwise, if the destination port number of the incoming packet is not found in the translation table, the packet is dropped or rejected because the PAT device doesn’t know where to send it.

Visibility of operation[edit]

NAT operation is typically transparent to both the internal and external hosts. The NAT device may function as the default gateway for the internal host which is typically aware of the true IP address and TCP or UDP port of the external host. However, the external host is only aware of the public IP address for the NAT device and the particular port being used to communicate on behalf of a specific internal host.

Applications[edit]

Routing
Network address translation can be used to mitigate IP address overlap.[7][8] Address overlap occurs when hosts in different networks with the same IP address space try to reach the same destination host. This is most often a misconfiguration and may result from the merger of two networks or subnets, especially when using RFC 1918 private network addressing. The destination host experiences traffic apparently arriving from the same network, and intermediate routers have no way to determine where reply traffic should be sent to. The solution is either renumbering to eliminate overlap or network address translation.
Load balancing
In client–server applications, load balancers forward client requests to a set of server computers to manage the workload of each server. Network address translation may be used to map a representative IP address of the server cluster to specific hosts that service the request.[9][10][11][12]

[edit]

IEEE Reverse Address and Port Translation (RAPT or RAT) allows a host whose real IP address changes from time to time to remain reachable as a server via a fixed home IP address.[13] Cisco’s RAPT implementation is PAT or NAT overloading and maps multiple private IP addresses to a single public IP address. Multiple addresses can be mapped to a single address because each private address is tracked by a port number. PAT uses unique source port numbers on the inside global IP address to distinguish between translations.[c] PAT attempts to preserve the original source port. If this source port is already used, PAT assigns the first available port number starting from the beginning of the appropriate port group 0–511, 512–1023, or 1024–65535. When there are no more ports available and there is more than one external IP address configured, PAT moves to the next IP address to try to allocate the original source port again. This process continues until it runs out of available ports and external IP addresses.

Mapping of Address and Port is a Cisco proposal that combines Address plus Port translation with tunneling of the IPv4 packets over an ISP provider’s internal IPv6 network. In effect, it is an (almost) stateless alternative to carrier-grade NAT and DS-Lite that pushes the IPv4 address/port translation function (and the maintenance of NAT state) entirely into the existing customer premises equipment NAT implementation. Thus avoiding the NAT444 and statefulness problems of carrier-grade NAT, and also provides a transition mechanism for the deployment of native IPv6 at the same time with very little added complexity.

Issues and limitations[edit]

Hosts behind NAT-enabled routers do not have end-to-end connectivity and cannot participate in some internet protocols. Services that require the initiation of TCP connections from the outside network, or that use stateless protocols such as those using UDP, can be disrupted. Unless the NAT router makes a specific effort to support such protocols, incoming packets cannot reach their destination. Some protocols can accommodate one instance of NAT between participating hosts («passive mode» FTP, for example), sometimes with the assistance of an application-level gateway (see § Applications affected by NAT), but fail when both systems are separated from the internet by NAT. The use of NAT also complicates tunneling protocols such as IPsec because NAT modifies values in the headers which interfere with the integrity checks done by IPsec and other tunneling protocols.

End-to-end connectivity has been a core principle of the Internet, supported, for example, by the Internet Architecture Board. Current Internet architectural documents observe that NAT is a violation of the end-to-end principle, but that NAT does have a valid role in careful design.[14] There is considerably more concern with the use of IPv6 NAT, and many IPv6 architects believe IPv6 was intended to remove the need for NAT.[15]

An implementation that only tracks ports can be quickly depleted by internal applications that use multiple simultaneous connections such as an HTTP request for a web page with many embedded objects. This problem can be mitigated by tracking the destination IP address in addition to the port thus sharing a single local port with many remote hosts. This additional tracking increases implementation complexity and computing resources at the translation device.

Because the internal addresses are all disguised behind one publicly accessible address, it is impossible for external hosts to directly initiate a connection to a particular internal host. Applications such as VOIP, videoconferencing, and other peer-to-peer applications must use NAT traversal techniques to function.

Fragmentation and checksums[edit]

Pure NAT, operating on IP alone, may or may not correctly parse protocols with payloads containing information about IP, such as ICMP. This depends on whether the payload is interpreted by a host on the inside or outside of the translation. Basic protocols as TCP and UDP cannot function properly unless NAT takes action beyond the network layer.

IP packets have a checksum in each packet header, which provides error detection only for the header. IP datagrams may become fragmented and it is necessary for a NAT to reassemble these fragments to allow correct recalculation of higher-level checksums and correct tracking of which packets belong to which connection.

TCP and UDP, have a checksum that covers all the data they carry, as well as the TCP or UDP header, plus a pseudo-header that contains the source and destination IP addresses of the packet carrying the TCP or UDP header. For an originating NAT to pass TCP or UDP successfully, it must recompute the TCP or UDP header checksum based on the translated IP addresses, not the original ones, and put that checksum into the TCP or UDP header of the first packet of the fragmented set of packets.

Alternatively, the originating host may perform path MTU Discovery to determine the packet size that can be transmitted without fragmentation and then set the don’t fragment (DF) bit in the appropriate packet header field. This is only a one-way solution, because the responding host can send packets of any size, which may be fragmented before reaching the NAT.

DNAT[edit]

Destination network address translation (DNAT) is a technique for transparently changing the destination IP address of a routed packet and performing the inverse function for any replies. Any router situated between two endpoints can perform this transformation of the packet.

DNAT is commonly used to publish a service located in a private network on a publicly accessible IP address. This use of DNAT is also called port forwarding, or DMZ when used on an entire server, which becomes exposed to the WAN, becoming analogous to an undefended military demilitarized zone (DMZ).

SNAT[edit]

The meaning of the term SNAT varies by vendor:[16][17][18]

  • source NAT is a common expansion and is the counterpart of destination NAT (DNAT). This is used to describe one-to-many NAT; NAT for outgoing connections to public services.
  • stateful NAT is used by Cisco Systems[19]
  • static NAT is used by WatchGuard[20]
  • secure NAT is used by F5 Networks[21] and by Microsoft (in regard to the ISA Server)

Secure network address translation (SNAT) is part of Microsoft’s Internet Security and Acceleration Server and is an extension to the NAT driver built into Microsoft Windows Server. It provides connection tracking and filtering for the additional network connections needed for the FTP, ICMP, H.323, and PPTP protocols as well as the ability to configure a transparent HTTP proxy server.

Dynamic network address translation[edit]

Dynamic NAT, just like static NAT, is not common in smaller networks but is found within larger corporations with complex networks. Where static NAT provides a one-to-one internal to public static IP address mapping, dynamic NAT uses a group of public IP addresses.[22][23]

NAT hairpinning[edit]

NAT hairpinning, also known as NAT loopback or NAT reflection,[24] is a feature in many consumer routers[25] where a machine on the LAN is able to access another machine on the LAN via the external IP address of the LAN/router (with port forwarding set up on the router to direct requests to the appropriate machine on the LAN). This notion is officially described in 2008, RFC 5128.

The following describes an example network:

  • Public address: 203.0.113.1. This is the address of the WAN interface on the router.
  • Internal address of router: 192.168.1.1
  • Address of the server: 192.168.1.2
  • Address of a local computer: 192.168.1.100

If a packet is sent to 203.0.113.1 by a computer at 192.168.1.100, the packet would normally be routed to the default gateway (the router)[d] A router with the NAT loopback feature detects that 203.0.113.1 is the address of its WAN interface, and treats the packet as if coming from that interface. It determines the destination for that packet, based on DNAT (port forwarding) rules for the destination. If the data were sent to port 80 and a DNAT rule exists for port 80 directed to 192.168.1.2, then the host at that address receives the packet.

If no applicable DNAT rule is available, the router drops the packet. An ICMP Destination Unreachable reply may be sent. If any DNAT rules were present, address translation is still in effect; the router still rewrites the source IP address in the packet. The local computer (192.168.1.100) sends the packet as coming from 192.168.1.100, but the server (192.168.1.2) receives it as coming from 203.0.113.1. When the server replies, the process is identical to an external sender. Thus, two-way communication is possible between hosts inside the LAN network via the public IP address.

NAT in IPv6[edit]

Network address translation is not commonly used in IPv6 because one of the design goals of IPv6 is to restore end-to-end network connectivity.[26] The large addressing space of IPv6 obviates the need to conserve addresses and every device can be given a unique globally routable address. Use of unique local addresses in combination with network prefix translation can achieve results similar to NAT.

Applications affected by NAT[edit]

Some application layer protocols, such as File Transfer Protocol (FTP) and Session Initiation Protocol (SIP), send explicit network addresses within their application data. FTP in active mode, for example, uses separate connections for control traffic (commands) and for data traffic (file contents). When requesting a file transfer, the host making the request identifies the corresponding data connection by its network layer and transport layer addresses. If the host making the request lies behind a simple NAT firewall, the translation of the IP address or TCP port number makes the information received by the server invalid. SIP commonly controls voice over IP calls, and suffer the same problem. SIP and its accompanying Session Description Protocol may use multiple ports to set up a connection and transmit voice stream via Real-time Transport Protocol. IP addresses and port numbers are encoded in the payload data and must be known before the traversal of NATs. Without special techniques, such as STUN, NAT behavior is unpredictable and communications may fail. Application Layer Gateway (ALG) software or hardware may correct these problems. An ALG software module running on a NAT firewall device updates any payload data made invalid by address translation. ALGs need to understand the higher-layer protocol that they need to fix, and so each protocol with this problem requires a separate ALG. For example, on many Linux systems, there are kernel modules called connection trackers that serve to implement ALGs. However, ALG cannot work if the protocol data is encrypted.

Another possible solution to this problem is to use NAT traversal techniques using protocols such as STUN or Interactive Connectivity Establishment (ICE), or proprietary approaches in a session border controller. NAT traversal is possible in both TCP- and UDP-based applications, but the UDP-based technique is simpler, more widely understood, and more compatible with legacy NATs.[citation needed] In either case, the high-level protocol must be designed with NAT traversal in mind, and it does not work reliably across symmetric NATs or other poorly behaved legacy NATs.

Other possibilities are Internet Gateway Device Protocol, NAT Port Mapping Protocol (NAT-PMP), or Port Control Protocol (PCP),[27] but these require the NAT device to implement that protocol.

Most client–server protocols (FTP being the main exception[e]), however, do not send layer 3 contact information and do not require any special treatment by NATs. In fact, avoiding NAT complications is practically a requirement when designing new higher-layer protocols today.

NATs can also cause problems where IPsec encryption is applied and in cases where multiple devices such as SIP phones are located behind a NAT. Phones that encrypt their signaling with IPsec encapsulate the port information within an encrypted packet, meaning that NAT devices cannot access and translate the port. In these cases, the NAT devices revert to simple NAT operations. This means that all traffic returning to the NAT is mapped onto one client, causing service to more than one client behind the NAT to fail. There are a couple of solutions to this problem: one is to use TLS, which operates at layer 4 and does not mask the port number; another is to encapsulate the IPsec within UDP – the latter being the solution chosen by TISPAN to achieve secure NAT traversal, or a NAT with «IPsec Passthru» support; another is to use a session border controller to help traverse the NAT.

Interactive Connectivity Establishment is a NAT traversal technique that does not rely on ALG support.

The DNS protocol vulnerability announced by Dan Kaminsky on July 8, 2008,[28] is indirectly affected by NAT port mapping. To avoid DNS cache poisoning, it is highly desirable not to translate UDP source port numbers of outgoing DNS requests from a DNS server behind a firewall that implements NAT. The recommended workaround for the DNS vulnerability is to make all caching DNS servers use randomized UDP source ports. If the NAT function de-randomizes the UDP source ports, the DNS server becomes vulnerable.

Examples of NAT software[edit]

  • Internet Connection Sharing (ICS): NAT & DHCP implementation included with Windows desktop operating systems
  • IPFilter: included with (Open)Solaris, FreeBSD and NetBSD, available for many other Unix-like operating systems
  • ipfirewall (ipfw): FreeBSD-native packet filter
  • Netfilter with iptables/nftables: the Linux packet filter
  • NPF: NetBSD-native Packet Filter
  • PF: OpenBSD-native Packet Filter
  • Routing and Remote Access Service: routing implementation included with Windows Server operating systems
  • WinGate: third-party routing implementation for Windows

See also[edit]

  • Anything In Anything (AYIYA) – IPv6 over IPv4 UDP, thus working IPv6 tunneling over most NATs
  • Gateway (telecommunications) – Connection between two network systems
  • Internet Gateway Device Protocol (IGD) – UPnP NAT-traversal method
  • Middlebox – Intermediary box on the data path between a source host and destination host
  • Port triggering – NAT traversal mechanism
  • Hairpinning
  • Subnetwork – Logical subdivision of an IP network
  • Teredo tunneling – NAT traversal using IPv6
  • Carrier-grade NAT – NAT behind NAT within ISP.

Notes[edit]

  1. ^ Most NAT devices today allow the network administrator to configure static translation table entries for connections from the external network to the internal masqueraded network. This feature is often referred to as static NAT. It may be implemented in two types: port forwarding which forwards traffic from a specific external port to an internal host on a specified port, and designation of a DMZ host which passes all traffic received on the external interface (on any port number) to an internal IP address while preserving the destination port. Both types may be available in the same NAT device.
  2. ^ The more common arrangement is having computers that require end-to-end connectivity supplied with a routable IP address, while having others that do not provide services to outside users behind NAT with only a few IP addresses used to enable Internet access.
  3. ^ The port numbers are 16-bit integers. The total number of internal addresses that can be translated to one external address could theoretically be as high as 65,536 per IP address. Realistically, the number of ports that can be assigned a single IP address is around 4000.
  4. ^ Unless an explicit route is set in the computer’s routing tables.
  5. ^ This issue can be avoided by using SFTP instead of FTP

References[edit]

  1. ^ Network Protocols Handbook (2 ed.). Javvin Technologies Inc. 2005. p. 27. ISBN 9780974094526. Retrieved 2014-09-16.
  2. ^ a b c d e f g h François Audet; Cullen Jennings (January 2007). Network Address Translation (NAT) Behavioral Requirements for Unicast UDP. IETF. doi:10.17487/RFC4787. RFC 4787.
  3. ^ a b Wing, Dan (2010-07-01). «Network Address Translation: Extending the Internet Address Space». IEEE Internet Computing. 14 (4): 66–70. doi:10.1109/MIC.2010.96. ISSN 1089-7801. S2CID 31082389.
  4. ^ «Characterization and Measurement of TCP Traversal through NATs and Firewalls». December 2006.
  5. ^ «Illuminating the shadows: Opportunistic network and web measurement». December 2006. Archived from the original on 2010-07-24.
  6. ^ «The Audio over IP Instant Expert Guide» (PDF). Tieline. January 2010. Archived from the original (PDF) on 2011-10-08. Retrieved 2011-08-19.
  7. ^ «Using NAT in Overlapping Networks». August 2005.
  8. ^ «VPNs with Overlapping Subnets Problem Scenario». September 2017.
  9. ^ Srisuresh, Pyda; Gan, Der-Hwa (August 1998). «Load Sharing using IP Network Address Translation». doi:10.17487/RFC2391.
  10. ^ «What Is Layer 4 Load Balancing?». June 2020.
  11. ^ «What is load balancing?». November 2018.
  12. ^ «Configure Server Load Balancing Using Dynamic NAT». June 2018.
  13. ^ Singh, R.; Tay, Y.C.; Teo, W.T.; Yeow, S.W. (1999). «RAT: A quick (and dirty?) push for mobility support». Proceedings WMCSA’99. Second IEEE Workshop on Mobile Computing Systems and Applications. pp. 32–40. CiteSeerX 10.1.1.40.461. doi:10.1109/MCSA.1999.749275. ISBN 978-0-7695-0025-6. S2CID 7657883.
  14. ^ Bush, R.; Meyer, D. (2002). Some Internet Architectural Guidelines and Philosophy. IETF. doi:10.17487/RFC3439. RFC 3439.
  15. ^ Velde, G. Van de; Hain, T.; Droms, R.; Carpenter, B.; Klein, E. (2007). Local Network Protection for IPv6. IETF. doi:10.17487/RFC4864. RFC 4864.
  16. ^ «Enhanced IP Resiliency Using Cisco Stateful NAT». Cisco.
  17. ^ «Use NAT for Public Accessto Servers with Private IP Addresses on the Private Network (WatchGuard configuration example)» (PDF). www.watchguard.com.
  18. ^ «K7820: Overview of SNAT features». AskF5. August 28, 2007. Retrieved February 24, 2019.
  19. ^ «Enhanced IP Resiliency Using Cisco Stateful NAT». Cisco.
  20. ^ «Use NAT for Public Accessto Servers with Private IP Addresses on the Private Network (WatchGuard configuration example)» (PDF). www.watchguard.com.
  21. ^ «K7820: Overview of SNAT features». AskF5. August 28, 2007. Retrieved February 24, 2019.
  22. ^ «Dynamic NAT». 26 January 2016. Retrieved 2022-04-19.
  23. ^ «Dynamic NAT». Retrieved 2022-04-19.
  24. ^ «What is NAT Reflection/NAT Loopback/NAT Hairpinning?». NYC Networkers. 2014-11-09. Retrieved 2017-04-27.
  25. ^ «NAT Loopback Routers – OpenSim» (MediaWiki). OpenSimulator. 2013-10-21. Retrieved 2014-02-21.
  26. ^ Iljitsch van Beijnum (2008-07-23). «After staunch resistance, NAT may come to IPv6 after all». Ars Technica. Retrieved 2014-04-24.
  27. ^ D. Wing, Ed; Cheshire, S.; Boucadair, M.; Penno, R.; Selkirk, P. (2013). Port Control Protocol (PCP). IETF. doi:10.17487/RFC6887. RFC 6887.
  28. ^ Messmer, Ellen (2008-07-08). «Major DNS flaw could disrupt the Internet». Network World. Archived from the original on 2009-02-13. Retrieved 14 June 2021.

External links[edit]

  • NAT-Traversal Test and results
  • Characterization of different TCP NATs – Paper discussing the different types of NAT
  • Anatomy: A Look Inside Network Address Translators – Volume 7, Issue 3, September 2004
  • Jeff Tyson, HowStuffWorks: How Network Address Translation Works
  • Routing with NAT (Part of the documentation for the IBM iSeries)
  • Network Address Translation (NAT) FAQ – Cisco Systems

3.4 Межсетевые экраны с возможностями NAT

3.4.1 Используемая терминология и основные понятия

Частные и внешние сети

Адресной областью будем называть такую совокупность адресов, в которой дейтаграммы могут маршрутизироваться к любому хосту, адрес которого принадлежит данной области. Для этого как минимум необходимо, чтобы каждый хост в адресной области имел уникальный IP-адрес.

Глобальной или публичной сетью будем называть сеть, в которой все хосты имеют уникальные сетевые адреса, которые назначены IANA или другой регистрирующей организацией. В терминологии NAT такая сеть часто называется внешней сетью.

Частной сетью будем называть сеть, в которой хосты имеют зарезервированные для частных сетей адреса. В RFC 1918 для частных сетей определены три диапазона IP-адресов:

С 10.0.0.0 по 10.255.255.255 (10.0.0.0/8 в CIDR нотации)

С 172.16.0.0 по 172.31.255.255 (172.16.0.0/12 в CIDR нотации)

С 192.168.0.0 по 192.168.255.255 (192.168.0.0/16 в CIDR нотации)

Эти адреса могут использоваться во многих организациях независимо друг от друга. Однако, если в дальнейшем эти организации решат взаимодействовать друг с другом или с публичным интернетом, они либо должны назначить новые адреса во всех своих сетях, либо использовать NAT на граничных маршрутизаторах.

Термин «прозрачная маршрутизация» используется для описания маршрутизации, выполняемой NAT. Традиционная маршрутизация, выполняемая традиционными маршрутизаторами, отличается тем, пакеты маршрутизируются внутри одной области адресов.

Прозрачная маршрутизация означает маршрутизацию дейтаграммы между различными адресными областями, при которой выполняется модификация адреса в IP-заголовке таким образом, чтобы он принадлежал области адресов, в которой дейтаграмма маршрутизируется.

Маршрутизатор NAT расположен на границе между двумя областями адресов и преобразует адреса в IP-заголовках таким образом, что пакет корректно маршрутизируется при переходе из одной области в другую. Маршрутизатор NAT имеет соединения с несколькими областями адресов, при этом он не должен распространять некорректную для области информацию (например, посредством протоколов маршрутизации) о сетях из одной области адресов в другую.

Прозрачная маршрутизация между хостами в частной области и внешней области – основная функция маршрутизатора NAT.

NAT обеспечивает возможность прозрачной маршрутизации к хостам из различных адресных областей. Это достигается изменением адреса получателя и поддержкой информации об этом изменении таким образом, чтобы дейтаграммы для этой сессии маршрутизировались бы нужному получателю из этой области. Данное решение можно использовать только в том случае, если приложения не используют IP-адреса в качестве части протокола. Например, идентификация конечных точек с помощью DNS-имен, а не IP-адресов делает приложения менее зависимыми от реальных адресов, которые использует NAT, и не приводит к необходимости также изменять и содержимое, когда NAT изменяет IP-адрес.

Трансляция адресов позволяет хостам в частной сети прозрачно взаимодействовать с получателем во внешней сети и наоборот. Существуют различные варианты NAT, терминология преобразования адресов в этих случаях может несколько отличаться.

NAT рассматривается исключительно для IPv4.

Функциональность NAT не может быть прозрачной для всех приложений, и по этой причине она часто используются вместе со шлюзом прикладного уровня (ALG). При принятии решения о развертывании NAT необходимо определить требования приложений и оценить необходимость развертывания дополнений к NAT (например, ALG), чтобы обеспечить прозрачность преобразования NAT для приложений.

Стандартные режимы IPSec, в которых IP-адреса конечных точек не изменяются, не работают с NAT. Такие протоколы как АН и ESP защищают содержимое IP-заголовков от изменения, а одна из основных функций NAT как раз и состоит в изменении адресов в IP-заголовке пакета.

Несмотря на частую путаницу понятий, NAT не является частью функциональности в межсетевом экране, относящейся к безопасности. Свойство NAT, относящееся к безопасности, – обеспечение того, что хосты с внешней стороны межсетевого экрана не могут инициировать соединение с хостом, расположенным позади NAT. Другой способ добиться того же самого можно с помощью политик межсетевого экрана, которые в той или иной степени отслеживают состояния. Однако использование NAT в межсетевом экране обычно означает, что нет необходимости конфигурировать политику, которая обеспечивает аналогичную защиту, поэтому часто считается, что NAT выполняет функцию безопасности.

Другим примером, когда NAT взаимосвязан с политикой безопасности, является возможность идентификации источника трафика в логах межсетевого экрана. Если используется NAT, он должен записывать в логи частный адрес, а не публичный адрес, на который NAT изменил частный. В противном случае в логах будут некорректно определяться многие хосты, которые будут представлены там единственным публичным адресом.

В простейшем случае NAT представляет собой маршрутизатор, у которого существует сеть с частными адресами внутри и единственный публичный адрес снаружи. NAT выполняет преобразование частных адресов в один публичный адрес. Способ этого отображения один-ко-многим зависит от реализации, но всегда включает следующее:

  • Для хостов из внутренней сети, инициализирующих соединения ко внешней сети, выполняется преобразование IP-адреса и порта источника на другие IP-адреса и порт источника, которые определяются NAT. Затем NAT использует обратное преобразование IP-адресов и номеров портов для пересылки пакетов из внешней сети к хосту во внутреннюю сеть.
  • Хосты из внешней сети не могут инициировать соединения к внутренней сети.
  • В некоторых межсетевых экранах NAT может предоставлять доступ к определенным хостам внутри частной сети.

Понятие сессии

Сессия характеризуется тем, что можно точно определить пакет, являющийся началом сессии, и, как правило, существует несколько пакетов, которые говорят о завершении сессии. Направление, в котором передается первый пакет сессии, определяет направление всей сессии.

Можно считать, что сессия – это совокупность трафика, который обрабатывается как единое целое. ТСР/UDP сессии однозначно определяются IP-адресом и портом источника и IP-адресом и портом получателя. Сессии ICMP-запросов определяются IP-адресом источника, ID ICMP-запроса и IP-адресом получателя. Все остальные сессии характеризуются IP-адресами источника и получателя и IP-протоколом.

Трансляция адресов, выполняемая NAT, основана на сессии и включает преобразование входящих и исходящих пакетов, принадлежащих сессии.

Заметим, что не гарантируется, что понятие сессии, определяемое для NAT, полностью совпадает с понятием сессии в приложении. Приложение может считать несколько сессий (с точки зрения NAT), которые с точки зрения приложения связаны между собой, как единую сессию или может не рассматривать свое взаимодействие с противоположной стороной как сессию. Для преобразования NAT важно отслеживать инициализацию и завершение сессий.

Первый пакет ТСР-сессии содержит информацию о начале сессии. Первый пакет ТСР-сессии можно распознать по наличию бита SYN и отсутствию бита ACK во флагах ТСР. Все ТСР-пакеты, за исключением первого пакета, должны иметь установленный бит ACK.

Однако не существует заранее определенного способа распознать начало UDP-сессии или любой не-ТСР-сессии. Можно предложить эвристический подход, при котором предполагается, что первый пакет с несуществующими на текущий момент параметрами сессии начинает новую сессию.

Завершение ТСР-сессии происходит при получении флага FIN обеими сторонами сессии или когда одна из сторон посылает пакет с флагом RST. Однако при выполнении NAT, так как невозможно знать, что пакеты действительно доставлены получателю (они могут быть отброшены между хостом, выполняющим NAT, и получателем), невозможно точно знать, что пакеты, содержащие FIN или RST, будут последними пакетами в сессии (так как могут быть повторные передачи). Следовательно, надо предполагать, что сессия завершена только по истечении 4 минут (2 * на максимальное время жизни пакета) с момента определения завершения.

Заметим также, что возможно, что ТСР-сессия будет завершена без обнаружения этого события устройством, выполняющим NAT (например, в случае перезапуска одной или обеих сторон). Следовательно, сбор мусора является необходимым сервисом NAT, чтобы очистить неиспользуемые соединения. Однако в общем случае невозможно различить соединение, по которому долгое время ничего не передается, от соединений, которые больше не существуют. В случае UDP-сессий не существует единственного способа определить завершения сессии, так как это во многом зависит от приложения.

Для определения завершения сессии используются различные эвристические подходы. Можно предположить, что ТСР-сессии, которые не используются, скажем, в течение 24 часов, и не-ТСР-сессии, которые не используются в течение пары минут, завершены. Часто такие предположения верные, но могут существовать случаи, когда предположения оказались неверными. Период простоя может существенно отличаться как от приложения к приложению, так и от сессии к сессии в одном приложении. Следовательно, таймауты сессии должны быть конфигурируемы. Но даже и в этом случае нет гарантии, что может быть найдено приемлемое значение. Не существует также гарантии, что завершенная с точки зрения NAT сессия будет завершенной с точки зрения приложения.

Другим способом обработки завершения сессии является использование записей с отметкой времени, которые будут храниться как можно дольше, удаляться в случаи необходимости будет только самая старая простаивающая сессия.

Шлюз прикладного уровня (ALG)

Не для всех приложений можно использовать NAT; в частности, это касается тех приложений, которые используют IP-адреса и ТСР/UDP порты в содержимом пакета. ALG является прикладным агентом, который позволяет приложению, выполняющемуся на хосте в одной адресной области, прозрачно взаимодействовать с противоположной стороной, выполняющейся на хосте в другой области. ALG должен взаимодействовать с NAT, чтобы установить состояние NAT, использовать информацию состояния NAT, модифицировать специфичное для приложения содержимое или выполнить что-то еще, что необходимо для выполнения приложения при пересылке пакетов из одной адресной области в другую.

ALG аналогичны прокси в том смысле, что и тот, и другой расположены между клиентом и сервером. Прокси используют специальный протокол для взаимодействия с клиентом и пересылке данных серверу и наоборот. В отличие от прокси ALG не используют специальный протокол и не требуют никаких изменений в прикладных клиентах.

3.4.2 Статическое и динамическое назначение адресов

NAT является методом, с помощью которого выполняется преобразование IP-адресов при пересылке пакета из одной области адресов в другую, обеспечивая прозрачную маршрутизацию между конечными хостами. Существует много различных способов преобразования адресов. Тем не менее, все технологии NAT должны разделять следующие характеристики.

  1. Прозрачное для протоколов маршрутизации и конечных хостов назначение адресов.
  2. Возможность выполнять обычную маршрутизацию после преобразования адресов (маршрутизация здесь означает пересылку пакетов, а не обмен информацией маршрутизации).
  3. Согласованное преобразование содержимого пакета ICMP-error.

NAT преобразует адреса в частной сети в адреса во внешней сети для обеспечения прозрачной маршрутизации дейтаграмм между разными адресными областями. В некоторых случаях преобразование может быть сделано и для идентификаторов транспортного уровня (такие как порты ТСР/UDP). Преобразование адреса выполняется при инициализации сессии. Может существовать два способа назначения адресов.

При статическом назначении адреса существует отображение один-к-одному между адресами частной сети и адресами внешней сети в течение всего времени функционирования NAT.

Внешние адреса могут назначаться хостам в частной сети динамически. Когда сессия, для которой используются назначенные адреса, заканчивается, NAT освобождает внешний адрес, чтобы в дальнейшем он мог опять использоваться для другого хоста из частной сети. Конкретный способ такого связывания специфичен для каждой реализации NAT.

3.4.3 Варианты выполнения NAT

Существует много вариантов выполнения преобразования адресов. Перечисленные ниже способы не претендуют на полноту, но описывают основные подходы.

Будем использовать следующую диаграмму в качестве базовой модели для иллюстрации вариантов выполнения NAT.

Хост-A с адресом Addr-A расположен в области с частными адресами, которая обозначена как сеть N-Pri. N-Pri изолирована от внешней сети с помощью маршрутизатора NAT. Хост-X с адресом Addr-X расположен во внешней области, обозначенной как сеть N-Ext. Маршрутизатор NAT имеет два интерфейса, каждый из которых соединен с соответствующей областью. Интерфейсу к внешней области назначен адрес Addr-Nx, интерфейсу к частной области назначен адрес Addr-Np. Адреса Addr-A и Addr-Np принадлежат сети N-Pri, а адреса Addr-X и Addr-Nx принадлежат сети N-Ext.

Традиционный (или исходящий) NAT

Традиционный NAT позволяет хостам в частной сети прозрачно получать доступ к хостам во внешней сети. В традиционном NAT сессия может существовать только в одном направлении, исходящим из частной сети. Это отличает его от двунаправленного NAT, который допускает сессии как во входящем, так и в исходящем направлениях.

Рассмотрим свойства области, в которой выполняется традиционный NAT. IP-адреса хостов во внешней сети являются уникальными и доступными как во внешней, так и в частной сети. Однако адреса хостов в частной сети являются уникальными только внутри этой частной сети и не являются доступными во внешней сети. Другими словами, NAT ничего не сообщает внешней области о частной сети. Но частная сеть может иметь информацию о сетях во внешней области. Адреса, используемые в частной сети, не должны перекрываться с внешними адресами. Любой адрес должен являться либо частным адресом, либо внешним.

Традиционный маршрутизатор NAT разрешает Хост-A инициировать сессию к Хост-X, но не наоборот. Также N-Ext является маршрутизируемой из N-Pri, в то время как N-Pri не может быть маршрутизируема из N-Ext.

Традиционный NAT первоначально использовался в тех случаях, когда хостам с частными адресами необходимо было разрешить исходящие сессии.

Существует два варианта традиционного NAT, называемые базовым NAT и NAPT (Network Address Port Translation).

Базовый NAT

Для исходящих из частной сети пакетов преобразуются IP-адрес источника и относящиеся к этому поля, такие как контрольные суммы заголовков IP, TCP, UDP и ICMP.

NAPT

NAPT дополнительно преобразует идентификатор транспорта, такой как номера портов ТСР и UDP. NAPT позволяет большому числу хостов разделять единственный внешний адрес. Заметим, что NAPT может быть скомбинирован с базовым NAT таким образом, чтобы использовался пул внешних адресов совместно с преобразованием портов.

Маршрутизатор NAPT может быть сконфигурирован для преобразования сессий из N-Pri в единственный внешний адрес, например, Addr-i.

Очень часто адрес внешнего интерфейса Addr-Nx маршрутизатора NAPT используется в качестве адреса, в который отображается N-Pri.

Использование IP-адреса интерфейса в качестве IP-адреса источника

При установлении нового соединения для него по таблице маршрутизации определяется выходной интерфейс. При выполнении преобразования адресов IP-адрес этого интерфейса используется в качестве нового IP-адреса источника. Этот способ преобразования используется чаще всего.

Использование выделенного IP-адреса в качестве IP-адреса источника

В качестве нового IP-адреса источника может быть указан выделенный IP-адрес. Для этого необходимо, чтобы этот IP-адрес был опубликован протоколом ARP на выходном интерфейсе, так как в противном случае возвращаемые пакеты не будут получены межсетевым экраном. Этот метод используется, когда IP-адрес источника должен отличаться от адреса интерфейса.

Использование IP-адреса из NAT-пула

В качестве IP-адреса источника может использоваться NAT-пул – диапазон IP-адресов, определенный администратором сети. В этом случае в качестве IP-адреса NAT будет использовать очередной доступный IP-адрес из пула. Причем NAT-пулов может существовать несколько. А также один NAT-пул может быть использоваться в более чем одном NAT-правиле.

NAT-пулы обычно применяются, если требуется создать много уникальных подключений используя один порт. Межсетевой экран обычно может поддерживать до 65 000 соединений с уникальной комбинацией из IP-адреса источника и IP-адреса назначения. Большее количество портов может потребоваться, если много клиентов одновременно должны иметь доступ в интернет через прокси-сервер. Проблема с ограниченным количеством портов решается с помощью выделения дополнительных внешних IP-адресов для выхода в интернет и использования NAT-пулов для создания новых соединений с использованием этих IP-адресов.

Типы NAT-пулов

Существует три типа NAT-пулов, каждый из которых производит распределение новых подключений разными способами:

  • Stateful (с поддержкой состояния)
  • Stateless (без поддержки состояния)
  • Fixed (Фиксированный)

NAT-пулы типа Stateful

При использовании NAT-пула Stateful, каждому соединению назначается IP-адрес из пула, через который в настоящий момент осуществляется наименьшее количество соединений. Во всех последующих соединениях с тем же внутренним хостом будет использоваться тот же самый IP-адрес.

Создание NAT-пула с поддержкой состояния и созданным ранее диапазоном IP-адресов

увеличить изображение
Рис.
3.28.
Создание NAT-пула с поддержкой состояния и созданным ранее диапазоном IP-адресов

Использование механизма Proxy ARP для опубликования IP-адресов на указанном интерфейсе

увеличить изображение
Рис.
3.29.
Использование механизма Proxy ARP для опубликования IP-адресов на указанном интерфейсе

Преимуществом данного подхода является обеспечение сбалансированной нагрузки нескольких внешних каналов связи интернет-провайдера по количеству соединений и гарантия того, что информация от внешнего хоста всегда вернется обратно на IP-адрес отправителя, что может быть важно в таких протоколах как HTTP. Недостатком является требование дополнительных ресурсов памяти для отслеживания соединения в таблице состояний, а также накладные расходы, связанные с обработкой данных в процессе установления нового соединения.

Для того чтобы таблица состояний не содержала записей о неактивных соединениях, можно установить время активного состояния соединения (State Keepalive) – время неактивности подключения в секундах, по истечении которого, запись об этом подключении будет удалена из таблицы состояний. По прошествии данного периода система считает, что исходящих соединений от данного хоста создаваться больше не будет. В случае если запись о состоянии подключения из таблицы удалена, то последующие подключения данного хоста будут заноситься в новую запись таблицы и могут иметь другой внешний IP-адрес из NAT-пула.

Так как таблица состояний расходует ресурсы памяти, существует возможность ограничить ее размер, используя параметр Max States объекта NAT-пул. Таблица состояний формируется не сразу, она увеличивается в размере по мере необходимости. Одна запись в таблице состояний отображает все соединения одного хоста за межсетевым экраном, независимо от того, к какому внешнему хосту данное соединение относится. Если размер таблицы состояний достиг значения параметра Max States, в таблице перезаписывается то состояние, у которого самое длительное время неактивности. Если все состояния из таблицы активны, тогда новое соединение игнорируется. Значение параметра Max States должно быть не меньше количества локальных хостов или клиентов имеющих доступ к интернету.

В каждом NAT-пуле есть только одна таблица соответствий, поэтому, если один NAT-пул несколько раз используется в разных IP-правилах NAT, то они будут совместно использовать одну и ту же таблицу состояний.

NAT-пулы типа Stateless

Если выбран тип NAT-пула Stateless, это означает, что таблица состояний не формируется, для каждого нового соединения будет использоваться новый IP-адрес из пула, через который осуществляется наименьшее количество соединений. В результате этого два разных соединения от одного внутреннего хоста к одному и тому же внешнему хосту могут использовать два разных внешних IP-адреса источника.

Преимуществом NAT-пула с типом Stateless является то, что он обеспечивает эффективное распределение новых соединений между внешними IP-адресами без лишних затрат памяти на формирование таблицы состояний. Помимо этого, время на обработку данных при установлении каждого нового соединения сокращается. К недостаткам способа относится то, что он не подходит для подключений, требующих наличия постоянного внешнего IP-адреса.

NAT-пулы типа Fixed

Если выбран тип NAT-пула Fixed, то каждому внутреннему хосту поставлен в соответствие один из внешних IP-адресов. Такое соответствие создается с помощью алгоритма хэширования. Хотя администратор не имеет возможности контролировать, какое из внешних подключений будет использоваться, такой подход гарантирует, что определенный внутренний хост всегда будет обмениваться информацией через один и тот же внешний IP-адрес.

Преимуществом типа Fixed является то, что он не требует ресурсов памяти на создание таблицы состояний и обеспечивает очень высокую скорость обработки данных при установлении нового соединения.

Двунаправленный (Two-Way) NAT

При двунаправленном NAT сессии могут инициализироваться как с хостов из внешней сети, так и с хостов из частной сети. Прозрачная маршрутизация для сессий, начинающихся с хостов из внешней сети, может быть реализована несколькими способами.

Первый способ. NAT должен быть сконфигурирован таким образом, чтобы отображать определенный порт получателя на конкретный хост и порт за NAT. Например, все НТТР-запросы, которые приходят на NAT, могут быть перенаправлены на один хост, расположенный в защищенной межсетевым экраном сети. Данная технология иногда называется pinholing. Например, если политикой требуется, чтобы все НТТР-сервера, доступные извне, были расположены в DMZ, то один из способов сделать – это определить в NAT возможность pinholing на ТСР-порт 80.

Правило SAT, обеспечивающее доступ к серверам, расположенным за преобразованием NAT

увеличить изображение
Рис.
3.31.
Правило SAT, обеспечивающее доступ к серверам, расположенным за преобразованием NAT

Обращение к серверу, расположенному за NAT, по IP-адресу межсетевого экрана

увеличить изображение
Рис.
3.33.
Обращение к серверу, расположенному за NAT, по IP-адресу межсетевого экрана

Второй способ. Хосту в частной сети (Хост-A) может быть назначен IP-адрес, доступный из внешней сети.

Двунаправленный маршрутизатор NAT позволяет Хост-A инициировать сессию к Хосту-X, и Хост-X инициировать сессию к Хосту-A, если Хост-A доступен либо первым, либо вторым способом. Также как и в случае традиционного NAT N-Ext является маршрутизируемой из N-Pri, но N-Pri остается не маршрутизируемой из N-Ext.

Рассмотрим особенности реализации второго способа создания двунаправленного NAT, когда хост в частной сети имеет IP-адрес из внешней сети. NAT-маршрутизатор является узлом, который расположен на границе между частной и внешней областями и имеет возможность выполнять маршрутизацию пакетов из внешней области в частную область. В случае двунаправленного NAT пакеты могут как исходить от Хоста-A, так и быть направлены к Хосту-A.

Хост-A при соединении с хостом во внешней области имеет IP-адрес из внешнего пространства адресов. После этого никакой другой хост в частном или внешнем домене не может иметь тот же самый адрес.

Обсудим возможные способы маршрутизации, которые могут иметь место внутри частной области.

  1. На маршрутизаторе должен быть явно прописан маршрут к Хосту-A.
  2. Если указание такого маршрута вызывает проблемы, то может быть использовано туннелирование. Один из возможных подходов состоит в установке туннеля между Хостом-A и NAT-маршрутизатором, соединяющим две адресные области. Пакеты к Хосту-A и от Хоста-A могут быть туннелированы, но пакеты между NAT-маршрутизатором и удаленным получателем будет пересылаться в обычном виде. Заметим, что туннель от Хоста-A к пограничному маршрутизатору может и не требоваться. Как правило туннель бывает необходим, если межсетевой экран фильтрует пакеты, в которых адрес получателя принадлежит внешней сети.

В примере Хост-A имеет адрес Addr-k из внешней области, что означает возможность создания сессий от Addr-X к Addr-k. Если Addr-k не маршрутизируется внутри частной сети, то для прохождения пакетов внутри частной области можно создать туннель:

Туннелирование внутри частной сети:

Могут существовать и другие подходы.

Хост-A будет иметь следующие характеристики

  1. Хосту-A назначается адрес из внешней области для взаимодействия с хостами из этой области. Такой адрес может быть связан статически или получаться динамически (с помощью заранее определенного протокола) от узла, который может назначать адреса из внешней области. Маршрутизатору NAT назначен адрес внешней области.
  2. Выполняется маршрутизация пакетов к внешним хостам, используя маршрутизатор NAT в качестве шлюза. Хосту-A может потребоваться возможность функционирования в качестве конечной точки туннеля для инкапсуляции пакетов для их пересылки и выполнять обратную де-капсуляцию при получении.

Маршрутизатор NAT принадлежит адресному пространству как в частной, так и во внешней областях и выполняет маршрутизацию пакетов из внешней области в частную область. Маршрутизатор NAT должен иметь следующие характеристики:

  1. Должен быть маршрутизатором, соединенным как с частной, так и с внешней областью адресов.
  2. Должен иметь возможность обеспечивать маршрутизацию пакетов из внешней области в частную область.
  3. Маршрутизатор должен иметь возможность быть конечной точкой туннеля с Хостом-A. Он будет де-туннелировать исходные пакеты, исходящие от Хоста-A, и перенаправлять их внешним хостам. На обратном пути он создает туннель для Хоста-A, основываясь на адресе получателя исходного пакета, и инкапсулировать пакет в туннель для перенаправления его к Хосту-A.

Возможен другой вариант, при котором несколько частных хостов используют единственный внешний адрес, но имеют различные идентификаторы транспортного уровня (т.е. номера портов TCP/UDP и ICMP Query ID).

В этом случае Хост-A может быть определен аналогично предыдущему случаю с той разницей, что Хост-A указывает пару (внешний адрес, идентификатор транспорта) при соединении с хостом во внешней области. При этом взаимодействие с внешними узлами для Хоста-A может быть ограничено TCP-, UDP- и ICMP-сессиями.

Маршрутизатор NAT аналогичен предыдущему случаю в том, что он должен маршрутизировать пакеты из внешней области к Хосту-A внутри частной области. Обычно маршрутизатор NAT также назначает параметры транспорта для Хоста-A.

В примере Хост-A получает параметры (Addr-Nx, TCP-порт T-Nx) от маршрутизатора NAPT. Пересылка пакетов между конечными точками внутри частной области может быть проиллюстрирована следующим образом. При использовании первого метода внешний заголовок исходящего пакета от Хоста-A использует (частный адрес Addr-A, порт источника T-Na) в качестве параметров источника для взаимодействия с Хостом-X. Маршрутизатор NAPT преобразует эти параметры в (Addr-Nx, порт T-Nxa).

Использование туннеля внутри частной области:

Двойной NAT

Двойной NAT является вариантом NAT, в котором адреса как источника, так и получателя модифицируются NAT при пересечении дейтаграммой границы пространства адресов. Это отличает его от традиционного NAT и двунаправленного NAT, в которых преобразуется только один адрес.

Двойной NAT необходим, когда в частной и внешней областях есть коллизия адресов. В большинстве случаев это происходит, когда внутренние хосты имеют внешние адреса, которые не являются уникальными во внешней области. В качестве примера можно привести случай, когда внешний адрес хоста должен был бы измениться при переходе от одного провайдера к другому, но при этом желательно иметь возможность оставить этот внешний адрес прежним. Основной проблемой в этом случае является то, что адрес некоторого хоста во внешней области может быть точно таким же, что и адрес нашего хоста внутри частной области. Если данный адрес появляется в пакете в частной сети, он должен быть в определенных случаях перенаправлен внутреннему хосту, а не через преобразование NAT во внешнюю область. Двойной NAT является мостом для подобных областей, преобразуя как адрес источника, так и адрес получателя в IP-пакете.

Маршрутизатор двойного NAT будет позволять Хосту-A инициировать сессии к Хосту-X. Тем не менее N-Ext (или подмножество N-Ext) не маршрутизируемо внутри N-Pri, и N-Pri не маршрутизируемо из N-Ext.

Например, частные хосты используют 200.200.200.0/24 пространство адресов, которое может быть одним и тем же с хостом в публичном интернете. Хост-A (200.200.200.1) в частном пространстве хочет соединиться с Хостом-X (200.200.200.100) во внешней сети. Для этого необходимо, чтобы адрес Хоста-X был отображен в адрес Хоста-A и наоборот. Двойной NAT, расположенный на границе частной сети, может быть сконфигурирован следующим образом:

Private to Public : 200.200.200.0/24 -> 138.76.28.0/24

Public to Private : 200.200.200.0/24 -> 172.16.1.0/24

В этом случае хост из частной сети будет во внешней сети иметь адрес 138.76.28.1, а хост из внешней сети в частной сети будет иметь адрес 172.16.1.1.

Поток дейтаграмм: Хост-A (Private) → Хост-X (Public)

1. Внутри частной сети

DA: 172.16.1.100 SA: 200.200.200.1

2. После преобразования двойным NAT

DA: 200.200.200.100 SA: 138.76.28.1

Поток дейтаграмм Хост-X (Public) → Хост-A (Private)

1. Во внешней сети

DA: 138.76.28.1 SA: 200.200.200.100

2. После преобразования двойным NAT в частной сети

SA: 200.200.200.1 SA: 172.16.1.100

Двойной NAT работает следующим образом. Когда Хост-A хочет инициировать сессию с Хостом-X, он создает DNS-запрос для Хост-X. DNS-ALG заменяет адрес Хост-X адресом, который корректно маршрутизируется в частной области (скажем Хост-XPRIME). Затем Хост-A инициализирует взаимодействие с Хост-XPRIME. Когда пакеты проходят через NAT, IP-адрес источника преобразуется аналогично случаю традиционного NAT, а адрес получателя преобразуется в Хост-X. Аналогичные преобразования выполняются для возвращаемых пакетов, приходящих от Хоста-X.

Multihomed NAT

Существует много ограничений на использование NAT. Например, запросы и ответы, относящиеся к сессии, должны маршрутизироваться через один и тот же маршрутизатор NAT, так как маршрутизатор NAT поддерживает информацию о состоянии сессий, установленных через него. По этой причине часто предполагается, что маршрутизаторы NAT расположены на границе в том месте, где все IP-пакеты выходят из домена и поступают в домен. Однако такая конфигурация означает, что маршрутизатор NAT является единой точкой отказа.

Для того чтобы гарантировать в частной сети, что соединение с внешней сетью будет поддерживаться, даже если один из маршрутизаторов NAT откажет, часто требуется иметь несколько соединений частной сети c одним или несколькими сервис-провайдерами. Причем реализация NAT на каждом маршрутизаторе может быть как одинаковой, так и разной.

Например, частная сеть может иметь связь с двумя различными провайдерами, и сессии от частных хостов могут проходить через маршрутизатор NAT с лучшей метрикой до получателя. Когда происходит сбой в одном из маршрутизаторов NAT, другой может выполнять маршрутизацию трафика для всех соединений.

NAT от нескольких производителей или несколько экземпляров от одного и того же производителя NAT, разделяя общую конфигурацию NAT, могут обеспечивать отказоустойчивость друг для друга. В этом случае необходимо выполнять резервное копирование NAT для обмена информацией о состоянии таким образом, чтобы можно было прозрачно загружать сессию при сбоях первичного NAT. Резервное копирование NAT выполняется проще, когда конфигурация основана на статическом отображении.

3.4.4 Сеть с частными адресами и туннели

Рассмотрим случай, когда сеть с частными адресами должна быть соединена с внешней сетью через туннель. В этом случае туннель инкапсулирует трафик, который может как содержать, так и не содержать преобразованные пакеты, в зависимости от характеристик адресных областей, с которыми соединен туннель.

Обсудим два сценария, когда туннели используются

1. Совместно с преобразованием адресов.

2. Без преобразования адресов.

Туннелирование преобразованных пакетов

Все варианты преобразования адресов, которые обсуждались ранее, могут применяться не только к прямым соединениям, но и к туннелям и VPN.

Например, сеть, соединяющая локальные сети деловых партнеров через VPN, может использовать традиционный NAT. Также возможно использовать двойной NAT, если адресные пространства локальных сетей перекрываются. Преобразование NAT может выполняться на одном конце туннеля или на обоих концах. Во всех случаях трафик через VPN может быть для обеспечения безопасности зашифрован. Безопасность здесь означает только безопасность при передачи по VPN. Безопасность между конечными точками не обеспечивается. Это означает, что частные сети должны быть доверяемыми.

Магистральные (Backbone) разделенные на сегменты частные сети

Существует много примеров, когда частная сеть (такая как сеть корпорации) состоит из отдельных подсетей, расположенных в разных местах, и использует публичную сеть для взаимодействия между ними. В таких случаях нежелательно выполнять преобразование адресов, как потому что большому числу хостов может потребоваться взаимодействие через основную сеть, что потребует большой таблицы адресов, так и потому, что будет большое число приложений, которые зависят от сконфигурированных адресов, что затруднит работу DNS-сервера. Будем называть такую частную сеть магистральной, разделенной на сегменты, (backbone-partitioned) частной сетью.

Тупиковые сети, соединенные с магистральной сетью, разделенной на сегменты, должны быть построены точно также, как если бы они были соединены с обычной магистральной сетью. Это означает, что пограничный маршрутизатор должен поддерживать маршруты к частным сетям во всех сегментах. При этом публичные основные сети могут не поддерживать маршруты ко всем локальным адресам. Следовательно, при использовании NAT пограничные маршрутизаторы должны туннелировать трафик, используя VPN, через основные сети. Чтобы сделать это, преобразование NAT следует выполнять для частных адресов, а глобальные адреса использовать для туннелирования.

Если необходимо доставить пакет из тупикового сегмента Х в тупиковый сегмент Y, то преобразование NAT для сегмента Х инкапсулирует пакет в IP-заголовок с адресом получателя, установленным в глобальный адрес устройства, выполняющего NAT для сегмента Y. Когда преобразование NAT для сегмента Y получает пакет с этим адресом получателя, NAT де-капсулирует IP-заголовок и перенаправляет пакет во внутреннюю сеть. Заметим, что в этом случае может как происходить преобразование адреса, так и не происходить, т.е. будет выполняться простая пересылка пакетов из одной частной сети в другую по внешней сети посредством туннеля.

Рассмотрим следующий пример.

Необходимо соединить две локальные сети через магистральную сеть, в которой возможна коллизия адресов как с локальной сетью LAN 1, так и с локальной сетью LAN 2.

Самым простым решением в этом случае является использование GRE-туннеля.

На МЭ 1 заданы правила.

После этого весь трафик из LAN 1 будет иметь IP-адрес источника, определенный для локальной точки GRE-туннеля.

Правила маршрутизации на МЭ 1 следующие.

На МЭ 2 заданы аналогичные правила.

После этого весь трафик из LAN 2 будет иметь IP-адрес источника, определенный для противоположной точки GRE-туннеля.

Правила маршрутизации на МЭ 1 следующие.

3.4.5 Свойства NAT

При преобразовании NAT должны изменяться только заголовки IP/TCP/UDP/ICMP и ICMP-сообщения error.

Преобразование NAT (за исключением ALG) не анализирует и не изменяет содержимое прикладного уровня. По этой причине в большинстве случаев преобразование NAT прозрачно для приложений. Тем не менее существуют две проблемы, из-за которых преобразование NAT может вызывать трудности:

  1. Если содержимое транспортного уровня содержит IP-адрес.
  2. Когда необходимо обеспечить безопасность до конечных точек.

Технологии безопасности прикладного уровня, которые не зависят от IP-адресов (т.е. TLS/SSL и SSH), работают корректно вместе с NAT. В отличие от этого, технологии безопасности на транспортном уровне, такие как IPSec, могут иметь проблемы при использовании NAT.

В транспортном режиме IPSec как АН, так и ESP обеспечивают проверку целостности всего содержимого. Если преобразование NAT модифицирует адрес, то проверка целостности не пройдет.

Заметим, что ESP в туннельном режиме допустимо, так как преобразование не затрагивает внешний IP-заголовок.

Преобразование NAT также влияет на инфраструктуры открытых ключей, такие как DNSSec и сертификаты Х.509. В случае DNSSec каждый RRset DNS подписан ключом своей зоны. Аутентичность ключа проверяется с помощью цепочки доверия, которая устанавливается от корневого DNS. Когда DNS-ALG модифицирует адреса (например, как в случае двойного NAT), проверка подписей не проходит.

Интересно заметить, что IKE является протоколом уровня сессии, основанном на UDP и не защищенном IPSec. Защищены только отдельные части содержимого внутри IKE. Как результат IKE-сессии проходят через NAT, кроме того также содержимое IKE не содержит адресов или идентификаторов транспорта, специфичных для той или иной области.

Поддержка FTP

Рассмотрим, как FTP может поддерживаться NAT. FTP ALG является составной частью большинства реализаций NAT. Некоторые производители включают дополнительные ALG для поддержки других приложений.

Команда PORT и ответ PASV в содержимом сессии протокола FTP содержит IP-адрес и TCP-порт, который участники должны использовать при передаче данных. Для успешного прохождения NAT требуется FTP ALG для просмотра и изменения содержимого управляющей сессии таким образом, чтобы информация содержимого соответствовала параметрам конечных точек. ALG должен также взаимодействовать с NAT таким образом, чтобы NAT мог установить информацию о состоянии FTP-сессии для данных.

Так как адрес и ТСР-порт представлены в ASCII кодировке, в результате может измениться размер пакета. Например, «10,18»– это 5 символов ASCII, а «110,118»– это 7 символов ASCII. Если новый размер совпадает с тем, который был до преобразования, то необходимо только изменить контрольную сумму ТСР. Если же новый размер меньше или больше, чем до преобразования, то необходимо также поменять последовательный номер ТСР, чтобы отобразить изменение длины в управляющем потоке FTP. ALG может использовать специальную таблицу, чтобы корректировать последовательный номер и номер подтверждения в ТСР. Причем это необходимо делать для всех последующих пакетов в соединении.

Приложения с несколькими взаимозависимыми сессиями

Преобразование NAT выполняется в предположении, что каждая сессия является независимой. Такие характеристики сессии, как ориентация сессии, IP-адреса источника и получателя, протокол сессии, идентификаторы отправителя и получателя транспортного уровня определяются независимо в начале каждой новой сессии.

Однако существуют приложения, такие как Н.323, которые используют одну или более управляющих сессий для установки характеристик последующих сессий. Такие приложения требуют специальных ALG, которые интерпретируют и при необходимости преобразуют содержимое.

Анализ логов

При использовании NAT существует возможность неправильной интерпретации адресов, которые будут записаны в логи. Например, один и тот же частный адрес может быть связан в разное время с разными внешними адресами и наоборот, один и тот же внешний адрес может быть в разное время связан с разными частными хостами. В результате этого анализ трафика, основанный исключительно на внешних адресах и номерах портов, может привести к неправильным выводам.

Если некоторый хост атакует другие хосты в интернете, может быть трудно определить его источник, потому что IP-адрес хоста скрыт за маршрутизатором NAT.

Вычислительная нагрузка

NAT имеет достаточно большую вычислительную нагрузку, так как каждый пакет просматривается и модифицируется NAT. Как результат маршрутизатор, может стать достаточно медленным.

3.4.6 Обсуждение безопасности

Часто традиционный NAT рассматривается как однонаправленный фильтр трафика, ограничивающий сессии от внешних хостов к внутренним. Кроме того, при динамическом назначении адресов маршрутизатором NAT атакующему труднее получить доступ к определенному хосту за маршрутизатором. Маршрутизаторы NAT могут использоваться совместно с межсетевыми экранами для фильтрования нежелательного трафика.

Если устройство, выполняющее NAT и ALG, не расположены в доверяемом месте, могут возникнуть серьезные проблемы с безопасностью, так как содержимое трафика можно будет подсмотреть. Содержимое уровня сессии можно зашифровать, но в этом случае оно не должно содержать IP-адреса или идентификаторы транспорта, которые действительны только в одной из областей.

Совмещение возможностей NAT, ALG и межсетевого фильтра обеспечивает прозрачно функционирующее окружение для частного домена. Если будем предполагать, что NAT расположен в доверенном месте, то туннельный режим IPSec может выполняться совместно с маршрутизатором NAT (или в комбинации NAT, ALG и межсетевой экран).

NAT в комбинации с ALG может гарантировать, что дейтаграммы в интернете не содержат частных адресов ни в заголовках, ни в содержимом. Приложения, которые не удовлетворяют этим требованиям, фильтруются межсетевым экраном. По этой причине функции NAT, ALG и межсетевых экранов совмещают для обеспечения безопасности на границе сетевого периметра частной сети. Шлюзы NAT могут использоваться как конечные точки туннелей для обеспечения безопасного транспорта с использованием VPN через внешнюю сеть.

Перечислим некоторые дополнительные характеристики безопасности, связанные с маршрутизаторами NAT.

  1. UDP-сессии по своей сути небезопасны. Ответы на дейтаграммы могут прийти с адреса, отличного от адреса, используемого отправителем. Как результат, входящий UDP-пакет может соответствовать исходящей сессии традиционного маршрутизатора NAT только частично (адрес получателя и номер UDP порта пакета совпадают, а адрес и номер порта источника могут не совпадать). В этом случае существует потенциальная возможность компрометации безопасности в том, что разрешаются частично соответствующие входящие пакеты. Данная проблема безопасности UDP также присуща и межсетевым экранам. Традиционный NAT реализует это, не отслеживая дейтаграммы на уровне сессии, а связывая несколько UDP-сессий, использующих один и тот же адрес, что может привести к компрометации безопасности.
  2. Групповые (Multicast) сессии (основанные на UDP) являются другим слабым местом для маршрутизаторов традиционного NAT. Следует заметить, что межсетевые экраны имеют такую же дилемму, связанную с безопасностью, что и маршрутизаторы NAT. Скажем, хост в частной сети инициализирует групповую сессию. Дейтаграммы, посылаемые частным хостом, могут инициировать ответы в обратном направлении от нескольких внешних хостов. Реализации традиционного NAT, которые используют единственное состояние для отслеживания групповой сессии, не могут определить в общем случае, что входящий UDP-пакет является ответом в существующей групповой сессии или начинает новую UDP-сессию, инициализируемую атакующим.

Устройства NAT могут быть целью атак. Так как устройства NAT являются хостами интернета, они могут быть целью различных атак, таких как SYN flood и ping flood. Устройства NAT должны использовать определенные технологии защиты, как это делают другие серверы интернета.

Понравилась статья? Поделить с друзьями:
  • Сценарий агитбригады мы против террора
  • Сценарий mothers day на английском языке
  • Сценарий академия амбрелла на английском
  • Сценарий агитбригады мы патриоты россии
  • Сценарий modern warfare 2