Caution
Use at your own risk, make sure you have alternative ways to access your server before making changes to firewall (like KVM etc.).
It is basically a convenient way to block countries by IP with iptables. Step-by-step instructions are combined into one Makefile to compile and optimize multiple ip blocks. Only three iptables rule added as a result, which is easily revertable. Two systemd services run at system startup and load ip lists to keep geoblock persistent.
Load countries IP ranges in CIDR format to the lists/
folder (see make load <country code>
instructions). Multiple lists will be automatically combined and optimized. Remember to update lists from time to time.
Install iprange
and ipset
with:
sudo apt install -y iprange ipset
make load <country code> [<country code> <country code> ...]
will load lists of IP ranges for specific countries from the herrbischoff/country-ip-blocks repository and save into lists
directory. For example, to load usual suspects:
make load ru cn by
make add
will copy everything where it supposed to be and start services:
sudo make add
To check services status:
sudo make status
Only one iptables rule is added as a result. To delete geoblock rule from iptables:
sudo make cleanup
To update lists:
make load <country code> [<country code> <country code> ...]
sudo make update
To uninstall - stop and remove services, iptables rule and ipset list:
sudo make uninstall
After combining and optimizing every list from lists
folder into one geoblock.txt
file, new geoblock
list is created with ipset
, then every line from geoblock.txt
is put into that list, finally the list is saved to /etc/ipset.conf
file.
Then there are two systemd services:
ipset-persistent.service
is configured so it starts at the right time in server startup sequence and loads/etc/ipset.conf
, sogeoblock
set is loaded and ready to be used by iptables.geoblock-persistent.service
starts next and runs a script that sets up a firewall rule to block incoming traffic from IP addresses listed in thegeoblock
set, log the blocked attempts up to a limit, and then drop the packets.
Blocket packets are logged to syslog by default.
To log blocked packets to the separate log file, use the following rsyslog configuration file /etc/rsyslog.d/20-geoblock.conf
:
# Geoblock generated log messages to file
:msg,contains,"geoblock: " /var/log/geoblock.log
& stop
Logrotate configuration could be useful as well
/etc/logrotate.d/geoblock
:
/var/log/geoblock.log
{
rotate 5
weekly
missingok
notifempty
compress
delaycompress
sharedscripts
}
https://github.com/herrbischoff/country-ip-blocks
https://www.digitalocean.com/community/tutorials/how-to-list-and-delete-iptables-firewall-rules
https://gist.github.com/jasonruyle/8870296
https://selivan.github.io/2018/07/27/ipset-save-with-ufw-and-iptables-persistent-and.html
- nisenbeck - added rate limited logging of blocked packets