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?
MarkR's right, you're not supposed to do this. The easiest way is to call iptables from the script or to write the iptables config and 'restore' it.
Still, if you want to, read the source of iptables. iptables uses matches and tables as shared objects. You can use the source or them.
The Linux netfilter also has some include files under /usr/include/netfilter*. These are somewhat low-level functions. It is what iptables uses. This is as near an API as one can get without iptables.
But this API is 'messy'. Bear in mind that it was designed to be used only by iptables. It's not very well documented, you can hit very specific problems, the API can change fairly quick without any warning, so an upgrade propably will break your code, etc.
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.
There is deliberately no API to manage these rules. You're not supposed to want to do so. Or something.
If you need rules which are sufficiently dynamic you care about the performance of executing /sbin/iptables, there are other ways to do it: