Guide to install mod_security for Apache Server

Thứ Hai, 26 tháng 5, 2014
ModSecurity is a web application firewall is opensource development for Ivan Ristic Apache Web Server. Ivan Ristic ModSecurity is the author of Hand Book. He is someone who has a lot of experience in protecting the Apache Web Server. He had a lot of time researching Web Application Security, Web Intrusion Detection, and Security Patterns. Before moving into the field of security, Ivan has worked for many years as a developer, system architect, technical director of software development. He is the founder of the company ThinkingStone as services related to web application security. Current ModSecurity uses GPL license, completely free of charge. Also if you want to support, then you can buy it in the company of his ThinkingStone http://www.thinkingstone.com/ 

1. The possibility of ModSecurity: 
  • Filter requests: all requests are sent to the web server analysis filter and block (filter) before they are taken to the other modules to handle.
  • Anti-attack techniques: paths and parameters are normalized before analysis to prevent attacks. This technique will be discussed in the next section.
  • Understanding the HTTP protocol: ModSecurity application firewall should be capable of understanding it HTTP protocol.ModSecurity has the ability to filter based on the information in the HTTP Header or may consider each of the requests parameters or cookies ...
  • Analysis of the contents of the POST method: in addition to filtering based on HTTP header block, ModSecurity can be based on the content (payload) of POST requests.
  • Automatic logging: all requests can be recorded (including POST) so that we can review later if needed.
  • Filtering HTTPS protocol: ModSecurity can analyze HTTPS.
  • Analysis of the requirements are compressed: ModSecurity will decompress after analyzing the data request.

The process of handling requests Apache and ModSecurity: 

Click image for larger version. Name: image2012-6-20 15-59-41.jpg Views: 29 Size: 12.8 KB ID: 56
ModSecurity rule allows you to set the time in a year in the cycle of Apache handled as follows 

Request Header Phase (Phase 1): the rule was put in here will be done immediately after reading Apache request headers, request body part at this time has not been read. 
Body Request Phase (Phase 2): this is the time of the general functional information to be included in the analysis and consideration of rule application-oriented nature are usually placed here. At this point you've gotten enough requests argument and the request body has been read. ModSecurity supports three encoding request body 
  • application / x-www-form-urlencoded form used to transmit data
  • multipart / form-data for file transfer
  • text / xml for XML data analysis

Phase Response Header (phase 3): this is the time immediately after the response header part is sent back to the client. You set the rules here if you want to monitor the process after the response is sent section. 

Body Response Phase (Phase: 4): This is the time you want to check the HTML data returned 

Logging: This is the time of the activity log is done, the rules set here specifies the log will look like, it will check the Apache error log message. This is also the last time for you to block unwanted connection, check the response header that you can not check in phase 3 and phase 4. 

2. Installing and configuring mod_security mod_security 
mod_security can be installed on multiple platforms to operate with the Apache as Windows, Linux, ... Here I'll show you how to install and configure mod_security on CentOS (5.6) 
2.1 Install: 
  • Prepare the following libraries (if not already):

PHP source code:
#yum install httpd-devel 
#yum install libxml2 
mod_unique_id.so load: 
access to the httpd.conf file (/ etc / httpd / conf) and remove the '#' in the following line: 
PHP source code:
LoadModule unique_id_module modules / mod_unique_id . so 
  • Download ModSecurity:


PHP source code:
#wget http://www.ModSecurity.org/download/ModSecurity-apache_2.5.13.tar.gz 
  • Unzip both files down:


PHP source code:
#tar xzvf ModSecurity-apache_2.5.13.tar.gz 
  • Compiling mod_security:

PHP source code:
cd modsecurity - apache_2.5.13 ./ configure 
make install 
cp modsecurity
 . conf - recommended / etc / httpd / conf . d / modsecurity . conf 
  • load mod_security

PHP source code:
LoadModule security2_module modules / ModSecurity2 . so 
Restart Apache: 

PHP source code:
#service httpd restart 
2.2 Basic configuration: 
  • ModSecurity application firewall is kind of rules-based, which means we need to set the rules (rules) to ModSecurity activities. The rules are expressed in the form of guidance (directive) and can be placed directly in the Apache configuration file (usually httpd.conf). 

    Also can put this configuration into a separate file, such ModSecurity.conf in conf.d folder and then we need to add to httpd.conf 

    Include conf.d / ModSecurity.conf 

    (Default httpd.conf has lines include conf.d / *. Conf with this line it will execute all the files have the extension. Conf)


  • Turn off or turn on the operation of the Rule 
    By default, the rule engine is disabled. To enable ModSecurity directive we need to add the following to the configuration file 
    SecRuleEngine On 
    This guide is used to control the rule engine, we can use the options are On, Off or DynamicOnly. 
    Off: Disable ModSecurity 
    DetectionOnly: When it matches a certain law, it would not make any public action (it is very useful in case want to test a law that does not want it any request block any problems with the law) 
    On: The ModSecurity's rules are applied to all contents

  • SecDefaultAction 
    Used to create the default action. When you create one rule that does not specify the legal action it will take the default action 

    For example: 

    PHP source code:
    SecDefaultAction "phase:2,deny,log,status:403" 
    Explanation: 

    Phase 2: This action is handled in the 2nd phase (Phase Request Body). 
    Deny: Block the request. 
    Log: Recorded log 
    Status: 403: set notification status is 403.

3.Rules 
  • The basic structure of the rules: 
    PHP source code:
    SecRule VARIABLES OPERATOR [ ACTIONS ] 
    Here is an example of the use of variable ARGS 
    PHP source code:
    SecRule ARGS dirty . 
    (Dirty strings representing the values ​​that can get ARGS) 
    You can use one or more variables 
    PHP source code:
    SecRule ARGS | REQUEST_HEADERS : User - Agent dirty 
    Collections 
    Some variables may include one or more data. When more than one variable value, then we call it a collection 
    For example, the ARGS variable parameters we have 2 p, and q 
    PHP source code:
    SecRule ARGS : p dirty 
    SecRule ARGS
     : q dirty 


Here is an HTTP request: 

PHP source code:
GET / documentation / index . html HTTP / 1.1 

Host
 : www . ModSecurity . org 

User
 - Agent : Mozilla / 5.0 ( X11 ; U ; Linux i686 ; en - US ; rv : 1.8.0.1 ) 
ecko / 20060124 Firefox / 1.5.0.1 

Accept
 : 
text / xml , application / xml , application / xhtml + xml , text / html ; q = 0.9 , text / plain ; q = 0.8 , image / png,* /*;q=0.5 
Accept-Language: en-us,en;q=0.5 

Accept-Encoding: gzip,deflate 

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 

Keep-Alive: 300 

Connection: keep-alive 

Referer: http://www.ModSecurity.org/index.php 

Cookie:__utmz=129890064.1139909500.1.1.utmccn=(direct)| utmcsr=(direct)|utmcmd=(none); __utma=129890064.347942152.1139909500. 1140275483.1140425527.13; 

__utmb=129890064; __utmc=129890064 
Considering the above request we can see the following HTTP header: 

  • GET - This is the request method
  • Host
  • User-Agent
  • Accept
  • Accept-Language
  • Accept-Encoding
  • Accept-Encoding
  • Keep-Alive
  • Connection
  • Referer

ModSecurity will use this information in its rules to filter requests. And not just the headers, ModSecurity can also consider the POST payload as mentioned above, ... 
For example we have the Referer request is banned
PHP source code:
www . abc . com 
we have the following rule: 
PHP source code:
SecRule HTTP_Referer “www \. abc \. com” 
Do not allow the User-Agent from Hotbar: 
PHP source code:
SecRule HTTP_User - Agent hotbar” 
Operator (Operators) 

Identify and compare matching methods to enable data Action. 

PHP source code:
SecRule ARGS "@rx dirty" 
Use! @ To indicate a negation of the operator 

PHP source code:
SecRule & ARGS "!@rx ^0$" 
Here we are referring to a rx operator (regular expression). RX specifies the show 

[Jj] oy represents all strings that contain Joy hoacjoy 
[0-9] every number from 0 to 9 
[A-zA-Z] any letter from a to z both uppercase and lowercase 
^ Start a chain 
$ End of string 
^ Abc $ string consists only from abc 
. all characters 
pt eg pat, pet, PZT ....

  • Actions 
    When a request violates the ModSecurity rule that will execute an action (action). When no action is specified in the rule, the rule will use the default action. There are three types of actions: 

    Primary actions: request would allow the decision to continue or not. Each rule has only one primary action. There are 5 

    deny: Request is canceled, ModSecurity will return HTTP status code 500 status code or set your status within directives: 

    pass: Allows the request to be processed further in the next rules 

    Allow: Allows access immediately and skip the other phases (phases except logging). If you want to pass the current phase, the need to explicitly allow  hase When it will still be checked by the law in the following phases. Only allow access to the request 

    phases: allow: request, it will pass inspection phase 1.2 and still in phase 3 onwards 

    redirect: Redirect a request to a specific url. 


    Secondary Primary actions will complement actions, a rule can have multiple Secondary actions 

    status: n when a violation Request a ModSecurity rule that they can return the HTTP status code n instead of the default status code 500. 

    exec: execute a command that if a request violations 

    logging: logging the request violates rules 

    nolog: no logging 

    pause: n ModSecurity will wait a while n ms and then returns the result. 

    Flow actions affect the rule order is processed 

    chain: connect 2 or more rules together 

    for example: 

    PHP source code:
    SecRule REQUEST_HEADERS : User - agent “Red Bullet”“chain , deny” 

    SecRule REMOTE_ADDR “
     ^ 192 \ .168 \ .1 \. ” Bullet” “chain , deny” SecRule REMOTE_ADDR “ ^ 192 \ .168 \ .1\.  
    skipnext: n skip n ModSecurity will follow its rules 

    for example: 

    PHP source code:
    SecRule REQUEST_HEADERS : User - agent“Red Bullet”“deny” skipnext : 3 
    The implementation of the action does not depend entirely on the order in writing, we consider the following example: 

    Question we need to block a site that URI is Hack, but just blocking SQL injection errors derived from the URI. 

    I built two rules as follows: 

    PHP source code:
    SecRule REQUEST_URI "HackMe" "deny,status:403,phase:2,chain" 
    SecRule REQUEST_URI "SQLinjection" 

    This rule will be processed in phase 2 then it will match with 

    PHP source code:
    SecRule REQUEST_URI "SQLinjection" 
    And deny SQLinjection URL. 
    Click image for larger version. Name: image2012-6-20 16-1-35.jpg Views: 29 Size: 15.7 KB ID: 67

4.Logging 
4.1 Debug Log 
Use the file selection SecDebugLog Navigate to record debug information 

PHP source code:
SecDebugLog logs / modsec - debug . log 
You can change the level of detail of the log information via Navigate: 

PHP source code:
SecDebugLogLevel 4 
Log values ​​can change from 0-9: 

  • 0 - no logging.
  • 1-The list of blocked requests.
  • 2-Warning.
  • 3 - Inform admin
  • 4 - Details of the transaction is processed.
  • 5 - number 4 as well as more detailed information than has been processed
  • 9 - Write down everything, very detailed and full information about the whole.

4.2 Audit logging 
ModSecurity supports a full audit information by logging and then can trace back the attacker's process, as well as edit the rules for rational avoid "false positive": 
PHP source code:
SecAuditEngine On //bật audit log lên SecAuditLog logs / audit . log //chỉ ra file lưu trữ log chính SecAuditLog2 logs / audit2 . log //chỉ ra file lưu trữ log phụ 
This is an example of the audit log: 

PHP source code:
== 378bfd37 ============================== 
Request : conmaz . com 203.160.1.170 - - [ 20 / Feb / 2006 : 02 : 21 : 52 -- 0600 ] 
"GET /favicon.ico HTTP/1.1" 403 285 "-" "-" - "-" 
---------------------------------------- 
GET / favicon . ico HTTP / 1.1 

Cookie
 : rocker = r0xker 

Host
 : conmaz . com 

Connection
 : Keep - Alive 

ModSecurity
 - message : Access denied with code 403. Pattern match 
"^$" at HEADER ( "User-Agent" ) 
ModSecurity - action : 403 

HTTP
 / 1.1 403 Forbidden 

Content
 - Length : 285 

Keep
 - Alive : timeout = 5 , max = 29 

Connection
 : Keep - Alive 

Content
 - Type : text / html ; charset = iso - 8859 - 1 
-- 378bfd37— 
4.3 Customizing the log information: 
3 SecAuditEngine accept the following values: 

  • On - log all requests
  • Off - do not log
  • RelevantOnly - just log what is generated by the filter rules


Also ModSecurity supports log-based status code, for example, you need to log requests to the 5xx error cause: 

PHP source code:
SecAuditLogRelevantStatus ^ 5 
5.Core Rule Set and a way to prevent some common errors on apache: 
5.1 Core Rule Set (CRS): 
CRS is a file system includes built-argument was based on common errors on Web applications such as XSS, SQL injection ... 

The use of core ruset will make administrators more simple in the construction of the rules, because core rule set has been built according to a common standard based on the error usually for Apache server. 

Use the following techniques: 

  • HTTP Protection - identifies the vulnerabilities of HTTP protocol and declaration of policy useful.
  • Real-time Blacklist Lookups - Use 3rd Party IP Reputation.
  • Web-based Malware Detection-identify sites with malicious content by checking the Google Safe Browsing API.
  • HTTP Denial of Service Prevention Protections-switch technology in the HTTP protocol and slow DDOS attack.
  • Common Web Attacks Protection-identify security attacks on web applications in general.
  • Automation Detection-automatically identify the machine, collect information, and the scan appearance malicious activity.
  • Integration with AV Scanning for File Uploads-identify malicious files uploaded via the web application.
  • Sensitive Data Tracking-Track Credit Card and key usefulness of leaked Credit Card.
  • Identify Trojan Protection-access Trojan.
  • Defects Identification of Application-warning-critical applications configuration error
  • Error Detection and Hiding - hiding the error information sent by the server.

How to install: 

I need to dowload Core Rule at the following address: http://sourceforge.net/projects/mod-...crs/0-CURRENT/ 

Unzip the downloaded file is ModSecurity-crs_2.2.4.zip. Inside the ModSecurity-crs_2.2.4 folder not the rule as follows: 

  • activated_rules.
  • base_rules.
  • experimental_rules.
  • experimental_rules.cc
  • slr_rules


Copy all of the preceding paragraph in the apache httpd.conf file and open it and add the following: 

With module base_rule 
PHP source code:
< IfModule security2_module > 
Include
 conf / ModSecurity_crs /*.conf 
Include conf/ModSecurity_crs/base_rules/*.conf 
</IfModule> 
The other module we do the same 

5.2 Set against a number of basic errors: 
  • SQL Injection


The main keywords often used in SQL Injection attacks and the corresponding regular expressions: 

PHP source code:
UNION SELECT union \ s + select 

UNION ALL SELECT union
 \ s + all \ s + select 

INTO OUTFILE into
 \ s + outfile 

DROP TABLE drop
 \ s + table 

ALTER TABLE alter
 \ s + table 

LOAD_FILE load_file 

SELECT
 * select \ s +* 
'\ S' is defined in PCRE is a regular expression that allows to detect all spaces and replace all the code (% 20). In order against SQL Injection attacks, one based on the characteristics which make the following rules: 

PHP source code:
SecRule ARGS "union\s+select" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "union\s+all\s+select" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "into\s+outfile" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "drop\s+table" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "alter\s+table" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "load_file" "t:lowercase,deny,msg:'SQL Injection'" 
SecRule ARGS "select\s+*" "t:lowercase,deny,msg:'SQL " 
  • XSS Attack



PHP source code:
SecRule ARGS "alert\s+*\(" t : lowercase , deny , msg : 'XSS'" 

SecRule ARGS "
 &\{.+\} " " t : lowchimercase , deny , msg : 'XSS'" 

SecRule ARGS "
 <.+> " " t : lowercase , deny , msg : 'XSS'" 

SecRule ARGS "
 javascript : "t:lowercase,deny,msg:'XSS'" 
SecRule ARGS "vbscript :""t:lowercase,deny,msg:'XSS'" 
  • Website defacement 
    This type of attack is based on the change of web content according to the hacker's site for example:


The mechanism for preventing this error we proceed as follows: first we create a token with the md5 hash of the ip who access the web site (illustrated with JSP code) 

PHP source code:
<%@ page import = "java.security.*" %> 

<% 
String tokenPlaintext = request . getRemoteAddr (); 
String tokenHashed = "" ; 
String hexByte = "" ; 
// Hash the IP address 
MessageDigest md5 = MessageDigest . getInstance ( "MD5" ); 
md5 . update ( tokenPlaintext . getBytes ()); 
byte [] digest = md5 . digest (); 

for (
 int i = 0 ; i < digest . length ; i ++) { 
hexByte = Integer . toHexString ( 0xFF & digest [ i ]); 

if (
 hexByte . length () < 2 ) { 
hexByte = "0" + hexByte ; 

} 
tokenHashed += hexByte ; 

} 
// Write MD5 sum token to HTML document 
out . println ( String . format ( "<span style='color: white'>%s</span>" , 
tokenHashed )); 

%> 
At the beginning there is a request to the client's token will be calculated based on MD5 IP users. Token will be placed on the web site to make white people browsing can not see it. 

At the time of the response body we will make comparisons between the client ip token encryption and MD5 was calculated and assigned to the page in response body.Neu not the same, we recognize that ip is defaced, conduct block and report back to the administrator via email 

We use the following rules to avoid: 

PHP source code:
SecRule REMOTE_ADDR ".*" "phase:4,deny,chain,t:md5,t:hexEncode, 

exec:/usr/bin/emailadmin.sh" 
SecRule RESPONSE_BODY "!@contains %{MATCHED_VAR}" 
  • Directory indexing 

    When a web site is no index file lists all the files and folders will be listed when we have not access to the web site address that 

    Based on this hacker can access or download a particular file, which will be analyzed and figured out how to attack websites.
    for example: 
    Click image for larger version. Name: image2012-6-20 16-3-11.jpg Views: 29 Size: 19.9 KB ID: 68

In the figure ctfDB.sql is not a database file of the web site, hackers can dow to know the name of the table, through which schools can conduct SQL injection opening. 
From there a way to prevent the ModSecurity as follows: 
PHP source code:
# Prevent directory listings from accidentally being returned 
SecRule REQUEST_URI "/$" "phase:4,deny,chain,log,msg:'Directory index returned'" 
SecRule RESPONSE_BODY "<h1>Index of /" 
  • Anti-DDos


As you know that DDoS (Short for Distributed Denial of Service) attacks making the computer system or network overload, can not provide services or activities must stop. In DDoS attacks, server services will be "flooded" by a series of commands accessible from the huge number of connections. When trying to access some too large, the server overloaded and unable to handle the request.Consequently, users can not access the services on the website are the DDoS attacks. 
Denial of service can be done in a number of ways. There are five basic types of attacks following: 

  • To consume computing resources such as bandwidth, disk space, or processor time
  • Break the configuration information such as routing information
  • Breaking the status information as the automatic reset TCP sessions.
  • Breaking the physical components of a computer network
  • Blocking communication between the intentional and the victim led users to the contact between the two sides are not smooth.

A denial of service attack could include the malware executable to: 
  • Overload handling capacity, leading to the system can not execute any other work.
  • The errors in the microcode of the call instant computer.
  • Those errors called Instant indicator chain, resulting computer into a state of unstable operation or spillage.
  • These bugs can be exploited in operating systems led to the lack of resources or thrashing. Eg like using all available capacity does not lead to a real job can be completed.
  • Cause the system crash.
  • Denial of service iFrame: in an HTML page can call a certain site with a lot of requests and a lot of times until that site's bandwidth is too limited.

Thus we can see the necessity of reducing to the maximum effect of DDoS attacks. So ModSecurity can do but what? 

As stated above we can see that happening DDoS floor 3 (network layer) and Layer 7 (Application Layer) OSI.Do MosSecurity modeled on the 7th floor activity, it is only capable of blocking DDoS HTTP protocol. 

This prevention is actually very simple we just need to create a rule to identify the number of requests from a certain IP address to the server. If the number of requests is too large for a certain time, then we will take that IP block. 

So we need to make that first step is the maximum number of requests the view of a site is how much can be loaded successfully on all Web sites. We will use Paros to count the maximum number of requests have to load a certain website complete 

Suppose want to load successfully homepage http://www.bkav.com.vn/ about 35 times we need to send a request to the server load time longer depending on network speed, but in the second one IP address can not send the request to the server to load 35http://www.bkav.com.vn/, Because , simply filtered view from a specific IP address if the request for a second that exceeded 35 times, then we proceed Drop all requests coming from this IP 

The following are rules: 

PHP source code:
SecAction initcol : ip =%{ REMOTE_ADDR }, nolog 

SecRule REQUEST_LINE
 "^GET (?:/|.+\.html|.+\.php|.+\.cgi|.+\.pl) HTTP" " nolog,setvar:ip.ddos=+1,deprecatevar:ip.ddos=100/10" 
SecRule IP : DDOS "@gt 35" "phase:1,id:'981052',t:none,log,drop,msg:'Client Connection Dropped due to high # of slow DoS alerts'" 
We can also check to see how many times the return status is 408 Server (HTTP Error 408 Request timeout) if this number exceeds a certain number assumed to be 5 times per second, we also carry the entire line Drop request 

PHP source code:
SecRule RESPONSE_STATUS "@streq 408" "phase:5,id:'981051',t:none,nolog,pass,setvar:ip.slow_dos_counter=+1,expirevar:ip.slow_dos_counter=60" 
SecRule IP : SLOW_DOS_COUNTER "@gt 5" "phase:1,id:'981052',t:none,log,drop,msg:'Client Connection Dropped due to high # of slow DoS alerts'" 
Chia sẻ bài viết ^^
Other post

All comments [ 0 ]


Your comments