Report issue Add example

iptables

Administration tool for IPv4 packet filtering and NAT.

Description

iptables is used to set up, maintain, and inspect the tables of IPv4 packet filter rules in the Linux kernel.

Syntax

iptables [options] [chain] [matching] [action]

Options

-t <table> : Specify the table (filter, nat, mangle, raw). Default is 'filter'.
-p <proto> : Specify the protocol (tcp, udp, icmp, etc.).
-s <addr>  : Specify source address.
-d <addr>  : Specify destination address.
-i <iface> : Input interface (e.g., eth0). Valid for INPUT, FORWARD, PREROUTING.
-o <iface> : Output interface. Valid for OUTPUT, FORWARD, POSTROUTING.
-L [chain] : List rules.
-A <chain> : Append rule to chain.
-I <chain> [num] : Insert rule at position (default 1).
-D <chain> [num] : Delete rule by position or specification.
-R <chain> <num> : Replace rule at position.
-P <chain> <target> : Set default policy for a built-in chain.
-F [chain] : Flush (clear) all rules in chain or all chains.
-N <chain> : Create a new user-defined chain.
-X [chain] : Delete a user-defined chain.
-Z [chain] : Zero counters.
-j <target> : Target action (ACCEPT, DROP, REJECT, SNAT, DNAT, MASQUERADE, LOG).
-h : Display help.

Core Concepts

Chains

Tables

Examples

Flush all rules:

iptables -F
iptables -X
iptables -Z

Allow SSH from a specific subnet:

iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT

Allow Loopback:

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

Set Default Policies:

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

Basic Firewall for a Web Server:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT

Port Forwarding (DNAT):

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10:80

Masquerading (NAT for Internet sharing):

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Block an IP:

iptables -I INPUT -s 1.2.3.4 -j DROP

List Rules with Numbers:

iptables -L -n -v --line-numbers