You are on page 1of 61

Advanced Web Application Defense with ModSecurity

Daniel Fernndez Bleda & Christian Martorella

Who we are? (I)

Christian Martorella:

+6 years experience on the security field, mostly doing audits and Pen-testing. Open Information System Security Group, Barcelona chapter President. First Improvised Security Testing Conference Organizer Security Forest, ExploitTree maintainer. CISSP, OPST

Who we are? (II)

Daniel Fernndez Bleda:


Security Engineer +5 years experience on the field. Institute for Security and Open Methodologies (ISECOM), Member, and OSSTMM promoter. Open Information System Security Group, Barcelona chapter Member. CISSP, CISA, OPST/OPSA Trainer

Aim of the Presentation

Security of web applications Introduce Modsecurity Show how can you protect your web applications Show our work in extending the features of this module.

Actual Scenario (I)


Web Applications are insecure Today are the most vulnerable part of company Everyday the attacks at the application layer are growing:

infrastructure.

SQL Injection XSS Command Injection Buffer Overflows Session manipulation Etc..

Actual Scenario (II)


The quantity of vulnerabilities is growing 80% of the last 30 exploits posted to Milw0rm target Web Applications: Wordpress, Phpbb, Xml-rpc, etc. We can find a lot of Firewalls to analyse and filter traffic at the network level, but at the Application level, what are our options? Open and Free, very little.. There are secure networks with insecure applications that jeopardize all security of the company.

What are the Problems? (I)


The web development is chaotic Lack of web security awareness. First users requirement, last security (if time allow) If it works don't touch it (sad but true) False sense of security: We have a firewall, we are safe We use SSL, we are safe

What are the Problems? (II)


Network firewalls doesn't do anything at this level:

Webserver
Webapps WebClient

Database

443 80

Firewall

What is ModSecurity?

Intrusion Detection / Prevention for Web Applications Operate as an Apache Module. Open Source and GPL Development by Ivan Ristic

The purpose of ModSecurity is to increase web application security by protecting them from known and unknown attacks

When can we use it?

Applications you can't modify: legacy applications, protected code like Zend encoder, Phpshield, etc. New vulnerability discovered, temporal protection until patch is released. Intrusion Detection . Extra layer of security. To protect Web services. Web applications operated by people other than original software developers.

Features (I)

Request filtering: incoming requests are analysed as they come in, and before they get handled by the web server or other modules. Output Filtering: It could analyse the server response. (Error, Critical data, Ex. PHP Errors) Understanding of the HTTP protocol: since the engine understands HTTP, it performs very specific and fine granulated filtering.

Features (II)

Anti-evasion techniques: paths and parameters are normalized before analysis takes place in order to fight evasion techniques.

Remove multiple forward slash characters Treat backslash and forward slash characters equally Remove directory self-references Detect and remove null-bytes (%00) Decode URL encoded characters

Features (III)

POST payload analysis: the engine will intercept the contents transmitted using the POST method. HTTPS and Compression: since the engine is embedded in the web server, it gets access to request data after decryption and decompression takes place.

Features (IV)

Audit logging: full details of every request (including POST) can be logged for later analysis.

For doing an effective forensic investigation in a web attack, we need at least:

Source IP Time stamp HTTP method URI requested Full Http Data

Special built-in checks


URL encoding validation Unicode encoding validation Byte range verification [0-255] detect and reject :

- Shellcode - Cross Request Form Forgerie (CR,LF)

If the language used in our application is English we can limit the byte range to [32-126].

Rules

What is a rule? Rules are formed using regular expressions Any number of custom rules supported Also negated rules supported Analyses:

Headers Environment variables Server variables Individual cookies

Individual page variables POST payload Script output

Actions (I)

What are the actions? Reject request with status code [403,500, ..] Reject request with redirection Execute external binary on rule match Log request

Actions (II)

Stop rule processing and let the request through Rule chaining Skip next n rules on match Pauses for a number of milliseconds

File Upload

Intercept files being uploaded through the web server Store uploaded files on disk Execute an external script to approve or reject files (ClamAV anti-virus)

Other

Change the identity of the web server: We can change the Server header to whatever we want, also will change the version in all server messages, like error, forbidden, etc. Easy to use internal chroot functionality.

How does it works


1. Parse the request. 2. Perform canonicalization and anti-evasion actions. 3. Perform special built-in checks. 4. Execute input rules:

If the request is allowed, then it will reach the handler where it executes. After the request:
1. Execute output rules. 2. Log the request.

Security models

A security is the posture we take at the time of setting rules for our protection systems.

There are two security models:


Positive Model Negative Model

Security models: Positive Model



We allow what we know is right (safe). Like network firewall model Deny All - Allow what we need. Pros:
Better performance Less false positives

Cons:
More time to implement, we need to identify all the scripts in the application, and create rules for them.

Example:
Page log.asp, the field Login could only accept characters [a-zA-Z0-9] and could be 12 char long.

Security Models: Negative Model (I)


Deny what is dangerous Do we know everything that is bad for our applications? Pros:
Less time to implement, we create a general that affect the whole application.

Cons:
More false positives More processing time

Example XSS:
There are a lot of tags and places to look for XSS, we can miss some of them leaving a hole in our application.

Security Models: Negative Model (II)

<object>...</object> <embed>...</embed> <applet>...</applet> <script>...</script> <script src="..."></script> <iframe src="..."> <img src="javascript:..."> <b onMouseOver="..."> &{...};

Configuration

Per Context configuration:


Main Server Virtual Host Directory

Inheritance: Virtual Host and Directory could Inherit the configuration of the Main Server. Same for Directory with Virtual Host.

Thoughts...

What about my web server, i don't use Apache...

Reverse Proxy Model (I)


Firewall
www.myiplanet.com www.myapache.com www.myiis.com

IIS

WebClient

Apache

Mod_security + Mod_Proxy

Iplanet

mod_security + mod_proxy = our own application firewall appliance

Reverse Proxy Model (II)

Advantages:

Single point of access Increased Performance Network Isolation Network Topology Hidden from outside Protect any Web server, IIS, Iplanet, etc.

Disadvantages:

Single point of Failure Increased Complexity

Extending Features

Strip Comments Cookie cripto-signing Link cripto-signing Hidden field signing Web based logs console Some of these features are present in commercial firewalls, so we thought it will be great if an Open Source project like Modsecurity could do the same.

Strip Comments (I)

Using the Libxml2 it allow us to build an HTML tree of the parsed code sended to the user. Having that, we could walk the tree looking for comments

<!-- xxxxxx -> and cut them off.

So just adding the directive:


SecStripCommentCode On/Off

Strip Comments (II)

Modsecurity will clean all commented code before sending the requested page to the user.

We considered the common situation of commented script code to allow backward compatibility with old browsers. This comments are not stripped.

We are working in the deletion of comments inside the code of different script languages (javascript, tcl, etc).

Cookie Signing

Another feature is the cripto-signing of cookies, to prevent tampering (cookie poisoning, session fixation) With directives:
SecSignCookies On/Off SecEncriptionPassword password

We are using Cryptlib and do the cripto-sign with the Advanced Encryption Standard (AES) algorithm. Still working on it

Link Signing (I)

As an extra layer of security we have added the option to sign all links browsables from Entry points, so users are able only to follow the intended flow of the application.

Again we use Cryptlib, to sign the links with the AES algorithm.

The directives to control this:


SecSignLinks On/Off SecEntryPoint /index.asp /images ... entry page n SecEncriptionPassword password

Link Signing (II)

Signing the links we can tackle this threats: Predictable Resource Location Forceful Browsing: the attacker "forces" a URL by accessesing it directly instead of following links. Automated scanners like Nikto, dirb, and others, will be foiled. Example of a link cripto-signed: http://www.securesign.com/help.asp?pagina=ayudalogin.asp&Secsign=MIHVBgkqhkiG9w0BBwOggccwgc QCAQAxcaNvAgEAoBsGCSqGSIb3DQEFDDAOBAhyxt 2Mf3s4KQICAfQwIwYLKoZ...6DQDpC

Form and Hidden Fields cripto-signing


Another security measure is the cripto-signing of form hidden fields and signing the forms itself, to prevent the values from being modified in the quantity, names, etc. of the inputs of the form.

Log Console (I)



Web based Log Console Facilitate the log analysis task Snort Acid Style Some of the listing that it provides:
Top 10 attacks or attackers Today attacks Last 15 Attacks

Other characteristics:
Attack details Search Delete records

Log Console (II)

Log Console (III)

Open Proxy Honeypots (I)

Web App Security Consortium (WASC) This project will use one of the web attacker's most trusted tools against him - the Open Proxy server. Instead of being the target of the attacks, we opt to be used as a conduit of the attack data in order to gather our intelligence. By deploying multiple, specially configured open proxy server (or proxypot), we aim to take a birds-eye look at the types of malicious traffic that traverse these systems.

Open Proxy Honeypots (II)

The honeypot systems will conduct real-time analysis on the HTTP traffic to categorize the requests into threat classifications outlined by the Web Security Threat Classification and report all logging data to a centralized location.

Examples

SQL Injection XSS Scripting Fine grained checks Buffer Overflows Positive Model File extensions

Output filtering, errors. Resource location prediction Strip comment code Blog/Forums spam protection

Example Scenario
www.secure.com

IIS
mod_security + mod_proxy

client

www.vulnerable.com

SQL Injection

Vulnerable parameter: Login Test String:


' or 1=1;--

Modsecurity rule:
Secfilter '.+-- redirect:http://www.secure.com/error123.html

Positive way:
SecfilterSelective ARG_login !^[a-zA-Z]+$

XSS Prevention

Vulnerable parameter: pagina Test String:


<script>alert('Next time I will eat your cookies ');</script>

Hex Encoded:
%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28 %27%4E%65%78%74%20%74%69%6D%65%20%49%20%77 %69%6C%6C%20%65%61%74%20%79%6F%75%72%20%63 %6F%6F%6B%69%65%73%20%27%29%3B%3C%2F%73%63 %72%69%70%74%3E

Modsecurity rule:
Secfilter <(.|\n)+> redirect:http://www.secure.com/error.html

Fine Grained (I) Positive Model

Vulnerable parameter: login Test String:


Test12121212

Modsecurity rule:
SecfilterSelective ARG_login !^[a-zA-Z]+$ Look at the server version!

File Extension Protection

File extension to protect: *.txt Requested file: admin/password.txt Modsecurity rule:


SecfilterSelective SCRIPT_FILENAME .+\.txt$ Positive way: SCRIPT_FILENAME !.+\.asp$

If we use Link Signing we don't need to worry about this rules.

Output Errors Protection

Vulnerable parameter: password Test String:


' (single quote) and 1 char in the login because one of the rules before.

Modsecurity rule:
SecfilterSelective OUTPUT Microsoft OLE DB Provider redirect:http://www.secure.com/default.asp

Strip Comment Code

Vulnerable page: help.asp Commented code: <!-- remember that admin zone is in /admin/ --> Modsecurity option: SecStripCommenCode On

Blog Spam Scenario, Wordpress


www.myblog.com

Web Client

Apache/Wordpress Here Modsecurity is working in the same server that is protecting.

Blog/Forums Spam Protection

Vulnerable parameter: comments Spam message: Cheap viagra Cheap vLagra Cheap v1agra Modsecurity Rule:
Secfilter ARGS v[iIL1]agra redirect:http://www.myblog.com/spam.swf

Link Signing Activated


www.securesign.com

IIS
mod_security + mod_proxy

client

www.vulnerable.com

Resource Location Prediction

Attack tool: Nikto Attack options:


nikto -host www.vulnerable.com nikto -host www.securesign.com

Modsecurity options:

SecSignLinks On SecEncriptionPassword our_Pass*Word-$

Resource Location using Nikto (I)

Resource Location using Nikto (II)

XSS with cripto-sign links enabled

Vulnerable parameter: pagina Test String:


<script>alert('Next time I will eat your cookies ');</script>

Modsecurity rule:
Secfilter <(.|\n)+>

Same for all other type of injection and variable manipulation, that involves a link, or direct access to URL.

File Extensions with Sign Links On

Vulnerable file extension: *.txt Requested file: /admin/password.txt Modsecurity rule:


SecfilterSelective SCRIPT_FILENAME .+\.txt$ Positive way: SCRIPT_FILENAME !.+\.asp$

We don't need to worry about this rules anymore!

Conclusions

Modsecurity is a great choice for protecting your web applications Easy to configure Very effective Remember that Modsecurity is an extra layer in our protection scheme, we have to secure our applications whenever we can. There is still much work to do to improve this features, they are an alpha version.

Question, doubts?

References
Download Modsecurity: www.modsecurity.org Mailing List: mod-security-users@lists.sourceforge.net Cryptlib: http://www.cs.auckland.ac.nz/~pgut001/cryptlib/ Libxml2: http://xmlsoft.org/

Thank you!
Advanced web application defense with Modsecurity

Daniel Fernandez Bleda dfernandez@isecauditors.com Christian Martorella cmartorella@isecauditors.com

Coding is no easy But programmers are patient

You might also like