Yes. Building new firewalls on top of iptables is discouraged.
- Current status
- Installing from git
- Should I replace an iptables firewall with a nftables one?
- Hints
- Настройка
- Просмотр цепочек и правил в таблице
- Полная перезагрузка правил
- ИсторияПравить
- Creating Tables
- Netfilter
- О чем эта статья
- Creating Chains
- What are the major differences?
- Использование
- Простой межсетевой экран
- Why a new framework?
- Примеры
- Несколько сетевых интерфейсов с разными правилами
- NAT с пробросом портов
- Should I mix nftables and iptables/ebtables/arptables rulesets?
- Save and Restore a Ruleset
- Синтаксис командной строки nftПравить
- Development
- Reverting to legacy xtables
- Validating your installation
- Демонстрация настройки файрволла
- Разрешаем входящие подключения к tcp и udb портам
- Разрешаем подключаться к loopback интерфейсу
- Разрешаем ping сервера
- Меняем политику цепочки input
- Механизм connection tracking
- Creating Rules
- Simple IP/IPv6 Firewall
- Use firewalld
- Installing Linux kernel with nftables support
- Tables Are Namespaces
- Verdict Maps
- External links
Current status
NOTE: Debian 10 Buster and later use the nftables framework by default.
Starting with Debian 10 Buster, nf_tables is the default backend when using iptables, by means of the iptables-nft layer (i.e, using iptables syntax with the nf_tables kernel subsystem). This also affects ip6tables, arptables and ebtables.
Installing from git
Just type these commands:
% git clone git://git.netfilter.org/nftables
% nftables
% sh autogen.sh
% ./configure
% make
% make install
You should check that nft is installed in your system by typing:
% nft
nft: no specified
That means nft has been correctly installed.
Should I replace an iptables firewall with a nftables one?
Yes, nftables is the replacement for iptables. There are some tools in place to ease in this task.
Hints
Some hints folks might find interesting in some situations.
Настройка
Утилита nft выполняет большую часть обработки правил перед передачей их ядру. Правила объединяются в цепочки, которые, в свою очередь, входят в состав таблиц. В последующих разделах описано создание и модифицирование этих структур.
Прочитать правила из файла можно с помощью опции -f/—file:
# nft —file имя-файла
Обратите внимание, что уже загруженные на этот момент правила не будут при этом автоматически стёрты.
Полный список команд можно найти в руководстве .
Таблицы содержат #Цепочки. В отличие от iptables, в nftables отсутствуют встроенные таблицы. Количество таблиц и их имена определяется пользователем. Тем не менее, каждая таблица имеет только одно семейство адресации и применяется к пакетам только этого семейства. Таблицы могут относиться к одному из пяти семейств.
ip (т.е. IPv4) — семейство по умолчанию; используется, если семейство не было указано.
Семейство inet объединяет протоколы IPv4 и IPv6, что позволяет унифицировать семейства ip и ip6 и упростить создание правил.
Описание остальных семейств адресации вы найдёте в руководстве nft(8) § ADDRESS FAMILIES.
В командах ниже параметр семейство будет указываться не всегда; если его нет, то подразумевается семейство ip.
Добавить новую таблицу:
# nft add table семейство таблица
Вывести список таблиц:
# nft list tables
Просмотр цепочек и правил в таблице
Вывести цепочки и правила выбранной таблицы:
# nft list table семейство таблица
Например, чтобы вывести на экран правила таблицы my_table семейства inet, выполните команду:
# nft list table inet my_table
Удалить таблицу со всеми цепочками:
# nft delete table семейство таблица
Стереть все правила в таблице:
# nft flush table семейство таблица
Цепочка содержит #Правила. В отличие от iptables, в nftables отсутствуют встроенные цепочки. Соответственно, если опрелённые типы или хуки фреймворка netfilter не задействованы ни в одной цепочке, то проходящие через эти цепочки пакеты обрабатываться не будут (в отличие от iptables).
Есть два типа цепочек. Базовая цепочка является точкой входа для пакетов из сетевого стека; в ней указывается хук. Обычная цепочка может использоваться в качестве цели перехода и используется для лучшей организации правил.
Добавить обычную цепочку цепочка в таблицу таблица:
# nft add chain семейство таблица цепочка
Например, чтобы добавить обычную цепочку my_tcp_chain к таблице my_table семейства адресации inet, выполните:
# nft add chain inet my_table my_tcp_chain
Чтобы добавить базовую цепочку, укажите хук и значение приоритета:
тип может принимать значения filter, route или nat.
Для семейств адресации IPv4/IPv6/Inet хук может принимать значения prerouting, input, forward, output или postrouting. Описание других возможных хуков вы найдёте в руководстве nft(8) § ADDRESS FAMILIES.
Например, добавим базовую цепочку для фильтрации входящих пакетов:
Если заменить команду add на create в любом из правил выше, то цепочка тоже будет создана, но если цепочка с таким названием уже существует, то вы получите сообщение об ошибке.
Следующая команда выводит на экран все правила в цепочке:
# nft list chain семейство таблица цепочка
Например, следующая команда выведет правила цепочки my_output таблицы my_table семейства inet:
# nft list chain inet my_table my_output
Для редактирования цепочки укажите её название и правила, которые нужно изменить:
Например, для изменения политики обработки входящих пакетов цепочки исходной таблицы с accept на drop выполните команду:
# nft delete chain семейство таблица цепочка
Цепочка должна быть пустой (не содержащей правил) и не должна быть целью перехода из другой цепочки.
Стереть все правила в цепочке:
# nft flush chain семейство таблица цепочка
Правила конструируются из выражений (expressions) и операторов (statements) и содержатся внутри цепочек.
Совет: Утилита iptables-translate поможет преобразовать правила iptables в формат nftables.
Добавить правило в цепочку:
# nft add rule семейство таблица цепочка handle маркер оператор
Правило будет прикреплено после маркер, который можно не указывать. Если маркер (handle) не задать, то правило добавится в конец цепочки.
Чтобы добавить правило перед определённой позицией, выполните
# nft insert rule семейство таблица цепочка handle маркер оператор
Если маркер не указан, то правило добавится в начало цепочки.
Обычно оператор включает некоторое выражение для сравнения и вынесения решения. Решениями могут быть accept, drop, queue, continue, return, jump цепочка и goto цепочка. Возможны и другие операторы помимо решений, подробнее смотрите .
В nftables доступен ряд выражений, по большей части совпадающий с аналогичными в iptables. Наиболее важное отличие заключается в том, что здесь нет обобщённых или неявных параметров. Обобщённый параметр (generic match) обычно доступен для всех правил, например, параметры —protocol или —source. Неявные правила (implicit matches) относятся к конкретному протоколу, как параметр —sport для пакетов TCP.
Ниже представлен неполный список возможных параметров:
Ниже приведён неполный список аргументов для параметров (подробнее см. ):
Отдельные правила могут быть удалены только с помощью маркера. Команда nft —handle list выведет список маркеров.
# nft —handle —numeric list chain inet my_table my_input
Стирание всех цепочек таблицы выполняется командой nft flush table. Отдельные цепочки могут быть стёрты командами nft flush chain или nft delete rule.
# nft flush table таблица
# nft flush chain семейство таблица цепочка
# nft delete rule семейство таблица цепочка
Первая команда стирает все цепочки в ip-таблице таблица. Вторая очищает цепочку цепочка в таблице таблица семейства семейство. Третья удаляет все правила в цепочке цепочка в таблице таблица семейства семейство.
Именованное множество можно изменить, а также присвоить ему тип и установить флаги. sshguard использует именованные множества для хранения адресов блокированных хостов.
Команды для добавления и удаления элементов из множества:
Полная перезагрузка правил
Создать файл для новых правил:
Сбросить дамп правил в новый файл:
Теперь можно редактировать файл /tmp/nftables, создавая и изменяя правила. Применить изменения можно командой:
# nft -f /tmp/nftables
ИсторияПравить
To install libnftnl, to can type these magic spells:
$ git clone git://git.netfilter.org/libnftnl
$ libnftnl
$ sh autogen.sh
$ ./configure
$ make
$ sudo make install
If you have any compilation problem, please report them to the netfilter developer mailing list providing as much detailed information as possible.
nft add rule ip filter output ip daddr 1.2.3.4 drop
Note that the new syntax differs significantly from that of iptables, in which the same rule would be written:
iptables -A OUTPUT -d 1.2.3.4 -j DROP
The new syntax can appear more verbose, but it is also far more flexible. nftables incorporates advanced data structures such as dictionaries, maps and concatenations that do not exist with iptables. Making use of these can significantly reduce the number of chains and rules needed to express a given packet filtering design.
Creating Tables
In nftables you need to manually create tables. Tables need to qualify a family; ip, ip6, inet, arp, bridge, or netdev. inet means the table will process both ipv4 and ipv6 packets. It’s the family we’ll use throughout this post.
: For those coming from iptables, the term table may be a bit confusing. In nftables a table is simply a namespace—nothing more, nothing less. It’s a collection of chains, rules, and sets, and other objects.
Let’s create our first table and list the rule set.
So now we have a table, but by itself it won’t do much. Let’s move on to chains.
Netfilter
В Linux брандмауэр встроен в ядро и называется он Netfilter. А для управления им могут использоваться различные утилиты. В Debian и Ubuntu более старших версий использовалась утилита iptables. А в Debian 11 и Ubuntu 22.04 начали использовать – nftables. Именно с этой утилитой я вас и познакомлю. Но вначале узнаем как вообще работает Netfilter.
Фаервол Netfilter делит весь трафик на цепочки (chain) и обрабатывает каждую цепочку по отдельности.

Прохождение пакетов по цепочкам Netfilter
Входящий трафик сразу же обрабатывается в цепочке prerouting (здесь может сработать входящий NAT).
После чего, если трафик:
Если трафик попал в цепочку forward, то перед самым выходом он попадёт в цепочку postrouting (здесь может сработать исходящий NAT).
А весь исходящий трафик обрабатывается цепочкой output (здесь тоже может отработать исходящий NAT).

Направление трафика и прохождение пакетами цепочек
Над пакетами совершаются различные действия, которые группируются в таблицы. И каждая цепочка может входить в ту или иную таблицу, или может находится в нескольких или во всех таблицах сразу. Если цепочка входит в определённую таблицу, это означает что в этой цепочке над пакетами можно выполнять действия из этой таблицы.
О чем эта статья
Этот курс предполагает что вы используете сервер Linux именно как сервер, а не как роутер. Поэтому проходящий сквозь сервер трафик я рассматривать не буду. И это условие значительно снижает количество таблиц и цепочек, которые мы рассмотрим.
Так как сервер принимает от клиентов какие-то запросы, обрабатывает их и отвечает на них. То здесь рассматриваются всего две цепочки:
Рассматривать мы будем запрещающие или разрешающие правила, они присутствуют в таблице filter.
Также в этой статье мы рассмотрим механизм connection tracking.
Creating Chains
Chains are the objects that will contain our firewall rules.
Just like tables, chains need to be explicitly created. When creating the chain you need to specify what table the chain belongs to as well as the type, the hook, and the priority. For this introduction we’ll keep things simple by using filter, input, and priority 0 to filter packets destined to the host.
: The backslash () is necessary so the shell doesn’t interpret the semicolon as the end of the command.
# nft add chain inet my_table my_utility_chain
What are the major differences?
nftables includes built-in data sets capabilities. In iptables this is not possible, and there is a separated tool: ?ipset.
In the iptables framework there are tools per family: iptables, ip6tables, arptables, ebtables. Now, nftables allows you to manage all families in one single CLI tool.
This new framework features a new linux kernel subsystem, known as nf_tables. The new engine mechanism is inspired by BPF-like systems, with a set of basic expressions, which can be combined to build complex filtering rules.
Использование
В nftables не различаются временные правила, добавленные из командной строки, и постоянные, загруженные из файла или сохранённые в файл.
Все правила должны создаваться или загружаться утилитой nft. Подробнее о работе с ней см. раздел #Настройка.
Текущий набор правил можно узнать командой:
# nft list ruleset
Простой межсетевой экран
В пакет входит простая и надёжная конфигурация экрана, сохранённая в файле /etc/nftables.conf.
Служба nftables.service загрузит эти правила при запуске или включении.
Why a new framework?
The previous framework (iptables) has several problems hard to address, regarding scalability, performance, code maintenance, etc..
Примеры
Если вы используете переходы (jumps), то целевая цепочка должна быть описана до перехода. Иначе будет получена ошибка Error: Could not process rule: No such file or directory.
Несколько сетевых интерфейсов с разными правилами
Если у вашей системы несколько сетевых интерфейсов и вы хотите использовать для них разные наборы правил, то создайте фильтрующую цепочку-диспетчер, а после неё опишите цепочки для сетевых интерфейсов. Например, пусть ваша машина выступает в качестве домашнего маршрутизатора и вы желаете запустить веб-сервер, доступный по локальной сети (интерфейс enp3s0), но не из публичного интернета (интерфейс enp2s0). Создайте таблицу вроде этой:
Можно поступить иначе — задать только одну строку iifname, например для интерфейса веб-сервера, а правила для остальных интерфейсов вместо диспетчеризации описать в одном месте.
Правила работы маскарадинга:
Пример правил межсетевого экрана для машины с двумя интерфейсами, локальным enp3s0 и публичным enp2s0:
Поскольку таблица выше относится к типу inet, то маскарадингу подвергаются пакеты и IPv4, и IPv6. Чтобы ограничить маскарадинг только IPv4-пакетами (т.к. у IPv6 большое пространство адресов и NAT не требуется) либо добавьте выражение meta nfproto ipv4 перед oifname «enp2s0» masquerade, либо измените тип таблицы на ip.
NAT с пробросом портов
Для вывода заблокированных адресов выполните nft list set inet dev blackhole.
Should I mix nftables and iptables/ebtables/arptables rulesets?
No, unless you know what you are doing.
Save and Restore a Ruleset
nftables rules can easily be saved and restored. The list output of nft can be fed back into the tool to restore everything. This is exactly how the nftables systemd service works.
To save your ruleset
To restore your ruleset
# nft -f /root/nftables.conf
Of course, you can enable the systemd service and have your rules restored on reboot. The service reads rules from /etc/sysconfig/nftables.conf.
: Some distributions, RHEL-8 included, ship predefined nftables configuration in /etc/nftables. These samples often include the setup of tables and chains in a manner similar to iptables. These are often listed in the existing /etc/sysconfig/nftables.conf file, but may be commented out.
Синтаксис командной строки nftПравить
nft add rule ip filter output ip addr 1.2.3.4 drop
Синтаксис такого же действия для iptables:
iptables -t filter -A OUTPUT -j DROP -d 1.2.3.4
Для обеспечения обратной совместимости предоставляется специальная прослойка, позволяющая использовать iptables/ip6tables поверх инфраструктуры nftables.
Development
Check Portal:DeveloperDocs — documentation for netfilter developers.
Some hints on the general development progress:
Reverting to legacy xtables
You can switch back and forth between iptables-nft and iptables-legacy by means of update-alternatives (same applies to arptables and ebtables).
The default starting with Debian 10 Buster:
# update-alternatives —set iptables /usr/sbin/iptables-nft
# update-alternatives —set ip6tables /usr/sbin/ip6tables-nft
# update-alternatives —set arptables /usr/sbin/arptables-nft
# update-alternatives —set ebtables /usr/sbin/ebtables-nft
Switching to the legacy version:
# update-alternatives —set iptables /usr/sbin/iptables-legacy
# update-alternatives —set ip6tables /usr/sbin/ip6tables-legacy
# update-alternatives —set arptables /usr/sbin/arptables-legacy
# update-alternatives —set ebtables /usr/sbin/ebtables-legacy
The argument -n shows the addresses and other information that uses names in numeric format. The -a argument is used to display the handle.
Validating your installation
You can validate that your installation is working by checking if you can install the ‘nf_tables’ kernel module.
Then, you can check that’s actually there via lsmod:
Make sure you also have loaded the family support, eg.
% modprobe nf_tables_ipv4
The lsmod command should show something like:
nf_tables_ipv4
nf_tables nf_tables_ipv4
These modules provide the corresponding table and the filter chain support for the given family.
You could also check which modules are supported by your current kernel. How to to do this, depends on your distro:
In the debian example below, CONFIG_NFT_REDIR_IPV4 and CONFIG_NFT_REDIR_IPV6 are not set, so you can’t use redirect in the ruleset:
% grep CONFIG_NFT_ /boot/config-4.2.0-1-amd64
m
m
m
m
m
m
m
m
m
m
m
m
m
m
m
m
m
m
m
# CONFIG_NFT_REDIR_IPV4 is not set
m
m
m
m
# CONFIG_NFT_REDIR_IPV6 is not set
m
m
Демонстрация настройки файрволла
Предположим наш сервер является samba сервером, web сервером и ntp сервером. В примере разрешим доступ к этим службам:
А также разрешим подключаться к серверу по SSH: tcp 22, но только с определённого компьютера.
Разрешим пинговать наш сервер и выходить ему в интернет.
Разрешаем входящие подключения к tcp и udb портам
Разрешим подключаться к серверу по ssh, но только со своего компьютера:
$ sudo nft add rule inet filter input iifname eth0 ip saddr 172.28.80.14 tcp dport 22 counter accept
То есть мы:
В своих правилах вы можете использовать следующее:
Теперь покажу как разрешить подключения к samba, web и ntp. Обратите внимание: порты можно сгруппировать уменьшив количество правил. И в примере я разрешаю подключаться к сервисам только из локальной сети:
Разрешаем подключаться к loopback интерфейсу
Для того чтобы сервисы внутри системы могли нормально работать, обязательно нужно разрешить все подключения к loopback интерфейсу:
$ sudo nft add rule inet filter input iifname lo counter accept
Разрешаем ping сервера
Разрешим пинговать наш сервер, другими словами разрешим входящие icmp запросы:
Чтобы разрешить icmp нужно указать протокол и тип запроса:
Меняем политику цепочки input
После того как мы добавили все разрешающие правила в цепочке input, поменяем её политику на drop:
То есть смена политик выполняется таким образом:
Механизм connection tracking
Политика в цепочки output у нас разрешающая. Давайте попробуем попинговать какой-нибудь точно доступный узел с нашего сервера:
$ ping 77.88.8.8
И почему-то этот узел не пингуется, сейчас объясню почему.
Допустим мы захотим обновить наш сервер. Сервер по цепочке output сможет выйти в интернет и подключится к репозиторию (про них будет написано позже в этом курсе). Но в нашу сторону обновления не полетят, потому что в цепочке input мы этого не разрешали.
В общем, в любом случае, когда наш сервер отправляет запрос куда-нибудь, то ответ будет блокироваться в цепочке input. И невозможно разрешить все, да и не нужно!
Тут вы должны понять, что задача у нас не разрешить подключения с тех адресов куда мы будем отправлять запросы. А просто разрешить все ответные пакеты. И механизм connection tracking как раз может определить ответное ли это соединение или нет.
Connection tracking – это модуль, который определяет состояния соединений. Соединения могут быть:
Получается что все ответные соединения это estableshed + related.
И чтобы разрешить такой трафик, выполните команду:
$ sudo nft add rule inet filter input ct state established,related counter accept
Каждое правило при добавлении получает свой номер (handle). Чтобы посмотреть эти номера нужно использовать ключ -a:
И затем можно удалить правило по его номеру указав путь до цепочки (inet filter input). Например так:
Когда мы выполняли команды добавления правил фаервола они не сохранялись в конфиге /etc/nftables.conf. Поэтому перезагрузка службы вернёт фаервол до первоначального состояния. Чтобы этого не произошло, нужно сохранить все правила в конфиг. Это можно сделать двумя способами.
Сохранение правил в файл (вариант с использованием sudo):
Сохранение правил в файл (под root)
После сохранения правил, просто перезагрузите фаервол и можете посмотреть список правил:
Creating Rules
Now that you’ve created a table and a chain you can finally add some firewall rules. Let’s add a rule to accept SSH.
# nft add rule inet my_table my_filter_chain tcp dport ssh accept
One thing to note here is that since we added this to a table of the inet family a single rule will process both IPv4 and IPv6 packets.
add verb will append the rule to the end of the chain. You can also use the insert verb which will prepend the rule to the head of the chain.
Having added two rules, let’s look at what the ruleset looks like.
You can also add a rule at an arbitrary location in a chain. There are two ways to do this.
In nftables a rule handle is stable and will not change until the rule is deleted. This gives a stable reference to the rule without having to rely on an index, which may change if another rule is inserted.
add rule inet my_table my_filter_chain udp dport 3333 accept # handle 4
: Older version of nftables used the keyword position. This keyword has since been deprecated in favor of handle.
Simple IP/IPv6 Firewall
Установите пакет или git-версию AUR.
Use firewalld
The firewalld software takes control of all the firewalling setup in your system, so you don’t have to know all the details of what is happening in the underground. There are many other system components that can integrate with firewalld, like NetworkManager, libvirt, podman, fail2ban, docker, etc.
Installing Linux kernel with nftables support
Prerequisites: nftables is available in Linux kernels since version 3.13 but this is software under development, so we encourage you to run the latest stable kernel.
Tables Are Namespaces
One interesting thing about tables in nftables is that they’re also full namespaces. This means that two tables can create chains, sets, and other objects that have the same name.
This property means applications can organize rules into their own table without impacting other applications. In iptables it was very difficult for applications to make firewall changes without impacting other applications.
However, there is a caveat to this. Each table and chain hook can be viewed as an independent and separate firewall. This means a packet must be accepted by all of them in order to be allowed. If table_one accepts a packet, it may still be dropped by table_two. This is where hook priorities come into play. A chain with a lower priority value is guaranteed to be executed before a chain with a higher priority value. If the priorities are equal, then the behavior is undefined.
Verdict Maps
Verdict maps are a very interesting feature in nftables that allow you to perform an action based on packet information. Said more plainly, they map match criteria to an action.
Say for example, in order to logically divide your ruleset you want dedicated chains for processing TCP and UDP packets. You can use a verdict map to steer packets to those chains using a single rule.
Of course, just like sets you can create mutable verdict maps.
Your eyes don’t deceive you. The syntax is very similar to sets. In fact, internally sets and verdict maps are built using a common data type.
Now you can use the mutable verdict map in a rule.
External links
Watch some videos:
Watch videos to track updates:
Additional documentations and articles:
nftables has native support for sets. This can be useful if you want a rule to match multiple IP addresses, port numbers, interfaces, or any other match criteria.
Any rule may contain inline sets. This is useful for sets that you don’t expect to change.
The downside to this method is if you need to alter the set you’ll need to replace the rule. For mutable sets you should use a named set.
As another example, instead of our first three rules we could have used an anonymous set.
nftables also has support for mutable named sets. To create them you must specify the type of elements they will contain. Some example types are; ipv4_addr, inet_service, ether_addr.
Let’s create an empty set to start.
Of course, that’s not very effective since our set is empty. Let’s add some elements.
However, attempting to add a range value will yield an error.
To use ranges in our set we must create the set using the interval flags. This is because the kernel must know in advance what type of data the set will store in order to use the appropriate data structure.
Sets can also use range values. The is very useful for IP addresses. To use ranges the set must be created with the interval flags.
: The netmask notation was implicitly converted into a range of IP addresses. We could have also used 10.20.20.0-10.20.20.255 to achieve the same effect.
Sets also support aggregate types and matches. This means a set element can contain multiple types and a rule can use the concatenation operator . when referencing the set.
This example will allow us to match IPv4 addresses, IP protocols, and port numbers all at once.
Now we can add elements to the list.
As you can see, symbolic names (tcp, telnet) are also usable when adding set elements.
Using the set in a rule is similar to the name set above, but the rule must perform the concatenation.
Also worth noting is that concatenation can be used with inline sets. Here is one last example showing that.
Hopefully you now understand how powerful nftables sets are.
: nftables set concatenations are similar to ipset’s aggregate types, e.g. hash:ip,port.
type refers to the kind of chain to be created. Possible types are:
hook refers to an specific stage of the packet while it’s being processed through the kernel. More info in Netfilter hooks.
priority refers to a number used to order the chains or to set them between some Netfilter operations. Possible values are: NF_IP_PRI_CONNTRACK_DEFRAG (-400), NF_IP_PRI_RAW (-300), NF_IP_PRI_SELINUX_FIRST (-225), NF_IP_PRI_CONNTRACK (-200), NF_IP_PRI_MANGLE (-150), NF_IP_PRI_NAT_DST (-100), NF_IP_PRI_FILTER (0), NF_IP_PRI_SECURITY (50), NF_IP_PRI_NAT_SRC (100), NF_IP_PRI_SELINUX_LAST (225), NF_IP_PRI_CONNTRACK_HELPER (300).
policy is the default verdict statement to control the flow in the base chain. Possible values are: accept (default) and drop. Warning: Setting the policy to drop discards all packets that
have not been accepted by the ruleset.
