Skip to main content

iptables

Ref: Arch Linux iptables

DescriptionCommand
Verbose list rulesiptables -v -L [<chain>]
List rulesiptables -S [<chain>]
Dump iptables to fileiptables-save > <file>
Restore iptables from fileiptables-restore < <file>
Save iptables (Red Hat <= 6)service iptables save
Create new chain (User-defined)iptables -N <chain>

Flow

ChainsINPUT / OUTPUT / FORWARD / PREROUTING / POSTROUTING
Tablesraw / filter / nat / mangle / security (Default is filter)
TargetsACCEPT / DROP / QUEUE / RETURN / REJECT / LOG

Ref

info
  • If any chain says DROP, it is killed there
  • If chain says ACCEPT, it continue process
  • User-defined chains can not have a default policy
  • If no rule is matched in a User-defined chain, the default behaviour is to jump back to the originating chain

Ref: iptables Processing Flowchart

iptables flow chart

Policy

Policy = Default target

iptables -P <chain> <target>

Rule

Ref: netfilter documentation

OptionDescription
-AAppend rule to chain
-IInsert rule to rule number position
-DDelete rule rule number
-pProtocol
Address10.0.0.1, 0.0.0.0/0, 10.0.0.0/24
!Not
iptables 
{ -A <chain> | -I <chain> [rule number] | -D <chain> [rule number] }
[[!] -i <interface>]
[[!] -o <interface>]
[[!] -s <src IP address>[/<prefix length>]]
[[!] -d <dest IP address>[/<prefix length>]]
[[!] -p {icmp|tcp|udp}]
[[!] --sport <src port>[,...]]
[[!] --dport <dest port>[,...]]
-j <target>

Extension

Ref: iptables-extensions

iptables <rule>
[-m state [!] --state { NEW | ESTABLISHED | RELATED }]
[-m conntrack
[[!] --ctstate { INVALID | NEW | ESTABLISHED | RELATED | UNTRACKED | SNAT | DNAT }]
]
-j <target>

Redirect input to other port

Ref: How To Mangle The Packets

iptables -t nat -A PREROUTING [-i <interface>] -p tcp --dport <from port> -j REDIRECT --to-port <to port>

Masquerading

Ref: Masquerading

Source NAT

Use the address of the interface the packet is going out as source address

iptables -t nat -A POSTROUTING -o <interface> -j MASQUERADE

Rule

Example rule

Allow all established packet

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

Allow TCP port 22 (SSH) connect

sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT