Iptables Command: A Guide to Firewall Configuration on Ubuntu Router

Abstract: Resolve Ubuntu router firewall misconfigurations by configuring iptables chains to secure traffic while maintaining SSH and DNS connectivity.

Created: 2026-08-08 by
Use the iptables command on Ubuntu to manage packet filtering rules for your router. This guide explains how to configure input, output, and forwarding chains to secure network traffic while maintaining connectivity for essential services like SSH and DNS resolution.

Understanding Iptables Basics

The iptables utility is a command-line firewall configuration tool for Linux systems. It operates by organizing rules into tables, with the filter table being the default. Within these tables, packets are processed through chains of rules in a specific order. The three primary built-in chains are INPUT, which handles packets destined for the local system; OUTPUT, for packets originating from the local system; and FORWARD, for packets passing through the system from one interface to another.

When configuring an Ubuntu router, understanding these chains is critical because misconfigured rules can block legitimate traffic or expose internal networks to external threats. Each rule specifies a target action, such as ACCEPT, DROP, or REJECT. By default, if no rule matches a packet, the chain's default policy determines the outcome. It is standard practice to set the default policy of INPUT and FORWARD chains to DROP to ensure a deny-by-default security posture.

Initial Setup and Verification

Before applying new rules, it is essential to verify the current state of the firewall. You can view existing rules using the iptables -L -n -v command. This displays detailed information about each rule, including the number of packets matched and bytes transferred. If you are setting up a new router, you will likely see empty chains with ACCEPT policies, which indicates that all traffic is currently allowed.

To begin securing your router, first establish a baseline by allowing loopback traffic. Loopback interfaces are used for inter-process communication on the same machine and should always be permitted. Use the following command to accept all traffic on the loopback interface:

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

This step ensures that local applications can communicate without interference. After adding this rule, verify its presence in the list to confirm it was added correctly. Failure to allow loopback traffic can cause unexpected behavior in many system services.

Configuring Core Firewall Rules

For a router, the most important chain to configure is the FORWARD chain, as it controls traffic passing between network interfaces. Start by accepting established and related connections. This allows return traffic for connections initiated by internal clients. Use the state module to identify these packets efficiently:

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

Next, define which external traffic is allowed to enter your internal network. For example, if you want to allow SSH access from a specific subnet, specify the source IP range and the destination port. Always restrict access to management ports to trusted networks only. Additionally, consider enabling NAT (Network Address Translation) if your router connects multiple private subnets to the public internet. While iptables can handle basic NAT, tools like ufw or nftables may offer simpler syntax for complex setups.

If you encounter issues with packet dropping after implementing these rules, refer to our guide on Troubleshooting Dropping Packets in iptables: tcpdump Analysis and Solutions. This resource provides diagnostic steps using tcpdump to identify where packets are being discarded.

Persisting Changes Across Reboots

A common pitfall for Ubuntu administrators is losing firewall rules after a system reboot. By default, iptables rules stored in memory are volatile. To persist them, you must save the current configuration and restore it during boot. On Ubuntu, the netfilter-persistent service handles this task.

First, install the necessary package if it is not already present:

sudo apt-get install netfilter-persistent

Once installed, save your current rules using the following command:

sudo netfilter-persistent save

This command writes the rules to /etc/iptables/rules.v4 for IPv4 and /etc/iptables/rules.v6 for IPv6. During the next boot, the netfilter-persistent service automatically loads these files, ensuring your firewall configuration remains intact. Regularly updating these saved rules is crucial when making changes to your network topology.

Advanced Considerations and Security

While iptables is powerful, it requires careful rule ordering. Rules are evaluated sequentially, so place more specific rules before general ones. For instance, a rule dropping malicious IPs should come before a rule accepting all traffic on a specific port. Additionally, monitor your logs for dropped packets to detect potential attacks. Enable logging by adding a rule with the --log-prefix option before the DROP target.

If your router also hosts containerized applications, be aware that Docker modifies iptables rules automatically. Unmanaged changes can conflict with your manual configurations. For insights into managing default network access in Docker environments, see Default Network Access to the Docker Host. This helps prevent accidental exposure of container services to the public internet.

Frequently Asked Questions

How do I delete a specific iptables rule?

You can delete a rule by specifying its line number within the chain. First, list the rules with numbers using iptables -L -n --line-numbers. Then, use the -D flag followed by the chain name and the line number, such as iptables -D INPUT 3. This removes the third rule from the INPUT chain immediately.

Why is my SSH connection timing out after applying iptables rules?

This usually happens because the default INPUT policy is set to DROP without an explicit rule allowing SSH traffic. Ensure you have added a rule like iptables -A INPUT -p tcp --dport 22 -j ACCEPT before changing the default policy. Always keep an active session open while testing new rules to avoid locking yourself out.

Can I use iptables to block specific countries?

Yes, but it requires a GeoIP database and matching rules based on source IP ranges. Tools like xt_geoip can be compiled with iptables to facilitate this. However, maintaining accurate GeoIP data is challenging due to dynamic IP allocations, and it may lead to false positives blocking legitimate users.

What is the difference between DROP and REJECT?

DROP silently discards packets without notifying the sender, which makes scanning slower but hides your system's existence. REJECT sends an error message back to the sender, providing immediate feedback. For public-facing services, REJECT is often preferred for better user experience, while DROP is better for stealth against attackers.

How do I restore iptables rules from a backup file?

If you have saved your rules to a text file, you can restore them using the iptables-restore command. Simply pipe the contents of the file into the command: cat /path/to/backup.txt | iptables-restore. This applies all rules defined in the file instantly, replacing the current active configuration.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More