Block Countries Behind ELB

October 14, 2013

To block countries behind an ELB (Elastic Load Balancer) you should use Maxmind’s GeoIP Country Database.

Problem

You are unable to use iptables or ipset to block countries because of your Amazon Elastic Load Balancer

Solution

Use Maxmind’s GeoIP Country Database in conjunction with Apache or NGINX

Example

This example is for Ubuntu 12.04 (Precise)

apt-get -y update
apt-get install -y libapache2-mod-geoip

pushd /opt/modsecurity/etc
curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gzip -d GeoIP.dat.gz

Replace contents of /etc/apache2/mods-available/geoip.conf

cat <<'EOF' > /etc/apache2/mods-available/geoip.conf
<IfModule mod_geoip.c>
  GeoIPEnable On
  GeoIPScanProxyHeaders On
  GeoIPDBFile /opt/modsecurity/etc/GeoIP.dat MemoryCache
</IfModule>
EOF

# place the following in a virtual host block to only allow USA, France, Spain, Great Britian, Italy
       <Location />
        # Only permit these Countries to access the site
        SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry
        SetEnvIf GEOIP_COUNTRY_CODE FR AllowCountry
        SetEnvIf GEOIP_COUNTRY_CODE ES AllowCountry
        SetEnvIf GEOIP_COUNTRY_CODE GB AllowCountry
        SetEnvIf GEOIP_COUNTRY_CODE IT AllowCountry

        Deny from all
        Allow from env=AllowCountry
        </Location>