Hello everyone! This post will show you how to save your fail2ban iptables records into ipset list.
You might ask? Why would I want to do that? What is the point?
Well, for my case here is that my fail2ban service has been acting up lately. It will fail to reload due to timeout - which I believe is because we have too many IP records to process.
Till I find an absolute solution to this, meantime I will use ipset to help blocking a little bit.
Here's the step:
1. Grep fail2ban iptables records and save to a file
$ iptables -S | grep f2b-abuse-ip > add-abuse-ip-set.sh
2. Modify the script file a little bit.
Edit the file and remove unrelevant rows (if you are using VIM).
$ vim add-abuse-ip-set.sh
In VIM, type this command to strip all the texts and keep the IP address only.
:%s/-A f2b-abuse-ip -s /\=''/g :%s/-j DROP/\=''/g
Exit VIM, run this command:
$ sed -i '/^#/d' add-abuse-ip-set.sh $ sed -i 's/^/ipset add abuse-ip-set /g' add-abuse-ip-set.sh $ sed -i '1i ipset create abuse-ip-set nethash' add-abuse-ip-set.sh
3. Make the script file executable and run it.
$ chmod +x add-abuse-ip-set.sh $ ./add-abuse-ip-set.sh
4. Add ipset to iptables.
This is the most crucial part. Without it, you will not be blocking IPs at all. Make sure you remember to run this command.
$ iptables -A INPUT -m set --match-set abuse-ip-set src -j DROP
5. Save the config for future use.
To save config to a file:
$ ipset save > /etc/abuse-ip-set
To restore config from a file:
$ ipset restore < /etc/abuse-ip-set
Use crontab to restore it on boot.
$ crontab -e
Add this line to the file:
@reboot ipset restore < /etc/abuse-ip/set && sleep 60 && /usr/sbin/iptables -A INPUT -m set --match-set abuse-ip-set src -j DROP
Essentially, it means that once the server is rebooted, restore the ipset, wait for 60 seconds, then add the ipset to iptables.
That's all about it! Hope this post helps!
Post was published on , last updated on .
Like the content? Support the author by paypal.me!