iptables cheat sheet

What is iptables?

iptables is a powerful firewall utility for Linux that is often included with the operating system. Behind the scenes many firewalls also use iptables, for example, WHM’s cPHulkd uses iptables.

This article has a few select commands to help you out of tight situations.

Quickly Block an IP

Be careful to use “I” for insert to beginning versus “A” for append mode!

iptables -I INPUT -s a.b.c.d -j DROP


iptables -A INPUT -s a.b.c.d -j DROP

The beauty of this rule is it’s immediate. The drawback of this rule is after a reboot, it will be gone.

Persist an block rule after reboot

You can use the command below to save the rule and make them persist after a reboot.

WARNING: We haven’t testing this with WHM.

iptables-save > /etc/iptables/rules.v4

Remove all rules

Only do this if you know that you are doing. Once done, no more firewall rules will exist:

iptables --flush

-F, –flush [chain]
Flush the selected chain (all the chains in the table if none is given). This is equivalent to deleting all the rules one by one.

Show Tables

iptables -S

-S, –list-rules [chain]
Print all rules in the selected chain. If no chain is selected, all chains are printed like iptables-save. Like every other iptables command, it applies to the specified table (filter is the default).

Find a specific rule:

iptables -L -v -n | grep a.b.c.d

-L, –list [chain]

List all rules in the selected chain. If no chain is selected, all chains are listed. Like every other iptables command, it applies to the specified table (filter is the default), so NAT rules get listed by
iptables -t nat -n -L

Please note that it is often used with the -n option, in order to avoid long reverse DNS lookups. It is legal to specify the -Z (zero) option as well, in which case the chain(s) will be atomically listed and zeroed. The exact output is affected by the other arguments given. The exact rules are suppressed until you use
iptables -L -v

-v, –verbose
Verbose output. This option makes the list command show the interface name, the rule options (if any), and the TOS masks. The packet and byte counters are also listed, with the suffix ‘K’, ‘M’ or ‘G’ for 1000, 1,000,000 and 1,000,000,000 multipliers respectively (but see the -x flag to change this). For appending, insertion, deletion and replacement, this causes detailed information on the rule or rules to be printed. -v may be specified multiple times to possibly emit more detailed debug statements.

List all rules with line numbers

iptables -L --line-numbers

Delete a rule (on the INPUT chain)

iptables -D INPUT 3

References

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top