Install and Configure Mod_Security on Ubuntu 16.04 Server

Reading Time: 5 minutes

Mod_security, also commonly called Modsec for short, is a powerful WAF (Web Application Firewall) that integrates directly into Apache’s module system. This direct integration allows the security module to intercept traffic at the earliest stages of a request. Early detection is crucial for blocking malicious requests before they are passed along to web applications hosted by Apache web sites. This provides and extra layer of protection against common threats a server faces. This article will explore the installation of mod_security along with the CRS (Core Rule Set) in a Ubuntu 16.04 LTS Server running Apache 2.4.


The target system environment must meet the following requirements:

  • Ubuntu 16.04 LTS Server
  • Baseline Apache 2.4 pre-installed
  • Pre-configured Network & Internet Connection
  • Root user shell access (console or SSH)

Additionally, familiarity with the following system administration concepts are necessary:


Pre-Flight Checks

Mod_security is a standard module in many Apache-based OS images and may already be installed on the target system. Before we continue, lets first make sure we are running Apache 2.4 and mod_security is not already installed. This is done simply with the following two commands.

sudo is a prefix to all commands in this documentation. It allows execution of root-level permissions on a command by command basis. If you are not familiar with sudo, you may be prompted for your password to authorize execution one or more of the commands in this outline.

Check Apache’s Version

sudo apache2ctl -v

Example Output:
Server version: Apache/2.4.18 (Ubuntu)
Server built:   2018-06-07T19:43:03

Check if the Security Module is Active

apache2ctl -M | grep security

– If this command returns nothing, mod_security is not installed so proceed to the Installation Section.

– If the command returns security2_module, mod_security is installed so proceed to the Configuration Section.


Installation Section

The apt package manager in all Debian-based system (like Ubuntu) makes installation quick and painless. Supply the correct package name, libapache-modsecurity in this case, to the apt command and confirm the installation.

Use Apt to Install the libpache2-modseurity Plugin

sudo apt install libapache2-modsecurity -y

Example Output:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libapache2-mod-security2 libyajl2 modsecurity-crs
Suggested packages:
lua geoip-database-contrib ruby
The following NEW packages will be installed:
libapache2-mod-security2 libapache2-modsecurity libyajl2 modsecurity-crs
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 545 kB of archives.
After this operation, 3,960 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 xenial/main amd64 libyajl2 amd64 2.1.0-2 [19.6 kB] Get:2 xenial/universe amd64 libapache2-mod-security2 amd64 2.9.0-1 [314 kB] Get:3 xenial/universe amd64 libapache2-modsecurity all 2.9.0-1 [2,006 B] Get:4 xenial/universe amd64 modsecurity-crs all 2.2.9-1 [210 kB] Fetched 545 kB in 0s (1,659 kB/s)
Selecting previously unselected package libyajl2:amd64.
(Reading database ... 92965 files and directories currently installed.)
Preparing to unpack .../libyajl2_2.1.0-2_amd64.deb ...
Unpacking libyajl2:amd64 (2.1.0-2) ...
Selecting previously unselected package libapache2-mod-security2.
Preparing to unpack .../libapache2-mod-security2_2.9.0-1_amd64.deb ...
Unpacking libapache2-mod-security2 (2.9.0-1) ...
Selecting previously unselected package libapache2-modsecurity.
Preparing to unpack .../libapache2-modsecurity_2.9.0-1_all.deb ...
Unpacking libapache2-modsecurity (2.9.0-1) ...
Selecting previously unselected package modsecurity-crs.
Preparing to unpack .../modsecurity-crs_2.2.9-1_all.deb ...
Unpacking modsecurity-crs (2.2.9-1) ...
Setting up libyajl2:amd64 (2.1.0-2) ...
Setting up libapache2-mod-security2 (2.9.0-1) ...
apache2_invoke: Enable module security2
Setting up libapache2-modsecurity (2.9.0-1) ...
Setting up modsecurity-crs (2.2.9-1) ...
Processing triggers for libc-bin (2.23-0ubuntu11) ...

Once installed, it’s a simple matter to confirm the security module is being loaded by Apache:

Check if the Security Module is Active

apache2ctl -M | grep security

Example Output:

security2_module (shared)


Configuration Section

Now that the base module is installed, we need to configure and enable it. This requires a few steps:

Step 1) Copy the recommended config over as the live config

sudo cp /etc/modsecurity/modsecurity.conf{-recommended,}

Step 2) Modify the live config and change “SecRuleEngine DetectionOnly” to “SecRuleEngine On”

sudo sed -i -e 's/DetectionOnly$/On/i' /etc/modsecurity/modsecurity.conf

Step 3) Check Apache’s config syntax & restart Apache if OK

sudo apache2ctl -t && sudo apache2ctl restart

Example output:

Syntax OK

Apache is now actively running with mod_security in place. However, there are no rules in place for it. The next section goes over configuring these rules.


Enable Core Rule Set & Base Rules

The security module is only as good as the rules governing it. To help get started, the libapache2-modsecurity package comes with a companion package (modsecurity-crs). This package contains the Core Rule Set or CRS, which is a basic set of rules that handle some of the most common malicious activity on the Internet today.  The CRS protects against many dangerous types of traffic include, but not limited to:

  • SQL Injections (SQLi)
  • Remote Code Execution (RCE)
  • Cross Site Scripting (XSS)
  • And many other common malicious behavior


The CRS gets installed along with the security module. Follow these next steps to enable CRS & it’s Base Rules.

Step 1) Add the following lines to modsecurity.conf with your preferred editor

# ModSecurity Core Rule Set (CRS)
IncludeOptional /usr/share/modsecurity-crs/*.conf
IncludeOptional /usr/share/modsecurity-crs/activated_rules/*.conf

Step 2) Create a symlink in the activated_rules directory for all *.conf files in the base_rules directory

CSRD=/usr/share/modsecurity-crs; for e in $CSRD/base_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done

Step 3) [Optional] Confirm symlinks are in the activated_rules directory

sudo ls /usr/share/modsecurity-crs/activated_rules/*.conf


Step 4) Check Apache’s config syntax & restart Apache if OK

sudo apache2ctl -t && sudo apache2ctl restart

Example output:

Syntax OK

The server is now configured and actively using the base_rules from the CRS. There are additional rules provided by the CRS package. These additional rules are discussed in greater detail in the next section.

Rule of Thumb:
It is necessary to verify syntax and restart Apache, anytime changes are made to one or more mod_security rules.


Enable Additional Rules [Optional]

The Core Rule Set includes many additional rules. These rules are separated into three distinct categories: experimental_rules, optional_rules, and slr_rules. Each category’s rules are contained within their own directory of the same name. Activating these rules is the same process as enabling the base_rules. Create a symlink to the desired rule from the activated_rules directory.  The following commands can be used to quickly enable these rules if needed.

Discernment is warranted when enabling additional rules beyond those in the base_rules set. The additional rules, especially experimental_rules, are more likely to encounter false positives, blocking legitimate traffic. The commands below are provided for convenience and is not an endorsement of enabling all rules indiscriminately.


CSRD=/usr/share/modsecurity-crs; for e in $CSRD/experimental_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done


CSRD=/usr/share/modsecurity-crs; for e in $CSRD/optional_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done


CSRD=/usr/share/modsecurity-crs; for e in $CSRD/slr_rules/*.conf; do sudo ln -s $e $CSRD/activated_rules/; done


Disable Rules

To disable rules, delete the symlink within the activated_rules directory that pertains to the rule in question. Once deleted, a quick restart of Apache services is necessary to make the change active.

Example: Delete the application_defects rule then restart Apache.

sudo rm -rf /usr/share/modsecurity-crs/activated_rules/modsecurity_crs_55_application_defects.conf

sudo apache2ctl restart


The Most Helpful Humans In Hosting

There is more than one-way Liquid Web can help. Whether it’s contacting our support or providing you the managed services you need to succeed, you can rely on us to be there with you. If you find yourself having trouble with these instructions our support teams are here to help. We pride ourselves on being  The Most Helpful Humans In Hosting™.  Our support teams work diligently with Apache and Mod_security daily. With availability 24 hours a day, 7 days a week, and 365 days a year, we are always available to assist when your tasks become too arduous to tackle on your own. We encourage you to share the burden with our support teams by phone, chat or email. We can help!


Fully Managed Servers & Applications

All of the Liquid Web Fully Managed Servers & Applications come with mod_security installed, configured, and managed by our support teams. In addition to the Core Rule Set packaged with mod_security, all of our fully managed server kicks include our very own Liquid Web internal rules. These additional rules protect against further threats that our security engineers have identified attacking servers in the wild. These additional rules are a direct countermeasure against known attack vectors and update when new attacks have been identified. We take care of it all, so you don’t have to worry.



Server Protection Packages

When standard security is not enough, you don’t have to wage war alone. The Liquid Web Server Protection Packages provides additional server hardening beyond just mod_security rules. These packages offer hardened configurations to maintain the best level of protection against intrusion and other malicious activity. This is merely one of our many security-related Hosting Add-on Services.

Whitelisting in ModSecurity

Reading Time: 6 minutes

Broken down into two parts our article’s first section hits on “how to whitelist IPs or URIs,” for people who are somewhat familiar with ModSecurity but want to know further about the process. Our second section examines why we configure ModSecurity and how to prevent the security of the server from getting in the way of our work. If you have a Fully Managed Liquid Web server reach out to our Heroic Support team for assistance with whitelisting!

How to Whitelist IPs or URIs

“ModSecurity is a toolkit for real-time web application monitoring, logging, and access control.” (  In simple terms, this means that ModSec, also called mod_security or ModSecurity, is a web application firewall that can actively look for attacks to the system and stop malicious activity. However, sometimes these rules trigger when legitimate work is taking place, blocking your IP and stopping you or your developer’s until you can remove the IP block. The way around for being blocked is known as whitelisting, which essentially allows for a specific IP to access the server.   There are a few ways to whitelist a request in ModSec, either by IP or by URI (URIs are specific pages on the website). 

Getting Started

  1. Find your IP or ask your developer for theirs. (You can find this by going to you or your developer have a static IP (one that will not change), one way you can whitelist the ModSec rules is by IP.
  2. Find the ModSec error in the Apache error logs with the following command (Be sure to modify the command with your IP in place of “IP here.”):
    grep ModSec /usr/local/apache/logs/error_log | grep “IP here”.
  3. The output of this command will give you a list of hits for ModSecurity from you or your developer’s IP, which you can see below. While this looks intimidating, you will only want to pay attention to 3 bits of information highlighted.  Please note, the output will not show these colors when you are viewing the files.
Blue = client, the IP which tripped the rule
= ID number of tripped rule within ModSec
Green = URI, the location where the error started from

[Fri May 25 23:07:04.178701 2018] [:error] [pid 78007:tid 139708457686784] [client] [client] ModSecurity: Access denied with code 406 (phase 2). Pattern match "Mozilla/(4|5)\\\\.0$" at REQUEST_HEADERS:User-Agent. [file "/etc/apache2/conf.d/modsec2.liquidweb.conf"] [line "109"] [id "20000221"] [hostname ""] [uri "/db/index.php"] [unique_id "WwjPWChxvG1CO4kz-D55eQAAACU"]


Whitelist By IP:

1. Once you have the correct ModSec error, you will need to edit the ModSec configuration. If you are using Easy Apache 4 you will find the configuration file with this path:

2. Open the file with your favorite text editor, such as vim, nano, or file manager like so:

vim /etc/apache2/conf.d/whitelist.conf

3.  The blue text above will be the IP address that you are whitelisting from the original error. You must keep the backslashes (\) and up-carrot (^) in order for the IP to be read correctly. Thus it will always look something like:


For for the id, noted in red, you will change the number after the colon, which will be the Apache error log like we saw above. This will look similar to:


Add the following code with the colored sections edited to match your intended IP.SecRule REMOTE_ADDR "^64\.14\.210\.4" "phase:1,nolog,allow,ctl:ruleEngine=off,id:20000221"


Whitelist By URI:

If your IP is dynamic (changing) and you keep getting blocked in the firewall, it is best to whitelist it via URI, the yellow item in the ModSec error.

1. Begin by opening the Easy Apache 4 configuration file:

vim /etc/apache2/conf.d/whitelist.conf

2. Add the following text to the configuration. Remember to pay attention to the highlighted parts.  Change the yellow “/db/index.php” to match your URI and the red id to match the id of your error (Do not use the colon in this one).

<LocationMatch "/db/index.php">
SecRuleRemoveById 20000221

3. The final step for whitelisting, before you finalize the process, is to ensure you have correctly set up the whitelist. For Easy Apache 4 you will run the command:
apachectl -t

As long as the command returns “Syntax Ok” you are safe to make the whitelist active by restarting Apache. Otherwise, review the whitelists to make sure the syntax matches up correctly with the above directions.

4. Lastly, restart Apache with the following command.


You have successfully whitelisted yourself in ModSec!


Using ModSec

Cyber Security is a hydra; once one threat is cut off, two more grow back. While this is not a new analogy, it’s important to understand as we battle threats to our network, computers, and servers. With all the complexities that come with security, I want to talk about adequately configuring ModSec to deter threats while still allowing you to work on your websites. Often, when it comes to server security, too much protection can hinder effectiveness.

For example, say you have the following set up on your server:

  • You do not allow root SSH login to the server
  • utilize dual-factor authentication for any SSH logins
  • use an SSH key for the sudo user and require other security safeguards

While this type of configuration is secure, it takes longer to log into your system to make a quick edit to your settings, a double-edged sword; how can you keep the server safe while not tying your own hands?  A great example of how this plays out is using ModSec.

ModSec can block your IP if it falsely flags your work. While this module improves system security, you’ll need to be aware of properly implementing and “scoping” the technology. Scoping in this sense means to manage risks, the focus of what is important for security while still allowing work on the server with minimal interference. To tune out legitimate requests to your server, such as when you are editing your website’s code via a plugin, ModSec has the options to whitelist rules or IPs and keep your work on track.

Whitelisting an IP from the rules that ModSec follows is a great option so long as the IP never changes (i.e. a static IP, see article here to learn more and is limited to only people you trust. This method prevents ModSec from viewing your requests as malicious and blocking your IP. This practice has the drawback that if someone (say an unhappy employee) has access to your network, they now have a way around ModSec to attack your server.

With non-static (dynamic) IPs the problems of whitelisting an IP are readily apparent. With the continual change of a dynamic IP, it creates the potential of exploiting your server, as someone could use an old IP to access the server. Whitelisting specific rules comes to save the day! When you whitelist by rules, you can edit with granularity and limit the rules to particular domains and URIs, protecting the rest of the server from attacks related to that same rule!

Example of ModSecurity

ModSec reads a series of rules and applies them to incoming requests being made to the web server. An example of what a block looks like is:

[Sat Jun 30 02:21:56.013837 2018] [:error] [pid 79577:tid 139862413879040] [client] [client] ModSecurity: Access denied with code 406 (phase 2). Pattern match "Mozilla/(4|5)\\\\.0$" at REQUEST_HEADERS:User-Agent. [file "/etc/apache2/conf.d/modsec2.liquidweb.conf"] [line "109"] [id "2000064"] [hostname ""] [uri "/mysql/index.php"] [unique_id "WzchhAjuZ6wPAzo9AwW1WwAAAE8"]

This error shows Apache stopped a potential attack on a file at /mysql/index.php. This is an error similar to what appears when the code is being written or edited within programs like Drupal or WordPress.

Evaluating ModSecurity

If you are persistently being blocked in your firewall while working on your code, ModSec is the likely culprit. The ModSec errors can be found in the Apache error log (in cPanel the path is /usr/local/apache/logs/error_log). The phrase “ModSec” can be quickly isolated from the log (via the command ‘grep “ModSec” /usr/local/apache/logs/error_log’). By comparing you or your developer(s) IP to the log, you’ll be able to identify stopped requests that are legitimate. Verify these are valid requests by double-checking that someone in your organization made them. Once you have done so, you can move forward in setting up a whitelist for the error, per the steps above.

Again, we want to scope to allow the least amount of wiggle room for an attack and ensure we can keep working. If you are unable to have a trusted static IP, you’ll need to use the whitelist URI  method, providing the specific page as an exemption. Once completed, remove both whitelisted items from the configuration file, in case of a genuine attack.

On a parting note, I encourage you to explore ModSec and learn more of the ins and outs of the software. Exploring different methods of whitelisting can be a lot of for to learn and most importantly helps to tighten server security. As always, our Fully Supported Customers can contact our Helpful Human Support team for assistance. Check out articles on security in our Knowledge Base, like this one on Maldet! It’s another excellent way to learn about your server and develop an understanding of server security.

When Mod Security Attacks

Reading Time: 2 minutes

One component of Liquid Web’s Server Secure service is an Apache module called Mod Security (often shortened to just “modsec”). Modsec monitors all incoming HTTP requests for malicious behavior and does not complete requests that meet certain criteria. These criteria are spelled out in what are called “rules” or “rulesets”.

In an ideal world, only malicious requests would be caught in modsec’s trap. Unfortunately, there are some instances where legitimate requests are stopped as well. How do we determine that this is what happens, and what can we do about it?
Continue reading “When Mod Security Attacks”