Files
oam/knowledge base/iptables.md
2025-12-23 22:28:49 +01:00

2.6 KiB

Iptables

Warning

It should be replaced with its successor, nftables.

Command line utility for configuring the Linux kernel-level firewall implemented within the netfilter project.

Inspects, modifies, forwards, redirects, and/or drops IP packets based on rules.

  1. TL;DR
  2. Further readings
    1. Sources

TL;DR

Use iptables for IPv4 and ip6tables for IPv6.
They have the same syntax, but some options are specific to either IPv4 or IPv6.

Rules are generally split up in three sections (A.K.A. chains):

  • INPUT manages all packets destined for the local host.
  • FORWARD manages all packets that are passing through.
    This chain is usually given rules when the local host is used as a router.
  • OUTPUT manages all packets originating from the local host.

Rules are applied to a packed, depending on the packet's direction and in the order the rules are specified.
Should no specific rule apply, the packet is applied the default policy for the chain.

Chains must be referenced using their uppercase name.

Each chain has its own default policy, and it can either be ACCEPT or DROP.
Rules can then be implemented to configure exceptions to the default policy.
Rules can either be appended (-A) to the bottom a chain or inserted (-I). When no rule is specified during insertion, that rule is inserted on the top of the chain.

Usage
# List current rules.
iptables -L
iptables -L --line-numbers

# Add rules.
iptables -I 'INPUT' -p 'tcp' --dport '443' -j 'ACCEPT'
iptables -I 'INPUT' -p 'tcp' -s '192.168.100.100' --dport 22 -j 'ACCEPT'
iptables -I 'INPUT' -p 'tcp' -s '!192.168.100.0/24' --dport 22 -j 'REJECT'

# Change default policies to 'DROP'.
iptables -P 'FORWARD' 'DROP'

# Delete specific rules.
iptables -D 'INPUT' 2

# Delete *all* rules.
iptables -F

# Backup and restore rules.
iptables-save -f '/etc/iptables/rules.v4'
iptables-restore '/etc/iptables/rules.v4'

Further readings

Sources