Back to Blog

From iptables to nftables: rule basics and persistence

Complete tutorial on iptables/nftables in Ubuntu. Learn tables and chains, NAT examples, nft syntax, save/restore.

From iptables to nftables: rule basics and persistence
# From iptables to nftables: Rule Basics and Persistence

## Introduction

In the world of Linux networking, **iptables** has long been the standard for managing network traffic through packet filtering and NAT (Network Address Translation). However, as network demands evolve, **nftables** has emerged as a more modern and efficient alternative, providing a unified framework for various packet processing tasks. With its more straightforward syntax and improved capabilities, nftables not only simplifies the management of firewall rules but also enhances performance.

Understanding the transition from iptables to nftables is crucial for system administrators and engineers, as it allows for better resource management, easier rule creation, and enhanced security configurations. This tutorial will cover the foundational concepts of both iptables and nftables, including their syntax, how to create and manage rules, and strategies for persisting these rules across reboots. With practical examples and best practices, readers will gain the skills needed to efficiently manage network traffic.

## Prerequisites

- **Ubuntu Version**: This tutorial assumes you are using Ubuntu 20.04 LTS or later.
- **Required Packages**: Ensure that the `nftables` package is installed. If using iptables, ensure it is already available on the system.
- **Permissions**: Root access is required to modify firewall rules.
- **Risks**: Incorrect rule configurations can lead to unintended blocking of legitimate traffic or exposure of sensitive services. Always test configurations in a safe environment before deploying them to production.

## Core Concepts

### Terminology

- **iptables**: A user-space utility that allows a system administrator to configure the IP packet filter rules of the Linux kernel.
- **nftables**: A successor to iptables, providing a single framework for packet filtering, NAT, and other packet mangling tasks.
- **Chains**: Within a table, chains define a set of rules. Each packet is checked against these rules in a defined order.
- **Tables**: The primary structure used to organize chains and rules.
- **NAT**: Network Address Translation is used to map private IP addresses to a public IP address.

### Architecture

- **iptables** operates with distinct tables (`filter`, `nat`, etc.) and chains (`INPUT`, `OUTPUT`, `FORWARD`).
- **nftables** combines these functionalities into a more coherent structure, allowing greater flexibility and easier management of rules.

### When to Use

- Use **iptables** for legacy systems or where existing scripts and configurations are heavily reliant on its syntax.
- Transition to **nftables** for new setups or when upgrading existing systems to leverage its advantages in performance and manageability.

### Limits

- While iptables can still be used, it is recommended to adopt nftables for modern networking tasks due to its limitations in scalability and complexity in configuration.

## Syntax/Commands

| Command          | Description                                 | Flags/Parameters                     |
|------------------|---------------------------------------------|--------------------------------------|
| `iptables`       | Configure packet filtering rules            | `-A`, `-D`, `-L`, `-F`, `-P`, etc.   |
| `nft`            | Manage nftables rules                       | `add`, `delete`, `list`, `flush`    |

## Practical Examples

### 1. Basic iptables Rule Creation

```bash
# Allow incoming SSH traffic
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

2. Basic nftables Rule Creation

# Allow incoming SSH traffic
nft add rule ip filter input tcp dport 22 accept

3. Listing Current Rules in iptables

# List all iptables rules
iptables -L -v

4. Listing Current Rules in nftables

# List all nftables rules
nft list ruleset

5. Creating a NAT Rule in iptables

# Enable NAT for outgoing connections
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

6. Creating a NAT Rule in nftables

# Enable NAT for outgoing connections
nft add rule ip nat postrouting oif "eth0" masquerade

7. Saving iptables Rules

# Save iptables rules to a file
iptables-save > /etc/iptables/rules.v4

8. Saving nftables Rules

# Save nftables rules to a file
nft list ruleset > /etc/nftables.conf

Real-World Scenarios

Scenario 1: Setting Up a Basic Firewall with iptables

Imagine you are setting up a basic firewall to secure a web server. You would create rules to allow HTTP (port 80) and HTTPS (port 443) traffic while denying all other incoming connections.

iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -j DROP

Scenario 2: Migrating from iptables to nftables

You have an existing iptables configuration that you want to migrate to nftables. First, save your current rules:

iptables-save > /etc/iptables/rules.v4

Then, translate these rules into nftables syntax and save them:

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
nft add rule ip filter input tcp dport 80 accept
nft add rule ip filter input drop

Scenario 3: Configuring a Router with NAT

You are configuring a Linux router that will share an internet connection with a private network. Using nftables, you set up NAT to allow all internal devices to access the internet.

nft add table ip nat
nft add chain ip nat postrouting { type nat hook postrouting priority 100; }
nft add rule ip nat postrouting oif "eth0" masquerade

Best Practices

  1. Backup Configuration: Always back up your current rules before making changes.
  2. Use Comments: Add comments to your rules to explain their purpose, improving maintainability.
  3. Test Changes: Test new rules in a controlled environment to prevent disruptions to services.
  4. Use Specific Rules: Rather than blanket accept rules, specify protocols and ports to minimize security risks.
  5. Regular Audits: Periodically review and audit firewall rules to ensure compliance with security policies.

Common Errors

1. Error: iptables: No chain/target/match by that name

Cause: You are trying to modify a chain that does not exist.

Fix: Create the necessary chain or table before adding rules.

2. Error: nft: rule already exists

Cause: You are attempting to add a rule that is identical to an existing one.

Fix: Check for existing rules using nft list ruleset and adjust accordingly.

3. Error: Permission denied

Cause: Insufficient privileges to modify the iptables/nftables rules.

Fix: Ensure you are running commands as root or with sudo.

4. Error: nft: could not open file

Cause: The specified file for saving or loading rules does not exist or is not accessible.

Fix: Check file paths and permissions to ensure they are correct.

Related Commands

Command Description
iptables Legacy packet filtering and NAT utility
nft Modern packet filtering and NAT utility
ip Network management utility for routing and interfaces

Automation Script

Below is a complete bash script for automating the setup of a basic nftables firewall configuration. This script will create a default firewall allowing SSH, HTTP, and HTTPS while dropping all other traffic.

#!/bin/bash

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

# Flush existing rules
nft flush ruleset

# Create a new table and chain
nft add table ip filter
nft add chain ip filter input { type filter hook input priority 0; }

# Allow established and related connections
nft add rule ip filter input ct state established,related accept

# Allow SSH
nft add rule ip filter input tcp dport 22 accept

# Allow HTTP
nft add rule ip filter input tcp dport 80 accept

# Allow HTTPS
nft add rule ip filter input tcp dport 443 accept

# Drop all other traffic
nft add rule ip filter input drop

# Save the rules
nft list ruleset > /etc/nftables.conf

echo "Firewall configuration applied and saved."

Conclusion

In this tutorial, we explored the transition from iptables to nftables, understanding the core concepts, syntax, and practical applications of both tools. By following the practical examples and best practices outlined, you should now have the foundational knowledge to manage firewall rules effectively in your Ubuntu/Linux environment. As networking continues to evolve, embracing nftables will ensure your systems remain secure and efficient.

References