Skip to main content

iptables

iptables

iptables is a Linux Firewall utility that's used to configure rules on the kernel netfilter firewall. iptables processes packets based on chains of rules, deciding whether to allow, drop, or manipulate them.

iptables does not preserve connection state across reloads - meaning that reloading the service/ruleset will drop existing connections. firewalld avoids this.

By default, iptables rules are lost on reboot. See HERE for info on how to save rules.

Tables & Chains

What are tables?

iptables has various different tables that perform different functions. Notable tables and their functions;

Table Purpose Example
Filter The default table for allowing/blocking traffic. Accept SSH, block pings, etc
NAT Used to implement  Network Address Translation rules. Port forwarding, IP masking
Mangle Used for modifying packet headers. Changing TTL,
Raw Used to configure exceptions for packets involved in connection tracking.
Security Used to mark packets with SELinux context.

If you don't specify a specific table when running iptables commands, you'll be using the filter table by default - which is the most commonly used anyway.

What are chains?

Chains are lists of rules that belong to a table. Each chain represents a rule that a packet must have imposed against it during its journey through the system.

Chain Function
INPUT For incoming packets.
OUTPUT For outgoing packets.
FORWARD For packets passing through the system.
PREROUTING & POSTROUTING Used in NAT/Mangle tables for altering packets before or after routing decisions. 

Basic Commands & Syntax

iptables [options] [-t table] [commands] {chain/rule specification}

iptables events (drops/blocks) are recorded in /var/log/messages or /var/log/kern.log)

DROP Packets

iptables -l CHAIN_NAME -j DROP

Ensure packets not processed by prior rules will jump to a specific chain:

Create a new chain

iptables -N CHAIN_NAME

Enable logging on a chain

iptables -I INPUT -j CHAIN_NAME

Saving & Persisting Rules 

There are additional iptables packages available to enable saving and persisting reboot options for chains/rules.

CentOS/RHEL

NOTE: Most modern RHEL based systems will have firewalld installed by default - this will handle any saving and rebooting.

Install the iptables-services package and ensure that this service is enabled.

Save Rules

sudo service iptables save

(rules are saved to /etc/sysconfig/iptables)

Ubuntu/Debian

Most Debian based systems by default don't use firewalld. They will have iptables and nftables installed by default.

Install the iptables-persistent package.

Save Rules

sudo netfilter-persistent save

Saves IPv4 rules to:
/etc/iptables/rules.v4

Saves IPv6 rules to:
/etc/iptables/rules.v6