Blocking Traffic Using GeoIP Data
Without the proper use of GeoIP data, bad actors from a specific country can interfere with your website. We can block traffic with server configurations or a third-party tool (AWS WAF, Cloudfront geo restrictions, etc). The server configuration solution is the cheapest and fastest way to complete this task but it does add to the maintenance of the server since the GeoIP.dat file does not get automatically updated.
Server configuration option
First, we are working with apache 2.4.53 on Amazon Linux 1 and it needs the mod24_security module installed to be able to use the SecRule instruction.
SSH into the web server and type: sudo yum install mod24_security
Now before restarting apache, you will need to get a .dat file with all geo ip info in it. You can purchase them on maxmind with a subscription or find them for free (not as updated) here: https://mailfud.org/geoip-legacy/
Now we can transfer the GeoIP.dat file over to the modules folder under /etc/httpd/modules
Editing the Module
Edit the mod_security.conf file located /etc/httpd/conf.d:
Sudo nano /etc/httpd/conf.d/mod_security.conf
Press Ctrl-W and search for SecRuleEngine ON
Under SecRuleEngine ON add the following lines:
SecRule REMOTE_ADDR "@geoLookup" "chain,id:20,drop,msg:'Block New Zealand IP address'"
SecRule GEO:COUNTRY_CODE "@streq NZ"
Press Ctrl+W, search for SecDebugLog, and comment out or change the line below:
SecDebugLog /var/log/httpd/modsec_debug.log or direct it to a path that it has permission to.
Testing the Configuration
To test the new configuration before restarting apache type: apachectl configtest
If we get a “syntax OK” back then we can restart apache by typing: sudo service httpd restart
After Apache restarts the server will no longer respond to traffic from IP’s that are associated with NZ in the .dat file.
Source for GeoIP.dat: https://mailfud.org/geoip-legacy/
By partnering with GoodJava, you can take your information to the next level. For articles like this, read our other wonderful blogs or visit our Contact Us Page and Get Started.