12
Pricing Features Customers Help & Community Sign Up Login Help & Community Articles & Tutorials Questions Chat Blog Try this tutorial on an SSD cloud server. Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more. Related Articles MySQL How To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04 How To Install and Secure phpMyAdmin on Ubuntu 12.04 How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6 How To Create a New User and Grant Permissions in MySQL How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu Apache How To Install and Secure phpMyAdmin on Ubuntu 12.04 How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6 How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6 How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu PHP How To Launch Your Site on a New Ubuntu 12.04 Server with LAMP, SFTP, and DNS How To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04 How To Install and Secure phpMyAdmin on Ubuntu 12.04 How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6 How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean 1 of 12

How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Embed Size (px)

DESCRIPTION

How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Citation preview

Page 1: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

PricingFeaturesCustomersHelp & Community

Sign Up LoginHelp & Community

Articles & Tutorials

Questions

Chat

Blog

Try this tutorialon an SSD cloud server.

Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more.Related Articles

MySQL

How To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04How To Install and Secure phpMyAdmin on Ubuntu 12.04How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6How To Create a New User and Grant Permissions in MySQLHow To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu

Apache

How To Install and Secure phpMyAdmin on Ubuntu 12.04How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTSHow To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu

PHP

How To Launch Your Site on a New Ubuntu 12.04 Server with LAMP, SFTP, and DNSHow To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04How To Install and Secure phpMyAdmin on Ubuntu 12.04How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 6How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

1 of 12

Page 2: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Security

How To Protect SSH with fail2ban on Ubuntu 12.04How To Setup a Basic IP Tables Configuration on Centos 6How To Setup Your Own VPN With PPTPHow To Set Up a Firewall Using IP Tables on Ubuntu 12.04How To Set Up SSH Keys

MariaDB

How To Install Moodle On A VPS Running Ubuntu 12.04 And LAMPHow To Use CakePHP to Create a Small Web Application (Part 2)How To Set Up mod_security with Apache on Debian/UbuntuHow To Install CakePHP On An Ubuntu 12.04 VPSHow To Set Up GitLab As Your Very Own Private GitHub Clone

How To Set Up mod_security with Apache onDebian/UbuntuPublished On: 21 Oct 16:16

6 5

submit

Write an Article

Prelude

Mod security is a free Web Application Firewall (WAF) that works with Apache, Nginx and IIS. Itsupports 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 hijackingand a lot of other exploits. For Apache, it is an additional module which makes it easy to install andconfigure.

In order to complete this tutorial, you will need LAMP installed on your server.

Installing mod_security

Modsecurity is available in the Debian/Ubuntu repository:

apt-get install libapache2-modsecurity

Verify if the mod_security module was loaded.

apachectl -M | grep --color security

You should see a module named security2_module (shared) which indicates that the module wasloaded.

4

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

2 of 12

Page 3: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Modsecurity's installation includes a recommended configuration file which has to be renamed:

mv /etc/modsecurity/modsecurity.conf{-recommended,}

Reload Apache

service apache2 reload

You'll find a new log file for mod_security in the Apache log directory:

root@droplet:~# ls -l /var/log/apache2/modsec_audit.log-rw-r----- 1 root root 0 Oct 19 08:08 /var/log/apache2/modsec_audit.log

Configuring mod_security

Out of the box, modsecurity doesn't do anything as it needs rules to work. The default configuration file isset to DetectionOnly which logs requests according to rule matches and doesn't block anything. This canbe changed by editing the modsecurity.conf file:

nano /etc/modsecurity/modsecurity.conf

Find this line

SecRuleEngine DetectionOnly

and change it to:

SecRuleEngine On

If you're trying this out on a production server, change this directive only after testing all your rules.

Another directive to modify is SecResponseBodyAccess. This configures whether response bodies arebuffered (i.e. read by modsecurity). This is only neccessary if data leakage detection and protection isrequired. Therefore, leaving it On will use up droplet resources and also increase the logfile size.

Find this

SecResponseBodyAccess On

and change it to:

SecResponseBodyAccess Off

Now we'll limit the maximum data that can be posted to your web application. Two directives configurethese:

SecRequestBodyLimitSecRequestBodyNoFilesLimit

The SecRequestBodyLimit directive specifies the maximum POST data size. If anything larger is sent bya client the server will respond with a 413 Request Entity Too Large error. If your web applicationdoesn't have any file uploads this value can be greatly reduced.

The value mentioned in the configuration file is

SecRequestBodyLimit 13107200

which is 12.5MB.

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

3 of 12

Page 4: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Similar to this is the SecRequestBodyNoFilesLimit directive. The only difference is that this directivelimits the size of POST data minus file uploads-- this value should be "as low as practical."

The value in the configuration file is

SecRequestBodyNoFilesLimit 131072

which is 128KB.

Along the lines of these directives is another one which affects server performance:SecRequestBodyInMemoryLimit. This directive is pretty much self-explanatory; it specifies how much of"request body" data (POSTed data) should be kept in the memory (RAM), anything more will be placed inthe hard disk (just like swapping). Since droplets use SSDs, this is not much of an issue; however, this canbe set a decent value if you have RAM to spare.

SecRequestBodyInMemoryLimit 131072

This is the value (128KB) specified in the configuration file.

Testing SQL Injection

Before going ahead with configuring rules, we will create a PHP script which is vulnerable to SQLinjection and try it out. Please note that this is just a basic PHP login script with no session handling. Besure to change the MySQL password in the script below so that it will connect to the database:

/var/www/login.php

<html><body><?php if(isset($_POST['login'])) { $username = $_POST['username']; $password = $_POST['password']; $con = mysqli_connect('localhost','root','password','sample'); $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$p if(mysqli_num_rows($result) == 0) echo 'Invalid username or password'; else echo '<h1>Logged in</h1><p>A Secret for you....</p>'; } else {?> <form action="" method="post"> Username: <input type="text" name="username"/><br /> Password: <input type="password" name="password"/><br /> <input type="submit" name="login" value="Login"/> </form><?php }?></body></html>

This script will display a login form. Entering the right credentials will display a message "A Secret foryou."

We need credentials in the database. Create a MySQL database and a table, then insert usernames andpasswords.

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

4 of 12

Page 5: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

mysql -u root -p

This will take you to the mysql> prompt

create database sample;connect sample;create table users(username VARCHAR(100),password VARCHAR(100));insert into users values('jesin','pwd');insert into users values('alice','secret');quit;

Open your browser, navigate to http://yourwebsite.com/login.php and enter the right pair ofcredentials.

Username: jesinPassword: pwd

You'll see a message that indicates successful login. Now come back and enter a wrong pair ofcredentials-- you'll see the message Invalid username or password.

We can confirm that the script works right. The next job is to try our hand with SQL injection to bypassthe login page. Enter the following for the username field:

' or true --

Note that there should be a space after -- this injection won't work without that space. Leave thepassword field empty and hit the login button.

Voila! The script shows the message meant for authenticated users.

Setting Up Rules

To make your life easier, there are a lot of rules which are already installed along with mod_security.These are called CRS (Core Rule Set) and are located in

root@droplet:~# ls -l /usr/share/modsecurity-crs/total 40drwxr-xr-x 2 root root 4096 Oct 20 09:45 activated_rulesdrwxr-xr-x 2 root root 4096 Oct 20 09:45 base_rulesdrwxr-xr-x 2 root root 4096 Oct 20 09:45 experimental_rulesdrwxr-xr-x 2 root root 4096 Oct 20 09:45 lua-rw-r--r-- 1 root root 13544 Jul 2 2012 modsecurity_crs_10_setup.confdrwxr-xr-x 2 root root 4096 Oct 20 09:45 optional_rulesdrwxr-xr-x 3 root root 4096 Oct 20 09:45 util

The documentation is available at

root@droplet1:~# ls -l /usr/share/doc/modsecurity-crs/total 40-rw-r--r-- 1 root root 469 Jul 2 2012 changelog.Debian.gz-rw-r--r-- 1 root root 12387 Jun 18 2012 changelog.gz-rw-r--r-- 1 root root 1297 Jul 2 2012 copyrightdrwxr-xr-x 3 root root 4096 Oct 20 09:45 examples-rw-r--r-- 1 root root 1138 Mar 16 2012 README.Debian-rw-r--r-- 1 root root 6495 Mar 16 2012 README.gz

To load these rules, we need to tell Apache to look into these directories. Edit the mod-security.conffile.

nano /etc/apache2/mods-enabled/mod-security.conf

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

5 of 12

Page 6: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Add the following directives inside <IfModule security2_module> </IfModule>:

Include "/usr/share/modsecurity-crs/*.conf"Include "/usr/share/modsecurity-crs/activated_rules/*.conf"

The activated_rules directory is similar to Apache's mods-enabled directory. The rules are available indirectories:

/usr/share/modsecurity-crs/base_rules/usr/share/modsecurity-crs/optional_rules/usr/share/modsecurity-crs/experimental_rules

Symlinks must be created inside the activated_rules directory to activate these. Let us activate theSQL injection rules.

cd /usr/share/modsecurity-crs/activated_rules/ln -s /usr/share/modsecurity-crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf .

Apache has to be reloaded for the rules to take effect.

service apache2 reload

Now open the login page we created earlier and try using the SQL injection query on the username field.If you had changed the SecRuleEngine directive to On, you'll see a 403 Forbidden error. If it was left tothe DetectionOnly option, the injection will be successful but the attempt would be logged in themodsec_audit.log file.

Writing Your Own mod_security Rules

In this section, we'll create a rule chain which blocks the request if certain "spammy" words are entered ina HTML form. First, we'll create a PHP script which gets the input from a textbox and displays it back tothe user.

/var/www/form.php

<html> <body> <?php if(isset($_POST['data'])) echo $_POST['data']; else { ?> <form method="post" action=""> Enter something here:<textarea name="data"></textarea> <input type="submit"/> </form> <?php } ?> </body></html>

Custom rules can be added to any of the configuration files or placed in modsecurity directories. We'llplace our rules in a separate new file.

nano /etc/modsecurity/modsecurity_custom_rules.conf

Add the following to this file:

SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

6 of 12

Page 7: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

SecRule REQUEST_METHOD "POST" chainSecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"

Save the file and reload Apache. Open http://yourwebsite.com/form.php in the browser and entertext containing any of these words: pills, insurance, rolex.

You'll either see a 403 page and a log entry or only a log entry based on SecRuleEngine setting. Thesyntax for SecRule is

SecRule VARIABLES OPERATOR [ACTIONS]

Here we used the chain action to match variables REQUEST_FILENAME with form.php,REQUEST_METHOD with POST and REQUEST_BODY with the regular expression (@rx) string(pills|insurance|rolex). The ?i: does a case insensitive match. On a successful match of all these threerules, the ACTION is to deny and log with the msg "Spam detected." The chain action simulates thelogical AND to match all the three rules.

Excluding Hosts and Directories

Sometimes it makes sense to exclude a particular directory or a domain name if it is running an applicationlike phpMyAdmin as modsecurity and will block SQL queries. It is also better to exclude admin backendsof CMS applications like WordPress.

To disable modsecurity for a complete VirtualHost place the following

<IfModule security2_module> SecRuleEngine Off</IfModule>

inside the <VirtualHost> section.

For a particular directory:

<Directory "/var/www/wp-admin"> <IfModule security2_module> SecRuleEngine Off </IfModule></Directory>

If you don't want to completely disable modsecurity, use the SecRuleRemoveById directive to remove aparticular rule or rule chain by specifying its ID.

<LocationMatch "/wp-admin/update.php"> <IfModule security2_module> SecRuleRemoveById 981173 </IfModule></LocationMatch>

Further Reading

Official modsecurity documentation https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual

Submitted By: Jesin A

Try this tutorial on an SSD cloud server.

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

7 of 12

Page 8: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more.

Comments

KiwoT

Thanks for the tutorial.But should I exclude all pages that runs queries?Eg: Users can search for old posts and delete their own posts on my website, would modsecurity blockthose queries?

Off topic, I am running my application together with cloudflare (pro plan), their support told me that Idont have to install and setup modsecurity myself since its included in their plan, is that something youcan confirm?I just feels safer to have it installed my self aswell.

Posted October 25th, 2013 14:19

Kamal Nasser

@KiwoT: I believe Cloudflare does indeed have mod_security-like functionality included out of the boxso you do not have to install it on your droplet.

But should I exclude all pages that runs queries?Eg: Users can search for old posts and delete their own posts on my website, wouldmodsecurity block those queries?

No. You should exclude phpmyadmin since the SQL queries are passed in request itself. If you pageaccepts input and writes the SQL query itself (i.e. most apps, such as a forum, blog, etc.) you do not needto exclude this page. It is even recommended to have mod_security enabled on those pages.

Posted October 25th, 2013 15:22

KiwoT

Thanks alot Kamal!

Posted October 25th, 2013 23:06

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

8 of 12

Page 9: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

jesin.a

@KiwoT Even though Cloudflare claims to have something similar to mod_security it doesn't offer thatmuch protection.

Have a look at this report on Cloudflare vs mod_security vs Incapsula http://zeroscience.mk/files/wafreport2013.pdf

Posted October 31st, 2013 11:13

Kaurer

Hello.

I have a problem with symbolic links to the rules. If I create these symlinks into /usr/share/modsecurity-crs/activated_rules/ and then try reload Apache with sudo service apache2 reload, I got the followingerror:

Syntax error on line 25 of /usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.confError creating rule: Could not open phrase file "/usr/share/modsecurity-crs/activated_rules/modsecurity_41_sql_injection_attacks.data": No such file or directory...fail!

Then Apache does not start.

Thanks for the tutorial. Greetings.

Posted December 29th, 2013 17:14

Kamal Nasser

@Kaurer: What OS are you using? What's the output of

ls -lah /usr/share/modsecurity-crs/activated_rules/modsecurity_41_sql_injection_attacks.data

?

Posted December 30th, 2013 11:45

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

9 of 12

Page 10: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Kaurer

Hi @Kamal.

The OS is Ubuntu 12.04 32bit.

Output of ls:ls: can not access /usr/share/modsecurity-crs/activated_rules/modsecurity_41_sql_injection_attacks.data:No such file or directory

Thank you.

Posted December 30th, 2013 17:25

Kamal Nasser

@Kaurer: The file seems to be missing, try disabling it:

mv /usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf /usr/share/

Posted December 30th, 2013 19:26

Kaurer

@Kamal, it worked. But what if I do not include anything in the directory "activated_rules"?

Thank you!

Posted January 1st, 2014 21:49

Kamal Nasser

@Kaurer: No rules will be loaded, which means that it would have the same effect as disablingmod_security completely.

Posted January 2nd, 2014 13:14

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

10 of 12

Page 11: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

Kaurer

Ok, I understand.

Thank you @Kamal.

Posted January 3rd, 2014 12:36

jcarppe

The issue @Kaurer is having here is because the sql_injection_attacks.conf references the .data file aswell, and the reference is looking for the data file in the same directory. The symlinking is breaking this,but the easy way around this is to link the .data file as well. From within the activated_rules directory:

ln -s /usr/share/modsecurity-crs/base_rules/modsecurity_41_sql_injection_attacks.data .

Reload apache2 and you should be golden.

Posted January 7th, 2014 22:31

Create your account or sign-in

Company

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

11 of 12

Page 12: How to Set Up Mod_security With Apache on Debian_Ubuntu _ DigitalOcean

PricingComparison ChartFeaturesCustomersAboutFAQPressCareersAPIIntegrationsNetwork StatusContact

Community

Articles & TutorialsGet Paid to WriteSuggest an ArticleChatQ&ABlogReferral ProgramEvents CalendarFeedbackBadges & LogosThe Shop

Getting Started

One-Click Install ApplicationsWhat is Cloud Hosting?Control Panel OverviewDeploy a Virtual ServerSet-Up SSH KeysInstall Git on UbuntuHow to Install Ruby on RailsHow to Install LAMP StackSet-Up a Host Name

©2011-2014 DigitalOcean™, Inc. All Rights Reserved. Terms & Privacy. Security.

How To Set Up mod_security with Apache on Debian/Ubuntu | DigitalOcean

12 of 12