I want to know how can I find out which rule was accessed and how many times, from the access list I have created using iptables.
My firewall has over 1000 input and output rules in iptbales; I want to find how many times each of them were accessed.
For example, suppose I have the following rules:
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT
I want to find out how many times each of the rules 1, 2, 3, 4, 5 and 6 were hit.
-v — Displays verbose output, such as the number of packets and bytes each chain has seen, the number of packets and bytes each rule has matched, and which interfaces apply to a particular rule.
To find the rule that matched, therefore, for each of the filter entries in the dmesg output, you just have to go through the output of iptables -L -n -v --line-numbers , looking for a chain with the name given in the log entry, and then go down to the matching line number.
I would suggest iptables-save|grep $ip instead as it is a more easily parseable format, especially in a script. You can check the exact syntax of the command too if you want. Neither of these actually answers the question, because iptables-save|grep $ip could very well match multiple rules.
iptables rules take effect immediately. Because your script is Appending (-A) to the INPUT and OUTPUT chains, your rules are being added to the end of those chains. If you have other terminating rules that precede these rules, then they will take effect (and later rules will not).
iptables
will list packet and byte counters if you specify option -v
for verbose, e.g. iptables -vL
. Likewise iptables-save
will list all entries including the mentioned counters for each chain, but not for each table entry (on some systems iptables-save
requires option -c
to include counters).
I use the following to check on my iptables rules:
iptables -nvL [INPUT|FORWARD|OUTPUT|myCHAINNAME] --line-numbers | less
The -n speeds up the process by not doing hostname lookups
The line numbers help with deleting rules:
iptables -D [INPUT|FORWARD|OUTPUT|myCHAINNAME] [Rule#]
HTH
You can also use collectds iptables module to aggregate the counters:
https://collectd.org/wiki/index.php/Iptables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With