‘python-nftables’ failed · Issue #319 · voxpupuli

:root {
—animation-state: paused;
}

/* user picked a theme where the «regular» scheme is dark */
/* user picked a theme a light scheme and also enabled a dark scheme */

/* deal with light scheme first */
@media (prefers-color-scheme: light) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* then deal with dark scheme */
@media (prefers-color-scheme: dark) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* these styles need to live here because the SVG has a different scope */
.dots {
animation-name: loader;
animation-timing-function: ease-in-out;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-play-state: var(—animation-state);
stroke: #fff;
stroke-width: 0.5px;
transform-origin: center;
opacity: 0;
r: max(1vw, 11px);
cy: 50%;
filter: saturate(2) opacity(0.85);
}

.dots:first-child {
fill: var(—quaternary);
}

.dots:nth-child(2) {
fill: var(—quaternary);
animation-delay: 0.15s;
}

.dots:nth-child(3) {
fill: var(—highlight);
animation-delay: 0.3s;
}

.dots:nth-child(4) {
fill: var(—tertiary);
animation-delay: 0.45s;
}

.dots:nth-child(5) {
fill: var(—tertiary);
animation-delay: 0.6s;
}

@keyframes loader {
0% {
opacity: 0;
transform: scale(1);
}
45% {
opacity: 1;
transform: scale(0.7);
}
65% {
opacity: 1;
transform: scale(0.7);
}
100% {
opacity: 0;
transform: scale(1);
}
}

OpenWrt Forum

:root {
—animation-state: paused;
}

/* user picked a theme where the «regular» scheme is dark */
/* user picked a theme a light scheme and also enabled a dark scheme */

/* deal with light scheme first */
@media (prefers-color-scheme: light) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* then deal with dark scheme */
@media (prefers-color-scheme: dark) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* these styles need to live here because the SVG has a different scope */
.dots {
animation-name: loader;
animation-timing-function: ease-in-out;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-play-state: var(—animation-state);
stroke: #fff;
stroke-width: 0.5px;
transform-origin: center;
opacity: 0;
r: max(1vw, 11px);
cy: 50%;
filter: saturate(2) opacity(0.85);
}

.dots:first-child {
fill: var(—quaternary);
}

.dots:nth-child(2) {
fill: var(—quaternary);
animation-delay: 0.15s;
}

.dots:nth-child(3) {
fill: var(—highlight);
animation-delay: 0.3s;
}

.dots:nth-child(4) {
fill: var(—tertiary);
animation-delay: 0.45s;
}

.dots:nth-child(5) {
fill: var(—tertiary);
animation-delay: 0.6s;
}

@keyframes loader {
0% {
opacity: 0;
transform: scale(1);
}
45% {
opacity: 1;
transform: scale(0.7);
}
65% {
opacity: 1;
transform: scale(0.7);
}
100% {
opacity: 0;
transform: scale(1);
}
}

OpenWrt Forum

:root {
—animation-state: paused;
}

/* user picked a theme where the «regular» scheme is dark */
:root {
—primary: #dddddd;
—secondary: #222222;
—tertiary: #0f82af;
—quaternary: #c14924;
—highlight: #a87137;
—success: #1ca551;
}

/* these styles need to live here because the SVG has a different scope */
.dots {
animation-name: loader;
animation-timing-function: ease-in-out;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-play-state: var(—animation-state);
stroke: #fff;
stroke-width: 0.5px;
transform-origin: center;
opacity: 0;
r: max(1vw, 11px);
cy: 50%;
filter: saturate(2) opacity(0.85);
}

.dots:first-child {
fill: var(—quaternary);
}

.dots:nth-child(2) {
fill: var(—quaternary);
animation-delay: 0.15s;
}

.dots:nth-child(3) {
fill: var(—highlight);
animation-delay: 0.3s;
}

.dots:nth-child(4) {
fill: var(—tertiary);
animation-delay: 0.45s;
}

.dots:nth-child(5) {
fill: var(—tertiary);
animation-delay: 0.6s;
}

@keyframes loader {
0% {
opacity: 0;
transform: scale(1);
}
45% {
opacity: 1;
transform: scale(0.7);
}
65% {
opacity: 1;
transform: scale(0.7);
}
100% {
opacity: 0;
transform: scale(1);
}
}

DietPi Community Forum

:root {
—animation-state: paused;
}

/* user picked a theme where the «regular» scheme is dark */
/* user picked a theme a light scheme and also enabled a dark scheme */

/* deal with light scheme first */
@media (prefers-color-scheme: light) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* then deal with dark scheme */
@media (prefers-color-scheme: dark) {
:root {
—primary: #222222;
—secondary: #ffffff;
—tertiary: #0088cc;
—quaternary: #e45735;
—highlight: #ffff4d;
—success: #009900;
}
}

/* these styles need to live here because the SVG has a different scope */
.dots {
animation-name: loader;
animation-timing-function: ease-in-out;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-play-state: var(—animation-state);
stroke: #fff;
stroke-width: 0.5px;
transform-origin: center;
opacity: 0;
r: max(1vw, 11px);
cy: 50%;
filter: saturate(2) opacity(0.85);
}

.dots:first-child {
fill: var(—quaternary);
}

.dots:nth-child(2) {
fill: var(—quaternary);
animation-delay: 0.15s;
}

.dots:nth-child(3) {
fill: var(—highlight);
animation-delay: 0.3s;
}

.dots:nth-child(4) {
fill: var(—tertiary);
animation-delay: 0.45s;
}

.dots:nth-child(5) {
fill: var(—tertiary);
animation-delay: 0.6s;
}

@keyframes loader {
0% {
opacity: 0;
transform: scale(1);
}
45% {
opacity: 1;
transform: scale(0.7);
}
65% {
opacity: 1;
transform: scale(0.7);
}
100% {
opacity: 0;
transform: scale(1);
}
}

OpenWrt Forum

Loading

Things tried

-installed net-firewall/ipset -modules

-tried copying a stock cent kernel config and using that.

-added all ip_set modules in kernel and rebooted.

I cannot seem to find any reference this this specific error.

(not sure why code tag isnt working)

Things tried

-installed net-firewall/ipset -modules

-tried copying a stock cent kernel config and using that.

-added all ip_set modules in kernel and rebooted.

I cannot seem to find any reference this this specific error.

(not sure why code tag isnt working)

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

<!— —>

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

clutch2sft opened this issue

Mar 29, 2022

· 12 comments

issue report with a confirmed bug

pull request/issue for core (in-tree) packages

I am trying to add SNAT NFT rule for IPv6 in my router. Any ougoing packet through interface enp1s0 should be SNATted with the below IPv6 address. These are the rules I tried and errors.

nft add rule inet nat postrouting oifname «enp1s0» snat ip6 to
2401:fb00:0:1ff::32d/64

Error: Could not process rule: No such file or directory
add rule inet nat postrouting oifname enp1s0 snat ip6 to 2401:fb00:0:1ff::32d/64
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

nft add rule nat postrouting oifname «enp1s0» snat to
2401:fb00:0:1ff::32d

Error: Could not resolve hostname: Address family for hostname not supported
add rule nat postrouting oifname enp1s0 snat to 2401:fb00:0:1ff::32d
^^^^^^^^^^^^^^^^^^^^

nft add rule nat postrouting ip6 oifname enp1s0 snat to
2401:fb00:0:1ff::32d

Error: syntax error, unexpected oifname
add rule nat postrouting ip6 oifname enp1s0 snat to 2401:fb00:0:1ff::32d
^^^^^^^

These are the issues I get. Any help would be appreciated.

I’m trying to add an IPSec-related rule to my router:

# nft add rule inet t_fw c_in 'ip saddr 192.168.10.17 ipsec in reqid 1 accept'
Error: Could not process rule: No such file or directory
add rule inet t_fw c_in ip saddr 192.168.10.17 ipsec in reqid 1 accept ^^^^^^^^^^^^^^

The system is a Raspberry Pi running Raspbian 11, Kernel 5.15.23-v7. nftables, libmnl and libnftnl have been compiled manually today with sources from current Git master. nftables version is «nftables v1.0.2 (Lester Gooch)».

I did the same compile job (from the same sources) on a x86 test system (running Debian 11 with the default kernel), and I could add this rule without any problems.

What am I doing wrong?

asked Feb 27 at 19:06

Zygmunt's user avatar

Just in case someone runs into the same problem: I recompiled the Raspbian kernel, and enabled all XFRM and nftables-realted options, some of which used to be disabled beforehand. The rule is working fine now.

answered Mar 1 at 20:11

Zygmunt's user avatar

jq '.nftables | length' ~/nftables.json
for i in $(seq 1 224); do \ jq --argjson index "$i" '{"nftables": [.nftables[0], .nftables[$index]]}' ~/nftables.json | tee nft.json; \ sudo nft --json --file nft.json || break; \
done
{ "nftables": [ { "metainfo": { "json_schema_version": 1 } }, { "add": { "chain": { "family": "inet", "table": "firewalld", "name": "raw_PREROUTING", "type": "filter", "hook": "prerouting", "prio": -290 } } } ]
}
internal:0:0-0: Error: No such file or directory

As this was just adding a chain, the only thing that could be wrong here is a missing table, which was confirmed by:

$ sudo nft list tables
table bridge filter
table bridge nat
sudo nft add table inet firewalld
table inet firewalld
table ip firewalld
table ip6 firewalld

Состояние перевода: На этой странице представлен перевод статьи nftables. Дата последней синхронизации: 11 июля 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

nftables состоит из трёх основных частей: низкоуровневая реализация в ядре, библиотека libnl, которая обеспечивает netlink-взаимодействие, и пользовательский фронтенд nftables. Ядро предоставляет интерфейс настройки netlink, а также занимается runtime-выполнением наборов правил. Библиотека libnl содержит низкоуровневые функции для взаимодействия с ядром. Фронтенд nftables — то, с чем пользователь взаимодействует утилитой nft.

Подробную информацию о nftables можно найти на вики-странице проекта.

Errors on running nft as kernel modules are missing from:
/lib/modules/5.4.40-v7l+/kernel/net/netfilter

Missing nf_tables.ko and all relevant nft_*.ko files

sudo apt install nftables
nftables v0.9.0 (Fearless Fosdick)
nftables.service loaded failed failed nftables

But with anything in .conf file service fails with errors:
/etc/nftables.conf:2:1-14: Error: Could not process rule: Operation not supported flush ruleset

Same for running nft in an interactive session

Примеры

/etc/nftables.conf
flush ruleset
table inet my_table {	set LANv4 {	type ipv4_addr	flags interval	elements = { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 }	}	set LANv6 {	type ipv6_addr	flags interval	elements = { fd00::/8, fe80::/10 }	}	chain my_input_lan {	udp sport 1900 udp dport >= 1024 meta pkttype unicast limit rate 4/second burst 20 packets accept comment "Accept UPnP IGD port mapping reply"	udp sport netbios-ns udp dport >= 1024 meta pkttype unicast accept comment "Accept Samba Workgroup browsing replies"	}	chain my_input {	type filter hook input priority filter; policy drop;	iif lo accept comment "Accept any localhost traffic"	ct state invalid drop comment "Drop invalid connections"	ct state established,related accept comment "Accept traffic originated from us"	meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, mld-listener-query, mld-listener-report, mld-listener-reduction, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert, ind-neighbor-solicit, ind-neighbor-advert, mld2-listener-report } accept comment "Accept ICMPv6"	meta l4proto icmp icmp type { destination-unreachable, router-solicitation, router-advertisement, time-exceeded, parameter-problem } accept comment "Accept ICMP"	ip protocol igmp accept comment "Accept IGMP"	udp dport mdns ip6 daddr ff02::fb accept comment "Accept mDNS"	udp dport mdns ip daddr 224.0.0.251 accept comment "Accept mDNS"	ip6 saddr @LANv6 jump my_input_lan comment "Connections from private IP address ranges"	ip saddr @LANv4 jump my_input_lan comment "Connections from private IP address ranges"	counter comment "Count any other traffic"	}	chain my_forward {	type filter hook forward priority filter; policy drop;	# Drop everything forwarded to us. We do not forward. That is routers job.	}	chain my_output {	type filter hook output priority filter; policy accept;	# Accept every outbound connection	}
}

/etc/nftables.conf
flush ruleset
table inet my_table {	set LANv4 {	type ipv4_addr	flags interval	elements = { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 }	}	set LANv6 {	type ipv6_addr	flags interval	elements = { fd00::/8, fe80::/10 }	}	chain my_input_lan {	meta l4proto { tcp, udp } th dport 2049 accept comment "Accept NFS"	udp dport netbios-ns accept comment "Accept NetBIOS Name Service (nmbd)"	udp dport netbios-dgm accept comment "Accept NetBIOS Datagram Service (nmbd)"	tcp dport netbios-ssn accept comment "Accept NetBIOS Session Service (smbd)"	tcp dport microsoft-ds accept comment "Accept Microsoft Directory Service (smbd)"	udp sport { bootpc, 4011 } udp dport { bootps, 4011 } accept comment "Accept PXE"	udp dport tftp accept comment "Accept TFTP"	}	chain my_input {	type filter hook input priority filter; policy drop;	iif lo accept comment "Accept any localhost traffic"	ct state invalid drop comment "Drop invalid connections"	ct state established,related accept comment "Accept traffic originated from us"	meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, mld-listener-query, mld-listener-report, mld-listener-reduction, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert, ind-neighbor-solicit, ind-neighbor-advert, mld2-listener-report } accept comment "Accept ICMPv6"	meta l4proto icmp icmp type { destination-unreachable, router-solicitation, router-advertisement, time-exceeded, parameter-problem } accept comment "Accept ICMP"	ip protocol igmp accept comment "Accept IGMP"	udp dport mdns ip6 daddr ff02::fb accept comment "Accept mDNS"	udp dport mdns ip daddr 224.0.0.251 accept comment "Accept mDNS"	ip6 saddr @LANv6 jump my_input_lan comment "Connections from private IP address ranges"	ip saddr @LANv4 jump my_input_lan comment "Connections from private IP address ranges"	tcp dport ssh accept comment "Accept SSH on port 22"	tcp dport ipp accept comment "Accept IPP/IPPS on port 631"	tcp dport { http, https, 8008, 8080 } accept comment "Accept HTTP (ports 80, 443, 8008, 8080)"	udp sport bootpc udp dport bootps ip saddr 0.0.0.0 ip daddr 255.255.255.255 accept comment "Accept DHCPDISCOVER (for DHCP-Proxy)"	}	chain my_forward {	type filter hook forward priority filter; policy drop;	# Drop everything forwarded to us. We do not forward. That is routers job.	}	chain my_output {	type filter hook output priority filter; policy accept;	# Accept every outbound connection	}
}

Ограничение скорости передачи

table inet my_table {	chain my_input {	type filter hook input priority filter; policy drop;	iif lo accept comment "Accept any localhost traffic"	ct state invalid drop comment "Drop invalid connections"	meta l4proto icmp icmp type echo-request limit rate over 10/second burst 4 packets drop comment "No ping floods"	meta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 10/second burst 4 packets drop comment "No ping floods"	ct state established,related accept comment "Accept traffic originated from us"	meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, mld-listener-query, mld-listener-report, mld-listener-reduction, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert, ind-neighbor-solicit, ind-neighbor-advert, mld2-listener-report } accept comment "Accept ICMPv6"	meta l4proto icmp icmp type { destination-unreachable, router-solicitation, router-advertisement, time-exceeded, parameter-problem } accept comment "Accept ICMP"	ip protocol igmp accept comment "Accept IGMP"	tcp dport ssh ct state new limit rate 15/minute accept comment "Avoid brute force on SSH"	}
}

Если вы используете переходы (jumps), то целевая цепочка должна быть описана до перехода. Иначе будет получена ошибка Error: Could not process rule: No such file or directory.

table inet my_table { chain web { tcp dport http accept tcp dport 8080 accept } chain my_input { type filter hook input priority filter; ip saddr 10.0.2.0/24 jump web drop }
}

Несколько сетевых интерфейсов с разными правилами

Если у вашей системы несколько сетевых интерфейсов и вы хотите использовать для них разные наборы правил, то создайте фильтрующую цепочку-диспетчер, а после неё опишите цепочки для сетевых интерфейсов. Например, пусть ваша машина выступает в качестве домашнего маршрутизатора и вы желаете запустить веб-сервер, доступный по локальной сети (интерфейс enp3s0), но не из публичного интернета (интерфейс enp2s0). Создайте таблицу вроде этой:

Про NFT:  Раскрытие секретов NFT-китов: путешествие с мальчиком, который их продал

table inet my_table { chain my_input { # this chain serves as a dispatcher type filter hook input priority filter; iif lo accept # always accept loopback iifname enp2s0 jump my_input_public iifname enp3s0 jump my_input_private reject with icmpx type port-unreachable # refuse traffic from all other interfaces } chain my_input_public { # rules applicable to public interface interface ct state {established,related} accept ct state invalid drop udp dport bootpc accept tcp dport bootpc accept reject with icmpx type port-unreachable # all other traffic } chain my_input_private { ct state {established,related} accept ct state invalid drop udp dport bootpc accept tcp dport bootpc accept tcp port http accept tcp port https accept reject with icmpx type port-unreachable # all other traffic } chain my_output { # we let everything out type filter hook output priority filter; accept }
}

Можно поступить иначе — задать только одну строку iifname, например для интерфейса веб-сервера, а правила для остальных интерфейсов вместо диспетчеризации описать в одном месте.

Правила работы маскарадинга:

  • опция masquerading в ядре Linux должна быть включена (в стандартном ядре она включена по умолчанию); в противном случае задайте параметр ядра CONFIG_NFT_MASQ=m.
  • ключевое слово masquerade может использоваться только в цепочке типа nat.
  • masquerading является подвидом SNAT, поэтому работает только для исходящих пакетов.

Пример правил межсетевого экрана для машины с двумя интерфейсами, локальным enp3s0 и публичным enp2s0:

table inet my_nat { chain my_masquerade { type nat hook postrouting priority srcnat; oifname "enp2s0" masquerade }
}

Поскольку таблица выше относится к типу inet, то маскарадингу подвергаются пакеты и IPv4, и IPv6. Чтобы ограничить маскарадинг только IPv4-пакетами (т.к. у IPv6 большое пространство адресов и NAT не требуется) либо добавьте выражение meta nfproto ipv4 перед oifname "enp2s0" masquerade, либо измените тип таблицы на ip.

NAT с пробросом портов

table ip my_nat { chain my_prerouting { type nat hook prerouting priority dstnat; tcp dport { ssh, http } dnat to destination_ip } chain my_postrouting { type nat hook postrouting priority srcnat; ip daddr destination_ip masquerade }
}

Счётчик новых соединений

/etc/nftables.conf
table inet filter { set https { type ipv4_addr; flags dynamic; size 65536; timeout 60m; } chain input { type filter hook input priority filter; ct state new tcp dport 443 update @https { ip saddr counter } }
}

/etc/nftables.conf
table inet dev { set blackhole { type ipv4_addr; flags dynamic, timeout; size 65536; } chain input { ct state new tcp dport 443 \ meter flood size 128000 { ip saddr timeout 10s limit rate over 10/second } \ add @blackhole { ip saddr timeout 1m } ip saddr @blackhole counter drop }
}

Для вывода заблокированных адресов выполните nft list set inet dev blackhole.

Configuration

  • stores the currently loaded ruleset in
  • loads the currently loaded ruleset in
  • is intended to be called on system shutdown, verifies if SAVE_ON_STOP is enabled in and saves the ruleset
  • is intended to be called on system boot and loads the last saved ruleset
  • flushes the currently loaded ruleset
  • lists the currently loaded ruleset

Don’t forget to add nftables service to startup:

root rc-update add nftables default

Note
It 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

Examples

See the Nftables examples article.

How to reproduce (e. g Puppet code you use)

This was for an initial Code Manager deployment, using code that ran OK on RHEL/CentOS 7

Установка

Установите пакет или git-версию AUR.

What are you seeing

In the puppet log, when it tried to reload firewalld, it spewed this:

Error: COMMAND_FAILED: ‘python-nftables’ failed: internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

internal:0:0-0: Error: Could not process rule: No such file or directory

Firewalld is now broken.
I put in a help ticket to Red Hat, but I wanted to see if you folks have seen this mess before.

Affected Puppet, Ruby, OS and module versions/distributions

Puppet: PE 2021.4
RHEL 8.5

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.

Sample Set

table netdev filter { set blocked_ipv4 { 169.254.0.0/16, 224.0.0.0/3, 240.0.0.0/5 } # fix the last two IPs overlapping auto-merge
}

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:

  1. that /etc/conf.d/nftables contains the parameter -n for the SAVE_OPTIONS
  2. and loading your rule set as root yields a working configuration
  3. and the save and restore cycle of restarting nftables service causes the issue

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

table netdev filter { chain ingress { type filter hook ingress device enp4s0 priority -500; # Drop all fragments. ip frag-off & 0x1fff != 0 counter drop # Drop XMAS packets. tcp flags & (fin|syn|rst|psh|ack|urg) == fin|syn|rst|psh|ack|urg counter drop # Drop NULL packets. tcp flags & (fin|syn|rst|psh|ack|urg) == 0x0 counter drop # Drop uncommon MSS values. tcp flags syn tcp option maxseg size 1-535 counter drop }
}

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

/etc/nftables.conf:94:9-15: Error: Could not...
chain ingress { ^^^^^^^
/etc/nftables.conf:94:9-15: Error: Could not... chain ingress { ^^^^^^^
/etc/nftables.conf:94:9-15: Error: Could not... chain ingress { ^^^^^^^
/etc/nftables.conf:94:9-15: Error: Could not... chain ingress { ^^^^^^^
/etc/nftables.conf:94:9-15: Error: Could not... chain ingress { ^^^^^^^

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

Usage

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

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

root nft list tables ip

table filter

The contents of the table filter can be listed with:

root nft list table ip filter

table ip filter { chain input { type filter hook input priority 0; ct state established,related accept iifname "lo" accept ip protocol icmp accept drop }
}

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

table ip filter { chain input { type filter hook input priority 0; ct state established,related accept # handle 2 iifname "lo" accept # handle 3 ip protocol icmp accept # handle 4 drop # handle 5 }
}

root nft delete table ip filter

Note
If 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

Note
Chains 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

table ip filter { chain input { type filter hook input priority 0; tcp dport http drop # handle 2 }
}

It is then possible to delete the rule with:

root nft delete rule ip filter input handle 2

Management

Atomic rule loading

supports atomic rule replacement by using . Thus it is possible to conveniently manage the rules in a text file. Comments may be added to the file by prefixing them with #, as with shell scripts; they can also be appended to the end of rules as comment "<arbitrary string>", and these will be preserved as-is in output.

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.

Про NFT:  Заказать создание NFT-арта (Art) для продажи

/etc/nftables-localskeleton nftables config file

#! /sbin/nft -f
# this is a skeleton file for an nftables ruleset
# load it with nft -f /etc/nftables-local
# it is supported to define variables here, that can later on be
# expanded in rule definitions
define http_ports = {80, 443}
flush ruleset
table inet local { chain input { type filter hook input priority 0; policy drop; tcp dport $http_ports counter accept comment "incoming http traffic"; } chain output { type filter hook output priority 0; policy drop; }
}

You can also backup your rules:

root nft list ruleset >> backup.nft

Note
If 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.

Logging

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

Jun 07 13:35:19 host kernel: nft.dropinput IN=eno1 OUT= MAC=...

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

#add destination for nft messages
destination netfilter { file("/var/log/nft.log"); };
#add filter for nft (netfilter) messages and messages
filter f_netfilter { message("nft"); };
filter f_messages { not message("nft"); };
#use filter for nft logging
log { source(src); filter(f_netfilter); destination(netfilter); };
#modify original lines to filter out nft messages
log { source(src); filter(f_messages); destination(messages); };
log { source(src); filter(f_messages); destination(console_all); };

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

[*] Networking support ---> Networking options ---> [*] Network packet filtering framework (Netfilter) ---> Core Netfilter Configuration ---> <M> Netfilter connection tracking support <M> Netfilter nf_tables support <M> Netfilter nf_tables conntrack module <M> Netfilter nf_tables counter module <M> Netfilter nf_tables log module <M> Netfilter nf_tables limit module <M> Netfilter nf_tables masquerade support <M> Netfilter nf_tables nat module IP: Netfilter Configuration ---> <M> IPv4 nf_tables support <M> IPv4 packet rejection <M> IP tables support (required for filtering/masq/NAT) <M> Packet filtering <M> REJECT target support <M> iptables NAT support <M> MASQUERADE target support

Note
Please 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:

Nftables inet family

[*] Networking support ---> Networking options ---> [*] Network packet filtering framework (Netfilter) ---> Core Netfilter Configuration ---> <M> Netfilter nf_tables support [*] Netfilter nf_tables mixed IPv4/IPv6 tables support

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

[*] Networking support ---> Networking options ---> [*] Network packet filtering framework (Netfilter) ---> Core Netfilter Configuration ---> <M> Netfilter nf_tables support [*] Netfilter nf_tables netdev tables support

root emerge --ask net-firewall/nftables

Настройка

Утилита 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).

Есть два типа цепочек. Базовая цепочка является точкой входа для пакетов из сетевого стека; в ней указывается хук. Обычная цепочка может использоваться в качестве цели перехода и используется для лучшей организации правил.

В командах ниже параметр семейство будет указываться не всегда; если его нет, то подразумевается семейство ip.

Добавить обычную цепочку цепочка в таблицу таблица:

# nft add chain семейство таблица цепочка

Например, чтобы добавить обычную цепочку my_tcp_chain к таблице my_table семейства адресации inet, выполните:

# nft add chain inet my_table my_tcp_chain

Чтобы добавить базовую цепочку, укажите хук и значение приоритета:

# nft add chain семейство таблица цепочка '{ type тип hook хук priority приоритет ; }'

тип может принимать значения filter, route или nat.

Для семейств адресации IPv4/IPv6/Inet хук может принимать значения prerouting, input, forward, output или postrouting. Описание других возможных хуков вы найдёте в руководстве nft(8) § ADDRESS FAMILIES.

Например, добавим базовую цепочку для фильтрации входящих пакетов:

# nft add chain inet my_table my_chain '{ type filter hook input priority 0; }'

Если заменить команду add на create в любом из правил выше, то цепочка тоже будет создана, но если цепочка с таким названием уже существует, то вы получите сообщение об ошибке.

Следующая команда выводит на экран все правила в цепочке:

# nft list chain семейство таблица цепочка

Например, следующая команда выведет правила цепочки my_output таблицы my_table семейства inet:

# nft list chain inet my_table my_output

Для редактирования цепочки укажите её название и правила, которые нужно изменить:

# nft chain семейство таблица цепочка '{ [ type тип hook хук device устройство priority приоритет ; policy политика ; ] }'

Например, для изменения политики обработки входящих пакетов цепочки исходной таблицы с accept на drop выполните команду:

# nft chain inet my_table my_input '{ policy 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.

Ниже представлен неполный список возможных параметров:

  • meta (метасущности, напр. интерфейсы)
  • icmp (протокол ICMP)
  • icmpv6 (протокол ICMPv6)
  • ip (протокол IP)
  • ip6 (протокол IPv6)
  • tcp (протокол TCP)
  • udp (протокол UDP)
  • sctp (протокол SCTP)
  • ct (отслеживание соединений)

Ниже приведён неполный список аргументов для параметров (подробнее см. ):

meta: oif <интерфейс-отправитель НОМЕР> iif <интерфейс-получатель НОМЕР> oifname <интерфейс-отправитель ИМЯ> iifname <интерфейс-получатель ИМЯ> (параметры oif и iif принимают строковые значения, которые конвертируются в номер) (параметры oifname и iifname более гибкие, но они медленнее из-за необходимости выполнять сравнение строк)
icmp: type <тип icmp>
icmpv6: type <тип icmpv6>
ip: protocol <протокол> daddr <адрес получателя> saddr <адрес отправителя>
ip6: daddr <адрес получателя> saddr <адрес отправителя>
tcp: dport <порт получателя> sport <порт отправителя>
udp: dport <порт получателя> sport <порт отправителя>
sctp: dport <порт получателя> sport <порт отправителя>
ct: state <new | established | related | invalid>

Отдельные правила могут быть удалены только с помощью маркера. Команда nft --handle list выведет список маркеров.

# nft --handle --numeric list chain inet my_table my_input
table inet my_table { chain my_input { type filter hook input priority 0; ip saddr 127.0.0.1 accept # handle 10 }
}
# nft delete rule inet my_table my_input handle 10

Стирание всех цепочек таблицы выполняется командой nft flush table. Отдельные цепочки могут быть стёрты командами nft flush chain или nft delete rule.

# nft flush table таблица# nft flush chain семейство таблица цепочка# nft delete rule семейство таблица цепочка

Первая команда стирает все цепочки в ip-таблице таблица. Вторая очищает цепочку цепочка в таблице таблица семейства семейство. Третья удаляет все правила в цепочке цепочка в таблице таблица семейства семейство.

# nft add rule ip6 filter input tcp dport {telnet, http, https} accept

Именованное множество можно изменить, а также присвоить ему тип и установить флаги. sshguard использует именованные множества для хранения адресов блокированных хостов.

table ip sshguard { set attackers { type ipv4_addr flags interval elements = { 1.2.3.4 } }

Команды для добавления и удаления элементов из множества:

# nft add element ip sshguard attackers { 5.6.7.8/32 }
# nft delete element ip sshguard attackers { 1.2.3.4/32 }

Полная перезагрузка правил

Создать файл для новых правил:

# echo "flush ruleset" > /tmp/nftables 

Сбросить дамп правил в новый файл:

# nft -s list ruleset >> /tmp/nftables

Теперь можно редактировать файл /tmp/nftables, создавая и изменяя правила. Применить изменения можно командой:

# nft -f /tmp/nftables

Comments

@clutch2sft

OpenWrt SNAPSHOT, r19293-1c7e146f7e

Setting zone log via the LUCI interface inserts option log ‘1’ into /etc/config/firewall but no firewall logs are generated.

I read some of the nft manual and nothing in the nft output would convince me that the setting in /etc/config/firewall has inserted log instructions to the actual fw4 configuration.

Can happily be proven wrong if you are better informed than I.

@dave14305

@clutch2sft

Thank you for the reference.

I had found that thread at one point. Though for my knowledge level it wasn’t clearly related since I was executing the zone logging feature from within LUCI and they were discussing manipulation at the command line via nft.

I’ll re-read all that and apply the suggestions to see if it address the challenge presented to me.

@jow-




Copy link


jow-

commented

Mar 31, 2022

Works for me.

root@er-x:~# uci set firewall.@zone[1].log=1
root@er-x:~# fw4 reload
Section @rule[8] (Support-UDP-Traceroute) is disabled, ignoring section
root@er-x:~# nft list ruleset | grep "reject wan"	iifname "switch0.1" counter packets 29 bytes 1316 log prefix "reject wan in: " jump handle_reject comment "!fw4: reject wan IPv4/IPv6 traffic"	oifname "switch0.1" counter packets 0 bytes 0 log prefix "reject wan out: " jump handle_reject comment "!fw4: reject wan IPv4/IPv6 traffic"
root@er-x:~# uci set firewall.@zone[1].log=0
root@er-x:~# fw4 reload
Section @rule[8] (Support-UDP-Traceroute) is disabled, ignoring section
root@er-x:~# nft list ruleset | grep "reject wan"	iifname "switch0.1" counter packets 0 bytes 0 jump handle_reject comment "!fw4: reject wan IPv4/IPv6 traffic"	oifname "switch0.1" counter packets 0 bytes 0 jump handle_reject comment "!fw4: reject wan IPv4/IPv6 traffic"
root@er-x:~# 

After setting log 1, log targets are emitted, after reverting it to 0, they’re removed again. I also see log entries in logread:

root@er-x:~# logread | grep "reject wan"
Thu Mar 31 22:57:04 2022 kern.warn kernel: [3464058.574556] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=17.57.146.173 DST=x.x.x.48 LEN=146 TOS=0x00 PREC=0x00 TTL=47 ID=1092 DF PROTO=TCP SPT=5223 DPT=58795 WINDOW=501 RES=0x00 ACK PSH URGP=0
Thu Mar 31 22:57:13 2022 kern.warn kernel: [3464067.330011] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=45.143.203.59 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=246 ID=49948 PROTO=TCP SPT=48425 DPT=5482 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:57:13 2022 kern.warn kernel: [3464067.406928] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=45.143.203.59 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=246 ID=49949 PROTO=TCP SPT=48425 DPT=5482 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:57:29 2022 kern.warn kernel: [3464083.860105] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.82 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=63309 PROTO=TCP SPT=48030 DPT=23364 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:57:29 2022 kern.warn kernel: [3464083.976088] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.82 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=63310 PROTO=TCP SPT=48030 DPT=23364 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:57:50 2022 kern.warn kernel: [3464104.317225] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=79.124.62.82 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=53598 PROTO=TCP SPT=48030 DPT=22859 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:57:50 2022 kern.warn kernel: [3464104.419271] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=79.124.62.82 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=53597 PROTO=TCP SPT=48030 DPT=22859 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:58:00 2022 kern.warn kernel: [3464114.189781] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=17.57.146.174 DST=x.x.x.48 LEN=78 TOS=0x00 PREC=0x00 TTL=47 ID=59023 DF PROTO=TCP SPT=5223 DPT=62734 WINDOW=501 RES=0x00 ACK PSH URGP=0
Thu Mar 31 22:58:11 2022 kern.warn kernel: [3464125.975190] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=92.63.197.94 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=19160 PROTO=TCP SPT=55162 DPT=3390 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:11 2022 kern.warn kernel: [3464126.073009] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=92.63.197.94 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=19161 PROTO=TCP SPT=55162 DPT=3390 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:58:24 2022 kern.warn kernel: [3464138.957666] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=193.57.40.49 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=246 ID=7242 PROTO=TCP SPT=45712 DPT=2912 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:24 2022 kern.warn kernel: [3464139.060578] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=193.57.40.49 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=246 ID=7243 PROTO=TCP SPT=45712 DPT=2912 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:58:37 2022 kern.warn kernel: [3464151.568209] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=167.94.138.109 DST=x.x.x.48 LEN=44 TOS=0x00 PREC=0x00 TTL=38 ID=6487 PROTO=TCP SPT=53887 DPT=6443 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:39 2022 kern.warn kernel: [3464153.486651] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=79.124.62.130 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=43991 PROTO=TCP SPT=48155 DPT=41161 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:39 2022 kern.warn kernel: [3464153.602478] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=79.124.62.130 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=43990 PROTO=TCP SPT=48155 DPT=41161 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:58:48 2022 kern.warn kernel: [3464162.305386] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=78.128.113.250 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=28270 PROTO=TCP SPT=45641 DPT=7459 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:48 2022 kern.warn kernel: [3464162.414859] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=78.128.113.250 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=28269 PROTO=TCP SPT=45641 DPT=7459 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:58:51 2022 kern.warn kernel: [3464165.953864] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.130 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=63461 PROTO=TCP SPT=48155 DPT=40917 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:58:51 2022 kern.warn kernel: [3464166.042629] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.130 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=63460 PROTO=TCP SPT=48155 DPT=40917 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:59:01 2022 kern.warn kernel: [3464175.323323] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=167.248.133.134 DST=x.x.x.48 LEN=44 TOS=0x00 PREC=0x00 TTL=36 ID=21974 PROTO=TCP SPT=39369 DPT=17778 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:59:02 2022 kern.warn kernel: [3464176.714812] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=91.240.118.77 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=35685 PROTO=TCP SPT=58687 DPT=20067 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:59:02 2022 kern.warn kernel: [3464176.812540] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=91.240.118.77 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=35684 PROTO=TCP SPT=58687 DPT=20067 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:59:06 2022 kern.warn kernel: [3464180.186166] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=17.57.146.173 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=47 ID=0 DF PROTO=TCP SPT=5223 DPT=58795 WINDOW=0 RES=0x00 RST URGP=0
Thu Mar 31 22:59:15 2022 kern.warn kernel: [3464189.242008] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=92.63.197.71 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=32446 PROTO=TCP SPT=55371 DPT=14896 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 22:59:15 2022 kern.warn kernel: [3464189.322973] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=92.63.197.71 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=32447 PROTO=TCP SPT=55371 DPT=14896 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 22:59:24 2022 kern.warn kernel: [3464198.665076] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=92.118.160.53 DST=x.x.x.48 LEN=44 TOS=0x00 PREC=0x00 TTL=242 ID=54321 PROTO=TCP SPT=50686 DPT=888 WINDOW=65535 RES=0x00 SYN URGP=0
Thu Mar 31 23:00:00 2022 kern.warn kernel: [3464234.613760] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=2.56.57.88 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=54321 PROTO=TCP SPT=50783 DPT=1080 WINDOW=65535 RES=0x00 SYN URGP=0
Thu Mar 31 23:00:00 2022 kern.warn kernel: [3464234.736853] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=185.156.73.109 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=42649 PROTO=TCP SPT=51474 DPT=3387 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 23:00:00 2022 kern.warn kernel: [3464234.811426] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:74:83:ef:4f:99:d5:08:00 SRC=185.156.73.109 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=42648 PROTO=TCP SPT=51474 DPT=3387 WINDOW=1200 RES=0x00 RST URGP=0
Thu Mar 31 23:00:31 2022 kern.warn kernel: [3464265.637603] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.86 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=4808 PROTO=TCP SPT=47578 DPT=47406 WINDOW=1024 RES=0x00 SYN URGP=0
Thu Mar 31 23:00:31 2022 kern.warn kernel: [3464265.743417] reject wan in: IN=switch0.1 OUT= MAC=74:ac:b9:a1:84:46:fc:bd:67:9d:1f:31:08:00 SRC=79.124.62.86 DST=x.x.x.48 LEN=40 TOS=0x00 PREC=0x00 TTL=244 ID=4809 PROTO=TCP SPT=47578 DPT=47406 WINDOW=1200 RES=0x00 RST URGP=0
root@er-x:~# 

@clutch2sft

/proc/self/fd/0:123:25-27: Error: Could not process rule: No such file or directory

@jow-




Copy link


jow-

commented

Mar 31, 2022

Okay, so it’s not an fw4 problem but likely missing kmods nf_log_ipv4 and nf_log_ipv6.

@dave14305

Works for me.

Do you have any ip6tables related packages/kmods installed?

@jow-




Copy link


jow-

commented

Mar 31, 2022

Yes, I do have kmod-ipt-core and kmod-ip6tables installed.

@dave14305

Wouldn’t this be non-default in a base image with firewall4? I only have kmod-ipt-core, for example.

@jow-




Copy link


jow-

commented

Mar 31, 2022

Yeah likely, the kmod packaging has to be revised

@pepe2k
pepe2k

added


core packages

pull request/issue for core (in-tree) packages

issue report with a confirmed bug

Apr 1, 2022

@clutch2sft

@oldium




Copy link


oldium

commented

Apr 11, 2022

This is related to #9632 (comment). When you completely remove all iptables stuff from build, the nft_log silently complains that it does not have any loggers registered (like kmod-nf-ipv4). This might be the reason why you saw Error: Could not process rule: No such file or directory (it happened on my router too). The IPv4 logger is currently included in kmod-ipt-core, which you actually do not want to be installed on nftables-only system, because it loads iptables modules.

@dave14305

issue report with a confirmed bug

pull request/issue for core (in-tree) packages

Использование

В nftables не различаются временные правила, добавленные из командной строки, и постоянные, загруженные из файла или сохранённые в файл.

Все правила должны создаваться или загружаться утилитой nft. Подробнее о работе с ней см. раздел #Настройка.

Текущий набор правил можно узнать командой:

# nft list ruleset

Простой межсетевой экран

В пакет входит простая и надёжная конфигурация экрана, сохранённая в файле /etc/nftables.conf.

Служба nftables.service загрузит эти правила при запуске или включении.

Советы и рекомендации

Сохранение текущего набора правил

Вывод команды nft list ruleset можно использовать в качестве входных данных для других команд. Текущий набор правил можно сохранить в файл, а позже — загрузить их из него.

# nft -s list ruleset | tee название_файла

Примечание: Команда nft list не выводит определения переменных. Если в файле /etc/nftables.conf есть какие-либо переменные, то в выводе команды вы их не увидите — все переменные будут заменены на значения.

Настройка межсетевого экрана

См. также Настройка межсетевого экрана.

Сотрите текущий набор правил:

# nft flush ruleset
# nft add table inet my_table

Добавьте базовые цепочки input, forward и output. Политика для входящих и пересылаемых пакетов должна быть drop. Политика для исходящих пакетов — accept.

# nft add chain inet my_table my_input '{ type filter hook input priority 0 ; policy drop ; }'
# nft add chain inet my_table my_forward '{ type filter hook forward priority 0 ; policy drop ; }'
# nft add chain inet my_table my_output '{ type filter hook output priority 0 ; policy accept ; }'

Добавьте две обычные цепочки, которые будут обрабатывать пакеты протоколов TCP и UDP:

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

Разрешите related и established трафик:

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

Разрешите трафик на петлевой интерфейс:

# nft add rule inet my_table my_input iif lo accept

Заблокируйте invalid трафик:

# nft add rule inet my_table my_input ct state invalid drop

Разрешите пакеты ICMP и IGMP:

# nft add rule inet my_table my_input meta l4proto ipv6-icmp icmpv6 type '{ destination-unreachable, packet-too-big, time-exceeded, parameter-problem, mld-listener-query, mld-listener-report, mld-listener-reduction, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert, ind-neighbor-solicit, ind-neighbor-advert, mld2-listener-report }' accept
# nft add rule inet my_table my_input meta l4proto icmp icmp type '{ destination-unreachable, router-solicitation, router-advertisement, time-exceeded, parameter-problem }' accept
# nft add rule inet my_table my_input ip protocol igmp accept

Новый UDP-трафик будет передаваться цепочке my_udp_chain:

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

Новый TCP-трафик будет передаваться цепочке my_tcp_chain:

# nft add rule inet my_table my_input 'meta l4proto tcp tcp flags & (fin|syn|rst|ack) == syn ct state new jump my_tcp_chain'

Заблокировать весь трафик, который не обрабатывается другими правилами:

# 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 type port-unreachable

В этом месте необходимо выбрать, какие порты будут оставаться открытыми для входящих соединений, обрабатываемых цепочками my_tcp_chain и my_udp_chain. Например, открыть соединения для веб-сервера:

# 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

Разрешить SSH-трафик на порт 22:

# nft add rule inet my_table my_tcp_chain tcp dport 22 accept

Разрешить входящие DNS-запросы:

# 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

В конце не забудьте сохранить набор правил, чтобы они стали постоянными.

Предотвращение атак перебором

Действие log позволяет вести журнал пакетов. Простейшее правило для сохранения информации обо всём поступающем трафике:

# nft add rule inet filter input log

Подробнее см. nftables wiki.

Решение проблем

Работа с Docker

nftables может создавать помехи сетевой работе контейнеров Docker (возможно, и другим средствам виртуализации тоже). В частности, политика drop цепочки forward блокирует пакеты, источником которых является docker. Если вы не хотите удалять эту цепочку, то сделайте следующее:

  1. Установите пакет ; он содержит iptables-совместимый интерфейс nftables, который docker сможет использовать.
  2. Модифицируйте цепочку forward таблицы inet:
    chain forward { type filter hook forward priority security; policy drop; mark 1 accept
    }
  3. Добавьте цепочку DOCKER-USER в таблицу ip filter, чтобы помечать (mark) пакеты docker:
    table ip filter { chain DOCKER-USER { mark set 1 }
    }

Теперь сгенерированные контейнером docker пакеты будут маркироваться и пересылаться дальше, поскольку docker уже их отфильтровал (цепочка forward в docker использует политику drop).

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