Nftables (nft list ruleset -ay)

Getting Started

On Debian/Ubuntu based systems, you should be able to install nftables by running:

sudo apt update && sudo apt install nftables

Enable And Start Nftables

sudo systemctl enable nftables
sudo systemctl start nftables

Translation(s): English — Italiano — Русский

nftables is a framework by the Netfilter Project that provides packet filtering, network address translation (NAT) and other packet mangling.

Two of the most common uses of nftables is to provide firewall support and Network Address Translation (NAT).

nftables is the default and recommended firewalling framework in Debian, and it replaces the old iptables (and related) tools.

Rules take action on network packets (e.g. accepting or dropping them) based on whether they match specified criteria.

Nftables — это новый программный продукт, который стремиться изменить существующий подход к фильтрации пакетов. До данного пакета работа с пакетами в сети осуществлялась с помощью утилит (iptables, ip6tables, arptables, entables). Данный framework доступен с версии ядра Linux 3.13 и позволяет запускать команды со старым синтаксисом iptables. По умолчанию же используется новый синтаксис построения команд. В основном используются такие понятия, как наборы, также для правил используют карты и конкатенации (склейки).

В сегодняшней статье мы разберемся как пользоваться nftables. Этот программный продукт позволяет отфильтровывать как каждый пакет, так и поток данных, выполнять NAT трансляцию, регистрировать подозрительную активность в трафике. При создании наборов правил следует избегать дублирования настроек. Nftables позволяет фильтровать и регистрировать одновременно трафик IPv4 и IPv6, благодаря новому семейству правил inet.

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:

# nft flush ruleset

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

Configuration

Don’t forget to add nftables service to startup:

root rc-update add nftables default

NoteIt is suggested to invoke manually after altering the ruleset. Otherwise, if there is an issue during system shutdown and saving the ruleset fails, the system might boot up with an older ruleset.

After first setup:

root touch /var/lib/nftables/rules-save

root systemctl enable —now nftables-restore

Установка nftables

В некоторых дистрибутивах nftables уже установлен (RedHat 8, CentOS 8) по умолчанию. В Debian 10.2 установка производится очень просто:

sudo apt-get install nftables

Nftables (nft list ruleset -ay)

Troubleshooting

Using nftables can interfere with Docker networking (and probably other container runtimes as well). You can find various workarounds on the internet which either involve patching iptables rules and ensuring a defined service start order or disabling dockers iptables management completely which makes using docker very restrictive (think port forwarding or docker-compose).

A reliable method is letting docker run in a separate network namespace where it can do whatever it wants. It is probably best to not use to prevent docker from mixing nftables and iptables rules.

Adjust the 10.0.0.* IP addresses if they are not appropriate for your setup.

iifname docker0 oifname eth0 masquerade

Then, ensure that kernel IP forwarding is enabled.

Now you can setup a firewall and port forwarding for the docker0 interface using nftables without any interference.

External resources

All nftable commands are done with the nft utility from net-firewall/nftables.

root nft add table ip filter

Likewise, a table for arp can be created with

root nft add table arp filter

NoteThe name «filter» used here is completely arbitrary. It could have any name

root nft list tables ip

The contents of the table filter can be listed with:

root nft list table ip filter

using -a with the nft command, it shows the handle of each rule. Handles are used for various operations on specific rules:

root nft -a list table ip filter

root nft delete table ip filter

NoteIf You’re running this command from Bash you need to escape the semicolon

A non-base chain can be added by not specifying the chain configurations between the curly braces.

root nft delete chain ip filter input

NoteChains can only be deleted if there are no rules in them.

root nft add rule ip filter input tcp dport 80 drop

To delete a rule, you first need to get the handle number of the rule. This can be done by using the -a flag on nft:

root nft rule ip filter input tcp dport 80 drop

It is then possible to delete the rule with:

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

Про NFT:  Конвертер в нфт

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

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.

Chain Commands

Chains filter packets and live under tables. You attach each rule to a chain so that packets are caught in the chains filter and are subsequently passed to the chain’s rules.

Create Base Chain

Base chains act as entry points for packets coming from the network stack.

Create Regular Chain

Regular chains do not act as filters, but can act as jump targets. They can help with controlling the flow and organization of your nftables.

ADDRESS_FAMILY=»inet»
TABLE_NAME=»my_table»
CHAIN_NAME=»my_chain»
sudo nft add chain $ADDRESS_FAMILY $TABLE_NAME $CHAIN_NAME

Import / Export

sudo nft —file ruleset.nft

Also, if you want to read from stdin, you can do so like so:

The rules defined within the configuration file at /etc/nftables.conf are what are used when a server restarts.
Thus, we can use the export command and a few manual additions to overwrite this configuration file
to make our dynamically added rules permanent like so:

List Rules In JSON Format

sudo nft —json list ruleset

You can use shorthand -j instead of —json if you wish.
I don’t think that you can use this for export/import. This is just listing the rules in JSON format.</warning.

This will output the rules in a compressed JSON format. If you want to be able to easily be able to read/edit the rules, you can use the jq tool like so:

You may need to install jq by running: sudo apt install jq -y

Schema

Information about the JSON schema can be found online.

Port iptables to nftables

sudo apt install iptables-nftables-compat

Use the porting tool we installed earlier to port the iptables rules over to nftables rules:

The shorthand to —file is just -f.

Tips and tricks

The output of nft list ruleset command is a valid input file for it as well. Current rule set can be saved to file and later loaded back in.

Note: nft list does not output variable definitions, if you had any in your original file they will be lost. Any variables used in rules will be replaced by their value.

Simple stateful firewall

Nftables (nft list ruleset -ay)

The factual accuracy of this article or section is disputed.

Reason: This is not a very simple firewall. I would consider what Arch Linux ships in /etc/nftables.conf simple. Recommend replacing this section with that script and give some directions on how to expand it for specific needs. (Discuss in Talk:Nftables)

Single machine

Add a table:

# nft add table inet my_table

Add the input, forward, and output base chains. The policy for input and forward will be to drop. The policy for output will be to accept.

Add two regular chains that will be associated with tcp and udp:

# nft add chain inet my_table my_tcp_chain
# nft add chain inet my_table my_udp_chain

Related and established traffic will be accepted:

# nft add rule inet my_table my_input ct state related,established accept

All loopback interface traffic will be accepted:

# nft add rule inet my_table my_input iif lo accept

Drop any invalid traffic:

# nft add rule inet my_table my_input ct state invalid drop

Accept ICMP and IGMP:

# nft add rule inet my_table my_input meta l4proto ipv6-icmp accept
# nft add rule inet my_table my_input meta l4proto icmp accept
# nft add rule inet my_table my_input ip protocol igmp accept

New udp traffic will jump to the UDP chain:

# nft add rule inet my_table my_input meta l4proto udp ct state new jump my_udp_chain

New tcp traffic will jump to the TCP chain:

Reject all traffic that was not processed by other rules:

# nft add rule inet my_table my_input meta l4proto udp reject
# nft add rule inet my_table my_input meta l4proto tcp reject with tcp reset
# nft add rule inet my_table my_input counter reject with icmpx port-unreachable

At this point you should decide what ports you want to open to incoming connections, which are handled by the TCP and UDP chains. For example to open connections for a web server add:

# nft add rule inet my_table my_tcp_chain tcp dport 80 accept

# nft add rule inet my_table my_tcp_chain tcp dport 443 accept

To accept SSH traffic on port 22:

# nft add rule inet my_table my_tcp_chain tcp dport 22 accept

To accept incoming DNS requests:

# nft add rule inet my_table my_tcp_chain tcp dport 53 accept
# nft add rule inet my_table my_udp_chain udp dport 53 accept

Be sure to make your changes permanent when satisifed.

Prevent brute-force attacks

Sshguard is program that can detect brute-force attacks and modify firewalls based on IP addresses it temporarily blacklists. See Sshguard#nftables on how to set up nftables to be used with it.

Logging traffic

You can log packets using the log action. The most simple rule to log all incoming traffic is:

# nft add rule inet filter input log

See nftables wiki for details.

Should I build a firewall using a nftables?

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

Nftables Families

Yes, but the nftables one is better

Nftables (nft list ruleset -ay)

Installation

Nftables is very modular, so the bare minimum would depend on your intended purposes. A recommended minimum for basic IPv4 firewalling with NAT would be:

Nftables kernel requirements

NotePlease note: nftables masquerade will not work if iptables masquerade is in the kernel, so be sure to unload or disable it.

To use family inet for tables with mixed IPv4 and IPv6 rules:

Про NFT:  Станьте зарабатывателем денег в NFT: запишитесь на курс Димаса сегодня!

Nftables inet family

If this is not enabled only families ip and ip6 can be used.

Early filtering based on network device requires netdev tables support:

Nftables netdev family

root emerge —ask net-firewall/nftables

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.

Should I mix nftables and iptables/ebtables/arptables rulesets?

No, unless you know what you are doing.

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.

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.

Masquerading

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

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.

Listing rules

% nft 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 ssh counter packets bytes

You can also list rules by chain, for example:

% nft list chain filter ouput
table ip filter
chain output
filter hook output priority
ip daddr .8.8.8 counter packets bytes
tcp dport ssh counter packets bytes

There are plenty of output text modifiers than can be used when listing your rules, to for example, translate IP addresses to DNS names, TCP protocols, etc.

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.

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.

Removing all the rules in a chain

% nft flush chain filter output

What is nftables?

Is the new framework by the Netfilter Project, allowing you to perform packet filtering (firewalling), NAT, mangling and packet classification.

Nftables and Docker

As others have pointed out, it is probably easiest to leave nftables out of the server running docker, and have an external firewall service that you use to manage the traffic going into and out of your server.

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:

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.

Terms

When creating chains, you will need to assign a priority. The priority needs to be 0 or above, and chains with a lower priority get processed first.
Thus, you may wish to think of it as «order» rather than «priority».

Logging of e.g. dropped packages is possible by adding a line with the keyword log at the end of the rule-set, e.g. log prefix «nft.dropinput»;.

Adding a prefix will produce a log entry to /var/log/messages, such as:

/var/log/messagesexample entry in messages file

Logging will be written by default to messages file and will fill up the file with annoying information. Based on using the prefix, the syslog-ng filters will be used to redirect those to its own file nft.log.

/etc/syslog-ng/syslog-ng.confentries for logging nft entries to its own file

Adding a rule at a given position

If you want to add a rule at a given position, you have to use the handle as reference:

Про NFT:  Co-Creating an Alpaca Christmas NFT

% nft -n -a list table filter
table filter
chain output
filter hook output priority
ip protocol tcp counter packets bytes # handle 8
ip saddr .0.0.1 ip daddr .0.0.6 drop # handle 7

If you want to add a rule after the rule with handler number 8, you have to type:

% nft add rule filter output position ip daddr .0.0.8 drop

Now, you can check the effect of that command by listing the rule-set:

% nft -n -a list table filter
table filter
chain output
filter hook output priority
ip protocol tcp counter packets bytes # handle 8
ip daddr .0.0.8 drop # handle 10
ip saddr .0.0.1 ip daddr .0.0.6 drop # handle 7

If you want to insert a rule before the rule with handler number 8, you have to type:

% nft insert rule filter output position ip daddr .0.0.8 drop

Replacing rules

You can replace any rule via the replace command by indicating the rule handle, which you have to find by first listing the ruleset with option -a:

To replace the rule with handle 2, specify its handle number and the new rule that you want to replace it:

nft replace rule filter input handle counter

Listing the ruleset after the above replacement:

# nft list ruleset
table ip filter
chain input
filter hook input priority policy accept
counter packets bytes

you can see that the old rule that counted TCP packets has been replaced by the new rule that counts all packets.

Hints

Some hints folks might find interesting in some situations.

Table Commands

sudo nft list tables

Add Table

ADDRESS_FAMILY=»inet»
TABLE_NAME=»my_table»
sudo nft add table $ADDRESS_FAMILY $TABLE_NAME

Delete Table

ADDRESS_FAMILY=»inet»
TABLE_NAME=»my_table»
sudo nft delete table $ADDRESS_FAMILY $TABLE_NAME

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

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

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

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

sudo nft add table inet test_table

Nftables (nft list ruleset -ay)

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

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

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

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

Nftables (nft list ruleset -ay)

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

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

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

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

sudo nft add rule inet table1 chain_input ip saddr 8.8.8.8 drop

Nftables (nft list ruleset -ay)

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

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

sudo nft delete rule inet table1 chain_input handle 3

Nftables (nft list ruleset -ay)

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

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

sudo nft delete chain inet table1 chain_input

Nftables (nft list ruleset -ay)

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

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

sudo nft delete table inet table1

Nftables (nft list ruleset -ay)

Why a new framework?

The previous framework (iptables) has several problems hard to address, regarding scalability, performance, code maintenance, etc..

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

See the Nftables examples article.

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.

Create a basic IPv4/IPv6 dual-stack table:

# nft add table inet filter

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):

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.

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.

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.

Выводы

Сегодня мы познакомились с современным инструментом для редактирования правил брандмауэра. А также разобрались как выполняется настройка Nftables в Debian 10. Nftables вводит много новых семантических конструкций для более грамотной организации правил — set, map, family. Также данный пакет содержит много усовершенствований по сравнению с набором утилит для брандмауэра x_tables. В рамках этой статьи мы познакомились с инструментом nft, используемым для управления всем множеством правил межсетевого экрана.

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

Appending new rules

To add new rules, you have to specify the corresponding table and the chain that you want to use, eg.

% nft add rule filter output ip daddr .8.8.8 counter

Where filter is the table and output is the chain. The example above adds a rule to match all packets seen by the output chain whose destination is 8.8.8.8, in case of matching it updates the rule counters. Note that counters are optional in nftables.

For those familiar with iptables, the rule appending is equivalent to -A command in iptables.

Prepending new rules

To prepend new rules through the insert command:

% nft insert rule filter output ip daddr .168.1.1 counter

This prepends a rule that will update per-rule packet and bytes counters for traffic addressed to 192.168.1.1.

The equivalent in iptables is:

Note that iptables always provides per-rule counters.

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