Tuesday, March 18, 2014

Iptables Basics I

This post will go over some of the basic functionality of iptables, the linux firewall.

To reset the rules of the firewall, execute:

iptables -F // delete every rule in the chain for the table
iptables -X // delete every non-builtin chain in the table
iptables -t nat -F // default table is filter, need to specify other tables.
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

To display the rules of the firewall, as well as packet count/byte count, execute:

iptables -t <table> -L -n -v --line-numbers

-t - specify the table to act on, default is filter if nothing is specified.
-L - list the chains in the default table, which is the filter table.  Use -t to switch tables.
-n - list ip addresses and ports as numbers.
-v - verbose output.
--line-numbers - show the line number of the rule in the chain.

To dump the iptables rules to stdout, execute:

iptables-save > rules.txt

Rules that get printed out from the format above can be restored by executing:

iptables-restore < rules.txt

To delete a specific rule, use the output from above to get the line number of the rule, and execute:

iptables -D <chain> <line>
e.g. iptables -D INPUT 1

To insert a rule, execute:

iptables -I <chain> <line-number> <rule>
e.g. iptables -I INPUT 2 -s 1.1.1.1 -j DROP

To set the default policy for a chain, execute:

iptables -P <chain> <policy>
e.g. iptables -P INPUT DROP

To log a rule, execute:

iptables <rule> -j LOG --log-prefix "Log Rule: "
e.g. iptables -s 1.1.1.1 -j LOG --log-prefix "Log Rule: "

Note that --log-prefix can be up to 29 characters long, and is useful for grepping through logs.  You may want to also limit the number of logs generated.  This can be done by adding on:

-m limit --limit <average-limit> --limit-burst <burst-limit>
e.g. iptables -s 1.1.1.1 -m limit --limit 3/m --limit-burst 5 -j LOG \
--log-prefix "Log Rule: "

Note that this rule is non-terminating, meaning after executing, the next rule will be executed.

No comments:

Post a Comment