Всем привет! Сегодня мы поговорим про то, что же такое NAT в роутере. Как вы, наверное, все знаете, большинство адресов в интернете использует IPv4 версию. Эти адреса имеют диапазон от 0.0.0.0 до 255.255.255.255. Если подсчитать, то у нас есть больше 4-х миллиардов айпишников. Вроде бы достаточно много, но на деле с ростом клиентов интернета свободных адресов почти уже не осталось. Приплюсуем сюда тот факт, что многие IP зарезервированы, а на планете активно развивается мобильный интернет, который забирает львиную долю IPv4.
Но как получается всем подключаться к интернету и не оставаться в стороне? – Для этих целей и используется NAT (Network Address Translation – трансляция сетевых адресов). А теперь о самой сетевой технологии более подробно в статье.
Содержание
- Что такое NAT и как работает и зачем он нужен
- Термины NAT
- Типы NAT
- Статический (Static) NAT
- Динамический (Dynamic) NAT
- PAT (Port Address Translation)
- Плюсы и минусы IP NAT
- Видео
- Как настроить и включить NAT на роутере
- Задать вопрос автору статьи
Если у вас есть дома роутер, то вы уже используете технологию 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.
Схема достаточно простая, давайте рассмотрим пример.
- Компьютер из домашней сети с ИП 192.168.1.10 отправил запрос на какой-то сайт.
- Запрос пришел на роутер (192.168.1.1).
- Роутер не может использовать свой локальный адрес, поэтому переводит запрос и использует внешний адрес.
- Сайт получает запрос с внешним IP и на него отсылает ответ.
- Роутер принимает ответ от сайта, и уже отправляет его на компьютер, но уже используя внутренний айпишник.
Как видите, NAT постоянно переводит внутренний адрес во внешний и обратно. Если локальная сеть имеет только один выходной маршрутизатор, который может быть связан с внешней сетью, то такую сеть называют Stub сетью.
Термины NAT
В сфере NAT есть различная терминология, которую вы можете встретить в настройках маршрутизатора или на схемах подключения.
Есть 4 вида NAT адресов:
- Insidelocal – внутренний локальный адрес, который прописывается в первичном запросе от клиента.
- Insideglobal – внешний айпишник роутера.
- Outsidelocal – внутренний глобальный адрес сервера в интернете. Внутренний он, потому что он прописывается в первичном запросе от компьютера во внутренней сети.
- Outsideglobal – внешний глобальный. IP запроса на конечный сервер, который записан во внешнем запросе от роутера.
Пока ничего не понятно? Сейчас постараюсь рассказать на примере. Давайте рассмотрим пример NAT адресации. Смотрим на картинку ниже.
- У нас есть компьютер с (Inside Local) адресом 192.168.0.30, который находится с домашней сети.
- Он посылает запрос на сервер с (Outside Local) адресом 246.10.79.235.
- Маршрутизатор принимает ответ и переводит запрос:
(Inside Local) 192.168.0.30 -> (Outside Local) 246.10.79.235
В
(Inside Global) 135.87.99.202 -> (Outside Global) 246.10.79.235
- Когда сервер получает запрос, он отсылает ответ и все запросы переделываются в обратном порядке. Чтобы роутеру было понятно от кого пришел ответ и кому отправить запрос, он все данные записывает в свою таблицу маршрутизации.
Типы NAT
Статический (Static) NAT
Статический NAT – это когда у каждого локального внутреннего адреса, есть свой глобальный адрес. Часто используется для Web-серверов. Весь трафик при этом проходит аналогично через один узел, и у каждого устройства есть свой как локальный, так и глобальный IP.
Динамический (Dynamic) NAT
У нас есть пул внутренних айпишников, который постоянно присваивается разные глобальные внешние адреса. Внешние IP присваиваются по принципу, какой есть свободный, тот и назначается маршрутизатором. Очень часто используется в городских сетях провайдерами, именно поэтому ваши глобальные IP постоянно меняются. Чтобы немного расширить эту тему, советую более подробно почитать про белые и серые IP.
PAT (Port Address Translation)
Самая популярная форма NAT. Про неё я в самом начале и говорил. Когда нескольким локальным адресам назначается один глобальный. То есть когда вся семья, грубо говоря, использует один внешний IP. Чтобы маршрутизатор понял, кому именно посылать ответ от сервера, на который ранее был запрос, он использует в своем запросе номер порта. И по нему отсылает ответ нужному локальному пользователю.
Посмотрите на картинку выше. Как видите при запросе на выделенный сервер, помимо того, что роутер переводит адреса, он еще в запросе добавляет номер порта. То есть ответ от сервера также имеет этот порт, который потом уже используется для того, чтобы ответ получил нужный компьютер.
Плюсы и минусы IP NAT
- Офисы, а также домашние сети при большом количестве клиентов могут использовать всего один или несколько внешних интернет-адресов.
- Повышается надежность локальной сети, где контроль за пропускной способностью и трафиком отслеживает роутер.
- Снижает стоимость, которая нужна для приобретения внешних IP.
- Контроль внешнего и внутреннего доступа к обоим сетям.
- Увеличивается задержка запроса, так как маршрутизатору нужно постоянно делать NAT перевод адресов.
- В больших сетях, где идет многоуровневая NAT адресация, сложно найти место поломки, так как IP постоянно изменяется.
Видео
Если вам что-то было не понятно, или вам лень читать, то советую посмотреть это полезное видео.
Как настроить и включить NAT на роутере
Стандартный NAT уже работает в режиме PAT и его настраивать не нужно. То есть вы просто настраиваете интернет и Wi-Fi на маршрутизаторе. Другой вопрос, если дома вы решили организовать Web, игровой или почтовый сервер. А быть может вы хотите подключить камеры видеонаблюдения и следить за домом или квартирой, отдыхая на Бали. Вот тут нам понадобится проброс портов – об смотрите статью про порты. Там коротко рассказано, что такое порты, для чего они нужны и как их пробросить.
Network Address Translation (NAT) is a service that enables private IP networks to use the internet and cloud. NAT translates private IP addresses in an internal network to a public IP address before packets are sent to an external network.
- Connect with NAT
How can organizations benefit from NAT?
Organizations managing multicloud architectures need NAT to connect their private IP networks to the internet and cloud.
Whether you access or deliver cloud services, NAT translates IP addresses for users who are logging in to these cloud services from on-premises and remote locations.
- Managing multicloud networks
Carrier-grade NAT
Carrier-grade network address translation, known also as CGN or CGNAT, translates IP addresses at a much larger scale, often handling tens of millions NAT translations. Service providers and companies with large-scale networks rely on CGN for internet and cloud connectivity. As a result, CGN should be supported by a capable platform that can serve high-scale demands.
NAT444 for service providers
Service providers using CGN may also employ a NAT444 architecture as a strategy to manage a waning IPv4 supply.
With NAT444, customer connections to internet services and the cloud can pass through three different IPv4 addressing domains: the customer’s private network, the carrier’s private network, and the public internet.
- See how we deliver NAT
High Availability (HA)
Many organizations seek greater reliability as their architectures expand to include the cloud. This is where NAT High Availability features can help.
Stateless and stateful NAT HA
When a standby NAT router or edge platform is unaware of the translations that an active NAT router or edge platform performs, it’s called stateless redundancy.
Stateless NAT HA provides fast switchover between active and standby routers due to faults that may occur in any part of the network. With stateless HA, the applications traffic has to re-create NAT translation in a new active router.
With stateful NAT HA, a standby router or edge platform knows all the translations that the active NAT router is performing. If an adverse event impacts the active router and traffic must switch to the standby router, then the standby router won’t need to re-create the translation. This enables sessions to continue sending traffic from new active router.
NAT64
NAT64 is an IPv6 transition technology that supports the translation of an IPv6 network address into an IPv4 address.
There are stateless and stateful versions of NAT64:
- Stateless NAT64: This mechanism is stateless because it doesn’t maintain any bindings or session state while performing address translation, and it supports both IPv6-initiated and IPv4-initiated communications. (A binding is a one-to-one association between a private IP address and its translated public IP address.)
- Stateful NAT64: This mechanism is stateful because it creates or modifies session state or bindings while performing address translation. Stateful NAT64 supports both IPv6-initiated and IPv4-initiated communications using static or manual mappings.
Interchassis redundancy
Organizations that use stateful NAT64 may also choose to employ interchassis redundancy. This is the process of configuring pairs of devices to act as hot standbys for each other. It creates redundancy at the application level and provides reliability. These pairs are known as redundancy groups and are ready to run application activity whenever they’re needed.
- Read about edge solutions
What are application-level gateways (ALGs)?
Application-level gateways are applications that translate IP address information inside the payload of an application packet. They can be used to perform NAT and firewall actions, depending on configurations.
ALGs that are configured to perform NAT and firewall actions can:
- Allow client applications to use dynamic TCP or UDP ports to communicate with a server app
- Recognize application-specific commands and offer granular security control over those commands
- Synchronize multiple streams or sessions of data between two hosts that are exchanging data
- Translate network-layer address information available in an application’s payload
ALG: A helper for NAT
Not all internet protocols carry source and destination IP addresses in an application data stream. Examples include HTTP, Network Time Protocol (NTP), remote login (rlogin), and remote copy (rcp). NAT can perform translation services on these types of protocols.
However, NAT needs ALG support when it encounters specific protocols that embed IP address information within the payload. In fact, NAT requires various ALGs to handle application data stream (Layer 7) protocol-specific services, such as translating embedded IP addresses and port numbers in the packet payload and extracting new connection and session information from control channels.
ALG also supports stateful NAT translation. For example, Session Initiation Protocol (SIP) files must be handled with special care when translated because they have control and data communication components associated with the same user transaction. These files can signal to routers when to set up voice and multimedia over IP networks.
An ALG needs to be used with NAT to translate the embedded protocol messages and keep the control and data components bound together.
- Explore ALG in NAT
High-speed logging
Today’s NAT technology can support high-speed logging (HSL) for multiple destinations. And leading NAT solutions can support tens of millions of translations on one data plane. This type of speed and volume for message logging isn’t possible using the traditional syslog logging standard.
HSL, when configured, can enable NAT to provide a log of the packets flowing through routing devices to an external collector. Records are sent for each binding created by NAT and also when sessions are created or destroyed. The session records include necessary tracking information such as source IP address, destination IP address, source port, destination port, and protocol information, and more importantly, event time and type.
NAT high-speed logging records can be invaluable documentation for investigations of illegal or other malicious or problematic activity on a network.
Доброго времени суток, уважаемые гости. Сегодня поговорим о NAT: что это в роутере за функция, можно ли обойтись без нее, обязательно ли нужно включать и как открыть NAT своего роутера.
Об адресации в локальной сети
Компьютер может подключаться к глобальной паутине несколькими способами. Если это выполняется напрямую, он получает собственный динамический или статистический IP адрес, по которому его можно всегда найти.
При подключении с помощью модема, собственный внешний IP адрес получает только модем (как вариант, маршрутизатор со встроенным модемом), все прочие девайсы уже являются участниками собственной локальной сети и получают адресацию внутри нее.
Роутер берет на себя функцию распределения исходящего и входящего трафика между шлюзом и клиентами интернета. Из-за нестыковки сетевых адресов, возможны некоторые глюки:
- Некорректно работают торрент-загрузчики и прочий софт для пилинговых сетей;
- Не всегда удается подключиться к серверу онлайн игры, особенно если он пиратский;
- Не проходят запросы извне к серверу внутри локальной сети.
Эти недостатки можно устранить при правильной настройке на маршрутизаторе.
Что такое режим NAT
Если совсем простыми словами, то НАТ – это интерпретация внутренних сетевых адресов локалки во внешние адреса интернета. Независимо от модели, стоимости и используемого протокола подключения эта функция присутствует абсолютно во всех роутерах.
Разница может быть только в наличии или отсутствии дополнительной опции nat loopback (обратная петля), когда пакет из локальной сети, приходящий на внешний порт маршрутизатора, считается пришедшим извне, поэтому обрабатывается согласно установленным брандмауэром или антивирусной программой сценариям.Как правило, нет необходимости отдельно включить NAT при настройке маршрутизатора: функция активна по умолчанию.
Более того, часто отключить аппаратный NAT невозможно: производитель убирает эту опцию в качестве «защиты от дурака», дабы слишком любопытный пользователь, который любит поиграть с настройками, не особо в них разбираясь, вообще не остался без интернета.
По умолчанию маршрутизатор находится в nat окружении, запрещая извне обращаться к девайсу внутри локалки: весь трафик проходит только через него.
Как определить, находится ли компьютер за NAT
Проверить, скрыт ли компьютер с помощью режима NAT или транслирует в сеть свой реальный IP, можно с помощью простого способа.
Выполняется он аналогично в любой версии Виндовс – запустить командную строку (нажать кнопку «Пуск» и в строке «Выполнить» ввести команду cmd). В открывшемся интерфейсе следует вручную ввести команду ipconfig. На экран выведутся такие данные:
- IP – реальный адрес, присвоенный компьютеру;
- Subnet mask – маска подсети;
- Gateway – адрес шлюза.
Согласно принятой спецификации, исключительно внутри локалки всегда используются следующие диапазоны:
- 10.0.0.0 – 10.255.255.255;
- 172.Х.0.0 – 172.Х.255.255 (Х в диапазоне от 16 до 32);
- 192.168.0.0 – 192.168.255.255;
- 196.254.0.0. – 169.254.255.255.
Если адрес компьютера попадает в один из этих диапазонов, то это означает, что устройство находится в локальной сети за НАТом. Самый распространенный пример – адрес 192.168.1.Х – именно такой диапазон используется для роутера и подсети большинством производителей.
Где найти в настройках маршрутизатора
Относительно того, нужно ли включать эту опцию дополнительно, то могу сказать что в большинстве моделей маршрутизаторов вай-фай она активирована по умолчанию. Проверить или настроить самостоятельно это можно, перейдя в браузере на страницу настроек роутера – как правило, для этого нужно ввести его сетевой адрес.
Нужная функция находится во вкладке Network в разделе Routing. Если она включена, то статус будет отображаться как Enable.
Также для вас будут полезны статьи «UPNP – что такое в роутере» и «Устройство роутера». Буду благодарен всем, кто поделится этой публикаций в социальных сетях. Еще увидимся!
С уважением, автор блога Андрей Андреев.
В этой статье поговорим про NAT в Mikrotik.
NAT (Network Address Translation) – это процедура изменения либо адреса источника (Source address), либо адреса назначения (Destination Address) в заголовке пакета.
Зачем мы используем NAT и с чем связано вообще использование NAT?
Дело в том, что ipv4 имеет ограниченное количество ip-адресов, и это было понятно изначально при разработке протокола ipv4. Уже к 1994 году стало понятно, что необходимо как-то выпутываться из сложившейся ситуации (не было альтернативного протокола, который мог бы расширить количество ip-адресов). Присутствовал только старый IPv4, а количество устройств в сети Интернет росло, росло, росло и, собственно, продолжает расти до сих пор. Поэтому, для начала придумали RFC1918, который описывает использование не маршрутизируемых сетей в локальных сегментах – таких как: 192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12 (так называемые «серые» адреса).
Использование этих диапазонов разрешено кем угодно внутри своих локальных сетей. В глобальной сети Интернет эти адреса не маршрутизируются.
Если вы используете эти адреса и нужно попасть в глобальную сеть Интернет, Вам нужно провести автоматическое изменение либо адреса источника пакета, либо адреса назначения пакета – для этого и существует NAT.
- В нашем случае на Mikrotik не совсем чистый NAT. Это Port Address Translation, то есть PAT, где используются не только IP адреса (3 уровень OSI), но также еще и с 4 уровнем OSI — есть 5 полей для изменения адреса:
- Source Address
- Destination Address
- Source Port
- Destination Port
- Протокол
Для чего используется NAT?
Самое частое использование — это доступ из локальной сети с серыми адресами куда-то в интернет.
Открыть доступ из внешней сети к ресурсам (напр., веб-сервер) находящимся во внутренней сети (так называемый «проброс портов»).
При «пробросе портов» для хоста с приватным IP-адресом, когда пакет проходит правила на маршрутизаторе, у пакета изменяется Source адрес пакета и до публичного адреса отправляется пакет с внешним адресом, который может прекрасно маршрутизироваться в глобальной сети Интернет. Такая ситуация называется Source Nat. В Mikrotik можно посмотреть, что есть дефолтное правило, которое реализует данную функцию.
Это правило находится в IP – Firewall — NAT (раздел NAT отвечает за преобразование адресов и портов, заголовках пакетов, сегментах, дейтаграммах и так далее).
В данном случае правило Source NAT — процедура изменения в заголовке пакета адреса (например, адреса локальной сети), где есть условие, что пакет, идущий в сторону Out interface List – WAN (в сторону интернета) и Action — masquerade.
Masquerade — это автоматическое выяснение внешнего ip-адреса, с которым будет идти через «внешний» Out interface и подставление его в заголовки пакета.
Если внешний ip-адрес статический, то более выгодно использовать процедуру Source NAT.
Можно посмотреть, что на внешнем интерфейсе ip-адрес 198.51.100.16 и использовать его в качестве правила Source Nat — это будет эффективнее по производительности, т.к. роутеру не понадобится выяснять внешний адрес на внешнем интерфейсе.
Или вторая процедура, которая описывается как DST-NAT и для ее работы используются цепочка DSTNAT — это процедура, например, для проброса портов с внешнего интерфейса во внутреннюю (локальную) сеть.
Или, например, внутри локальной сети есть какой-то веб-сервер, который слушает TCP 80 порт и нужно, чтобы он был доступен из интернета. Только вот, если сказать адрес сервера 192.168.88.2, никто не сможет получить доступ к веб-серверу.
Нужно сделать правило, которое будет решать вопрос доступа из внешней сети во внутреннюю сеть.
Для этого нужно создать правило — цепочка DSTNAT, протокол TCP, Destination Port – 80, In interface List – WAN (внешний). (можно использовать In interface, если наличие интернета только на одном интерфейсе), Action – dst-nat на IP-адрес 192.168.88.2
/ip firewall nat
add action=dst-nat chain=dstnat dst-port=80 in-interface-list=WAN protocol=tcp to-addresses=192.168.88.2 to-ports=80
Если служба запущена на 80 порту, то в Action — dst-nat, to Ports не нужно указывать 80 порт, т.к. это, по сути, будет повторение одного и того же действия. Роутер будет в заголовках сегмента 4 уровня менять TCP 80 на TCP 80, что немножко повлияет на производительность. Поэтому, в ситуации прямого проброса, нужно убрать поле to ports.
В другой ситуации, когда внешний 80 порт нужно пробросить на внутренний 8080, тогда поле to ports нужно заполнить.
Также можно пробросить несколько портов, например, 80, 443, 8080 и тд.
В данном случае не нужно указывать to ports, проброс будет осуществляться с порта на порт. То есть – с 80 на 80, с 443 на 443, с 8080 на 8080.
/ip firewall nat
add action=dst-nat chain=dstnat dst-port=80,443,8080 in-interface=WAN protocol=tcp to-addresses=192.168.88.2
Если нужно пробросить все эти порты на один порт, то нужно указать в to ports нужный порт.
При пробросе портов и при стандартной настройке файрволла не нужно добавлять дополнительные правила в цепочку Filter. Правило forward, запрещающее доступ из внешнего интерфейса, решает вопрос с пробросом портов «кроме DST-NAT»
Если необходимо разрешать это все дело в файрволле, например, для производительности или, если не используется в правиле «кроме DST Nat» в Drop Forward и на Interface list WAN (внешний), то необходимо писать правила, которые будут разрешать проброшенные порты с внешнего интерфейса и указать порты, которые открыты на веб-сервере (все те порты, на которые нужно пробросить с внешнего интерфейса).
Например, если пробрасывается внешний порт TCP 8080 на порт внутренний TCP 80, то в Forward нужно указать порт TCP 80.
/ip firewall nat
add action=dst-nat chain=forward dst-port=80 in-interface=WAN protocol=tcp to-addresses=192.168.88.2 to-ports=8080
Это все связано с тем, что правила dst-nat отрабатывают до firewall filter и сначала изменяются в заголовках 4 уровня и адреса, и порты, а потом пакет попадает в firewall. Это всё связано работой Packet Flow diagram Mikrotik RouterOS.
На этом знакомство с NAT в Mikrotik завершено.
Introduction
Network Address Translation is an Internet standard that allows hosts on local area networks to use one set of IP addresses for internal communications and another set of IP addresses for external communications. A LAN that uses NAT is ascribed as a natted network. For NAT to function, there should be a NAT gateway in each natted network. The NAT gateway (NAT router) performs IP address rewriting on the way packet travel from/to LAN.
Nat matches only the first packet of the connection, connection tracking remembers the action and performs on all other packets belonging to the same connection.
Whenever NAT rules are changed or added, the connection tracking table should be cleared otherwise NAT rules may seem to be not functioning correctly until connection entry expires.
Types of NAT:
- source NAT or srcnat. This type of NAT is performed on packets that are originated from a natted network. A NAT router replaces the private source address of an IP packet with a new public IP address as it travels through the router. A reverse operation is applied to the reply packets traveling in the other direction.
- destination NAT or dstnat. This type of NAT is performed on packets that are destined for the natted network. It is most commonly used to make hosts on a private network to be accessible from the Internet. A NAT router performing dstnat replaces the destination IP address of an IP packet as it travels through the router towards a private network.
Since RouterOS v7 the firewall NAT has two new INPUT and OUTPUT chains which are traversed for packets delivered to and sent from applications running on the local machine:
- input — used to process packets entering the router through one of the interfaces with the destination IP address which is one of the router’s addresses. Packets passing through the router are not processed against the rules of the input chain.
- output — used to process packets that originated from the router and leave it through one of the interfaces. Packets passing through the router are not processed against the rules of the output chain.
Destination NAT
Network address translation works by modifying network address information in the packets IP header. Let`s take a look at the common setup where a network administrator wants to access an office server from the internet.
We want to allow connections from the internet to the office server whose local IP is 10.0.0.3. In this case, we have to configure a destination address translation rule on the office gateway router:
/ip firewall nat add chain=dstnat action=dst-nat dst-address=172.16.16.1 dst-port=22 to-addresses=10.0.0.3 protocol=tcp
The rule above translates: when an incoming connection requests TCP port 22 with destination address 172.16.16.1, use the dst-nat action and depart packets to the device with local IP address 10.0.0.3 and port 22.
To allow access only from the PC at home, we can improve our dst-nat rule with «src-address=192.168.88.1» which is a Home`s PC public (this example) IP address. It is also considered to be more secure!
Source NAT
If you want to hide your local devices behind your public IP address received from ISP, you should configure the source network address translation (masquerading) feature of the MikroTik router.
Let`s assume you want to hide both office computer and server behind the public IP 172.16.16.1, the rule will look like the following one:
/ip firewall nat add chain=srcnat src-address=10.0.0.0/24 action=src-nat to-addresses=172.16.16.1 out-interface=WAN
Now your ISP will see all the requests coming with IP 172.16.16.1 and they will not see your LAN network IP addresses.
Masquerade
Firewall NAT action=masquerade is a unique subversion of action=srcnat, it was designed for specific use in situations when public IP can randomly change, for example, DHCP server change assigned IP or PPPoE tunnel after disconnect gets different IP, in short — when public IP is dynamic.
/ip firewall nat add chain=srcnat src-address=10.0.0.0/24 action=masquarade out-interface=WAN
Every time when interface disconnects and/or its IP address changes, the router will clear all masqueraded connection tracking entries related to the interface, this way improving system recovery time after public IP change. If srcnat is used instead of masquerade, connection tracking entries remain and connections can simply resume after a link failure.
Unfortunately, this can lead to some issues with unstable links when the connection gets routed over different links after the primary link goes down. In such a scenario following things can happen:
- on disconnect, all related connection tracking entries are purged;
- next packet from every purged (previously masqueraded) connection will come into the firewall as new, and, if a primary interface is not back, a packet will be routed out via an alternative route (if you have any) thus creating a new masqueraded connection;
- the primary link comes back, routing is restored over the primary link, so packets that belong to existing connections are sent over the primary interface without being masqueraded, that way leaking local IPs to a public network.
To work around this situation blackhole route can be created as an alternative to the route that might disappear on disconnect.
Hosts behind a NAT-enabled router do not have true end-to-end connectivity. Therefore some Internet protocols might not work in scenarios with NAT. Services that require the initiation of TCP connection from outside the private network or stateless protocols such as UDP, can be disrupted.
To overcome these limitations RouterOS includes a number of so-called NAT helpers, that enable NAT traversal for various protocols. When action=srcnat is used instead, connection tracking entries remain and connections can simply resume.
Though Source NAT and masquerading perform the same fundamental function: mapping one address space into another one, the details differ slightly. Most noticeably, masquerading chooses the source IP address for the outbound packet from the IP bound to the interface through which the packet will exit.
CGNAT (NAT444)
To combat IPv4 address exhaustion, a new RFC 6598 was deployed. The idea is to use shared 100.64.0.0/10 address space inside the carrier’s network and perform NAT on the carrier’s edge router to a single public IP or public IP range.
Because of the nature of such setup, it is also called NAT444, as opposed to a NAT44 network for a ‘normal’ NAT environment, three different IPv4 address spaces are involved.
CGNAT configuration on RouterOS does not differ from any other regular source NAT configuration:
/ip firewall nat add chain=src-nat action=srcnat src-address=100.64.0.0/10 to-address=2.2.2.2 out-interface=<public_if>
Where:
- 2.2.2.2 — public IP address,
- public_if — interface on providers edge router connected to the internet
The advantage of NAT444 is obvious, fewer public IPv4 addresses are used. But this technique comes with major drawbacks:
- The service provider router performing CGNAT needs to maintain a state table for all the address translations: this requires a lot of memory and CPU resources.
- Console gaming problems. Some games fail when two subscribers using the same outside public IPv4 address try to connect to each other.
- Tracking users for legal reasons means extra logging, as multiple households go behind one public address.
- Anything requiring incoming connections is broken. While this already was the case with regular NAT, end-users could usually still set up port forwarding on their NAT router. CGNAT makes this impossible. This means no web servers can be hosted here, and IP Phones cannot receive incoming calls by default either.
- Some web servers only allow a maximum number of connections from the same public IP address, as a means to counter DoS attacks like SYN floods. Using CGNAT this limit is reached more often and some services may be of poor quality.
- 6to4 requires globally reachable addresses and will not work in networks that employ addresses with a limited topological span.
Packets with Shared Address Space source or destination addresses MUST NOT be forwarded across Service Provider boundaries. Service Providers MUST filter such packets on ingress links. In RouterOS this can be easily done with firewall filters on edge routers:
/ip firewall filter add chain=input src-address=100.64.0.0/10 action=drop in-interface=<public_if> add chain=output dst-address=100.64.0.0/10 action=drop out-interface=<public_if> add chain=forward src-address=100.64.0.0/10 action=drop in-interface=<public_if> add chain=forward src-address=100.64.0.0/10 action=drop out-interface=<public_if> add chain=forward dst-address=100.64.0.0/10 action=drop out-interface=<public_if>
Service providers may be required to log of MAPed addresses, in a large CGN deployed network that may be a problem. Fortunately, RFC 7422 suggests a way to manage CGN translations in such a way as to significantly reduce the amount of logging required while providing traceability for abuse response.
RFC states that instead of logging each connection, CGNs could deterministically map customer private addresses (received on the customer-facing interface of the CGN, a.k.a., internal side) to public addresses extended with port ranges.
In RouterOS described algorithm can be done with few script functions. Let’s take an example:
Inside IP | Outside IP/Port range |
100.64.1.1 | 2.2.2.2:2000-2099 |
100.64.1.2 | 2.2.2.2:2100-2199 |
100.64.1.3 | 2.2.2.2:2200-2299 |
100.64.1.4 | 2.2.2.2:2300-2399 |
100.64.1.5 | 2.2.2.2:2400-2499 |
100.64.1.6 | 2.2.2.2:2500-2599 |
Instead of writing NAT mappings by hand, we could write a function that adds such rules automatically.
:global sqrt do={ :for i from=0 to=$1 do={ :if (i * i > $1) do={ :return ($i - 1) } } } :global addNatRules do={ /ip firewall nat add chain=srcnat action=jump jump-target=xxx \ src-address="$($srcStart)-$($srcStart + $count - 1)" :local x [$sqrt $count] :local y $x :if ($x * $x = $count) do={ :set y ($x + 1) } :for i from=0 to=$x do={ /ip firewall nat add chain=xxx action=jump jump-target="xxx-$($i)" \ src-address="$($srcStart + ($x * $i))-$($srcStart + ($x * ($i + 1) - 1))" } :for i from=0 to=($count - 1) do={ :local prange "$($portStart + ($i * $portsPerAddr))-$($portStart + (($i + 1) * $portsPerAddr) - 1)" /ip firewall nat add chain="xxx-$($i / $x)" action=src-nat protocol=tcp src-address=($srcStart + $i) \ to-address=$toAddr to-ports=$prange /ip firewall nat add chain="xxx-$($i / $x)" action=src-nat protocol=udp src-address=($srcStart + $i) \ to-address=$toAddr to-ports=$prange } }
After pasting the above script in the terminal function «addNatRules» is available. If we take our example, we need to map 6 shared network addresses to be mapped to 2.2.2.2 and each address uses a range of 100 ports starting from 2000. So we run our function:
$addNatRules count=6 srcStart=100.64.1.1 toAddr=2.2.2.2 portStart=2000 portsPerAddr=100
Now you should be able to get a set of rules:
[admin@rack1_b18_450] /ip firewall nat> print Flags: X - disabled, I - invalid, D - dynamic 0 chain=srcnat action=jump jump-target=xxx src-address=100.64.1.1-100.64.1.6 log=no log-prefix="" 1 chain=xxx action=jump jump-target=xxx-0 src-address=100.64.1.1-100.64.1.2 log=no log-prefix="" 2 chain=xxx action=jump jump-target=xxx-1 src-address=100.64.1.3-100.64.1.4 log=no log-prefix="" 3 chain=xxx action=jump jump-target=xxx-2 src-address=100.64.1.5-100.64.1.6 log=no log-prefix="" 4 chain=xxx-0 action=src-nat to-addresses=2.2.2.2 to-ports=2000-2099 protocol=tcp src-address=100.64.1.1 log=no log-prefix="" 5 chain=xxx-0 action=src-nat to-addresses=2.2.2.2 to-ports=2000-2099 protocol=udp src-address=100.64.1.1 log=no log-prefix="" 6 chain=xxx-0 action=src-nat to-addresses=2.2.2.2 to-ports=2100-2199 protocol=tcp src-address=100.64.1.2 log=no log-prefix="" 7 chain=xxx-0 action=src-nat to-addresses=2.2.2.2 to-ports=2100-2199 protocol=udp src-address=100.64.1.2 log=no log-prefix="" 8 chain=xxx-1 action=src-nat to-addresses=2.2.2.2 to-ports=2200-2299 protocol=tcp src-address=100.64.1.3 log=no log-prefix="" 9 chain=xxx-1 action=src-nat to-addresses=2.2.2.2 to-ports=2200-2299 protocol=udp src-address=100.64.1.3 log=no log-prefix="" 10 chain=xxx-1 action=src-nat to-addresses=2.2.2.2 to-ports=2300-2399 protocol=tcp src-address=100.64.1.4 log=no log-prefix="" 11 chain=xxx-1 action=src-nat to-addresses=2.2.2.2 to-ports=2300-2399 protocol=udp src-address=100.64.1.4 log=no log-prefix="" 12 chain=xxx-2 action=src-nat to-addresses=2.2.2.2 to-ports=2400-2499 protocol=tcp src-address=100.64.1.5 log=no log-prefix="" 13 chain=xxx-2 action=src-nat to-addresses=2.2.2.2 to-ports=2400-2499 protocol=udp src-address=100.64.1.5 log=no log-prefix="" 14 chain=xxx-2 action=src-nat to-addresses=2.2.2.2 to-ports=2500-2599 protocol=tcp src-address=100.64.1.6 log=no log-prefix="" 15 chain=xxx-2 action=src-nat to-addresses=2.2.2.2 to-ports=2500-2599 protocol=udp src-address=100.64.1.6 log=no log-prefix=""
Hairpin NAT
Hairpin network address translation (NAT Loopback) is where the device on the LAN is able to access another machine on the LAN via the public IP address of the gateway router.
In the above example the gateway router has the following dst-nat configuration rule:
/ip firewall nat add chain=dstnat action=dst-nat dst-address=172.16.16.1 dst-port=443 to-addresses=10.0.0.3 to-ports=443 protocol=tcp
When a user from the PC at home establishes a connection to the webserver, the router performs DST NAT as configured:
- the client sends a packet with a source IP address of 192.168.88.1 to a destination IP address of 172.16.16.1 on port 443 to request some web resources;
- the router destination NAT`s the packet to 10.0.0.3 and replaces the destination IP address in the packet accordingly. The source IP address stays the same: 192.168.88.1;
- the server replies to the client’s request and the reply packet have a source IP address of 10.0.0.3 and a destination IP address of 192.168.88.1.
- the router determines that the packet is part of a previous connection and undoes the destination NAT, and puts the original destination IP address into the source IP address field. The destination IP address is 192.168.88.1, and the source IP address is 172.16.16.1;
- The client receives the reply packet it expects, and the connection is established;
But, there will be a problem, when a client on the same network as the web server requests a connection to the web server’s public IP address:
- the client sends a packet with a source IP address of 10.0.0.2 to a destination IP address of 172.16.16.1 on port 443 to request some web resources;
- the router destination NATs the packet to 10.0.0.3 and replaces the destination IP address in the packet accordingly. The source IP address stays the same: 10.0.0.2;
- the server replies to the client’s request. However, the source IP address of the request is on the same subnet as the web server. The web server does not send the reply back to the router but sends it back directly to 10.0.0.2 with a source IP address in the reply of 10.0.0.3;
- The client receives the reply packet, but it discards it because it expects a packet back from 172.16.16.1, and not from 10.0.0.3;
To resolve this issue, we will configure a new src-nat rule (the hairpin NAT rule) as follows:
/ip firewall nat add action=masquerade chain=srcnat dst-address=10.0.0.3 out-interface=LAN protocol=tcp src-address=10.0.0.0/24
After configuring the rule above:
- the client sends a packet with a source IP address of 10.0.0.2 to a destination IP address of 172.16.16.1 on port 443 to request some web resources;
- the router destination NATs the packet to 10.0.0.3 and replaces the destination IP address in the packet accordingly. It also source NATs the packet and replaces the source IP address in the packet with the IP address on its LAN interface. The destination IP address is 10.0.0.3, and the source IP address is 10.0.0.1;
- the web server replies to the request and sends the reply with a source IP address of 10.0.0.3 back to the router’s LAN interface IP address of 10.0.0.1;
- the router determines that the packet is part of a previous connection and undoes both the source and destination NAT, and puts the original destination IP address of 10.0.0.3 into the source IP address field, and the original source IP address of 172.16.16.1 into the destination IP address field
Endpoint-Independent NAT
Endpoint-independent NAT creates mapping in the source NAT and uses the same mapping for all subsequent packets with the same source IP and port. This mapping is created with the following rule:
/ip firewall nat add action=endpoint-independent-nat chain=srcnat out-interface=WAN protocol=udp
This mapping allows running source-independent filtering, which allows forwarding packets from any source from WAN to mapped internal IP and port. Following rule enables filtering:
/ip firewall nat add action=endpoint-independent-nat chain=dstnat in-interface=WAN protocol=udp
Endpoint-independent NAT works only with UDP protocol.
Additionally, endpoint-independent-nat can take a few other parameters:
- randomize-port — randomize to which public port connections will be mapped.
More info https://www.ietf.org/rfc/rfc5128.txt section 2.2.3 and 2.2.5
IPv4
Properties
Property | Description |
---|---|
action (action name; Default: accept) | Action to take if a packet is matched by the rule:
|
address-list (string; Default: ) | Name of the address list to be used. Applicable if action is add-dst-to-address-list or add-src-to-address-list |
address-list-timeout (none-dynamic | none-static | time; Default: none-dynamic) | Time interval after which the address will be removed from the address list specified by address-list parameter. Used in conjunction with add-dst-to-address-list or add-src-to-address-list actions
|
chain (name; Default: ) | Specifies to which chain rule will be added. If the input does not match the name of an already defined chain, a new chain will be created |
comment (string; Default: ) | Descriptive comment for the rule |
connection-bytes (integer-integer; Default: ) | Matches packet only if a given amount of bytes has been transferred through the particular connection. 0 — means infinity, for example connection-bytes=2000000-0 means that the rule matches if more than 2MB has been transferred through the relevant connection |
connection-limit (integer,netmask; Default: ) | Matches connections per address or address block after a given value is reached |
connection-mark (no-mark | string; Default: ) | Matches packets marked via mangle facility with particular connection mark. If a no-mark is set, the rule will match any unmarked connection |
connection-rate (Integer 0..4294967295; Default: ) | Connection Rate is a firewall matcher that allows capturing traffic based on the present speed of the connection |
connection-type (ftp | h323 | irc | pptp | quake3 | sip | tftp; Default: ) | Matches packets from related connections based on information from their connection tracking helpers. A relevant connection helper must be enabled under /ip firewall service-port |
content (string; Default: ) | Match packets that contain specified text |
dscp (integer: 0..63; Default: ) | Matches DSCP IP header field. |
dst-address (IP/netmask | IP range; Default: ) | Matches packets whose destination is equal to specified IP or falls into a specified IP range. |
dst-address-list (name; Default: ) | Matches the destination address of a packet against a user-defined address list |
dst-address-type (unicast | local | broadcast | multicast; Default: ) | Matches destination address type:
|
dst-limit (integer[/time],integer,dst-address | dst-port | src-address[/time]; Default: ) | Matches packets until a given PPS limit is exceeded. As opposed to the limit matcher, every destination IP address/destination port has its own limit. Parameters are written in the following format: count[/time],burst,mode[/expire] .
|
dst-port (integer[-integer]: 0..65535; Default: ) | List of destination port numbers or port number ranges in format Range[,Port], for example, dst-port=123-345,456-678 |
fragment (yes|no; Default: ) | Matches fragmented packets. The first (starting) fragment does not count. If connection tracking is enabled there will be no fragments as the system automatically assembles every packet |
hotspot (auth | from-client | http | local-dst | to-client; Default: ) | Matches packets received from HotSpot clients against various HotSpot matchers.
|
icmp-options (integer:integer; Default: ) | Matches ICMP type: code fields |
in-bridge-port (name; Default: ) | Actual interface the packet has entered the router if the incoming interface is a bridge |
in-interface (name; Default: ) | Interface the packet has entered the router |
ingress-priority (integer: 0..63; Default: ) | Matches ingress the priority of the packet. Priority may be derived from VLAN, WMM or MPLS EXP bit. |
ipsec-policy (in | out, ipsec | none; Default: ) | Matches the policy used by IPSec. Value is written in the following format: direction, policy . The direction is Used to select whether to match the policy used for decapsulation or the policy that will be used for encapsulation.
For example, if a router receives an IPsec encapsulated Gre packet, then rule |
ipv4-options (any | loose-source-routing | no-record-route | no-router-alert | no-source-routing | no-timestamp | none | record-route | router-alert | strict-source-routing | timestamp; Default: ) | Matches IPv4 header options.
|
jump-target (name; Default: ) | Name of the target chain to jump to. Applicable only if action=jump |
layer7-protocol (name; Default: ) | Layer7 filter name defined in layer7 protocol menu. |
limit (integer,time,integer; Default: ) | Matches packets until a given PPS limit is exceeded. Parameters are written in the following format: count[/time],burst .
|
log (yes | no; Default: no) | Add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port, and length of the packet. |
log-prefix (string; Default: ) | Adds specified text at the beginning of every log message. Applicable if action=log or log=yes configured. |
out-bridge-port (name; Default: ) | Actual interface the packet is leaving the router if the outgoing interface is a bridge |
out-interface (; Default: ) | Interface the packet is leaving the router |
packet-mark (no-mark | string; Default: ) | Matches packets marked via mangle facility with particular packet mark. If no-mark is set, the rule will match any unmarked packet |
packet-size (integer[-integer]:0..65535; Default: ) | Matches packets of specified size or size range in bytes |
per-connection-classifier (ValuesToHash:Denominator/Remainder; Default: ) | PCC matcher allows dividing traffic into equal streams with the ability to keep packets with a specific set of options in one particular stream |
port (integer[-integer]: 0..65535; Default: ) | Matches if any (source or destination) port matches the specified list of ports or port ranges. Applicable only if protocol is TCP or UDP |
protocol (name or protocol ID; Default: tcp) | Matches particular IP protocol specified by protocol name or number |
psd (integer,time,integer,integer; Default: ) | Attempts to detect TCP and UDP scans. Parameters are in the following format WeightThreshold, DelayThreshold, LowPortWeight, HighPortWeight
|
random (integer: 1..99; Default: ) | Matches packets randomly with a given probability |
routing-mark (string; Default: ) | Matches packets marked by mangle facility with particular routing mark |
same-not-by-dst (yes | no; Default: ) | Specifies whether to take into account or not destination IP address when selecting a new source IP address. Applicable if action=same |
src-address (Ip/Netmaks, Ip range; Default: ) | Matches packets whose source is equal to specified IP or falls into a specified IP range. |
src-address-list (name; Default: ) | Matches source address of a packet against user-defined address list |
src-address-type (unicast | local | broadcast | multicast; Default: ) |
Matches source address type:
|
src-port (integer[-integer]: 0..65535; Default: ) | List of source ports and ranges of source ports. Applicable only if a protocol is TCP or UDP. |
src-mac-address (MAC address; Default: ) | Matches source MAC address of the packet |
tcp-mss (integer[-integer]: 0..65535; Default: ) | Matches TCP MSS value of an IP packet |
time (time-time,sat | fri | thu | wed | tue | mon | sun; Default: ) | Allows to create a filter based on the packets’ arrival time and date or, for locally generated packets, departure time and date |
to-addresses (IP address[-IP address]; Default: 0.0.0.0) | Replace the original address with the specified one. Applicable if action is dst-nat, netmap, same, src-nat |
to-ports (integer[-integer]: 0..65535; Default: ) | Replace the original port with the specified one. Applicable if action is dst-nat, redirect, masquerade, netmap, same, src-nat |
ttl (integer: 0..255; Default: ) | Matches packets TTL value |
Stats
Property | Description |
---|---|
bytes (integer) | The total amount of bytes matched by the rule |
packets (integer) | The total amount of packets matched by the rule |
To show additional read-only properties:
[admin@MikroTik] > ip firewall nat print stats all Flags: X - disabled, I - invalid, D - dynamic # CHAIN ACTION BYTES PACKETS 0 srcnat masquerade 265 659 987
IPv6
NAT66 is supported since RouterOS v7.1.
Properties
Property | Description |
---|---|
action (action name; Default: accept) | Action to take if a packet is matched by the rule:
|
address-list (string; Default: ) | Name of the address list to be used. Applicable if action is add-dst-to-address-list or add-src-to-address-list |
address-list-timeout (none-dynamic | none-static | time; Default: none-dynamic) | Time interval after which the address will be removed from the address list specified by address-list parameter. Used in conjunction with add-dst-to-address-list or add-src-to-address-list actions
|
chain (name; Default: ) | Specifies to which chain rule will be added. If the input does not match the name of an already defined chain, a new chain will be created |
comment (string; Default: ) | Descriptive comment for the rule |
connection-bytes (integer-integer; Default: ) | Matches packets only if a given amount of bytes has been transferred through the particular connection. 0 — means infinity, for example connection-bytes=2000000-0 means that the rule matches if more than 2MB has been transferred through the relevant connection |
connection-limit (integer,netmask; Default: ) | Matches connections per address or address block after a given value is reached |
connection-mark (no-mark | string; Default: ) | Matches packets marked via mangle facility with particular connection mark. If no-mark is set, the rule will match any unmarked connection |
connection-rate (Integer 0..4294967295; Default: ) | Connection Rate is a firewall matcher that allows capturing traffic based on the present speed of the connection |
connection-state (established | invalid | new | related | untracked; Default: ) | Interprets the connection tracking analytics data for a particular packet:
|
connection-type (ftp | h323 | irc | pptp | quake3 | sip | tftp; Default: ) | Matches packets from related connections based on information from their connection tracking helpers. A relevant connection helper must be enabled under /ip firewall service-port |
content (string; Default: ) | Match packets that contain specified text |
dscp (integer: 0..63; Default: ) | Matches DSCP IP header field. |
dst-address (IP/netmask | IP range; Default: ) | Matches packets whose destination is equal to specified IP or falls into a specified IP range. |
dst-address-list (name; Default: ) | Matches destination address of a packet against user-defined address list |
dst-address-type (unicast | local | broadcast | multicast; Default: ) | Matches destination address type:
|
dst-limit (integer[/time],integer,dst-address | dst-port | src-address[/time]; Default: ) | Matches packets until a given PPS limit is exceeded. As opposed to the limit matcher, every destination IP address/destination port has its own limit. Parameters are written in the following format: count[/time],burst,mode[/expire] .
|
dst-port (integer[-integer]: 0..65535; Default: ) | List of destination port numbers or port number ranges in format Range[,Port], for example, dst-port=123-345,456-678 |
icmp-options (integer:integer; Default: ) | Matches ICMP type: code fields |
in-bridge-port (name; Default: ) | Actual interface the packet has entered the router if the incoming interface is a bridge |
in-bridge-port-list (name; Default: ) | Set of interfaces defined in interface list. Works the same as in-bridge-port |
in-interface (name; Default: ) | Interface the packet has entered the router |
in-interface-list (name; Default: ) | Set of interfaces defined in interface list. Works the same as in-interface |
ingress-priority (integer: 0..63; Default: ) | Matches ingress the priority of the packet. Priority may be derived from VLAN, WMM or MPLS EXP bit. |
ipsec-policy (in | out, ipsec | none; Default: ) | Matches the policy used by IPSec. Value is written in the following format: direction, policy . The direction is Used to select whether to match the policy used for decapsulation or the policy that will be used for encapsulation.
For example, if a router receives an IPsec encapsulated Gre packet, then rule |
jump-target (name; Default: ) | Name of the target chain to jump to. Applicable only if action=jump |
layer7-protocol (name; Default: ) | Layer7 filter name defined in layer7 protocol menu. |
limit (integer,time,integer; Default: ) | Matches packets until a given PPS limit is exceeded. Parameters are written in the following format: count[/time],burst .
|
log (yes | no; Default: no) | Add a message to the system log containing the following data: in-interface, out-interface, src-mac, protocol, src-ip:port->dst-ip:port, and length of the packet. |
log-prefix (string; Default: ) | Adds specified text at the beginning of every log message. Applicable if action=log or log=yes configured. |
out-bridge-port (name; Default: ) | Actual interface the packet is leaving the router if the outgoing interface is a bridge |
out-bridge-port-list (name; Default: ) | Set of interfaces defined in interface list. Works the same as out-bridge-port |
out-interface (; Default: ) | Interface the packet is leaving the router |
out-interface-list (name; Default: ) | Set of interfaces defined in interface list. Works the same as out-interface |
packet-mark (no-mark | string; Default: ) | Matches packets marked via mangle facility with particular packet mark. If no-mark is set, the rule will match any unmarked packet |
packet-size (integer[-integer]:0..65535; Default: ) | Matches packets of specified size or size range in bytes |
per-connection-classifier (ValuesToHash:Denominator/Remainder; Default: ) | PCC matcher allows dividing traffic into equal streams with the ability to keep packets with a specific set of options in one particular stream |
port (integer[-integer]: 0..65535; Default: ) | Matches if any (source or destination) port matches the specified list of ports or port ranges. Applicable only if protocol is TCP or UDP |
protocol (name or protocol ID; Default: tcp) | Matches particular IP protocol specified by protocol name or number |
priority (integer: 0..63; Default:) | Matches the packet’s priority after a new priority has been set. Priority may be derived from VLAN, WMM, DSCP, MPLS EXP bit, or from the priority that has been set using the set-priority action. |
random (integer: 1..99; Default: ) | Matches packets randomly with a given probability |
routing-mark (string; Default: ) | Matches packets marked by mangle facility with particular routing mark |
src-address (Ip/Netmaks, Ip range; Default: ) | Matches packets whose source is equal to specified IP or falls into a specified IP range. |
src-address-list (name; Default: ) | Matches source address of a packet against user-defined address list |
src-address-type (unicast | local | broadcast | multicast; Default: ) |
Matches source address type:
|
src-port (integer[-integer]: 0..65535; Default: ) | List of source ports and ranges of source ports. Applicable only if a protocol is TCP or UDP. |
tcp-flags (ack | cwr | ece | fin | psh | rst | syn | urg; Default: ) | Matches specified TCP flags
|
src-mac-address (MAC address; Default: ) | Matches source MAC address of the packet |
tcp-mss (integer[-integer]: 0..65535; Default: ) | Matches TCP MSS value of an IP packet |
time (time-time,sat | fri | thu | wed | tue | mon | sun; Default: ) | Allows to create a filter based on the packets’ arrival time and date or, for locally generated packets, departure time and date |
to-addresses (IP address[-IP address]; Default: 0.0.0.0) | Replace the original address with the specified one. Applicable if action is dst-nat, netmap, same, src-nat |
to-ports (integer[-integer]: 0..65535; Default: ) | Replace the original port with the specified one. Applicable if action is dst-nat, redirect, masquerade, netmap, same, src-nat |
Stats
Property | Description |
---|---|
bytes (integer) | The total amount of bytes matched by the rule |
packets (integer) | The total amount of packets matched by the rule |
To show additional read-only properties:
ipv6/firewall/nat/print stats