Правила сохранения NFT

Usage

nftables makes no distinction between temporary rules made in the command line and permanent ones loaded from or saved to a file.

All rules have to be created or loaded using nft command line utility.

Refer to #Configuration section on how to use.

Current ruleset can be printed with:

# nft list ruleset

Remove all ruleset leaving the system with no firewall:

# nft flush ruleset

Read ruleset from /etc/nftables.conf by restarting nftables.service.

comes with a simple and secure firewall configuration stored in the /etc/nftables.conf file.

The nftables.service will load rules from that file when started or enabled.

Автозагрузка правил iptables

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

Правила сохранения NFT

Сохранить набор правил межсетевого экрана с помощью команды:

sudo iptables-save -f /etc/iptables-conf/iptables_rules.ipv4

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

sudo vi /etc/network/if-pre-up.d/iptables

Заметим — в сети есть много вариантов места размещения скрипта на локальной машине, но я считаю именно размещение в папке if-pre-up.d наиболее верным, так как при этом скрипт будет выполнятся перед включением сетевого интерфейса. Добавляем в данный файл следующий скрипт:

#!/bin/sh
/sbin/iptables-restore < /etc/iptables_rules.ipv4

Правила сохранения NFT

Сохраняем файл iptables Ctrl+O. Выходим из editor Ctrl+X. Устанавливаем необходимые права для созданного файла:

sudo chmod +x /etc/network/if-pre-up.d/iptables

Перезагружаем компьютер и проверяем результат для таблицы filter с помощью команды:

sudo -t filter iptables -L

Для обеспечения безопасности необходимо, чтобы конфигурация iptables применялась до запуска сетевых интерфейсов, сетевых служб и маршрутизации. Если данные условия не будут соблюдены — появляется окно уязвимости между загрузкой операционной системы и правил защиты межсетевого экрана. Для реализации такого варианта защиты можно использовать пакет iptables-persistent.

Автозагрузка правил iptables-persistent

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

sudo apt-get install iptables-persistent

Этот пакет впервые стал доступен в Debian (Squeeze) и Ubuntu (Lucid). Используемые этим пакетом правила iptables хранятся в следующих директориях:

Но они должны быть сохранены в понятном утилите iptables-persistent виде.

Правила сохранения NFT

Правила сохранения NFT

Правила сохранения NFT

Требования к формату данных файлах не задокументированны, что создает некоторые сложности для создания этих файлов вручную. Их можно создать с помощью dpkg-reconfigure:

sudo dpkg-reconfigure iptables-persistent

Правила сохранения NFT

Или можно использовать iptables-save и ip6tables-save:

Правила сохранения NFT

Утилита netfilter-persistent тоже позволяет управлять автозагрузкой правил. Вот её синтаксис:

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

sudo netfilter-persistent save

Для загрузки же сохраненных правил мы можем использовать команду:

sudo netfilter-persistent start

Замечание: После установки netfilter-persistent система при использовании iptables и формата хранения файлов, связанного с ним, начинает при работе выдавать предупреждение

# Warning: iptables-legacy tables present, use iptables-legacy to see them.

Это связано с наличием новой утилиты настройки и редактирования правил Netfilter — nftables, для миграцию на эту утилиту старых правил iptables можно использовать автоматический транслятор правил iptables-translate. Но это уже тема для отдельной статьи.

Правила сохранения NFT

Nftables in Debian the easy way

# aptitude install nftables
# systemctl enable nftables.service

This way, nftables is active at boot. By default, rules are located in /etc/nftables.conf.

To stop nftables from doing anything, just drop all the rules:

To prevent nftables from starting at boot:

# systemctl mask nftables.service

To uninstall it and purge any traces of nftables in your system:

# aptitude purge nftables

Testing your rule

% ping -c .8.8.8
PING .8.8.8 .8.8.8 bytes of data.
bytes from .8.8.8: .31 ms

Then, if we list the rule-set, we obtain:

% nft -nn list table filter
table ip filter
chain input
filter hook input priority

chain output
filter hook output priority
ip daddr .8.8.8 counter packets bytes
tcp dport counter packets bytes

Note that the counters have been updated.

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.

Should I build a firewall using a nftables?

Yes. Building new firewalls on top of iptables is discouraged.

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

Про NFT:  Solrarity nft

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.

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

Removing all the rules in a chain

% nft flush chain filter output

Примеры использования nftables

Теперь рассмотрим примеры nftables. Команда nft – это утилита администрирования фреймворком nftables при управлении потоками данных. Именно с помощью неё выполняется настройка nftables. Использует при работе интерфейс командной строки. Позволяет создавать новые правила nftables, удалять старые и просматривать уже созданные цепочки и таблицы правил.

Создание таблицы в nftables

При создании таблицы (table) должно быть определено семейство (family) адресов. Например, давайте создадим таблицу с именем, test_table, которая отрабатывает одновременно пакеты IPv4 и IPv6:

sudo nft add table inet test_table

Правила сохранения NFT

Создание цепочки в nftables

Цепочки (chain) являются контейнерами для правил. Существуют два типа цепочек:

Базовые цепочки (base chain) — можно использовать в качестве точки входа для пакетов из стека протоколов.

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

Правила сохранения NFT

Примечание: чтобы командный интерпретатор не интерпретировал ; как конец команды необходимо  экранировать точку с запятой следующим образом ;

Эта цепочка фильтрует входящие пакеты. Приоритет (priority) задает порядок, в котором nftables обрабатывает цепочки с одинаковым значением hook. Параметр policy устанавливает действие по умолчанию для правил в этой цепочке. В данном случае мы установили действие accept (принимать пакет).

Добавление правила

Добавить правило (rule) в настраиваемую конфигурацию можно с помощью следующей синтаксической конструкции:

sudo nft add rule inet table1 chain_input ip saddr 8.8.8.8 drop

Правила сохранения NFT

Удаление правила

Для удаления правила nftables используется команда со следующим синтаксисом:

sudo nft delete rule inet table1 chain_input handle 3

Правила сохранения NFT

Удаление цепочки

Цепочка удаляется с помощью следующей команды:

sudo nft delete chain inet table1 chain_input

Правила сохранения NFT

Удаление таблицы

Таблицу можно удалить с конструкции со следующим синтаксисом:

sudo nft delete table inet table1

Правила сохранения NFT

Installation

Alternatively, install , which includes as a dependency, will automatically uninstall (an indirect dependency of the meta package) and prevent conflicts between and when used together.

External resources

See the Nftables examples article.

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.

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

Deleting Rules

Deleting rules is done by using the rule handle similar to the add and insert commands above.

The first step is to find the handle of the rule you want to delete.

Then use the handle to delete the rule.

I knew the iptables syntax. Is there a new syntax in nftables?

Yes, but the nftables one is better

Правила сохранения NFT

Management

Compared to building a ruleset with multiple calls in a shell script, this also ensures that failures in such a script do not end with an only partially applied ruleset.

/etc/nftables-localskeleton nftables config file

You can also backup your rules:

NoteIf you are loading your ruleset with from a file, do not overwrite this file with the nft list ruleset output. This overwrites comments and variable definitions.

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.

Create a basic IPv4/IPv6 dual-stack table:

# nft add table inet filter

Про NFT:  Как вывести в топ nft opensea

Create a chain for input IPv4/IPv6 dual-stack traffic:

A rule to check that all is fine (IPv4/IPv6 dual-stack):

# nft add rule inet filter input counter accept

Show all the previous:

# nft list table inet filter

Flush rules in chain filter/input:

# nft flush chain inet filter input

Delete the chain filter/input:

# nft delete chain inet filter input

Delete the table filter:

# nft delete table inet filter

The family parameter is optional. The default is ‘ip’. Other families are ‘inet’, ‘ip6’, ‘arp’, ‘bridge’ or ‘netdev’:

# nft add table ip6 filter
# nft add chain ip6 filter input
# nft add rule ip6 filter input counter accept

Debian ships example configurations in:

Count traffic on destination port tcp/22 (IPv4/IPv6 dual-stack):

# nft add rule inet filter input tcp dport 22 counter

Count and accept traffic in 80/tcp and 443/tcp in new and established state (IPv4/IPv6 dual-stack):

Troubleshooting

Before loading new or edited rules check them with

No such file or directory

If this error is printed for every chain of a table definition make sure, that the table’s family is available through the kernel. This happens for example if the table uses family inet and the kernel configuration did not enable mixed IPv4 and IPv6 rules (CONFIG_NF_TABLES_INET).

A set definition of IP ranges causes this error if ranges overlap. For example 224.0.0.0/3 and 240.0.0.0/5 overlap completely. Either add auto-merge to the set’s options, drop the range that is fully included or change syntax to 224.0.0.0-255.255.255.255.

Default configuration of the save and restore function use numeric mode to store the rule set. The persisted rule set could have changed from the original upload from a manually written file. Such a transformation might break things. Therefore make sure:

If all three conditions are met remove the -n parameter from SAVE_OPTIONS in /etc/conf.d/nftables. Then load your rule set again from the manually written file and restart the service again. This cycles through save and restore and should create a fully working rule set.

This affected at least version 0.9.9, see bug #819456.

Family netdev and ingress hook

Broken packets should be rejected early which requires an ingress hook for family netdev. This sets up a chain that acts for a dedicated network device before packets enter further processing – improved performance. The configuration looks like this:

Family netdev and ingress chain

Mind the device name enp4s0. If this changes for example when changing hardware or an upgrade changed device naming this family is broken. In turn none of the rules will be loaded. The error looks like this (filename and line numbers differ depending on the host configuration):

Error at chains instead of non-existing device

Check the device name is actually correct and exists, e.g. ip addr list.

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.

Examples

When using jumps in configuration file, it is necessary to define the target chain first. Otherwise one could end up with Error: Could not process rule: No such file or directory.

Different rules for different interfaces

If your box has more than one network interface, and you would like to use different rules for different interfaces, you may want to use a «dispatching» filter chain, and then interface-specific filter chains. For example, let us assume your box acts as a home router, you want to run a web server accessible over the LAN (interface enp3s0), but not from the public internet (interface enp2s0), you may want to consider a structure like this:

Alternatively you could choose only one iifname statement, such as for the single upstream interface, and put the default rules for all other interfaces in one place, instead of dispatching for each interface.

nftables has a special keyword masquerade «where the source address is automagically set to the address of the output interface» (source). This is particularly useful for situations in which the IP address of the interface is unpredictable or unstable, such as the upstream interface of routers connecting to many ISPs. Without it, the Network Address Translation rules would have to be updated every time the IP address of the interface changed.

To use it:

Example for a machine with two interfaces: LAN connected to enp3s0, and public internet connected to enp2s0:

Since the table type is inet both IPv4 and IPv6 packets will be masqueraded. If you want only ipv4 packets to be masqueraded (since extra adress space of IPv6 makes NAT not required) meta nfproto ipv4 expression can be used infront of oifname «enp2s0» or the table type can be changed to ip.

NAT with port forwarding

The factual accuracy of this article or section is disputed.

Reason: I think my_postrouting chain will cause the destination computer see that connections are made by router rather than from some global IP. Also this does not masquerade outbound traffic. (Discuss in Talk:Nftables)

This example will forward ports 22 and 80 to destination_ip. You will need to set net.ipv4.ip_forward and net.ipv4.conf.wan_interface.forwarding to 1 via sysctl.

Count new connections per IP

To print the blackholed IPs, run nft list set inet dev blackhole.

Про NFT:  Оптимизация распределения NFT Solana для эффективных цифровых транзакций

Removing rules

You have to obtain the handle to delete a rule via the -a option. The handle is automagically assigned by the kernel and it uniquely identifies the rule.

% nft -a list table filter
table ip filter
chain input
filter hook input priority

chain output
filter hook output priority
ip daddr .168.1.1 counter packets bytes # handle 5

% nft delete rule filter output handle

Note: There are plans to support rule deletion by passing:

% nft delete rule filter output ip saddr .168.1.1 counter

but this is not yet implemented. So you’ll have to use the handle to delete rules until that feature is implemented.

Listing Rules

In previous examples above we listed the entire rule set. There are many other ways to list a subset of rules.

List all rules in a given table.

List all rules in a given chain.

Configuration

To read input from a file use the -f/—file option:

# nft —file filename

Note that any rules already loaded are not automatically flushed.

See for a complete list of all commands.

ip (i.e. IPv4) is the default family and will be used if family is not specified.

To create one rule that applies to both IPv4 and IPv6, use inet. inet allows for the unification of the ip and ip6 families to make defining rules for both easier.

See nft(8) § ADDRESS FAMILIES for a complete description of address families.

# nft add table family_type table_name

To list all tables:

# nft list tables

List chains and rules in a table

To list all chains and rules of a specified table do:

# nft list table family_type table_name

For example, to list all the rules of the my_table table of the inet family:

# nft list table inet my_table

To delete a table do:

# nft delete table family_type table_name

This will destroy all chains in the table.

To flush all rules from a table do:

# nft flush table family_type table_name

The purpose of chains is to hold #Rules. Unlike chains in iptables, there are no built-in chains in nftables. This means that if no chain uses any types or hooks in the netfilter framework, packets that would flow through those chains will not be touched by nftables, unlike iptables.

Chains have two types. A base chain is an entry point for packets from the networking stack, where a hook value is specified. A regular chain may be used as a jump target for better organization.

To add a base chain specify hook and priority values:

chain_type can be filter, route, or nat.

For IPv4/IPv6/Inet address families hook_type can be prerouting, input, forward, output, or postrouting. See nft(8) § ADDRESS FAMILIES for a list of hooks for other families.

For example, to add a base chain that filters input packets:

Replace add with create in any of the above to add a new chain but return an error if the chain already exists.

# nft add chain family_type table_name chain_name

For example, to add a regular chain named my_tcp_chain to the my_table table of the inet address family do:

# nft add chain inet my_table my_tcp_chain

# nft list chain family_type table_name chain_name

# nft list chain inet my_table my_output

To edit a chain, simply call it by its name and define the rules you want to change.

For example, to change the my_input chain policy of the default table from accept to drop

Delete a chain

To delete a chain do:

# nft delete chain family_type table_name chain_name

The chain must not contain any rules or be a jump target.

Flush rules from a chain

To flush rules from a chain do:

# nft flush chain family_type table_name chain_name

Rules are either constructed from expressions or statements and are contained within chains.

To add a rule to a chain do:

# nft add rule family_type table_name chain_name handle handle_value statement

The rule is appended at handle_value, which is optional. If not specified, the rule is appended to the end of the chain.

The —handle switch, which can be added to any valid list command, must be used to determine a rule handle. This switch tells nft to list the handles in its output. The —numeric argument is useful for viewing some numeric output, like unresolved IP addresses.

# nft —handle —numeric list chain inet my_table my_input

To prepend the rule to the position do:

# nft insert rule family_type table_name chain_name handle handle_value statement

If handle_value is not specified, the rule is prepended to the chain.

There are various expressions available in nftables and, for the most part, coincide with their iptables counterparts. The most noticeable difference is that there are no generic or implicit matches. A generic match was one that was always available, such as —protocol or —source. Implicit matches were protocol-specific, such as —sport when a packet was determined to be TCP.

Individual rules can only be deleted by their handles. Obtaining the handles was shown at #Add rule. Assuming

All the chains in a table can be flushed with the nft flush table command. Individual chains can be flushed using either the nft flush chain or nft delete rule commands.

# nft flush table table_name
# nft flush chain family_type table_name chain_name
# nft delete rule family_type table_name chain_name

The first command flushes all of the chains in the ip table_name table. The second flushes the chain_name chain in the family_type table_name table. The third deletes all of the rules in chain_name chain in the family_type table_name table.

To add or delete elements from the set, use:

Flush the current ruleset:

Dump the current ruleset:

Now you can edit /tmp/nftables and apply your changes with:

# nft -f /tmp/nftables

Оцените статью
NFT Эксперт