Questo contenuto non è disponibile nella lingua selezionata.
Chapter 8. Getting started with nftables
If your scenario does not fall under typical packet-filtering cases covered by firewalld, or you want to have complete control of rules, you can use the nftables framework.
The nftables framework classifies packets, and it is the successor to the iptables, ip6tables, arptables, ebtables, and ipset utilities. It offers numerous improvements in convenience, features, and performance over previous packet-filtering tools, most notably:
- Built-in lookup tables instead of linear processing
-
A single framework for both the
IPv4andIPv6protocols - Updating the kernel rule set in place through transactions instead of fetching, updating, and storing the entire rule set
-
Support for debugging and tracing in the rule set (
nftrace) and monitoring trace events (in thenfttool) - More consistent and compact syntax, no protocol-specific extensions
- A Netlink API for third-party applications
The nftables framework uses tables to store chains. The chains contain individual rules for performing actions. The nft utility replaces all tools from the previous packet-filtering frameworks. You can use the libnftables library for low-level interaction with nftables Netlink API through the libnftnl library.
To display the effect of rule set changes, use the nft list ruleset command. To clear the kernel rule set, use the nft flush ruleset command. Note that this may also affect the rule set installed by the iptables-nft command, as it utilizes the same kernel infrastructure.
8.1. Creating and managing nftables tables, chains, and rules Copia collegamentoCollegamento copiato negli appunti!
You can display nftables rule sets and manage them.
8.1.1. Basics of nftables tables Copia collegamentoCollegamento copiato negli appunti!
A table in nftables is a namespace that contains a collection of chains, rules, sets, and other objects.
Each table must have an address family assigned. The address family defines the packet types that this table processes. You can set one of the following address families when you create a table:
-
ip: Matches only IPv4 packets. This is the default if you do not specify an address family. -
ip6: Matches only IPv6 packets. -
inet: Matches both IPv4 and IPv6 packets. -
arp: Matches IPv4 address resolution protocol (ARP) packets. -
bridge: Matches packets that pass through a bridge device. -
netdev: Matches packets from ingress.
If you want to add a table, the format to use depends on your firewall script:
In scripts in native syntax, use:
table <table_address_family> <table_name> { }table <table_address_family> <table_name> { }Copy to Clipboard Copied! Toggle word wrap Toggle overflow In shell scripts, use:
nft add table <table_address_family> <table_name>
nft add table <table_address_family> <table_name>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.1.2. Basics of nftables chains Copia collegamentoCollegamento copiato negli appunti!
Tables consist of chains which in turn are containers for rules. The following two rule types exists:
- Base chain: You can use base chains as an entry point for packets from the networking stack.
-
Regular chain: You can use regular chains as a
jumptarget to better organize rules.
If you want to add a base chain to a table, the format to use depends on your firewall script:
In scripts in native syntax, use:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow In shell scripts, use:
nft add chain <table_address_family> <table_name> <chain_name> { type <type> hook <hook> priority <priority> \; policy <policy> \; }nft add chain <table_address_family> <table_name> <chain_name> { type <type> hook <hook> priority <priority> \; policy <policy> \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow To avoid that the shell interprets the semicolons as the end of the command, place the
\escape character in front of the semicolons.
Both examples create base chains. To create a regular chain, do not set any parameters in the curly brackets.
Chain types
The following are the chain types and an overview with which address families and hooks you can use them:
| Type | Address families | Hooks | Description |
|---|---|---|---|
|
| all | all | Standard chain type |
|
|
|
| Chains of this type perform native address translation based on connection tracking entries. Only the first packet traverses this chain type. |
|
|
|
| Accepted packets that traverse this chain type cause a new route lookup if relevant parts of the IP header have changed. |
Chain priorities
The priority parameter specifies the order in which packets traverse chains with the same hook value. You can set this parameter to an integer value or use a standard priority name.
The following matrix is an overview of the standard priority names and their numeric values, and with which address families and hooks you can use them:
| Textual value | Numeric value | Address families | Hooks |
|---|---|---|---|
|
|
|
| all |
|
|
|
| all |
|
|
|
|
|
|
|
|
| |
|
|
|
| all |
|
|
| all | |
|
|
|
| all |
|
|
|
|
|
|
|
|
| |
|
|
|
|
|
Chain policies
The chain policy defines whether nftables should accept or drop packets if rules in this chain do not specify any action. You can set one of the following policies in a chain:
-
accept(default) -
drop
8.1.3. Basics of nftables rules Copia collegamentoCollegamento copiato negli appunti!
Rules define actions to perform on packets that pass a chain that contains this rule. If the rule also contains matching expressions, nftables performs the actions only if all previous expressions apply.
If you want to add a rule to a chain, the format to use depends on your firewall script:
In scripts in native syntax, use:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow In shell scripts, use:
nft add rule <table_address_family> <table_name> <chain_name> <rule>
nft add rule <table_address_family> <table_name> <chain_name> <rule>Copy to Clipboard Copied! Toggle word wrap Toggle overflow This shell command appends the new rule at the end of the chain. If you prefer to add a rule at the beginning of the chain, use the
nft insertcommand instead ofnft add.
8.1.4. Managing tables, chains, and rules using nft commands Copia collegamentoCollegamento copiato negli appunti!
To manage an nftables firewall on the command line or in shell scripts, use the nft utility.
The commands in this procedure do not represent a typical workflow and are not optimized. This procedure only demonstrates how to use nft commands to manage tables, chains, and rules in general.
Procedure
Create a table named
nftables_svcwith theinetaddress family so that the table can process both IPv4 and IPv6 packets:nft add table inet nftables_svc
# nft add table inet nftables_svcCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add a base chain named
INPUT, that processes incoming network traffic, to theinet nftables_svctable:nft add chain inet nftables_svc INPUT { type filter hook input priority filter \; policy accept \; }# nft add chain inet nftables_svc INPUT { type filter hook input priority filter \; policy accept \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow To avoid that the shell interprets the semicolons as the end of the command, escape the semicolons using the
\character.Add rules to the
INPUTchain. For example, allow incoming TCP traffic on port 22 and 443, and, as the last rule of theINPUTchain, reject other incoming traffic with an Internet Control Message Protocol (ICMP) port unreachable message:nft add rule inet nftables_svc INPUT tcp dport 22 accept nft add rule inet nftables_svc INPUT tcp dport 443 accept nft add rule inet nftables_svc INPUT reject with icmpx type port-unreachable
# nft add rule inet nftables_svc INPUT tcp dport 22 accept # nft add rule inet nftables_svc INPUT tcp dport 443 accept # nft add rule inet nftables_svc INPUT reject with icmpx type port-unreachableCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you enter the
nft add rulecommands as shown,nftadds the rules in the same order to the chain as you run the commands.Display the current rule set including handles:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Insert a rule before the existing rule with handle 3. For example, to insert a rule that allows TCP traffic on port 636, enter:
nft insert rule inet nftables_svc INPUT position 3 tcp dport 636 accept
# nft insert rule inet nftables_svc INPUT position 3 tcp dport 636 acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow Append a rule after the existing rule with handle 3. For example, to insert a rule that allows TCP traffic on port 80, enter:
nft add rule inet nftables_svc INPUT position 3 tcp dport 80 accept
# nft add rule inet nftables_svc INPUT position 3 tcp dport 80 acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow Display the rule set again with handles. Verify that the later added rules have been added to the specified positions:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Remove the rule with handle 6:
nft delete rule inet nftables_svc INPUT handle 6
# nft delete rule inet nftables_svc INPUT handle 6Copy to Clipboard Copied! Toggle word wrap Toggle overflow To remove a rule, you must specify the handle.
Display the rule set, and verify that the removed rule is no longer present:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Remove all remaining rules from the
INPUTchain:nft flush chain inet nftables_svc INPUT
# nft flush chain inet nftables_svc INPUTCopy to Clipboard Copied! Toggle word wrap Toggle overflow Display the rule set, and verify that the
INPUTchain is empty:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Delete the
INPUTchain:nft delete chain inet nftables_svc INPUT
# nft delete chain inet nftables_svc INPUTCopy to Clipboard Copied! Toggle word wrap Toggle overflow You can also use this command to delete chains that still contain rules.
Display the rule set, and verify that the
INPUTchain has been deleted:nft list table inet nftables_svc
# nft list table inet nftables_svc table inet nftables_svc { }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Delete the
nftables_svctable:nft delete table inet nftables_svc
# nft delete table inet nftables_svcCopy to Clipboard Copied! Toggle word wrap Toggle overflow You can also use this command to delete tables that still contain chains.
NoteTo delete the entire rule set, use the
nft flush rulesetcommand instead of manually deleting all rules, chains, and tables in separate commands.
8.2. Migrating from iptables to nftables Copia collegamentoCollegamento copiato negli appunti!
If your firewall configuration still uses iptables rules, you can migrate your iptables rules to nftables.
8.2.1. When to use firewalld, nftables, or iptables Copia collegamentoCollegamento copiato negli appunti!
On RHEL 8, you can use the following packet-filtering utilities depending on your scenario:
-
firewalld: Thefirewalldutility simplifies firewall configuration for common use cases. -
nftables: Use thenftablesutility to set up complex and performance-critical firewalls, such as for a whole network. -
iptables: Theiptablesutility on Red Hat Enterprise Linux uses thenf_tableskernel API instead of thelegacyback end. Thenf_tablesAPI provides backward compatibility so that scripts that useiptablescommands still work on Red Hat Enterprise Linux. For new firewall scripts, usenftables.
To prevent the different firewall-related services (firewalld, nftables, or iptables) from influencing each other, run only one of them on a RHEL host, and disable the other services.
8.2.2. Concepts in the nftables framework Copia collegamentoCollegamento copiato negli appunti!
Compared to the iptables framework, nftables offers a more modern, efficient, and flexible alternative. The nftables framework provides advanced capabilities and improvements over iptables, which simplify rule management and enhance performance. This makes nftables a modern alternative for complex and high-performance networking environments.
- Tables and namespaces
-
In
nftables, tables represent organizational units or namespaces that group together related firewall chains, sets, flowtables, and other objects. Innftables, tables provide a more flexible way to structure firewall rules and related components. While iniptables, the tables were more rigidly defined with specific purposes. - Table families
-
Each table in
nftablesis associated with a specific family (ip,ip6,inet,arp,bridge, ornetdev). This association determines which packets the table can process. For example, a table in theipfamily handles only IPv4 packets. On the other hand,inetis a special case of table family. It offers a unified approach across protocols, because it can process both IPv4 and IPv6 packets. Another case of a special table family isnetdev, because it is used for rules that apply directly to network devices, enabling filtering at the device level. - Base chains
Base chains in
nftablesare highly configurable entry-points in the packet processing pipeline that enable users to specify the following:- Type of chain, for example, "filter"
- The hook point in the packet processing path, for example, "input", "output", "forward"
- Priority of the chain
This flexibility enables precise control over when and how the rules are applied to packets as they pass through the network stack. A special case of a chain is the
routechain, which is used to influence the routing decisions made by the kernel, based on packet headers.- Virtual machine for rule processing
The
nftablesframework uses an internal virtual machine to process rules. This virtual machine executes instructions that are similar to assembly language operations (loading data into registers, performing comparisons, and so on). Such a mechanism allows for highly flexible and efficient rule processing.Enhancements in
nftablescan be introduced as new instructions for that virtual machine. This typically requires a new kernel module and updates to thelibnftnllibrary and thenftcommand-line utility.Alternatively, you can introduce new features by combining existing instructions in innovative ways without a need for kernel modifications. The syntax of
nftablesrules reflects the flexibility of the underlying virtual machine. For example, the rulemeta mark set tcp dport map { 22: 1, 80: 2 }sets a packet’s firewall mark to 1 if the TCP destination port is 22, and to 2 if the port is 80. This demonstrates how complex logic can be expressed concisely.- Complex filtering and verdict maps
The
nftablesframework integrates and extends the functionality of theipsetutility, which is used iniptablesfor bulk matching on IP addresses, ports, other data types and, most importantly, combinations thereof. This integration makes it easier to manage large and dynamic sets of data directly withinnftables. Next,nftablesnatively supports matching packets based on multiple values or ranges for any data type, which enhances its capability to handle complex filtering requirements. Withnftablesyou can manipulate any field within a packet.In
nftables, sets can be either named or anonymous. The named sets can be referenced by multiple rules and modified dynamically. The anonymous sets are defined inline within a rule and are immutable. Sets can contain elements that are combinations of different types, for example IP address and port number pairs. This feature provides greater flexibility in matching complex criteria. To manage sets, the kernel can select the most appropriate backend based on the specific requirements (performance, memory efficiency, and others). Sets can also function as maps with key-value pairs. The value part can be used as data points (values to write into packet headers), or as verdicts or chains to jump to. This enables complex and dynamic rule behaviors, known as "verdict maps".- Flexible rule format
The structure of
nftablesrules is straightforward. The conditions and actions are applied sequentially from left to right. This intuitive format simplifies rule creating and troubleshooting.Conditions in a rule are logically connected (with the AND operator) together, which means that all conditions must be evaluated as "true" for the rule to match. If any condition fails, the evaluation moves to the next rule.
Actions in
nftablescan be final, such asdroporaccept, which stop further rule processing for the packet. Non-terminal actions, such ascounter log meta mark set 0x3, perform specific tasks (counting packets, logging, setting a mark, and others), but allow subsequent rules to be evaluated.
8.2.3. Concepts in the deprecated iptables framework Copia collegamentoCollegamento copiato negli appunti!
Similar to the actively-maintained nftables framework, the deprecated iptables framework enables you to perform a variety of packet filtering tasks, logging and auditing, NAT-related configuration tasks, and more.
The iptables framework is structured into multiple tables, where each table is designed for a specific purpose:
filter- The default table, ensures general packet filtering
nat- For Network Address Translation (NAT), includes altering the source and destination addresses of packets
mangle- For specific packet alteration, enables you to do modification of packet headers for advanced routing decisions
raw- For configurations that need to happen before connection tracking
These tables are implemented as separate kernel modules, where each table offers a fixed set of builtin chains such as INPUT, OUTPUT, and FORWARD. A chain is a sequence of rules that packets are evaluated against. These chains hook into specific points in the packet processing flow in the kernel. The chains have the same names across different tables, however their order of execution is determined by their respective hook priorities. The priorities are managed internally by the kernel to make sure that the rules are applied in the correct sequence.
Originally, iptables was designed to process IPv4 traffic. However, with the inception of the IPv6 protocol, the ip6tables utility needed to be introduced to provide comparable functionality (as iptables) and enable users to create and manage firewall rules for IPv6 packets. With the same logic, the arptables utility was created to process Address Resolution Protocol (ARP) and the ebtables utility was developed to handle Ethernet bridging frames. These tools ensure that you can apply the packet filtering abilities of iptables across various network protocols and provide comprehensive network coverage.
To enhance the functionality of iptables, the extensions started to be developed. The functionality extensions are typically implemented as kernel modules that are paired with user-space dynamic shared objects (DSOs). The extensions introduce "matches" and "targets" that you can use in firewall rules to perform more sophisticated operations. Extensions can enable complex matches and targets. For instance you can match on, or manipulate specific layer 4 protocol header values, perform rate-limiting, enforce quotas, and so on. Some extensions are designed to address limitations in the default iptables syntax, for example the "multiport" match extension. This extension allows a single rule to match multiple, non-consecutive ports to simplify rule definitions, and thereby reducing the number of individual rules required.
An ipset is a special kind of functionality extension to iptables. It is a kernel-level data structure that is used together with iptables to create collections of IP addresses, port numbers, and other network-related elements that you can match against packets. These sets significantly streamline, optimize, and accelerate the process of writing and managing firewall rules.
8.2.4. Converting iptables and ip6tables rule sets to nftables Copia collegamentoCollegamento copiato negli appunti!
Use the iptables-restore-translate and ip6tables-restore-translate utilities to translate iptables and ip6tables rule sets to nftables.
Prerequisites
-
The
nftablesandiptablespackages are installed. -
The system has
iptablesandip6tablesrules configured.
Procedure
Write the
iptablesandip6tablesrules to a file:iptables-save >/root/iptables.dump ip6tables-save >/root/ip6tables.dump
# iptables-save >/root/iptables.dump # ip6tables-save >/root/ip6tables.dumpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Convert the dump files to
nftablesinstructions:iptables-restore-translate -f /root/iptables.dump > /etc/nftables/ruleset-migrated-from-iptables.nft ip6tables-restore-translate -f /root/ip6tables.dump > /etc/nftables/ruleset-migrated-from-ip6tables.nft
# iptables-restore-translate -f /root/iptables.dump > /etc/nftables/ruleset-migrated-from-iptables.nft # ip6tables-restore-translate -f /root/ip6tables.dump > /etc/nftables/ruleset-migrated-from-ip6tables.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Review and, if needed, manually update the generated
nftablesrules. To enable the
nftablesservice to load the generated files, add the following to the/etc/sysconfig/nftables.conffile:include "/etc/nftables/ruleset-migrated-from-iptables.nft" include "/etc/nftables/ruleset-migrated-from-ip6tables.nft"
include "/etc/nftables/ruleset-migrated-from-iptables.nft" include "/etc/nftables/ruleset-migrated-from-ip6tables.nft"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Stop and disable the
iptablesservice:systemctl disable --now iptables
# systemctl disable --now iptablesCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you used a custom script to load the
iptablesrules, ensure that the script no longer starts automatically and reboot to flush all tables.Enable and start the
nftablesservice:systemctl enable --now nftables
# systemctl enable --now nftablesCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display the
nftablesrule set:nft list ruleset
# nft list rulesetCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.2.5. Converting single iptables and ip6tables rules to nftables Copia collegamentoCollegamento copiato negli appunti!
Red Hat Enterprise Linux provides the iptables-translate and ip6tables-translate utilities to convert an iptables or ip6tables rule into the equivalent one for nftables.
Prerequisites
-
The
nftablespackage is installed.
Procedure
Use the
iptables-translateorip6tables-translateutility instead ofiptablesorip6tablesto display the correspondingnftablesrule, for example:iptables-translate -A INPUT -s 192.0.2.0/24 -j ACCEPT
# iptables-translate -A INPUT -s 192.0.2.0/24 -j ACCEPT nft add rule ip filter INPUT ip saddr 192.0.2.0/24 counter acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that some extensions lack translation support. In these cases, the utility prints the untranslated rule prefixed with the
#sign, for example:iptables-translate -A INPUT -j CHECKSUM --checksum-fill
# iptables-translate -A INPUT -j CHECKSUM --checksum-fill nft # -A INPUT -j CHECKSUM --checksum-fillCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.2.6. Comparison of common iptables and nftables commands Copia collegamentoCollegamento copiato negli appunti!
The following is a comparison of common iptables and nftables commands:
Listing all rules:
Expand iptables nftables iptables-savenft list rulesetListing a certain table and chain:
Expand iptables nftables iptables -Lnft list table ip filteriptables -L INPUTnft list chain ip filter INPUTiptables -t nat -L PREROUTINGnft list chain ip nat PREROUTINGThe
nftcommand does not pre-create tables and chains. They exist only if a user created them manually.Listing rules generated by firewalld:
nft list table inet firewalld nft list table ip firewalld nft list table ip6 firewalld
# nft list table inet firewalld # nft list table ip firewalld # nft list table ip6 firewalldCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.3. Configuring NAT using nftables Copia collegamentoCollegamento copiato negli appunti!
With nftables, you can configure the following network address translation (NAT) types:
- Masquerading
- Source NAT (SNAT)
- Destination NAT (DNAT)
- Redirect
You can only use real interface names in iifname and oifname parameters, and alternative names (altname) are not supported.
8.3.1. NAT types Copia collegamentoCollegamento copiato negli appunti!
These are the different network address translation (NAT) types:
- Masquerading and source NAT (SNAT)
Use one of these NAT types to change the source IP address of packets. For example, Internet Service Providers (ISPs) do not route private IP ranges, such as
10.0.0.0/8. If you use private IP ranges in your network and users should be able to reach servers on the internet, map the source IP address of packets from these ranges to a public IP address.Masquerading and SNAT are very similar to one another. The differences are:
- Masquerading automatically uses the IP address of the outgoing interface. Therefore, use masquerading if the outgoing interface uses a dynamic IP address.
- SNAT sets the source IP address of packets to a specified IP and does not dynamically look up the IP of the outgoing interface. Therefore, SNAT is faster than masquerading. Use SNAT if the outgoing interface uses a fixed IP address.
- Destination NAT (DNAT)
- Use this NAT type to rewrite the destination address and port of incoming packets. For example, if your web server uses an IP address from a private IP range and is, therefore, not directly accessible from the internet, you can set a DNAT rule on the router to redirect incoming traffic to this server.
- Redirect
- This type is a special case of DNAT that redirects packets to the local machine depending on the chain hook. For example, if a service runs on a different port than its standard port, you can redirect incoming traffic from the standard port to this specific port.
8.3.2. Configuring masquerading using nftables Copia collegamentoCollegamento copiato negli appunti!
Masquerading enables a router to dynamically change the source IP of packets sent through an interface to the IP address of the interface. This means that if the interface gets a new IP assigned, nftables automatically uses the new IP when replacing the source IP.
Replace the source IP of packets leaving the host through the ens3 interface to the IP set on ens3.
Procedure
Create a table:
nft add table nat
# nft add table natCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
preroutingandpostroutingchains to the table:nft add chain nat postrouting { type nat hook postrouting priority 100 \; }# nft add chain nat postrouting { type nat hook postrouting priority 100 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantEven if you do not add a rule to the
preroutingchain, thenftablesframework requires this chain to match incoming packet replies.Note that you must pass the
--option to thenftcommand to prevent the shell from interpreting the negative priority value as an option of thenftcommand.Add a rule to the
postroutingchain that matches outgoing packets on theens3interface:nft add rule nat postrouting oifname "ens3" masquerade
# nft add rule nat postrouting oifname "ens3" masqueradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.3.3. Configuring source NAT using nftables Copia collegamentoCollegamento copiato negli appunti!
On a router, Source NAT (SNAT) enables you to change the IP of packets sent through an interface to a specific IP address. The router then replaces the source IP of outgoing packets.
Procedure
Create a table:
nft add table nat
# nft add table natCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
preroutingandpostroutingchains to the table:nft add chain nat postrouting { type nat hook postrouting priority 100 \; }# nft add chain nat postrouting { type nat hook postrouting priority 100 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantEven if you do not add a rule to the
postroutingchain, thenftablesframework requires this chain to match outgoing packet replies.Note that you must pass the
--option to thenftcommand to prevent the shell from interpreting the negative priority value as an option of thenftcommand.Add a rule to the
postroutingchain that replaces the source IP of outgoing packets throughens3with192.0.2.1:nft add rule nat postrouting oifname "ens3" snat to 192.0.2.1
# nft add rule nat postrouting oifname "ens3" snat to 192.0.2.1Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.3.4. Configuring destination NAT using nftables Copia collegamentoCollegamento copiato negli appunti!
Destination NAT (DNAT) enables you to redirect traffic on a router to a host that is not directly accessible from the internet.
For example, with DNAT the router redirects incoming traffic sent to port 80 and 443 to a web server with the IP address 192.0.2.1.
Procedure
Create a table:
nft add table nat
# nft add table natCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
preroutingandpostroutingchains to the table:nft -- add chain nat prerouting { type nat hook prerouting priority -100 \; } nft add chain nat postrouting { type nat hook postrouting priority 100 \; }# nft -- add chain nat prerouting { type nat hook prerouting priority -100 \; } # nft add chain nat postrouting { type nat hook postrouting priority 100 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantEven if you do not add a rule to the
postroutingchain, thenftablesframework requires this chain to match outgoing packet replies.Note that you must pass the
--option to thenftcommand to prevent the shell from interpreting the negative priority value as an option of thenftcommand.Add a rule to the
preroutingchain that redirects incoming traffic to port80and443on theens3interface of the router to the web server with the IP address192.0.2.1:nft add rule nat prerouting iifname ens3 tcp dport { 80, 443 } dnat to 192.0.2.1# nft add rule nat prerouting iifname ens3 tcp dport { 80, 443 } dnat to 192.0.2.1Copy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on your environment, add either a SNAT or masquerading rule to change the source address for packets returning from the web server to the sender:
If the
ens3interface uses a dynamic IP addresses, add a masquerading rule:nft add rule nat postrouting oifname "ens3" masquerade
# nft add rule nat postrouting oifname "ens3" masqueradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
ens3interface uses a static IP address, add a SNAT rule. For example, if theens3uses the198.51.100.1IP address:nft add rule nat postrouting oifname "ens3" snat to 198.51.100.1
# nft add rule nat postrouting oifname "ens3" snat to 198.51.100.1Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Enable packet forwarding:
echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/95-IPv4-forwarding.conf sysctl -p /etc/sysctl.d/95-IPv4-forwarding.conf
# echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/95-IPv4-forwarding.conf # sysctl -p /etc/sysctl.d/95-IPv4-forwarding.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.3.5. Configuring a redirect using nftables Copia collegamentoCollegamento copiato negli appunti!
The redirect feature is a special case of destination network address translation (DNAT) that redirects packets to the local machine depending on the chain hook.
For example, you can redirect incoming and forwarded traffic sent to port 22 of the local host to port 2222.
Procedure
Create a table:
nft add table nat
# nft add table natCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
preroutingchain to the table:nft -- add chain nat prerouting { type nat hook prerouting priority -100 \; }# nft -- add chain nat prerouting { type nat hook prerouting priority -100 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Note that you must pass the
--option to thenftcommand to prevent the shell from interpreting the negative priority value as an option of thenftcommand.Add a rule to the
preroutingchain that redirects incoming traffic on port22to port2222:nft add rule nat prerouting tcp dport 22 redirect to 2222
# nft add rule nat prerouting tcp dport 22 redirect to 2222Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.4. Writing and executing nftables scripts Copia collegamentoCollegamento copiato negli appunti!
The major benefit of using the nftables framework is that the execution of scripts is atomic. This means that the system either applies the whole script or prevents the execution if an error occurs. This guarantees that the firewall is always in a consistent state.
Additionally, with the nftables script environment, you can:
- Add comments
- Define variables
- Include other rule-set files
When you install the nftables package, Red Hat Enterprise Linux automatically creates *.nft scripts in the /etc/nftables/ directory. These scripts contain commands that create tables and empty chains for different purposes.
8.4.1. Supported nftables script formats Copia collegamentoCollegamento copiato negli appunti!
You can write scripts in the nftables scripting environment in the following formats:
The same format as the
nft list rulesetcommand displays the rule set:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The same syntax as for
nftcommands:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.4.2. Running nftables scripts Copia collegamentoCollegamento copiato negli appunti!
You can run an nftables script either by passing it to the nft utility or by executing the script directly.
Procedure
To run an
nftablesscript by passing it to thenftutility, enter:nft -f /etc/nftables/<example_firewall_script>.nft
# nft -f /etc/nftables/<example_firewall_script>.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow To run an
nftablesscript directly:For the single time that you perform this:
Ensure that the script starts with the following shebang sequence:
#!/usr/sbin/nft -f
#!/usr/sbin/nft -fCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantIf you omit the
-fparameter, thenftutility does not read the script and displays:Error: syntax error, unexpected newline, expecting string.Optional: Set the owner of the script to
root:chown root /etc/nftables/<example_firewall_script>.nft
# chown root /etc/nftables/<example_firewall_script>.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow Make the script executable for the owner:
chmod u+x /etc/nftables/<example_firewall_script>.nft
# chmod u+x /etc/nftables/<example_firewall_script>.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Run the script:
/etc/nftables/<example_firewall_script>.nft
# /etc/nftables/<example_firewall_script>.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow If no output is displayed, the system executed the script successfully.
Even if nft executes the script successfully, incorrectly placed rules, missing parameters, or other problems in the script can cause that the firewall behaves not as expected.
8.4.3. Using comments in nftables scripts Copia collegamentoCollegamento copiato negli appunti!
The nftables scripting environment interprets everything to the right of a # character to the end of a line as a comment.
Comments can start at the beginning of a line, or next to a command:
8.4.4. Using variables in nftables script Copia collegamentoCollegamento copiato negli appunti!
To define a variable in an nftables script, use the define keyword. You can store single values and anonymous sets in a variable. For more complex scenarios, use sets or verdict maps.
- Variables with a single value
The following example defines a variable named
INET_DEVwith the valueenp1s0:define INET_DEV = enp1s0
define INET_DEV = enp1s0Copy to Clipboard Copied! Toggle word wrap Toggle overflow You can use the variable in the script by entering the
$sign followed by the variable name:... add rule inet example_table example_chain iifname $INET_DEV tcp dport ssh accept ...
... add rule inet example_table example_chain iifname $INET_DEV tcp dport ssh accept ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Variables that contain an anonymous set
The following example defines a variable that contains an anonymous set:
define DNS_SERVERS = { 192.0.2.1, 192.0.2.2 }define DNS_SERVERS = { 192.0.2.1, 192.0.2.2 }Copy to Clipboard Copied! Toggle word wrap Toggle overflow You can use the variable in the script by writing the
$sign followed by the variable name:add rule inet example_table example_chain ip daddr $DNS_SERVERS accept
add rule inet example_table example_chain ip daddr $DNS_SERVERS acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteCurly braces have special semantics when you use them in a rule because they indicate that the variable represents a set.
8.4.5. Including files in nftables scripts Copia collegamentoCollegamento copiato negli appunti!
In the nftables scripting environment, you can include other scripts by using the include statement.
If you specify only a file name without an absolute or relative path, nftables includes files from the default search path, which is set to /etc on Red Hat Enterprise Linux.
Example 8.1. Including files from the default search directory
To include a file from the default search directory:
include "example.nft"
include "example.nft"
Example 8.2. Including all *.nft files from a directory
To include all files ending with *.nft that are stored in the /etc/nftables/rulesets/ directory:
include "/etc/nftables/rulesets/*.nft"
include "/etc/nftables/rulesets/*.nft"
Note that the include statement does not match files beginning with a dot.
8.4.6. Automatically loading nftables rules when the system boots Copia collegamentoCollegamento copiato negli appunti!
The nftables systemd service loads firewall scripts that are included in the /etc/sysconfig/nftables.conf file.
Prerequisites
-
The
nftablesscripts are stored in the/etc/nftables/directory.
Procedure
Edit the
/etc/sysconfig/nftables.conffile.-
If you modified the
*.nftscripts that were created in/etc/nftables/with the installation of thenftablespackage, uncomment theincludestatement for these scripts. If you wrote new scripts, add
includestatements to include these scripts. For example, to load the/etc/nftables/example.nftscript when thenftablesservice starts, add:include "/etc/nftables/_example_.nft"
include "/etc/nftables/_example_.nft"Copy to Clipboard Copied! Toggle word wrap Toggle overflow
-
If you modified the
Optional: Start the
nftablesservice to load the firewall rules without rebooting the system:systemctl start nftables
# systemctl start nftablesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
nftablesservice.systemctl enable nftables
# systemctl enable nftablesCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.5. Using sets in nftables commands Copia collegamentoCollegamento copiato negli appunti!
The nftables framework natively supports sets. You can use sets, for example, if a rule should match multiple IP addresses, port numbers, interfaces, or any other match criteria.
8.5.1. Using anonymous sets in nftables Copia collegamentoCollegamento copiato negli appunti!
An anonymous set contains comma-separated values enclosed in curly brackets, such as { 22, 80, 443 }, that you use directly in a rule. You can use anonymous sets also for IP addresses and any other match criteria.
The drawback of anonymous sets is that if you want to change the set, you must replace the rule. For a dynamic solution, use named sets as described in Using named sets in nftables.
Prerequisites
-
The
example_chainchain and theexample_tabletable in theinetfamily exists.
Procedure
For example, to add a rule to
example_chaininexample_tablethat allows incoming traffic to port22,80, and443:nft add rule inet example_table example_chain tcp dport { 22, 80, 443 } accept# nft add rule inet example_table example_chain tcp dport { 22, 80, 443 } acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display all chains and their rules in
example_table:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.5.2. Using named sets in nftables Copia collegamentoCollegamento copiato negli appunti!
The nftables framework supports mutable named sets. A named set is a list or range of elements that you can use in multiple rules within a table. Another benefit over anonymous sets is that you can update a named set without replacing the rules that use the set.
When you create a named set, you must specify the type of elements the set contains. You can set the following types:
-
ipv4_addrfor a set that contains IPv4 addresses or ranges, such as192.0.2.1or192.0.2.0/24. -
ipv6_addrfor a set that contains IPv6 addresses or ranges, such as2001:db8:1::1or2001:db8:1::1/64. -
ether_addrfor a set that contains a list of media access control (MAC) addresses, such as52:54:00:6b:66:42. -
inet_protofor a set that contains a list of internet protocol types, such astcp. -
inet_servicefor a set that contains a list of internet services, such asssh. -
markfor a set that contains a list of packet marks. Packet marks can be any positive 32-bit integer value (0to2147483647).
Prerequisites
-
The
example_chainchain and theexample_tabletable exists.
Procedure
Create an empty set. The following examples create a set for IPv4 addresses:
To create a set that can store multiple individual IPv4 addresses:
nft add set inet example_table example_set { type ipv4_addr \; }# nft add set inet example_table example_set { type ipv4_addr \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow To create a set that can store IPv4 address ranges:
nft add set inet example_table example_set { type ipv4_addr \; flags interval \; }# nft add set inet example_table example_set { type ipv4_addr \; flags interval \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow
ImportantTo prevent the shell from interpreting the semicolons as the end of the command, you must escape the semicolons with a backslash.
Optional: Create rules that use the set. For example, the following command adds a rule to the
example_chainin theexample_tablethat will drop all packets from IPv4 addresses inexample_set.nft add rule inet example_table example_chain ip saddr @example_set drop
# nft add rule inet example_table example_chain ip saddr @example_set dropCopy to Clipboard Copied! Toggle word wrap Toggle overflow Because
example_setis still empty, the rule has currently no effect.Add IPv4 addresses to
example_set:If you create a set that stores individual IPv4 addresses, enter:
nft add element inet example_table example_set { 192.0.2.1, 192.0.2.2 }# nft add element inet example_table example_set { 192.0.2.1, 192.0.2.2 }Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you create a set that stores IPv4 ranges, enter:
nft add element inet example_table example_set { 192.0.2.0-192.0.2.255 }# nft add element inet example_table example_set { 192.0.2.0-192.0.2.255 }Copy to Clipboard Copied! Toggle word wrap Toggle overflow When you specify an IP address range, you can alternatively use the Classless Inter-Domain Routing (CIDR) notation, such as
192.0.2.0/24in the above example.
8.5.3. Using dynamic sets to add entries from the packet path Copia collegamentoCollegamento copiato negli appunti!
Dynamic sets in the nftables framework allow automatic addition of elements from packet data. For example, IP addresses, destination ports, MAC addresses, and others. This functionality enables you to collect those elements in real-time and use them to create deny lists, ban lists, and others so that you can instantly react to security threats.
Prerequisites
-
The
example_chainchain and theexample_tabletable in theinetfamily exist.
Procedure
Create an empty set. The following examples create a set for IPv4 addresses:
To create a set that can store multiple individual IPv4 addresses:
nft add set inet example_table example_set { type ipv4_addr \; }# nft add set inet example_table example_set { type ipv4_addr \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow To create a set that can store IPv4 address ranges:
nft add set inet example_table example_set { type ipv4_addr \; flags interval \; }# nft add set inet example_table example_set { type ipv4_addr \; flags interval \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantTo prevent the shell from interpreting the semicolons as the end of the command, you must escape the semicolons with a backslash.
Create a rule for dynamically adding the source IPv4 addresses of incoming packets to the
example_setset:nft add rule inet example_table example_chain set add ip saddr @example_set
# nft add rule inet example_table example_chain set add ip saddr @example_setCopy to Clipboard Copied! Toggle word wrap Toggle overflow The command creates a new rule within the
example_chainrule chain and theexample_tableto dynamically add the source IPv4 address of the packet to theexample_set.
Verification
Ensure the rule was added:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The command displays the entire ruleset currently loaded in
nftables. It shows that IPs are actively triggering the rule, andexample_setis being updated with the relevant addresses.
Next steps
Once you have a dynamic set of IPs, you can use it for various security, filtering, and traffic control purposes. For example:
- block, limit, or log network traffic
- combine with allow-listing to avoid banning trusted users
- use automatic timeouts to prevent over-blocking
8.6. Using verdict maps in nftables commands Copia collegamentoCollegamento copiato negli appunti!
Verdict maps, which are also known as dictionaries, enable nft to perform an action based on packet information by mapping match criteria to an action.
8.6.1. Using anonymous maps in nftables Copia collegamentoCollegamento copiato negli appunti!
An anonymous map is a { match_criteria : action } statement that you use directly in a rule. The statement can contain multiple comma-separated mappings.
The drawback of an anonymous map is that if you want to change the map, you must replace the rule. For a dynamic solution, use named maps as described in Using named maps in nftables.
For example, you can use an anonymous map to route both TCP and UDP packets of the IPv4 and IPv6 protocol to different chains to count incoming TCP and UDP packets separately.
Procedure
Create a new table:
nft add table inet example_table
# nft add table inet example_tableCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create the
tcp_packetschain inexample_table:nft add chain inet example_table tcp_packets
# nft add chain inet example_table tcp_packetsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add a rule to
tcp_packetsthat counts the traffic in this chain:nft add rule inet example_table tcp_packets counter
# nft add rule inet example_table tcp_packets counterCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create the
udp_packetschain inexample_tablenft add chain inet example_table udp_packets
# nft add chain inet example_table udp_packetsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add a rule to
udp_packetsthat counts the traffic in this chain:nft add rule inet example_table udp_packets counter
# nft add rule inet example_table udp_packets counterCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create a chain for incoming traffic. For example, to create a chain named
incoming_trafficinexample_tablethat filters incoming traffic:nft add chain inet example_table incoming_traffic { type filter hook input priority 0 \; }# nft add chain inet example_table incoming_traffic { type filter hook input priority 0 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add a rule with an anonymous map to
incoming_traffic:nft add rule inet example_table incoming_traffic ip protocol vmap { tcp : jump tcp_packets, udp : jump udp_packets }# nft add rule inet example_table incoming_traffic ip protocol vmap { tcp : jump tcp_packets, udp : jump udp_packets }Copy to Clipboard Copied! Toggle word wrap Toggle overflow The anonymous map distinguishes the packets and sends them to the different counter chains based on their protocol.
To list the traffic counters, display
example_table:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The counters in the
tcp_packetsandudp_packetschain display both the number of received packets and bytes.
8.6.2. Using named maps in nftables Copia collegamentoCollegamento copiato negli appunti!
The nftables framework supports named maps. You can use these maps in multiple rules within a table. Another benefit over anonymous maps is that you can update a named map without replacing the rules that use it.
When you create a named map, you must specify the type of elements:
-
ipv4_addrfor a map whose match part contains an IPv4 address, such as192.0.2.1. -
ipv6_addrfor a map whose match part contains an IPv6 address, such as2001:db8:1::1. -
ether_addrfor a map whose match part contains a media access control (MAC) address, such as52:54:00:6b:66:42. -
inet_protofor a map whose match part contains an internet protocol type, such astcp. -
inet_servicefor a map whose match part contains an internet services name port number, such assshor22. -
markfor a map whose match part contains a packet mark. A packet mark can be any positive 32-bit integer value (0to2147483647). -
counterfor a map whose match part contains a counter value. The counter value can be any positive 64-bit integer value. -
quotafor a map whose match part contains a quota value. The quota value can be any positive 64-bit integer value.
For example, you can allow or drop incoming packets based on their source IP address. Using a named map, you require only a single rule to configure this scenario while the IP addresses and actions are dynamically stored in the map.
Procedure
Create a table. For example, to create a table named
example_tablethat processes IPv4 packets:nft add table ip example_table
# nft add table ip example_tableCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create a chain. For example, to create a chain named
example_chaininexample_table:nft add chain ip example_table example_chain { type filter hook input priority 0 \; }# nft add chain ip example_table example_chain { type filter hook input priority 0 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantTo prevent the shell from interpreting the semicolons as the end of the command, you must escape the semicolons with a backslash.
Create an empty map. For example, to create a map for IPv4 addresses:
nft add map ip example_table example_map { type ipv4_addr : verdict \; }# nft add map ip example_table example_map { type ipv4_addr : verdict \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create rules that use the map. For example, the following command adds a rule to
example_chaininexample_tablethat applies actions to IPv4 addresses which are both defined inexample_map:nft add rule example_table example_chain ip saddr vmap @example_map
# nft add rule example_table example_chain ip saddr vmap @example_mapCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add IPv4 addresses and corresponding actions to
example_map:nft add element ip example_table example_map { 192.0.2.1 : accept, 192.0.2.2 : drop }# nft add element ip example_table example_map { 192.0.2.1 : accept, 192.0.2.2 : drop }Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example defines the mappings of IPv4 addresses to actions. In combination with the rule created above, the firewall accepts packet from
192.0.2.1and drops packets from192.0.2.2.Optional: Enhance the map by adding another IP address and action statement:
nft add element ip example_table example_map { 192.0.2.3 : accept }# nft add element ip example_table example_map { 192.0.2.3 : accept }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Remove an entry from the map:
nft delete element ip example_table example_map { 192.0.2.1 }# nft delete element ip example_table example_map { 192.0.2.1 }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the rule set:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.7. Example: Protecting a LAN and DMZ using an nftables script Copia collegamentoCollegamento copiato negli appunti!
Use the nftables framework on a RHEL router to write and install a firewall script that protects the network clients in an internal LAN and a web server in a DMZ from unauthorized access from the internet and from other networks.
This example is only for demonstration purposes and describes a scenario with specific requirements.
Firewall scripts highly depend on the network infrastructure and security requirements. Use this example to learn the concepts of nftables firewalls when you write scripts for your own environment.
8.7.1. Network conditions Copia collegamentoCollegamento copiato negli appunti!
The network in this example has the following conditions:
The router is connected to the following networks:
-
The internet through interface
enp1s0 -
The internal LAN through interface
enp7s0 -
The DMZ through
enp8s0
-
The internet through interface
-
The internet interface of the router has both a static IPv4 address (
203.0.113.1) and IPv6 address (2001:db8:a::1) assigned. -
The clients in the internal LAN use only private IPv4 addresses from the range
10.0.0.0/24. Consequently, traffic from the LAN to the internet requires source network address translation (SNAT). -
The administrator PCs in the internal LAN use the IP addresses
10.0.0.100and10.0.0.200. -
The DMZ uses public IP addresses from the ranges
198.51.100.0/24and2001:db8:b::/56. -
The web server in the DMZ uses the IP addresses
198.51.100.5and2001:db8:b::5. - The router acts as a caching DNS server for hosts in the LAN and DMZ.
8.7.2. Security requirements to the firewall script Copia collegamentoCollegamento copiato negli appunti!
The following are the requirements to the nftables firewall in the example network:
The router must be able to:
- Recursively resolve DNS queries.
- Perform all connections on the loopback interface.
Clients in the internal LAN must be able to:
- Query the caching DNS server running on the router.
- Access the HTTPS server in the DMZ.
- Access any HTTPS server on the internet.
- The PCs of the administrators must be able to access the router and every server in the DMZ using SSH.
The web server in the DMZ must be able to:
- Query the caching DNS server running on the router.
- Access HTTPS servers on the internet to download updates.
Hosts on the internet must be able to:
- Access the HTTPS servers in the DMZ.
Additionally, the following security requirements exists:
- Connection attempts that are not explicitly allowed should be dropped.
- Dropped packets should be logged.
8.7.3. Configuring logging of dropped packets to a file Copia collegamentoCollegamento copiato negli appunti!
By default, systemd logs kernel messages, such as for dropped packets, to the journal. Additionally, you can configure the rsyslog service to log such entries to a separate file. To ensure that the log file does not grow infinitely, configure a rotation policy.
Prerequisites
-
The
rsyslogpackage is installed. -
The
rsyslogservice is running.
Procedure
Create the
/etc/rsyslog.d/nftables.conffile with the following content::msg, startswith, "nft drop" -/var/log/nftables.log & stop
:msg, startswith, "nft drop" -/var/log/nftables.log & stopCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using this configuration, the
rsyslogservice logs dropped packets to the/var/log/nftables.logfile instead of/var/log/messages.Restart the
rsyslogservice:systemctl restart rsyslog
# systemctl restart rsyslogCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create the
/etc/logrotate.d/nftablesfile with the following content to rotate/var/log/nftables.logif the size exceeds 10 MB:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
maxage 30setting defines thatlogrotateremoves rotated logs older than 30 days during the next rotation operation.
8.7.4. Writing and activating the nftables script Copia collegamentoCollegamento copiato negli appunti!
This example is an nftables firewall script that runs on a RHEL router and protects the clients in an internal LAN and a web server in a DMZ. For details about the network and the requirements for the firewall used in the example, see Network conditions and Security requirements to the firewall script.
This nftables firewall script is only for demonstration purposes. Do not use it without adapting it to your environments and security requirements.
Prerequisites
- The network is configured as described in Network conditions.
Procedure
Create the
/etc/nftables/firewall.nftscript with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Include the
/etc/nftables/firewall.nftscript in the/etc/sysconfig/nftables.conffile:include "/etc/nftables/firewall.nft"
include "/etc/nftables/firewall.nft"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Enable IPv4 forwarding:
echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/95-IPv4-forwarding.conf sysctl -p /etc/sysctl.d/95-IPv4-forwarding.conf
# echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/95-IPv4-forwarding.conf # sysctl -p /etc/sysctl.d/95-IPv4-forwarding.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
nftablesservice:systemctl enable --now nftables
# systemctl enable --now nftablesCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Optional: Verify the
nftablesrule set:nft list ruleset
# nft list ruleset ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow Try to perform an access that the firewall prevents. For example, try to access the router using SSH from the DMZ:
ssh router.example.com
# ssh router.example.com ssh: connect to host router.example.com port 22: Network is unreachableCopy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on your logging settings, search:
The
systemdjournal for the blocked packets:journalctl -k -g "nft drop"
# journalctl -k -g "nft drop" Oct 14 17:27:18 router kernel: nft drop IN : IN=enp8s0 OUT= MAC=... SRC=198.51.100.5 DST=198.51.100.1 ... PROTO=TCP SPT=40464 DPT=22 ... SYN ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
/var/log/nftables.logfile for the blocked packets:Oct 14 17:27:18 router kernel: nft drop IN : IN=enp8s0 OUT= MAC=... SRC=198.51.100.5 DST=198.51.100.1 ... PROTO=TCP SPT=40464 DPT=22 ... SYN ...
Oct 14 17:27:18 router kernel: nft drop IN : IN=enp8s0 OUT= MAC=... SRC=198.51.100.5 DST=198.51.100.1 ... PROTO=TCP SPT=40464 DPT=22 ... SYN ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.8. Using nftables to limit the amount of connections Copia collegamentoCollegamento copiato negli appunti!
You can use nftables to limit the number of connections or to block IP addresses that attempt to establish a given amount of connections to prevent them from using too many system resources.
8.8.1. Limiting the number of connections by using nftables Copia collegamentoCollegamento copiato negli appunti!
By using the ct count parameter of the nft utility, you can limit the number of simultaneous connections per IP address. For example, you can use this feature to configure that each source IP address can only establish two parallel SSH connections to a host.
Procedure
Create the
filtertable with theinetaddress family:nft add table inet filter
# nft add table inet filterCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
inputchain to theinet filtertable:nft add chain inet filter input { type filter hook input priority 0 \; }# nft add chain inet filter input { type filter hook input priority 0 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a dynamic set for IPv4 addresses:
nft add set inet filter limit-ssh { type ipv4_addr\; flags dynamic \;}# nft add set inet filter limit-ssh { type ipv4_addr\; flags dynamic \;}Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add a rule to the
inputchain that allows only two simultaneous incoming connections to the SSH port (22) from an IPv4 address and rejects all further connections from the same IP:nft add rule inet filter input tcp dport ssh ct state new add @limit-ssh { ip saddr ct count over 2 } counter reject# nft add rule inet filter input tcp dport ssh ct state new add @limit-ssh { ip saddr ct count over 2 } counter rejectCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Establish more than two new simultaneous SSH connections from the same IP address to the host. Nftables refuses connections to the SSH port if two connections are already established.
Display the
limit-sshdynamic set:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
elementsentry displays addresses that currently match the rule. In this example,elementslists IP addresses that have active connections to the SSH port. Note that the output does not display the number of active connections or if connections were rejected.
8.8.2. Blocking IP addresses that attempt more than ten new incoming TCP connections within one minute Copia collegamentoCollegamento copiato negli appunti!
You can temporarily block hosts that are establishing more than ten IPv4 TCP connections within one minute.
Procedure
Create the
filtertable with theipaddress family:nft add table ip filter
# nft add table ip filterCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
inputchain to thefiltertable:nft add chain ip filter input { type filter hook input priority 0 \; }# nft add chain ip filter input { type filter hook input priority 0 \; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add a rule that drops all packets from source addresses that attempt to establish more than ten TCP connections within one minute:
nft add rule ip filter input ip protocol tcp ct state new, untracked meter ratemeter { ip saddr timeout 5m limit rate over 10/minute } drop# nft add rule ip filter input ip protocol tcp ct state new, untracked meter ratemeter { ip saddr timeout 5m limit rate over 10/minute } dropCopy to Clipboard Copied! Toggle word wrap Toggle overflow The
timeout 5mparameter defines thatnftablesautomatically removes entries after five minutes to prevent that the meter fills up with stale entries.
Verification
To display the meter’s content, enter:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.9. Debugging nftables rules Copia collegamentoCollegamento copiato negli appunti!
The nftables framework provides different options for administrators to debug rules and if packets match them.
8.9.1. Creating a rule with a counter Copia collegamentoCollegamento copiato negli appunti!
To identify if a rule is matched, you can use a counter.
-
For more information about a procedure that adds a counter to an existing rule, see Adding a counter to an existing rule in
Configuring and managing networking
Prerequisites
- The chain to which you want to add the rule exists.
Procedure
Add a new rule with the
counterparameter to the chain. The following example adds a rule with a counter that allows TCP traffic on port 22 and counts the packets and traffic that match this rule:nft add rule inet example_table example_chain tcp dport 22 counter accept
# nft add rule inet example_table example_chain tcp dport 22 counter acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow To display the counter values:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.9.2. Adding a counter to an existing rule Copia collegamentoCollegamento copiato negli appunti!
To identify if a rule is matched, you can use a counter.
-
For more information about a procedure that adds a new rule with a counter, see Creating a rule with the counter in
Configuring and managing networking
Prerequisites
- The rule to which you want to add the counter exists.
Procedure
Display the rules in the chain including their handles:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add the counter by replacing the rule but with the
counterparameter. The following example replaces the rule displayed in the previous step and adds a counter:nft replace rule inet example_table example_chain handle 4 tcp dport 22 counter accept
# nft replace rule inet example_table example_chain handle 4 tcp dport 22 counter acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow To display the counter values:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.9.3. Monitoring packets that match an existing rule Copia collegamentoCollegamento copiato negli appunti!
The tracing feature in nftables in combination with the nft monitor command enables administrators to display packets that match a rule. You can enable tracing for a rule an use it to monitoring packets that match this rule.
Prerequisites
- The rule to which you want to add the counter exists.
Procedure
Display the rules in the chain including their handles:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add the tracing feature by replacing the rule but with the
meta nftrace set 1parameters. The following example replaces the rule displayed in the previous step and enables tracing:nft replace rule inet example_table example_chain handle 4 tcp dport 22 meta nftrace set 1 accept
# nft replace rule inet example_table example_chain handle 4 tcp dport 22 meta nftrace set 1 acceptCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
nft monitorcommand to display the tracing. The following example filters the output of the command to display only entries that containinet example_table example_chain:nft monitor | grep "inet example_table example_chain"
# nft monitor | grep "inet example_table example_chain" trace id 3c5eb15e inet example_table example_chain packet: iif "enp1s0" ether saddr 52:54:00:17:ff:e4 ether daddr 52:54:00:72:2f:6e ip saddr 192.0.2.1 ip daddr 192.0.2.2 ip dscp cs0 ip ecn not-ect ip ttl 64 ip id 49710 ip protocol tcp ip length 60 tcp sport 56728 tcp dport ssh tcp flags == syn tcp window 64240 trace id 3c5eb15e inet example_table example_chain rule tcp dport ssh nftrace set 1 accept (verdict accept) ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow WarningDepending on the number of rules with tracing enabled and the amount of matching traffic, the
nft monitorcommand can display a lot of output. Usegrepor other utilities to filter the output.
8.10. Backing up and restoring the nftables rule set Copia collegamentoCollegamento copiato negli appunti!
You can backup nftables rules to a file and later restoring them. Also, administrators can use a file with the rules to, for example, transfer the rules to a different server.
8.10.1. Backing up the nftables rule set to a file Copia collegamentoCollegamento copiato negli appunti!
You can use the nft utility to back up the nftables rule set to a file.
Procedure
To backup
nftablesrules:In a format produced by
nft list rulesetformat:nft list ruleset > file.nft
# nft list ruleset > file.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow In JSON format:
nft -j list ruleset > file.json
# nft -j list ruleset > file.jsonCopy to Clipboard Copied! Toggle word wrap Toggle overflow
8.10.2. Restoring the nftables rule set from a file Copia collegamentoCollegamento copiato negli appunti!
You can restore the nftables rule set from a file.
Procedure
To restore
nftablesrules:If the file to restore is in the format produced by
nft list rulesetor containsnftcommands directly:nft -f file.nft
# nft -f file.nftCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the file to restore is in JSON format:
nft -j -f file.json
# nft -j -f file.jsonCopy to Clipboard Copied! Toggle word wrap Toggle overflow