nft - Linux


Overview

The nft command is part of the nftables framework, which is a subsystem of the Linux kernel providing firewalling and packet filtering features. This command replaces earlier tools like iptables, offering a simpler and more consistent syntax, improved performance, and enhanced features. nft is used for configuring tables, chains, and rules that inspect and manipulate IP packets.

Syntax

The general syntax for the nft command is:

nft [options] [commands]

Each command can consist of adding, deleting, listing, or modifying tables, chains, or rules. The syntax differs based on the specific operation being performed.

Options/Flags

  • -a, --handle: Show the handle (a unique identifier) for rules when listing or adding them.
  • -c, --check: Check whether a specified rule already exists in the specified table and chain.
  • -f, --file: Execute the commands from the specified file.
  • -I, --includepath: Add an include path searching for files.
  • -j, --json: Output in JSON format. This is particularly useful for integration with automated scripts or applications.
  • -s, --stateless: Omit output that depends on the internal state (counters, conntrack).
  • -n, --numeric: Show numerical output instead of resolving symbolic names (like port names).
  • -y, --debug: Enable debugging mode.
  • -v, --version: Display version information.

These options modify how the nft command interprets the supplied commands or changes its output format and verbosity.

Examples

  1. Creating a table:

    nft add table ip mytable
    
  2. Adding a chain:

    nft add chain ip mytable mychain { type filter hook input priority 0 \; }
    
  3. Adding a rule:

    nft add rule ip mytable mychain ip protocol icmp accept
    
  4. Listing all rules:

    nft list ruleset
    
  5. Deleting a table:

    nft delete table ip mytable
    

Common Issues

Error: Could not process rule: This generally indicates syntax errors or logical issues in the rules. Ensure syntax is correct and all specified elements (like tables and chains) exist.

Permission Denied: nft must be run with root or equivalent privileges. Using sudo is often required.

Integration

nft can be integrated with scripts to automate setup processes. For example, a startup script to configure firewall settings on boot:

#!/bin/bash
nft add table ip filter
nft add chain ip filter input { type filter hook input priority 0 \; }
nft add rule ip filter input tcp dport 22 accept
  • iptables: Previous generation tool for managing netfilter rules.
  • ip6tables: Similar to iptables but for IPv6.
  • firewalld: A firewall management tool that interfaces with nftables.

For further details and complete documentation, refer to the official nftables wiki: nftables Wiki