In this section, we will see how to install and configure the ModSecurity Web Application Firewall (WAF) to block country-specific traffic:
- Once Apache has been installed on Ubuntu, the next step is to install ModSecurity by running the following command:
- After installing ModSecurity, restart Apache:
- To confirm that ModSecurity has been installed successfully, run the following command:
If the installation is successful, we should see something like this: security2_module (shared), as shown in the preceding screenshot.
- After completing the installation, we start configuring ModSecurity. For this, we use the pre-included and recommended configuration file—modsecurity.conf-recommended—which is located in the /etc/modsecurity directory.
- Rename the modsecurity.conf-recommended file, as follows:
- After renaming the file, we edit the modsecurity.conf file and change the value for SecRuleEngine detectiononly to SecRuleEngine on:
- After saving these changes, restart Apache:
- ModSecurity comes with many Core Set Rules (CSR). However, we can download the latest OWASP ModSecurity CRS from GitHub by using the following command:
git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git
- Once downloaded, move into the downloaded directory. Next, move and rename the crs-setup.conf.example file to /etc/modsecurity/, as follows. Move the rules/ directory to /etc/modsecurity/ as well:
- Now, edit the Apache configuration file, /etc/apache2/mods-available/security2.conf, and add the Include directive to point to the rule set, as follows:
- Restart Apache again to reflect the changes:
- ModSecurity supports the use of geolocation data by integrating with the free Maxmind database.
- To block country-specific traffic, we first have to download the geolocation database on the same server where we have configured ModSecurity. To download the database, use the following command:
- After completing the download, extract and move the file to /usr/share/GeoIP/.
- The next step is to edit the /etc/modsecurity/crs-setup.conf file to enable the use of the geolocation database. For this, we enable the SecGeoLookupDb directive and also define the path to the downloaded GeoIP database file:
- Next, we need rule for blocking traffic from any country. The configuration file has an example rule for reference, which can be used by uncommenting the rule:
- After uncommenting the rule and adding the country code of the country we want to block, as shown in the following screenshot, we can save the file:
- If we want our server to be accessible only from a specific country and block the traffic from all other countries, we can create a rule such as the following:
SecRule GEO:COUNTRY_CODE3 "!@streq USA" "phase:1,t:none,log,deny,msg:'Client IP not from USA'"
In this way, we can use ModSecurity to block or allow country-specific traffic.