keepcalculator

06 Numbers and Powers

How to Configure iptables Firewall on Linux

Card No. 06·87980 · Updated · Standard formula, shown below

To configure an iptables firewall on Linux, you add, delete, and modify rules in the built-in chains (INPUT, OUTPUT, FORWARD) using commands like iptables -A, -D, and -I, then save the ruleset with iptables-save. This article explains the core concepts, shows practical examples, and covers common pitfalls so you can build a working firewall for your server or desktop.

What iptables Actually Does

iptables is the user-space utility that manages netfilter, the packet-filtering framework inside the Linux kernel. Every packet that enters, leaves, or is forwarded through your machine passes through a set of tables (filter, nat, mangle, raw), each containing chains of rules. The filter table is where you define allow/deny decisions, and its three built-in chains are:

  • INPUT – packets destined for the local system
  • OUTPUT – packets generated by the local system
  • FORWARD – packets routed through the system (e.g., when acting as a router)

Each rule matches packets based on criteria like source IP, destination port, protocol, or interface, and then applies a target such as ACCEPT, DROP, REJECT, or LOG. Rules are evaluated in order; the first match wins, so rule ordering is critical.

Basic Syntax and Common Commands

The general syntax for an iptables command is:

iptables -t <table> -<command> <chain> <match-conditions> -j <target>

If you omit -t, the filter table is assumed. The most frequently used commands are:

  • -A (append) – add a rule to the end of a chain
  • -I (insert) – add a rule at a specified position (default 1)
  • -D (delete) – remove a rule by number or by matching its specification
  • -F (flush) – remove all rules from a chain
  • -L (list) – show the current rules
  • -P (policy) – set the default policy for a chain

For example, to allow incoming SSH (port 22) and drop all other incoming traffic, you would run:

iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -P INPUT DROP

Note that the default policy applies only to packets that don’t match any rule. Setting the INPUT policy to DROP is a common security hardening step, but you must ensure you have a rule to allow established connections, or you’ll lock yourself out.

Stateful Rules: Allowing Established Connections

A firewall that only allows specific ports will break most protocols because responses come from a different port. For example, if you allow outbound HTTP (port 80) but block all INPUT, the response packets from the web server will be dropped. The solution is to use connection tracking:

iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT

This allows packets that are part of an already-approved connection. The RELATED state covers auxiliary connections like FTP data channels or ICMP errors. Always add these rules before your restrictive ones.

Common Use Cases and Example Rules

Here are practical rules you’ll likely need:

  • Allow SSH from a specific IP only:
    iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j ACCEPT
  • Allow HTTP and HTTPS:
    iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
  • Allow ping (ICMP echo-request):
    iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
  • Block a specific IP address:
    iptables -A INPUT -s 203.0.113.5 -j DROP
  • Forward traffic between interfaces (router):
    iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

Remember that DROP silently discards the packet, while REJECT sends back an error (like “connection refused”). DROP is often preferred to hide open ports, but REJECT can speed up client timeouts.

Persistence: Saving Rules Across Reboots

iptables rules are lost on reboot unless you save them. The method depends on your distribution:

  • Debian/Ubuntu: iptables-save > /etc/iptables/rules.v4 (install the iptables-persistent package to auto-load)
  • RHEL/CentOS/Fedora: service iptables save or iptables-save > /etc/sysconfig/iptables
  • Arch: iptables-save > /etc/iptables/iptables.rules and enable the iptables service

To restore rules manually, use iptables-restore < /path/to/file. Always test a new ruleset before saving it, because a mistake can cut off your remote access.

Common Mistakes and Troubleshooting

Even experienced admins make these errors:

  • Locking yourself out: Forgetting to allow SSH before setting the default policy to DROP. Always add an allow rule for your current SSH connection first, or use a cron job to flush rules after a few minutes as a safety net.
  • Wrong rule order: Placing a broad DROP rule before a specific ACCEPT rule. For example, iptables -A INPUT -j DROP before iptables -A INPUT -p tcp --dport 22 -j ACCEPT will block everything. Use -I to insert at the top.
  • Forgetting loopback: Many services communicate via the loopback interface (lo). If you block it, local applications break. Add iptables -A INPUT -i lo -j ACCEPT.
  • Not allowing established connections: As noted above, this breaks almost everything.
  • Using the wrong table: NAT rules (like port forwarding) go in the nat table, not the filter table.

To debug, run iptables -L -v to see packet counts per rule. A high count on a DROP rule tells you it’s being hit. Also check dmesg if you added a LOG rule.

iptables vs. nftables and firewalld

Modern Linux distributions are moving away from iptables. nftables is the successor, offering a more consistent syntax and better performance. You can still use iptables commands on many systems because they are translated to nftables in the background, but learning nftables is a good investment. firewalld is a higher-level tool that manages nftables or iptables for you, using “zones” and “services” instead of raw rules. It’s the default on RHEL-based distros and is easier for beginners, but if you need fine-grained control or are on an older system, iptables remains relevant.

Frequently Asked Questions

How do I see my current iptables rules?

Run iptables -L -n -v. The -n flag shows numeric IP addresses and ports instead of resolving hostnames, which is faster and clearer. -v adds packet and byte counts.

What’s the difference between DROP and REJECT?

DROP silently discards the packet, making the port appear closed or nonexistent. REJECT sends back an ICMP error or TCP RST, so the client immediately knows the connection was refused. DROP can slow down port scans but may cause timeouts; REJECT is friendlier for legitimate users.

How do I delete a specific rule?

First list rules with line numbers: iptables -L --line-numbers. Then delete by number, e.g., iptables -D INPUT 3. Alternatively, you can specify the exact rule again with -D instead of -A.

Why do my rules disappear after reboot?

iptables is not persistent by default. You must save the ruleset to a file and restore it at boot, as described above. Some distributions have services like netfilter-persistent that handle this automatically once you save.

Can I use iptables to block outbound traffic?

Yes, the OUTPUT chain controls outbound packets. For example, to block all outbound traffic except DNS and HTTP: set the OUTPUT policy to DROP, then allow --dport 53 (UDP/TCP) and --dport 80,443. Be careful—this can break system updates and other services.

Is iptables still relevant in 2024?

Yes, especially on older servers and embedded systems. While nftables is the future, iptables syntax is still widely used in tutorials, scripts, and documentation. Understanding iptables also makes learning nftables easier because the concepts are similar.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →