ipsec nat traversal что это

IPsec NAT Transparency

The IPsec NAT Transparency feature introduces support for IP Security (IPsec) traffic to travel through Network Address Translation (NAT) or Port Address Translation (PAT) points in the network by addressing many known incompatibilities between NAT and IPsec.

Before the introduction of this feature, a standard IPsec virtual private network (VPN) tunnel would not work if there were one or more NAT or PAT points in the delivery path of the IPsec packet. This feature makes NAT IPsec-aware, thereby, allowing remote access users to build IPsec tunnels to home gateways.

Finding Feature Information

Your software release may not support all the features documented in this module. For the latest feature information and caveats, see the release notes for your platform and software release. To find information about the features documented in this module, and to see a list of the releases in which each feature is supported, see the Feature Information Table at the end of this document.

Use Cisco Feature Navigator to find information about platform support and Cisco software image support. To access Cisco Feature Navigator, go to www.cisco.com/go/cfn. An account on Cisco.com is not required.

Restrictions for IPsec NAT Transparency

Although this feature addresses many incompatibilities between NAT and IPsec, the following problems still exist:

Internet Key Exchange (IKE) IP Address and NAT

This incompatibility applies only when IP addresses are used as a search key to find a preshared key. Modification of the IP source or destination addresses by NAT or reverse NAT results in a mismatch between the IP address and the preshared key.

Embedded IP Addresses and NAT

Because the payload is integrity protected, any IP address enclosed within IPsec packets cannot be translated by NAT. Protocols that use embedded IP addresses include FTP, Internet Relay Chat (IRC), Simple Network Management Protocol (SNMP), Lightweight Directory Access Protocol (LDAP), H.323, and Session Initiation Protocol (SIP).

Information About IPsec NAT Transparency

Feature Design of IPsec NAT Traversal

The IPsec NAT Transparency feature introduces support for IPsec traffic to travel through NAT or PAT points in the network by encapsulating IPsec packets in a User Datagram Protocol (UDP) wrapper, which allows the packets to travel across NAT devices. The following sections define the details of NAT traversal:

IKE Phase 1 Negotiation NAT Detection

During Internet Key Exchange (IKE) phase 1 negotiation, two types of NAT detection occur before IKE Quick Mode begins—NAT support and NAT existence along the network path.

To detect NAT support, you should exchange the vendor identification (ID) string with the remote peer. During Main Mode (MM) 1 and MM 2 of IKE phase 1, the remote peer sends a vendor ID string payload to its peer to indicate that this version supports NAT traversal. Thereafter, NAT existence along the network path can be determined.

Detecting whether NAT exists along the network path allows you to find any NAT device between two peers and the exact location of NAT. A NAT device can translate the private IP address and port to public value (or from public to private). This translation changes the IP address and port if the packet goes through the device. To detect whether a NAT device exists along the network path, the peers should send a payload with hashes of the IP address and port of both the source and destination address from each end. If both ends calculate the hashes and the hashes match, each peer knows that a NAT device does not exist on the network path between them. If the hashes do not match (that is, someone translated the address or port), then each peer needs to perform NAT traversal to get the IPsec packet through the network.

The hashes are sent as a series of NAT discovery (NAT-D) payloads. Each payload contains one hash; if multiple hashes exist, multiple NAT-D payloads are sent. In most environments, there are only two NAT-D payloads—one for the source address and port and one for the destination address and port. The destination NAT-D payload is sent first, followed by the source NAT-D payload, which implies that the receiver should expect to process the local NAT-D payload first and the remote NAT-D payload second. The NAT-D payloads are included in the third and fourth messages in Main Mode and in the second and third messages in Aggressive Mode (AM).

IKE Phase 2 Negotiation NAT Traversal Decision

While IKE phase 1 detects NAT support and NAT existence along the network path, IKE phase 2 decides whether or not the peers at both ends will use NAT traversal. Quick Mode (QM) security association (SA) payload in QM1 and QM2 is used to for NAT traversal negotiation.

Because the NAT device changes the IP address and port number, incompatibilities between NAT and IPsec can be created. Thus, exchanging the original source address bypasses any incompatibilities.

UDP Encapsulation of IPsec Packets for NAT Traversal

In addition to allowing IPsec packets to traverse across NAT devices, UDP encapsulation also addresses many incompatibility issues between IPsec and NAT and PAT. The resolved issues are as follows:

Incompatibility Between IPsec ESP and PAT—Resolved

If PAT found a legislative IP address and port, it would drop the Encapsulating Security Payload (ESP) packet. To prevent this scenario, UDP encapsulation is used to hide the ESP packet behind the UDP header. Thus, PAT treats the ESP packet as a UDP packet, processing the ESP packet as a normal UDP packet.

Читайте также:  что делать если вай фай плохо грузит на компе
Incompatibility Between Checksums and NAT—Resolved

In the new UDP header, the checksum value is always assigned to zero. This value prevents an intermediate device from validating the checksum against the packet checksum, thereby, resolving the TCP UDP checksum issue because NAT changes the IP source and destination addresses.

Incompatibility Between Fixed IKE Destination Ports and PAT—Resolved

PAT changes the port address in the new UDP header for translation and leaves the original payload unchanged.

To see how UDP encapsulation helps to send IPSec packets see the figures below.

Figure 1 Standard IPsec Tunnel Through a NAT/PAT Point (No UDP Encapsulation)

Figure 2 IPsec Packet with UDP Encapsulation

UDP Encapsulated Process for Software Engines Transport Mode and Tunnel Mode ESP Encapsulation

After the IPsec packet is encrypted by a hardware accelerator or a software crypto engine, a UDP header and a non-IKE marker (which is 8 bytes in length) are inserted between the original IP header and ESP header. The total length, protocol, and checksum fields are changed to match this modification. The first figure below shows an IPsec packet before and after transport mode is applied; the second figure below shows an IPsec packet before and after tunnel mode is applied.

Figure 3 Transport Mode—IPsec Packet Before and After ESP Encapsulation

Figure 4 Tunnel Mode—IPsec Packet Before and After ESP Encapsulation

NAT Keepalives

NAT keepalives are enabled to keep the dynamic NAT mapping alive during a connection between two peers. NAT keepalives are UDP packets with an unencrypted payload of 1 byte. Although the current dead peer detection (DPD) implementation is similar to NAT keepalives, there is a slight difference: DPD is used to detect peer status, while NAT keepalives are sent if the IPsec entity did not send or receive the packet at a specified period of time—valid range is between 5 to 3600 seconds.

If NAT keepalives are enabled (through the crypto isamkp nat keepalive command), users should ensure that the idle value is shorter than the NAT mapping expiration time, which is 20 seconds.

Источник

IPIP IPsec VPN туннель между Linux машиной и Mikrotik за NAT провайдера

upd: Отличный разбор про устройство современного стэка IPsec протоколов ESPv3 и IKEv2 опубликовал stargrave2. Рекомендую почитать.

Linux: Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64)

Mikrotik: CCR 1009, RouterOS 6.46.5

IPsec туннель на Linux машине будем поднимать с помощью racoon. Не буду описывать подробности, есть хорошая статья у vvpoloskin.

Устанавливаем необходимые пакеты:

Настраиваем racoon, он условно будет выступать в роли ipsec сервера. Так как mikrotik в main режиме не может передавать дополнительный идентификатор клиента, а внешний ip адрес через который он коннектится к Linux динамический, использовать preshared key (авторизацию по паролю) не получится, так как пароль должен сопоставляться либо с ip адресом подключающегося хоста, либо с идентификатором.

Будем использовать авторизацию по RSA ключам.

Демон racoon использует ключи в формате RSA, а mikrotik — в формате PEM. Если генерировать ключи утилитой plainrsa-gen идущей вместе с racoon, то конвертировать публичный ключ для Mikrotika в формат PEM с ее помощью не получится — она конвертирует только в одну сторону: PEM в RSA. Сгенерированный plainrsa-gen ключ не смогли прочитать ни openssl, ни ssh-keygen, поэтому с их помощью также не получится выполнить конвертацию.

Мы сгенерируем PEM ключ с помощью openssl, а затем конвертируем его для racoon с помощью plainrsa-gen:

Полученные ключи положим в папку: /etc/racoon/certs/server. Не забываем установить владельцем пользователя, от чьего имени запускается демон racoon (обычно root), права 600.

Настройку mikrotik опишу при подключении через WinBox.

Ключ server-name.pub.pem загрузим в mikrotik: Меню «Files» — «Upload».

Открываем раздел «IP» — «IP sec» — вкладка «Keys». Теперь генерируем ключи — кнопка «Generate Key», затем экспортируем публичный ключ mikrotika «Expor Pub. Key», скачать его можно из раздела «Files», правой кнопкой по файлу — «Download».

Импортируем публичный ключ racoon, «Import», в выпадающем списке поля «File name» ищем загруженный ранее нами server-name.pub.pem.

Публичный ключ mikrotik нужно сконвертировать

и положить в папку /etc/racoon/certs не забыв про владельца и права.

Возвращаемся в раздел «IP» — «IPsec»

Вкладка «Profiles»
Параметр
Значение
Name На ваше усмотрение (по умолчанию default)
Hash Algorithm sha512
Encryption Algorithm aes-128
DH-Group modp2048
Proposhal_check claim
Lifetime 1d 00:00:00
NAT Traversal true (ставим галочку)
DPD 120
DPD Maximum failure 5
Вкладка «Peers»
Параметр
Значение
Name На ваше усмотрение (далее MyPeer)
Address 1.1.1.1 (IP linux машины)
Local Address 10.0.0.2 (IP WAN интерфейса mikrotik)
Profile default
Exchange Mode main
Passive false
Send INITIAL_CONTACT true
Вкладка «Proposal»
Параметр
Значение
Name На ваше усмотрение (далее MyPeerProposal)
Auth. Algorithms sha512
Encr. Algorithms aes-128-cbc
Lifetime 08:00:00
PFS Group modp2048
Вкладка «Identities»
Параметр
Значение
Peer MyPeer
Atuh. Method rsa key
Key mikrotik.privet.key
Remote Key server-name.pub.pem
Policy Tamplate Group default
Notrack Chain пусто
My ID Type auto
Remote ID Type auto
Match By remote id
Mode Configuration пусто
Generate Policy no
Вкладка «Policies — General»
Параметр
Значение
Peer MyPeer
Tunnel true
Src. Address 192.168.0.0/30
Dest. Address 192.168.0.0/30
Protocol 255 (all)
Template false
Вкладка «Policies — Action»
Параметр
Значение
Action encrypt
Level requier
IPsec Protocols esp
Proposal MyPeerProposal

Скорее всего у вас, как и у меня, на WAN интерфейсе настроен snat/masquerade, это правило надо скорректировать, чтобы исходящие пакеты ipsec уходили в наш туннель:
Переходим в раздел «IP» — «Firewall».
Вкладка «NAT», открываем наше правило snat/masquerade.

Рестартуем демона racoon

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

Демон racoon при загрузке ОС стартует раньше поднятия сетевых интерфейсов, а мы указали в секции listen опцию strict_address, необходимо добавить в файл systemd юнита racoon
/lib/systemd/system/racoon.service, в секцию [Unit], строку After=network.target.

Сейчас наши ipsec туннели должны подняться, смотрим вывод:

Теперь необходимо настроить L3 интерфейсы, чтобы можно было маршрутизировать трафик. Есть разные варианты, мы будем использовать IPIP, так как его mikrotik поддерживает, я бы использовал vti, но, к сожалению, в mikrotik его до сих пор не реализовали. От IPIP он отличается тем, что дополнительно может инкапсулировать multicast и ставить метки (fwmark) на пакеты, по которым можно их фильтровать в iptables и iproute2 (policy-based routing). Если нужна максимальная функциональность — тогда, например, GRE. Но не стоит забывать, что за дополнительную функциональность платим большим оверхедом.

Перевод неплохого обзора туннельных интерфейсов можно посмотреть тут.

На Linux:

Теперь можно добавить маршруты для сетей за mikrotik

Чтобы наш интерфейс и маршруты поднимались после перезагрузки, нужно описать интерфейс в /etc/network/interfaces и там же в post-up добавлять маршруты, либо прописать все в одном файле, например, /etc/ipip-ipsec0.conf и дергать его через post-up, не забудьте про владельца файла, права и сделать его исполняемым.

На Mikrotik:

Раздел «Interfaces», добавляем новый интерфейс «IP tunnel»:

Вкаладка «IP tunnel» — «General»
Параметр
Значение
Name На ваше усмотрение (далее IPIP-IPsec0)
MTU 1480 (если не указывать, то mikrotik начинает резать mtu до 68)
Local Address 192.168.0.2
Remote Address 192.168.0.1
Ipsec Secret Деактивируем поле (иначе будет создан новый Peer)
Keepalive Деактивируем поле (иначе интерфейс будет постоянно выключаться, так как у mikrotika какой-то свой формат этих пакетов и с linux не работает)
DSCP inherit
Dont Fragment no
Clamp TCP MSS true
Allow Fast Path true

Раздел «IP» — «Addresses», добавляем адрес:

Теперь можно добавлять маршруты в сети за linux машиной, при добавлении маршрута, gateway будет наш интерфейс IPIP-IPsec0.

Так как наш сервер linux является транзитным, то на нем имеет смысл задать параметр Clamp TCP MSS для ipip интерфейсов:

создаем файл /etc/iptables.conf со следующим содержимым:

и в /etc/network/interfaces
post-up iptables-restore

Источник

NAT traversal

Протокол NAT Traversal (NAT-T) инкапсулирует трафик IPSec и одновременно создает пакеты UDP, которые NAT корректно пересылает. Для этого NAT-T помещает дополнительный заголовок UDP перед пакетом IPSec, чтобы он во всей сети обрабатывался как обычный пакет UDP и хост получателя не проводил никаких проверок целостности. После поступления пакета к месту назначения заголовок UDP удаляется, и пакет данных продолжает свой дальнейший путь как инкапсулированный пакет IPSec. Итак, с помощью техники NAT-T возможно установление связи между клиентами IPSec в защищённых сетях и общедоступными хостами IPSec через межсетевые экраны.

Смотреть что такое «NAT traversal» в других словарях:

NAT traversal — is a general term for techniques that establish and maintain Internet protocol connections traversing network address translation (NAT) gateways. Network address translation breaks end to end connectivity. Intercepting and modifying traffic can… … Wikipedia

Traversal Using Relay NAT — (TURN) is a protocol that allows for an element behind a NAT or firewall to receive incoming data over TCP or UDP connections. It is most useful for elements behind symmetric NATs or firewalls that wish to be on the receiving end of a connection… … Wikipedia

NAT Port Mapping Protocol — (NAT PMP) is an Internet Engineering Task Force Internet Draft, introduced by Apple Computer as an alternative to the more common Internet Gateway Device (IGD) Standardized Device Control Protocol implemented in many network address translation… … Wikipedia

NAT-T — (NAT traversal in the IKE) is a method of enabling IPsec protected IP datagrams to pass through network address translation (NAT). RFC 3947 defines the negotiation during the Internet key exchange (IKE) phase and RFC 3948 defines the UDP… … Wikipedia

NAT transversal — Este artículo está huérfano, pues pocos o ningún artículo enlazan aquí. Por favor, introduce enlaces hacia esta página desde otros artículos relacionados … Wikipedia Español

Traversal Using Relays around NAT — TURN redirects here. For other uses, see Turn (disambiguation). Traversal Using Relays around NAT (TURN) is a protocol that allows for an element behind a Network address translator (NAT) or firewall to receive incoming data over TCP or UDP… … Wikipedia

Traversal Using Relay NAT — Необходимо проверить качество перевода и привести статью в соответствие со стилистическими правилами Википедии. Вы можете помочь улучшить эту статью, исправив в ней ошибки. Оригинал на английском языке … Википедия

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

NAT-T — En réseau informatique, NAT T (NAT traversal dans le cadre de l IKE) est une méthode permettant aux datagrammes IPsec de traverser un NAT. En effet, le NAT repose sur les ports des couches 4 (UDP ou TCP) pour discriminer entre les différents flux … Wikipédia en Français

NAT-Router — Dieser Artikel oder Abschnitt bedarf einer Überarbeitung. Näheres ist auf der Diskussionsseite angegeben. Hilf mit, ihn zu verbessern, und entferne anschließend diese Markierung. Network Address Translation (NAT) ist in Rechnernetzen der… … Deutsch Wikipedia

Источник

Ipsec nat traversal что это

Продукты, решения и услуги для организаций

IPsec NAT Traversal

However, a new incompatibility problem arises. When the NAT changes the IP address and (or) port number in a packet, the NAT generally updates the TCP or UDP checksum. If the TCP or UDP checksum is encrypted by ESP, the NAT cannot update the checksum.

Processing of IPsec NAT traversal

IKEv2 and NAT Traversal

NAT-T Capability Detection

The NAT-T capability detection is performed by inserting a Vendor ID payload that identifies the NAT-T capability in the first two IKE negotiation messages. If both parties insert the payload in the messages sent to the peer party, both parties support the NAT-T. Other negotiations can be performed only when both parties support the NAT-T.

NAT Gateway Discovery

When NAT devices exist, data must be transmitted by using UDP. Therefore, at the first phase of IKEv2 negotiation, NAT devices must be detected.

The popular method for detecting NAT devices is to send the NAT-D payload.

In the IKE protocol, the NAT-D payload is contained in the third and fourth messages in main mode and the second and the third messages in aggressive mode. For the parties that create the VPN connection, a message generally contains two consecutive NAT-D payloads. The first NAT-D payload contains the destination IP address and the second contains the source IP address. The sender has several interfaces and the application program does not know through which interface the data packets go out. If the sender does not know its exact IP address, more NAT-D payloads are needed. Except the first payload, each of the payloads contains an IP address of the sender. After receiving the NAT-D payloads, the two parties compute and compare the hash values based on the actual IP addresses and port numbers to decide whether there is a NAT device and which party is behind the NAT device. This method can detect whether NAT devices exist between two IKE parties, but it has obvious defects. In main mode and aggressive mode, the NAT-D payloads are not authenticated. Therefore, attackers can delete, change, or add payloads to launch DoS attacks. By changing the NAT-D payloads, the attackers can induce the two parties to adopt the UDP encapsulation mode rather than the normal mode. As a result, bandwidths may be wasted.

To correct the preceding defects, two Notify payloads can be added for IKE of both negotiation parties. One Notify payload contains NAT_DETECTION_SOURCE_IP, which identifies the IP address of the sender. The other Notify payload contains NAT_DETECTION_DESTINATION_IP, which identifies the IP address of the receiver. The two Notify payloads mainly help to detect NAT devices and decide which party is behind NAT devices.

This is accomplished during the first message exchange of IKEv2 negotiation. The specific process is as follows:

In IKEv2, the number of NAT_DETECTION_SOURCE_IP is 16388 and the number of NAT_DETECTION_DESTINATION_IP is 16389 in the Notify messages. The payloads use the generic ISAKMP payload header. The values of the payloads are the hash values (IKEv2 uses SHA-1) of SPIs, IP addresses, and numbers of the ports for sending data packets. The hash value is computed as follows: hash = SHA-1 (SPIs|IP|Port).

SPI indicates the security parameter index in the HDR payload.

IP indicates the IP address of the sender or receiver of data packets.

Port indicates the port number of the sender or receiver of data packets.

When the receiver receives a data packet, it computes the hash value with the SPIs, IP address, and port number in the packet. Then it compares the hash value with that of the Notify payload. If the hash values do not match, it indicates that a NAT device exists in the communications link. If the hash value does not match that of NAT_DETECTION_SOURCE_IP, it indicates that the sender is behind the NAT device. If the hash value does not match that of NAT_DETECTION_DESTINATION_IP, it indicates that the receiver is behind the NAT device.

Enabling the NAT Traversal

After the phase-1 negotiation is complete, both parties are clear about whether a NAT device exists between them and the NAT device position. The quick negotiation mode determines whether to enable the NAT traversal.

The negotiation enabling for NAT traversal is performed using the SA payload in quick mode. In transport mode, both parties send the original address of the IPsec packet during the negotiation, so that the peer party can check and rectify the TCP or IP header if the NAT is performed.

NAT-keepalive

A NAT session has a certain survival period on the NAT gateway. After a tunnel is established, if no packet traverses the gateway for a long period of time, the NAT session is deleted. As a result, data cannot be transmitted over the tunnel. A NAT-keepalive message can be sent to the peer party before the NAT session expires to maintain the NAT session and address the preceding issue.

Источник

Читайте также:  какой камень похож на янтарь
Сказочный портал