iptables can be used to manage firewalls in Linux.
A chain contains a list of rules.
Creating a new chain
# iptables --new USER-FOO
-N switch can be used instead of
Listing rules in a chain
# iptables --list USER-FOO
-L switch can be used instead of
It will return 1 if the chain does not exist.
iptables: No chain/target/match by that name. # echo $? 1
If it is empty it will be successful.
Chain USER-FOO (0 references) target prot opt source destination # echo $? 0
To display more details, add
-n for numeric IPs, add
-v to show packet and byte counts.
# iptables --list USER-FOO --numeric --verbose
Deleting a chain
# iptables --delete-chain USER-FOO
-X switch can be used instead of
A chain consists of an ordered list of rules. Each rule can be referred by its ordinal or
rulenum within a chain.
Rules are numbered starting from 1.
Each rule has a specification.
For a packet to match a rule and perform an action, the packet is matched against the rule-specification.
Rule-specification can include tests such as
--protocolto match a protocol. Examples include
--sourcefor source address/mask.
--destinationfor destination address/mask.
Rule-specifications can include an action such as
--jumpto jump to a target. Valid targets include
RETURNto exit this chain and continue the previous / calling chain
DROPto silently drop the packet. The caller will not see a response.
REJECTto actively reject the packet.
ACCEPTallow the packet through.
- a chain. Processing will move to the specified chain, and continue in the current chain if a
--gotoa chain. Processing will move to the specified chain, but continue in the previous chain if a
RETURNis matched. This effectively stops any further processing in the current chain.
conntrack: connection tracking module
conntrack module is useful for packets that have already been NATed, such as those seen in
docker is installed.
To enable this module on a rule,
-m conntrack must be added to the rule specification.
Rule-specification now has additional options available when using this module.
--ctstateconnection statuses to match, e.g.
--ctorigdstoriginal destination address/mask
To exit the chain when a packet matches 333.333.333.333:25
iptables -A DOCKER-USER -j RETURN -p tcp -m conntrack --ctstate NEW,RELATED,ESTABLISHED --ctorigdst 333.333.333.333 --dport 25
See the man page
iptables-extensions for more details.
Packets flow in the original or reply direction. Rules usually block packets in the original direction only.
To append a rule allowing reply packets in the
DOCKER-USER chain, run:
iptables -A DOCKER-USER -j RETURN -p tcp -m conntrack --ctdir REPLY
Chain and Rule Ordering - Whitelist
To configure a chain to behave like a whitelist
- Add rules that jump to
RETURNif the packet matches. The previous chain should be configured to
- Add a final rule in the chain that
DROPs the packet