terça-feira, 16 de setembro de 2014

Overview configuration and integrate NGINX

Sequence giving our series, we install mod_security in web server NGINX.
If you have done installing NGINX using the repository can check if the module mod_security is enabled with the command:

- strings /usr/sbin/nginx | grep -i sec //Folder where binaries NGINX

if no return, it will be necessary to recompile the NGINX if already installed or do an installation using sources.
At the time this matter, the version below was the most current (http://wiki.nginx.org/Install)

- wget http://nginx.org/download/nginx-1.6.0.tar.gz
**Let's see the installation of NGINX, only superficially, because it is not our goal**

Installing ModSecurity (The installation is based on RedHat derivatives)

First we will install all dependencies
- yum install gcc make libxml2 libxml2-devel httpd-dev pcre-devel curl-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 --enable-standalone-module --disable-mlogc
- make
- make install


** In case of doubt during installation, please come back in our first article. **
Being successful our installation, we will install or recompile the NGINX

- tar zxvf nginx-1.6.0.tar.gz
- cd nginx-1.6.0/
- ./configure --add-module=../ModSecurity/nginx/modsecurity
- make && make install


Now if we execute the command below, we have a return

- strings /usr/local/nginx/sbin/nginx | grep -i modsec

Mod_security settings are defined in nginx.conf
Add the following lines within the policy location /

- ModSecurityEnabled on;
- ModSecurityConfig modsecurity.conf;


    ex.
     location / {
            ModSecurityEnabled on;
            ModSecurityConfig modsecurity.conf;
            root   html;
            index  index.html index.htm;
        }



Well, now that we have the mod_sec already compiled and ready to run on the web server of our preferred,
let's start looking mod_security settings.
In that first moment I'll just show some of the major sections of the configuration file and
from the next article, go ja explaining in a little more detail.
It is important to say that it is good we go through all the settings, because even if they do not see the use at that time, you can
might need and it's good to know that we have available.
Again I say:

    THE PURPOSE OF SUCH ARTICLES It EXPLAIN HOW IT WORKS mod_security AND HOW'S YOUR STRUCTURE,
    That we are not hostages TO RULE THAT NOT, BECAUSE EACH HAVE YOUR NEED


Below is an overview of policy standards mod_security

SecArgumentSeparator ---------- Sets the application/x-www-form-urlencoded parameter separator
SecCookieFormat ---------- Sets the cookie parser version
SecDataDir ---------- Sets the folder for persistent storage
SecRequestBodyAccess ---------- Controls request body buffering
SecRequestBodyInMemoryLimit ---------- Sets the size of the per-request memory buffer
SecRequestBodyLimit ---------- Sets the maximum request body size ModSecurity will accept
SecRequestBodyLimitAction ---------- Controls what happens once the request body limit is reached
SecRequestBodyNoFilesLimit ---------- Sets the maximum request body size, excluding uploaded files
SecResponseBodyAccess ---------- Controls response body buffering
SecResponseBodyLimit ---------- Specifies the response body buffering limit
SecResponseBodyLimitAction ---------- Controls what happens once the response body limit is reached
SecResponseBodyMimeType ---------- Specifies a list of response body MIME types to inspect
SecResponseBodyMimeTypesClear ---------- Clears the list of response body MIME types
SecRuleEngine ---------- Controls the operation of the rule engine
SecTmpDir ---------- Sets the folder for temporary files

In the next article we will continue to see the structure of mod_security and drill some more.
It is very important to see these concepts, to understand how mod_security works.




Ref:
ModSecurity HandBook https://www.feistyduck.com/books/modsecurity-handbook/
http://blog.spiderlabs.com/

Integrando com NGINX e Vendo algumas configurações

Dando sequencia a nossa serie, vamos instalar o mod_security no web server NGINX.
Se tiver feito a instalação do NGINX usando o repositorio, podem verificar se o módulo para o mod_security esta habilitado, com o comando:

- strings /usr/sbin/nginx | grep -i sec //Pasta onde se encontra o binario do NGINX

se não tiver retorno, sera necessario recompilar o NGINX, caso ja esteja instalado ou fazer uma instalação usando os fontes.
No momento dessa materia, a versão abaixo era a mais atual (http://wiki.nginx.org/Install)

- wget http://nginx.org/download/nginx-1.6.0.tar.gz
**Sera abortado a instalação do NGINX, apenas, de maneira superficial, pois, não é o nosso objetivo**

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

Primeiro vamos instalar todas as dependencias
- yum install gcc make libxml2 libxml2-devel httpd-dev 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 --enable-standalone-module --disable-mlogc
- make
- make install


**Em caso de duvidas durante a instalação, favor voltar em nosso primeiro artigo.**

Sendo bem sucedida a nossa instalação, vamos instalar ou recompilar o NGINX
- tar zxvf nginx-1.6.0.tar.gz
- cd nginx-1.6.0/
- ./configure --add-module=../ModSecurity/nginx/modsecurity
- make && make install


Agora se executarmos o comando abaixo, nos temos um retorno

- strings /usr/local/nginx/sbin/nginx | grep -i modsec
As configurações do mod_security são definidas dentro de nginx.conf
Adicione as seguintes linhas dentro da diretiva location /

- ModSecurityEnabled on;
- ModSecurityConfig modsecurity.conf;

    ex.
     location / {
            ModSecurityEnabled on;
            ModSecurityConfig modsecurity.conf;
            root   html;
            index  index.html index.htm;
        }



Bom, agora que ja temos o mod_sec compilado e pronto para rodar no web server de nossa preferencia,
vamo começar a olhar as configurações do mod_security.
Nesse primeiro momento vou apenas mostrar algumas das principais seções do arquivo de configuração e
a partir do proximo artigo, ja ir explicando de uma maneira um pouco mais detalhada.
É importante dizer que é bom passarmos por todas as configurações, porque, mesmo que não va usar nesse momento, voce pode
vir a precisar e é bom sabermos que temos a disposição.
Volto a dizer que:

    O OBJETIVO DESSES ARTIGOS É EXPLICAR COMO O MOD_SECURITY FUNCIONA E COMO É SUA ESTRUTURA,
    PARA QUE NÃO FIQUEMOS REFENS DE REGRAS ALHEIAS, TENDO EM VISTA QUE CADA UM TEM A SUA NECESSIDADE


Abaixo temos uma visão geral das diretivas padrões do mod_securit
**Tentei traduzir os itens abaixo, mas não ficou com e resolvi deixar em ingles mesmo.**

SecArgumentSeparator ---------- Sets the application/x-www-form-urlencoded parameter separator
SecCookieFormat ---------- Sets the cookie parser version
SecDataDir ---------- Sets the folder for persistent storage
SecRequestBodyAccess ---------- Controls request body buffering
SecRequestBodyInMemoryLimit ---------- Sets the size of the per-request memory buffer
SecRequestBodyLimit ---------- Sets the maximum request body size ModSecurity will accept
SecRequestBodyLimitAction ---------- Controls what happens once the request body limit is reached
SecRequestBodyNoFilesLimit ---------- Sets the maximum request body size, excluding uploaded files
SecResponseBodyAccess ---------- Controls response body buffering
SecResponseBodyLimit ---------- Specifies the response body buffering limit
SecResponseBodyLimitAction ---------- Controls what happens once the response body limit is reached
SecResponseBodyMimeType ---------- Specifies a list of response body MIME types to inspect
SecResponseBodyMimeTypesClear ---------- Clears the list of response body MIME types
SecRuleEngine ---------- Controls the operation of the rule engine
SecTmpDir ---------- Sets the folder for temporary files

No proximo artigo vamos continuar a ver a estrutura do mod_security e detalhar um pouco mais.
É muito importante vermos esses conceitos, para entendermos como o mod_security funciona.



Ref:
ModSecurity HandBook -- https://www.feistyduck.com/books/modsecurity-handbook/
http://blog.spiderlabs.com/

segunda-feira, 8 de setembro de 2014

Integrating Mod Security to Apache.

Well, this week we will learn to integrate apache mod security.
What we did last week was just install mod security,
but he is not yet active in the system.

The command "make install" just add the modules that mod security
need, apache, but does not enable, we will see later on how
enables it.

We made a standard installation, but if you want to customize the
installation, security mod has a very complete help.

$. /configure --help

as a small example we have the following features: ** The above command in
shows much more than that.

Optional Features:
   --disable-option-checking ignore unrecognized --enable / - with options
   --disable-FEATURE do not include FEATURE (same as --enable-FEATURE = no)
   --enable-FEATURE [= ARG] include FEATURE [ARG = yes]
   --enable-silent-rules less verbose build output (undo: "make V = 1")
   --disable-silent-rules verbose build output (undo: "make V = 0 ')
   --enable-dependency-tracking
                       do not reject slow dependency extractors
   --disable-dependency-tracking
                       speeds up one-time build
   --enable-shared [= PKGS] build shared libraries [default = yes]
   --enable-static [= PKGS] build static libraries [default = yes]
   --enable-fast-install [= PKGS]
                       optimize for fast installation [default = yes]
   --disable-libtool-lock avoid locking (might break parallel builds)
   --disable-apache2-module
                       Disable building Apache2 module.


When you finish installing the mod security by default creates the directory,
with the following structure:

/usr/local/modsecurity/
├── bin
│ ├── mlogc
│ ├── mlogc-batch-load.pl
│ └── rules-updater.pl
└── lib
└── mod_security2.so

run the following command to check if the lib mod_security2.so
already is in the directory /etc/httpd/modules/

ls -l /etc/httpd/modules/ | grep mod_sec

if the lib is not in the directory, they can copy it with the following command:

cp /usr/local/modsecurity/lib/mod_security2.so  /etc/httpd/modules/


If you are using a version 6.x or it previous RedHat, let's edit
the /etc/httpd/conf/httpd.conf


vim /etc/httpd/conf/httpd.conf

If you are already using a derivative of RedHat 7.x we edit
/etc/httpd/conf.modules.d/00-base.conf


vim /etc/httpd/conf.modules.d/00-base.conf

and we add the following lines to the file.

32-Bits
LoadFile /usr/lib/libxml2.so
LoadFile /usr/lib/liblua-5.1.so

64-Bits
LoadFile /usr/lib64/libxml2.so
LoadFile /usr/lib64/liblua-5.1.so

#Enable Mod Security Module
LoadModule  Security2_module modules / mod_security2.so






Now is to restart Apache.

If you encounter the below error:

AH00526: Syntax error on line 218 of /etc/httpd/conf.d/modsecurity.conf:
Could not open unicode map file "/etc/httpd/conf.d/unicode.mapping": No such file or directory

just go back to the directory where the sources of mod_security and copy the file
unicode.mapping.

cp unicode.mapping /etc/httpd/conf.d/


Now the mod security already is active.
In our next article we will see how to enable the NGINX and perhaps in IIS.
We'll also have a general of the mod_security configuration file.



Integrando o Mod Security ao Apache

Bem, nessa semana vamos aprender a integrar o mod security ao apache.
O que fizemos na semana passada foi apenas instalar o mod security,
mas ele ainda não se encontra ativo no sistema.

O comando make install apenas adiciona os modulos que o mod security
precisa, ao apache, mas não o habilita, vamos ver mais a frente como
habilita-lo.

Nos fizemos uma instalação padrão, mas caso queira personalizar a
instalação, o mod security possui um help bem completo.
$./configure --help

como um pequeno exemplo temos as seguintes features:**O comando acima nos
mostra muito mais que isso.

Optional Features:
 --disable-option-checking  ignore unrecognized --enable/--with options
 --disable-FEATURE    do not include FEATURE (same as --enable-FEATURE=no)
 --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
 --enable-silent-rules   less verbose build output (undo: "make V=1")
 --disable-silent-rules  verbose build output (undo: "make V=0")
 --enable-dependency-tracking
                      do not reject slow dependency extractors
 --disable-dependency-tracking
                      speeds up one-time build
 --enable-shared[=PKGS]  build shared libraries [default=yes]
 --enable-static[=PKGS]  build static libraries [default=yes]
 --enable-fast-install[=PKGS]
                      optimize for fast installation [default=yes]
 --disable-libtool-lock  avoid locking (might break parallel builds)
 --disable-apache2-module
                      Disable building Apache2 module.


Quando terminar a instalação, o mod security cria por padrão a o diretorio,
com a seguinte estrutura:
/usr/local/modsecurity/
├── bin
│   ├── mlogc
│   ├── mlogc-batch-load.pl
│   └── rules-updater.pl
└── lib
└── mod_security2.so

execute o comando abaixo para verificar se a lib mod_security2.so
ja se encontra no diretorio /etc/httpd/modules/
ls -l /etc/httpd/modules/ | grep mod_sec

caso a lib não esteja no diretorio, podem copia-la com o comando abaixo:

cp /usr/local/modsecurity/lib/mod_security2.so  /etc/httpd/modules/


Se estiver usando uma versão 6.x ou anterio do RedHat, vamos editar
o /etc/httpd/conf/httpd.conf

vim /etc/httpd/conf/httpd.conf

Se ja estiver usando um derivado do RedHat 7.x vamos editar o
/etc/httpd/conf.modules.d/00-base.conf

vim /etc/httpd/conf.modules.d/00-base.conf

e vamos adicionar as seguinte linhas, ao arquivo.

32-Bits
LoadFile /usr/lib/libxml2.so
LoadFile /usr/lib/liblua-5.1.so
64-Bits
LoadFile /usr/lib64/libxml2.so
LoadFile /usr/lib64/liblua-5.1.so



LoadModule security2_module modules/mod_security2.so

Agora é reiniciar o Apache.

Caso se depare com o erro abaixo:

AH00526: Syntax error on line 218 of /etc/httpd/conf.d/modsecurity.conf:
Could not open unicode map file "/etc/httpd/conf.d/unicode.mapping": No such file or directory

basta voltar ao diretorio onde se encontram os fontes do mod_security e copiar o arquivo
unicode.mapping.

cp unicode.mapping /etc/httpd/conf.d/

Agora o mod security ja se encontra ativo.
Em nosso proximo artigo veremos como habilitar o no NGINX e talvez no IIS.
Vamos tambem ter uma geral do arquivo de configuração do mod_security.