Two important modules to secure your Apache

View previous topic View next topic Go down

Two important modules to secure your Apache

Post by jamied_uk on 1st December 2013, 21:37

Denial of Service attack (DoS), Distributed Denial of Service attack (DDoS), code injection and SQL injection are common attacks on the Internet. If you are running your web server, you may notice that your server in under these kinds of attacks everyday?? However, there are two Apache's modules (mod_evasive & mod_security) available which can secure your website again those attacks. Here, I am going to introduce these modules and give you the complete steps to install these modules on Ubuntu 10.04.
mod_evasive
The mod_evasive is a great Apache module to provide evasive action in the event of HTTP DoS or DDoS or brute force attack. This module detect such attacks by creating an internal dynamic hash table of IP addresses and URIs, and denying any IP address if match any suitation of the folllowing:

  1. Requesting the same page more than a few times per second;
  2. Making more than 50 concurrent requeset on the same child per second;
  3. Making any requests while temporarily blacklisted;
Instal mod_evasive on Ubuntu 10.04
Install the mod_evasive is simple. Just execute the command on below.

sudo apt-get install libapache2-mod-evasive
 
Once we installed the module. We have to create a directory to hold all of the log files created by mod_evasive. And we need to change the owner of this folder to www-data.

sudo mkdir /var/log/mod_evasive
sudo chown www-data:www-data /var/log/mod_evasive/
 
In order to add custom configuration, we need to create mod-evasive.conf file in /etc/apache2/mods-available folder. 


   DOSHashTableSize 3097
   DOSPageCount  2
   DOSSiteCount  50
   DOSPageInterval 1
   DOSSiteInterval  1
   DOSBlockingPeriod  3600
   DOSLogDir   /var/log/mod_evasive
   DOSEmailNotify  info@yourdomain.com
   DOSWhitelist   127.0.0.1

 
To let you understand the meaning of each parameter, here are description of each parameter:
DOSHashTableSize: Size of the hash table used to store the IPs.
DOSPageCount: Number of pages allowed per DOSPageInterval.
DOSPageInterval: Time in seconds used by DOSPageCount.
DOSSiteCount: Number of objects allowed per DOSSiteInterval.
DOSSiteInterval: Time in seconds used by DOSSiteCount.
DOSBlockingPeriod: Time in seconds that IPs will be banned. If an IP tries to access the server within this period, the count will be restarted.
DOSLogDir: Optional. Directory to store the logs. If not specified, /tmp will be used.
DOSEmailNotify: Optional. Mail where notifications will be sent.
DOSWhitelist: Optional. List of IPs which won't be blocked.
Once you understand it, now you can changes the value to optimize for your server.
In order to activate the module, we have to inform Apache to enable mod_evasive. To activate the changes, we need to restart the Apache as well.

sudo a2enmod mod-evasive
sudo /etc/init.d/apache2 restart
 
Okay, mod_evasive module can guard again DoS or DDoS attack now. How are we going to secure Apache again SQL injection or Code Injection attack??? Other than, providing proper input validation or input filtering. We can install mod_security module to act as the first level web application security.
mod_security

The mod_security is an apache modules that protect your website from various attacks, such as: Code Injection attacks, SQL injection .....etc. And mod_security block commonly exploits by using regular expression and rule sets. In fact, mod_security module is a Web Application Firewall, providing access to every tiny bit of a HTTP Connection. HTTP Headers, Cookie and Post Payloads in their entirety, XML-RPC calls from Ajax, protocol and connection information, etc... its totally stacked.
When coding a dynamic website, developers may forget to write code to help prevent hacks by doing proper input validation and input filtering. However, mod_security can help in most of the cases to prevent such security threat.

http://www.yourdomain.com/user_login.php?username=admin'">DROP%20TABLE%20users--
 
There is the typical SQL injection attack which would cause the database to DROP and delete users table from database. However, if your web server configurated with mod_security, this request would block from running. And your Apache would return 406 error.
Why mod_security is important???
Before, I am going to talk about how to install mod_security module, I would like to show you an example how your server may under potential vulnerability. 
First, let create a php (insecure.php) file with the following conent in your root directory to store website files (i.e.: /var/www ).
   $secret_file = $_GET['secret_file'];
   include ( $secret_file);
?>
Then, open a browser to access the php file (i.e.: http://yourdomain.com/insecure.php?secret_file=/etc/passwd) your just created. Here, I use curl to access the URL.  

bodhi@home# curl -i "http://yourdomain.com/insecure.php?secret_file=/etc/passwd"
HTTP/1.1 200 OK
Date: Tue, 28 Apr 2009 22:24:11 GMT
Server: Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch
X-Powered-By: PHP/5.2.6-3ubuntu4.1
Vary: Accept-Encoding
Content-Length: 860
Content-Type: text/html
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
sshd:x:101:65534::/var/run/sshd:/usr/sbin/nologin
postfix:x:104:107::/var/spool/postfix:/bin/false
 
You can see that if the user access the URL by providing the query value as "/etc/passwd", then all of the system value exploded to hacker immediately. 
Install mod_security on Ubuntu 10.04 server
Now, I am going to introduce you how to install mod_security module in Ubunut 10.04.

apt-get install libapache-mod-security
 
Once you executed the command above, the mod_security module installed. However, we need to add some extra configuration to make it work. First, we need to adopt those default rule sets available from mod_security package.

cp -R /usr/share/doc/mod-security-common/examples/rules /etc/apache2/
 
Okay, the rules are copied to apache2 folder. Now, we need to inform Apache to load those corresponding configurations and rules once the module enabled.

sudo nano /etc/apache2/conf.d/security

   # Append those lines at the end of the file
 
        Include /etc/apache2/rules/*.conf
        Include /etc/apache2/rules/base_rules/*.conf
 

 
Now we need to add some extra configuation on mod_security. Add the following lines in your httpd.conf (/etc/apache2/httpd.conf).


    # Turn the filtering engine On or Off
    SecFilterEngine On
    # Make sure that URL encoding is valid
    SecFilterCheckURLEncoding On
    # Unicode encoding check
    SecFilterCheckUnicodeEncoding Off
    # Only allow bytes from this range
    SecFilterForceByteRange 0 255
    # Only log suspicious requests
    SecAuditEngine RelevantOnly
    # The name of the audit log file
    SecAuditLog /var/log/apache2/audit_log
    # Debug level set to a minimum
    SecFilterDebugLog /var/log/apache2/modsec_debug_log
    SecFilterDebugLevel 0
    # Should mod_security inspect POST payloads
    SecFilterScanPOST On
    # By default log and deny suspicious requests
    # with HTTP status 500
    SecFilterDefaultAction "deny,log,status:500"

 
Great! All of the configuration to enable mod_security is done. Now, we can tell to Apache to load mod_security module. In order, to activate the change, we need to restart Apache.

a2enmod mod-security
/etc/init.d/apache2 restart
 
Verify mod_security is working
To make sure that mod_security is working properly, we can do the testing again. Open a browser to access the php file (i.e.: http://yourdomain.com/insecure.php?secret_file=/etc/passwd).
Here, I use curl to access the URL. You can see that Apache return 403 Forbidden instead of those system information. Hence, we can prove that mod_security module is working.

HTTP/1.1 403 Forbidden
Date: Wed, 12 Sep 2012 09:15:25 GMT
Server:
Last-Modified: Wed, 12 Sep 2012 07:38:34 GMT
ETag: "1207dd-37b-4c97c472b7280"
Accept-Ranges: bytes
Content-Length: 891
Vary: Accept-Encoding
Content-Type: text/html



 
  ERROR | The page you were looking for doesn't exist
 


   

   
   

It looks like that page you were looking has been mislaid, sorry.


 



 
Make mod_security work well with Drupal 6
To make mod_security play nice with Drupal 6, we have to add the following rules in the base_rules/modsecurity_crs_41_phpids_filters.conf :

# Drupal rules
# Drupal 6 ajax admin pages
#
SecRule REQUEST_URI ".*admin/build/views/ajax/.*" phase:1,log,pass,ctl:ruleEngine=Off
SecRule REQUEST_URI ".*admin/settings/gmap_location$" phase:1,log,pass,ctl:ruleEngine=Off
# Drupal System CSS pages
#
SecRule REQUEST_URI "/modules/system/.*" phase:1,log,pass,ctl:ruleEngine=Off
# Drupal node editing (FIXME - too loose. Tighten up)
#
SecRule REQUEST_URI "/node/.*/edit" phase:1,log,pass,ctl:ruleEngine=Off
# Fix some Drupal posting stuff in phpids (remove 'name' from regex)
#
SecRule REQUEST_BODY|REQUEST_URI_RAW|XML:/* "([^*:\s\w,.\/?+-]\s*)?(?\|])(\s*return\s*)?(?:hash|href|navigateandfind|source|pathname|close|constructor|port|protocol|assign
|replace|back|forward|document|ownerdocument|window|self|parent|frames|_?content|date|cookie
|innerhtml|innertext|csstext+?|outerhtml|print|moveby|resizeto|createstylesheet|stylesheets)
(?(1)[^\w%\"]|(?:\s*[^@\/\s\w%,.+\-]))" "phase:2,capture,t:none,t:urlDecodeUni,t:htmlEntityDecode,t:replaceComments,t:compressWhiteSpace,t:lowercase,ctl:auditLogParts=+E,block,nolog,auditlog,msg:'Detects JavaScript object properties and methods',id:'phpids-local_17',tag:'WEB_ATTACK',logdata:'%{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+20,setvar:tx.%{rule.id}-WEB_ATTACK-%{matched_var_name}=%{matched_var}"
SecRuleRemoveById phpids-17
# Remove tight security rule (prohibits http|ftp in comments forms)
SecRuleRemoveById 950117
 
Above rule get from http://drupal.org/node/669972
These rules will let your basic Drupal 6 site working well with mod_security. However, if you have more modules installed then you will have to add more treak a little bit more.
avatar
jamied_uk
Admin

Posts : 2155
Join date : 2010-05-09
Age : 34
Location : UK

http://address-shortner.co.uk

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum