Cyber Security | Prevent SQL injection using ModSecurity.
About ModSecurity
ModSecurity is a free web application firewall (WAF) that works with Apache, Nginx, and IIS. It supports a flexible rule engine to perform simple and complex operations and comes with a Core Rule Set (CRS) which has rules for SQL injection, cross-site scripting, Trojans, bad user agents, session hijacking and a lot of other exploits. For Apache, it is loaded as an additional module which makes it easy to install and configure.
Installation and Configuration
ModSecurity can be installed by firing the following command.
sudo apt-get install libapache2-mod-security2 -y
The installation can be verified by firing the following command. If the output reads security2_module (shared), this indicates that the module was loaded.
sudo apachectl -M | grep — color security2
Reload the Apache server after making changes to the configuration file as follows.
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo service apache2 reload
The default ModSecurity configuration file is set to DetectionOnly, which logs requests according to rule matches and does not block anything. This can be changed by editing the ModSecurity.conf file and modifying the SecRuleEngine directive.
Setting Rules for SQL Injection
l Enabling the CRS
To make things easier, there are a lot of rules which are already installed along with ModSecurity. These are called the CRS (Core Rule Set) and are located in the /usr/share/modsecurity-crs directory. To load these rules, we need to configure Apache to read .conf files in these directories.
2 Activating the SQL Injection Rule
The required rule files should be symlinked to activated_rules directory, which is similar to Apache’s mods-enabled directory. Change to the activated_rules directory.
Create a symbolic link from the modsecurity_crs_41_sql_injection_attacks.conf file and reload the Apache.
sudo ln -s ../base_rules/modsecurity_crs_41_sql_injection_attacks.conf
sudo service apache2 reload
Testing SQL Injection
Here we have changed the SecRuleEngine directive to On, a 403 Forbidden error will be displayed. If SecRuleEngine was left to the DetectionOnly option, the injection will be successful but the attempt would be logged in the modsec_audit.log file.