domingo, 31 de agosto de 2014

Introduction to ModSecurity

To begin I will address the installation of mod_security, which is a web application firewall, also known as WAF.
The mod_security is now supported by the SpiderLabs (http://blog.spiderlabs.com/), sustained by Truswave blog, one of the giants of the security team.
The mod_security is an opencsource WAF in my opinion loses nothing to the owners. He has paid some rules, developed by the staff of SiperLabs and has rules available for free on the OWASP site, but our intention is not to take anything but ready to understand how the tool works, to create our own rules.

In this first article, we discuss the design, operation and installation of mod_security, already in the next we will see the integration of it with the two leading opencsource web servers.

Let's start by listing where mod_security can help us:

- Real time accesses and attempts to circumvent our application.
- Virtual patching protecting our application until the team of developers can fix a possible failure.
- Log all HTTP traffic
- Continuous evaluation of safety through safety testing and analysis of logs, we can know if our application this vulnerable before a third party.
- Hardening web application.

Installation Options

The mod_security can be installed directly on the web server or can be used with the reverse proxy.

- On the web server, it would be the best choice for those who already have their network architecture and not want to change. The weakness of this choice would be the administration of resources, since mod_security would share these resources with the system.
- As a reverse proxy, in my opinion the best choice, because you are so full isolating your network and does not compromise the web server resources.

Main features
- Parsing
- Buffering
In the default installation, mod_security the request and response, which can change both before completing the action causes buffer.
- Logging
All transactions are logged, so you can make an analysis, if needed
- Rule Engine
The rules, we can say that are the heart of mod_security therefore are responsible for the executions of the locks.
A code example of rule: SecRule ARGS "<script>" log, deny, status: 404

the Rules

By default rules follow the following sequence:
SecRule VARIABLE OPERATOR ACTION

Variables, mod_security will tell where to look. In our example was used to ARGS variable, which tells mod_security to look at all the parameters of request
Operator will tell mod_security, what to look for. In our example we have the string JS <script>, used in XSS attacks.
Shares, will tell mod_security action you should take, if the previous condition is true. In our example mod_security log in will register, will deny access and give the answer as 404 status.
Flow

We can divide the rules into 5 phases, where each phase specifies the mod_security runs the rule set to the same.
1 Request headers
2 Request body
3 Response headers
4 Response body
Logging 5-
- In phases of request mod_security makes analysis of requests and applies the rules according to what was configured, it is for header or body and then passes to a request to webserver
- In response phases of mod_security is the analysis of the webserver response, the request sent both to header as to body and then passes the response to the client.
- At the time of logging, mod_security to say how we want the requests and responses are recorded in the log.


Installation (The installation is based on RedHat )

First we will install all dependencies
- Yum install gcc make curl-devel libxml2 libxml2-devel httpd-devel pcre-devel

For installing mod_security, we use git (yum install git), and download the latest version of the project.
- git clone git: //github.com/SpiderLabs/ModSecurity.git
- cd ModSecurity
- ./autogen.sh
- ./configure
- make
- make install


Ready, we completed our installation. Next week we will see how to integrate mod_security the webserver.
@l0c4lh05t 
Introdução - ModSecurity




Para começar vou abordar a instalação do mod_security, que é um firewall de aplicação web, tambem conhecido como WAF.
O mod_security é hoje suportado pela equipe da SpiderLabs (http://blog.spiderlabs.com/) , blog sustentado pela Truswave, uma das gigantes da segurança.
O mod_security é um WAF opensource que na minha opinião não perde nada para os proprietarios. Ele possui algumas regras pagas, desenvolvidas pelo pessoal do SiperLabs e possui regras disponiveis de forma gratuita no site da OWASP, mas, a nossa intenção não é pegar nada pronto e sim entender como a ferramenta funciona, para criarmos nossas proprias regras.


Nesse primeiro artigo, iremos abordar o conceito, funcionamento e instalação do mod_security, ja no proximo vamos ver a integração dele com os dois principais web servers open source.
Vamos começar listando onde o mod_security pode nos ajudar:

- Visualização em tempo real dos acessos e das tentativas de burlar nossa aplicação.
- Virtual patching, protegendo nossa aplicação ate que a equipe de developers possa corrigir uma possivel falha.
- Log de todo o trafego HTTP
- Avaliação continua da segurança, atraves de testes de segurança e analise dos logs, pode-se saber se nossa aplicação esta vulneravel, antes de um terceiro.
- Hardening de aplicação web.

Opções de instalação

O mod_security pode ser instalado direto no servidor web ou pode ser usado como proxy reverso.

- No servidor web, seria a melhor escolha pra quem ja tem sua arquitetura de rede e não deseja alterar. O ponto fraco dessa escolha seria a administração dos recursos, ja que o mod_security iria compartilhar desses recursos junto com o sistema.
- Como proxy reverso, na minha opinião a melhor escolha, pois, voce esta isolando de forma completa a sua rede e não compromete os recursos do servidor web.

Principais Caracteristicas
- Parsing
- Buffering
Na instalação padrão, o mod_security faz buffer do request e do response, podendo assim alterar ambos antes de concluir a ação
- Logging
Todas as transações são logadas, para que se possa fazer uma analise, caso seja preciso
- Rule Engine
As rules, nos podemos dizer que são o coração do mod_security, pois, são as responsaveis pelas execuções dos bloqueios.
Um exemplo de rule: SecRule ARGS "<script>" log,deny,status:404

As Regras

Por padrão as regras seguem a seguinte sequencia:
SecRule VARIAVEIS OPERADOR AÇOES

Variaveis, vão dizer ao mod_security onde procurar. Em nosso exemplo foi usado a variavel ARGS, que diz ao mod_security para olhar todo os parametros de request
Operador, vai dizer ao mod_security, o que procurar. Em nosso exemplo temos a string JS <script>, usado em ataques XSS.
Ações, vai dizer ao mod_security a ação que deve tomar, caso a condição anterior for verdadeira. Em nosso exemplo o mod_security vai registrar em log, vai negar o acesso e dar como resposta o status 404.

Fluxo

Podemos dividir as regras em 5 fases, onde em cada fase especifica, o mod_security executa a regra definida para a mesma.
1- Request headers
2- Request body
3- Response headers
4- Response body
5- Logging
- Nas fases de request o mod_security faz analise das requisições e aplica as regras de acordo com o que foi configurado, se é pra header ou pra body e depois repassa a requisição ao webserver
- Nas fases de response o mod_security faz a analise da resposta do webserver, a requisição enviada, tanto pra header quanto para body e depois repassa a resposta ao cliente.
- Na fase de logging, dizemos ao mod_security como queremos que as requisições e respostas sejam registradas no log.

Instalação ( A instalação é baseada em derivados RedHat)

Primeiro vamos instalar todas as dependencias
- yum install gcc make libxml2 libxml2-devel httpd-devel pcre-devel curl-devel

Para a instalação do mod_security, vamos usar o git (yum install git), e baixar a versão mais recente do projeto.
- git clone git://github.com/SpiderLabs/ModSecurity.git
- cd ModSecurity
- ./autogen.sh
- ./configure
- make
- make install


Pronto, finalizamos a nossa instalação. Napróximaa semana veremos como integrar o mod_security a webserver.

@l0c4lh05t 
Beginning

I decided to start this blog, I see the deficiency finding security materials, but do not speak of the attack but part of the defense.
Eg Hardening both applications, the OS, application firewall, mod_security and the beginning of a very little known more versatile IDS, the BRO-IDS.
The idea is that every week matters related to these issues are addressed and also suggested by readers will be addressed. Try to be as clear as possible.

Começando

Resolvi iniciar esse blog, pela dificuldade que vejo em encontrar materiais em portugues a respeito de segurança, mas não falo da parte de ataque e sim da parte de defence.
Como por exemplo, Hardening, tanto de aplicações, quanto de SO, firewall de aplicação, a principio o mod_security e de um IDS pouco conhecido mais muito versatil, o BRO-IDS.
A ideia é que toda semana assuntos relacionados a esses sejam abordados e tambem serão abordados temas sugeridos por leitores. Tentarei ser o mais claro possivel.