Good to know: Iptables reads rules from top to bottom, stopping at the first rule that matches.
chain: group of rules (Default ones are INPUT, OUTPUT and FORWARD).
target: What to do with a packet (Often used are ACCEPT, DROP (No echo/"offline"), REJECT (Echoes back 'not authorized icmp')).
Targets are what the firewall with do with a packet.
Commonly used targets:
Target | Description |
---|---|
ACCEPT | Accepts a packet |
DROP | Drops a packet (Makes it look like the host is offline) |
REJECT | Drops a packet and replies with 'Not authorized'. |
RETURN | Returns from a subchain to the main chain. (Immediately stops processing the subchain). |
To change the default policy of a chain, use the following command:
iptables -P chain target
where chain is the chain name and target is one of DROP, ACCEPT, REJECT.
Examples:
iptables -P INPUT ACCEPT // change INPUT table policy to ACCEPT
iptables -P OUTPUT ACCEPT // change OUTPUT chain policy to ACCEPT
iptables -P FORWARD ACCEPT // change FORWARD chain policy to ACCEPT
iptables -P chain DROP // change custom chain default to DROP
To create a chain run the following command:
iptables -N chain_name
To rename a chain:
iptables -E new_name old_name
To delete a chain:
iptables -X chain_name
To redirect a packet to be processed by a (sub)chain:
iptables -A INPUT -p icmp -j new_chain
Redirect packets from default chain INPUT with icmp protocol to custom chain 'new_chain'
List rules:
iptables -L // list all rules of all chains
iptables -L -v // display rules and their counters
iptables -L -t nat // display rules for a specific chain
iptables -L -n --line-numbers // listing rules with line number for all chains
iptables -L INPUT -n --line-numbers // listing rules with line number for specific chain
Manage rules:
iptables -A chain <rule> // append rule to bottom of chain
iptables -I chain [rulenum] <rule> // insert rule at specific position
iptables -R chain rulenum <rule> // replace rule at position
iptables -D chain rulenum <rule> // delete rule at position
iptables -D chain <rule> // delete rule by full syntax
Flush (delete all rules):
iptables -F
Recommended to use this only after you ran default accept for all chains (This could kill your SSH connection!).
Protocol:
-p tcp
Usually TCP, UDP or ICMP.
Port filtering:
--destination-port 443
Sometimes also used as --dport (Does not work in all distros as far as I tested). To use this parameter, you have to specify the protocol.
IP Filtering:
-s 131.0.72.0/22
Makes this rule apply only to this SOURCE (incoming/external packet) IP.
-d 192.168.1.1
Makes this rule apply only to destination (usually internal) IP.
Target:
-j ACCEPT
Either ACCEPT, DROP, REJECT or a name of a custom chain to continue processing.