A friend did ask me, if its possible to block access to his SSH server by blocking via GeoIP which he is already successful using on his webserver to lower the amount of spam he gets (at the cost of potential visitors, but thats his choice after all, right ?). So I dugg a bit in the net, and came across the module pam_geoip.so which allows me based on Maxmind’s GeoIP City Database to block access to services using PAM for authentification. What I show here is a example how to install it and block certain countries using GeoIP City DB lite (aka Maxmind’s free database) from accessing our SSH accounts. This works on a Ubuntu/Debian Linux, for other Distributions/OSes please check if the libary packages named similar. I expect you to have the basic development tools installed already. So let’s start:
sudo apt-get install libgeoip-dev libpam0g-dev wget http://ankh-morp.org/code/pam_geoip/pam_geoip-0.9.tar.gz tar xzvf pam_geoip-0.9.tar.gz cd pam_geoip-0.9 make sudo -i cp pam_geoip.so /lib/security/ chown root:root /lib/security/pam_geoip.so && chmod 644 /lib/security/pam_geoip.so cp geoip.conf /etc/security chown root:root /etc/security/geoip.conf && chmod 644 /etc/security/geoip.conf cd /etc/security wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz gunzip GeoLiteCity.dat.gz chmod 644 /etc/security/GeoLiteCity.dat
When that is done, fire up nano and set the geoip.conf to something similar as this:
# # /etc/security/geoip.conf - config for pam_geoip.so # #<domain> <service> <action> <location> * sshd deny CN * * ignore UNKNOWN
When you’ve done this, fire up nano again to edit this time /etc/pam.d/sshd and add this:
account required pam_geoip.so geoip_db=/etc/security/GeoLiteCity.dat system_file=/etc/security/geoip.conf action=allow
With all this we set the pam_geoip module to default allow, and block all access attempts from Chinese IP’s. Don’t forget to restart the sshd and logout, as we don’t wanna be root longer then needed. You can use way more complex configurations like allowing access to a certain account only in a specific place or within a radius around this place. But for that I would really suggest to buy the premium version of the GeoIP City Database for the higher accuracy. For country-blocking the free should be fine for most of us through. For more complex usage check out the modules website at http://ankh-morp.org/code/pam_geoip/geoip.conf.html. And also checkout the included manpages/config samples. Thanks for help with the installation and the sample to block Chinese IP’s goes to guruway’s blog.
