I recently noticed some odd HTTP requests on my web server, which I exclusively use for private purposes like hosting Nextcloud, GOGS, or Wallabag. I did a bit of research where these requests come from – just fire something like for elem in $(awk '{print $1 | "sort | uniq"}' /var/log/nginx/access.log); do curl ipinfo.io/$elem; done
– and found out that they all originate from Russia, China or India. That sounds a bit suspicious to me.
I got the idea to add geofencing to my server’s other hardening measures. Geofencing only allows connections to a server from certain white listed regions of the world. As it turns out this is actually pretty simple to achieve and a nice little after work project.
First, you need to install xtables-addons-common
. On Debian-based systems just fire apt install xtables-addons-common
. This will install some extensions for iptables and various required tools. On my system I also had to install apt install libtext-csv-xs-perl libnet-cidr-lite-perl
as otherwise the build step in the script below fails.
Now you need a database that lists which IP ranges belong to which country. Such a database can be obtained from Maxmind. Furthermore, the database (which comes in csv format) must be converted in a binary format and placed in /usr/share/xt_geoip
. Just put something like the following lines into a bash script, add it to cron and let cron run the script weekly or so. xt_geoip_dl
downloads the databases from Maxmind, xt_geoip_build
takes care for the conversion.
#!/bin/bash
MYPATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DL_DIR=$MYPATH/dl
mkdir -p $DL_DIR
cd $DL_DIR
/usr/lib/xtables-addons/xt_geoip_dl
/usr/lib/xtables-addons/xt_geoip_build *.csv -D /usr/share/xt_geoip
rm -rf $DL_DIR
Finally, add something like $IPTABLES -A INPUT -i eth0 -m conntrack --ctstate NEW -m geoip ! --src-cc DE -j DROP
to your iptables configuration. For additional white listed countries, just append the corresponding country codes, e.g., DE,AT,CH,FR
.
Done.
Of cause, someone who really wants to attack your server can overcome the geofence using a proxy that sits in a region of the world you permitted. Furthermore, a geofence does not protect at all against attackers that happen to live in these regions. However, I think this is a good addition to other hardening measures like Fail2Ban as the geofence will exclude many random attacks.
Edit 02.01.2020: As xt_geoip_dl
doesn’t work with the new Maxmind accounts, read here how to fix this issue.