I need to query existing rules, as well as being able to easily add and delete rules. I haven\'t found any API\'s for doing this. Is there something that I\'m missing?
This is an example of using bash and iptables to dynamically block hackers abusing sshd on CentOS. In this case, I configured sshd to disallow password login (allows keys). I look in /var/log/secure for entries of "Bye Bye", which is sshd's polite way of saying f-off...
IP=$(awk '/Bye Bye/{print $9}' /var/log/secure |
sed 's/://g' |sort -u | head -n 1)
[[ "$IP" < "123" ]] || {
echo "Found $IP - blocking it..." >> /var/log/hacker.log
/sbin/iptables -A INPUT -s $IP -j DROP
service iptables save
sed -i "/$IP/d" /var/log/secure
}
I run this in a loop every second, or minute, or whatever makes me happy. I test the value of $IP to verify it found a useful value, if so I invoke iptables to drop it, and I use sed to purge the log file of $IP so the entry doesn't get added again.
I do a little pre-processing (not shown) to white list some important IPs that are always valid and that might have had trouble connecting (due to user error).
From time-to-time I sort the iptables filter list and create IP ranges from them (using a different script - and when checked, they are usually IP ranges from india, china and russia). Thus, my overall iptables filter rule set stays between 50 and 500 entries; ipset doesn't really improve much on a list that short.