viernes, 21 de marzo de 2014

Protegiendo nuestro servidor con fail2ban - Parte 2 "Frenando bots y scanners web simples"

Buenas noches! Debido al éxito rotundo (10 visitas :D) del post anterior de fail2ban hoy les traigo uno nuevo. Esta vez la idea es bloquear esos scanner de vulnerabilidades web que se suelen utilizar de manera automatizada para buscar sitios débiles.

En particular hoy vamos a detectar y bloquear un intento de escaneo con Nikto. Nikto es una herramienta muy común en el ámbito del web pentesting, cuenta con una gran batería de pruebas y es muy flexible. Usaré la versión de nikto 2.1.5 y el objetivo de prueba será un sitio con la versión 3.0.1 de wordpress, una versión ya en desuso y con conocidos fallos de seguridad.

Lanzaremos nikto contra un objetivo y buscaremos cómo identificarlo dentro de los logs de apache, para poder luego indicarle a fail2ban cómo reconocerlo y qué hacer al respecto.


¿Cómo obtener nikto?


Hay al menos dos formas de instalar nikto, siendo la mas sencilla (pero mas desactualizada) desde los repositorios de la distribución en cuestión y la mas "complicada" (pero mas actualizada) descargandolo manualmente. En este caso tomaremos el camino dificil, pero mas satisfactorio :D.


Lo descargamos y descomprimimos


juan@moon: ~/borrar$ wget --no-check-certificate https://www.cirt.net/nikto/nikto-2.1.5.tar.gz
juan@moon: ~/borrar$ tar -xvf nikto-2.1.5.tar.gz
...
juan@moon: ~/borrar$ cd nikto-2.1.5/


Lo hacemos ejecutable y lo actualizamos


juan@moon:~/borrar/nikto-2.1.5$ chmod +x nikto.pl 
juan@moon:~/borrar/nikto-2.1.5$ ./nikto.pl -update
+ Retrieving 'nikto_report_csv.plugin'
+ Retrieving 'nikto_headers.plugin'
+ Retrieving 'nikto_cookies.plugin'
+ Retrieving 'db_tests'
+ Retrieving 'db_parked_strings'
+ Retrieving 'CHANGES.txt'
+ CIRT.net message: Please submit Nikto bugs to http://trac2.assembla.com/Nikto_2/report/2
juan@moon:~/borrar/nikto-2.1.5$ 

Ready to run!!! Nikto está escrito en PERL y podría darse el caso de que no tengan todos los módulos de perl necesarios instalados y tengan que instalarlos (esa es la parte dificil jajaj).


Lanzando nikto al servidor objetivo


Vamos a lanzar nikto con su configuración por defecto y sin mas parámetros que el objetivo.

juan@moon:~/borrar/nikto-2.1.5$ ./nikto.pl -h 172.16.62.149
- Nikto v2.1.5
---------------------------------------------------------------------------
+ Target IP:          172.16.62.149
+ Target Hostname:    172.16.62.149
+ Target Port:        80
+ Start Time:         2014-03-20 00:04:55 (GMT-3)
---------------------------------------------------------------------------
+ Server: Apache/2.2.22 (Ubuntu)
+ Retrieved x-powered-by header: PHP/5.3.10-1ubuntu3.10
+ The anti-clickjacking X-Frame-Options header is not present.
+ Uncommon header 'x-pingback' found, with contents: http://172.16.62.149/xmlrpc.php
+ DEBUG HTTP verb may show server debugging information. See http://msdn.microsoft.com/en-us/library/e8z01xdh%28VS.80%29.aspx for details.
+ OSVDB-12184: /index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ Server leaks inodes via ETags, header found with file /readme, inode: 0x66046, size: 0x23a2, mtime: 0x48bfa299bbdc0;4f50077b4b85f
+ Uncommon header 'tcn' found, with contents: choice
+ OSVDB-3092: /xmlrpc.php: xmlrpc.php was found.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /wp-content/plugins/akismet/readme.txt: The WordPress Akismet plugin 'Tested up to' version usually matches the WordPress version
+ /readme.html: This WordPress file reveals the installed version.
+ OSVDB-3092: /license.txt: License file found may identify site software.
+ Cookie wordpress_test_cookie created without the httponly flag
+ /wp-login/: Admin login page/section found.
+ 6545 items checked: 0 error(s) and 14 item(s) reported on remote host
+ End Time:           2014-03-20 00:06:11 (GMT-3) (76 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
juan@moon:~/borrar/nikto-2.1.5$ 

Interesante... Qué podemos rescatar del análisis?

-Identificó el Sistema Operativo, Ubuntu.
-Identificó la versión de Apache, 2.2.22.
-Identificó la versión de PHP, 5.3.10-1ubuntu3.10.
-Identificó la versión de Wordpress, 3.0.1 (en /readme.html)
-También identificó potenciales exposiciones de información como

Nikto consiguió bastante información sobre el objetivo, aunque no encontró ninguna vulnerabilidad muy explícita podría haberlo hecho. Entonces acabamos de demostrar que nuestro servidor no es capaz de darse cuenta de que fue escaneado por un software en busca de vulnerabilidades.


¿Cómo identificamos el ataque?


Si le damos una breve mirada a los logs de apache podemos encontrar lo siguiente:

juan@ubuntu:/etc/fail2ban/filter.d$ cat /var/log/apache2/access.log |grep -i nikto
...
172.16.62.1 - - [19/Mar/2014:20:44:39 -0700] "GET /mobileadmin/bin/ HTTP/1.1" 404 532 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006606)"
172.16.62.1 - - [19/Mar/2014:20:44:39 -0700] "GET /mobileadmin/home.cs HTTP/1.1" 404 535 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006607)"
172.16.62.1 - - [19/Mar/2014:20:44:40 -0700] "GET /3rdparty/phpMyAdmin/server_sync.php?c=phpinfo() HTTP/1.1" 404 551 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006608)"
172.16.62.1 - - [19/Mar/2014:20:44:40 -0700] "GET /phpMyAdmin/server_sync.php?c=phpinfo() HTTP/1.1" 404 542 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006608)"
172.16.62.1 - - [19/Mar/2014:20:44:40 -0700] "GET /3rdparty/phpmyadmin/server_sync.php?c=phpinfo() HTTP/1.1" 404 551 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006608)"
172.16.62.1 - - [19/Mar/2014:20:44:40 -0700] "GET /phpmyadmin/server_sync.php?c=phpinfo() HTTP/1.1" 404 542 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006608)"
172.16.62.1 - - [19/Mar/2014:20:44:40 -0700] "GET /pma/server_sync.php?c=phpinfo() HTTP/1.1" 404 535 "-" "Mozilla/5.00 (Nikto/2.1.5) (Evasions:5) (Test:006608)"
juan@ubuntu:/etc/fail2ban/filter.d$

Cientos de entradas correspondientes a los accesos de Nikto, todas vienen con el user-agent Mozilla/5.00 (Nikto/2.1.5), y por lo tanto podría ser la cadena ideal para detectarlo. 


Indicándole a fail2ban como detectar Nikto:


Chusmeando un poco los filtros disponibles de fail2ban podemos ver que hay uno llamado apache-badbots.conf. Este filtro provee una lista de bots (robots scanners web) que han sido identificados como de no confiar o directamente peligrosoz, por lo tanto vamos a hacer uso de esta lista y expandirla para incluir Nikto en ella.

Editamos el archivo en cuestión (/etc/fail2ban/filter.d/apache-badbots.conf) y agregamos una nueva expresión regular a failregex. Quedando así:


failregex = ^ -.*"(GET|POST).*HTTP.*"(?:%(badbots)s|%(badbotscustom)s)"$
            ^ -.*"(GET|POST).*HTTP.*".*Nikto.*$

Ahora debemos crear el jail correspondiente en /etc/fail2ban/jail.conf . Agregamos lo siguiente al final del archivo:

[apache-badbots]

enabled  = true
port     = http,https
filter   = apache-badbots
logpath  = /var/log/apache*/*access*.log
maxretry = 1

Ahora es necesario agregar la jaula al proceso fail2ban, podemos lograrlo reiniciando el servicio:

root@ubuntu:/home/juan# service fail2ban restart
 * Restarting authentication failure monitor fail2ban                    [ OK ] 
root@ubuntu:/home/juan# 

Luego corroboramos que se haya cargado exitosamente:

root@ubuntu:/home/juan# fail2ban-client status
Status
|- Number of jail: 2
`- Jail list: apache-badbots, ssh
root@ubuntu:/home/juan# fail2ban-client status apache-badbots
Status for the jail: apache-badbots
|- filter
|  |- File list: /var/log/apache2/access.log /var/log/apache2/other_vhosts_access.log 
|  |- Currently failed: 0
|  `- Total failed: 0
`- action
   |- Currently banned: 0
   |  `- IP list:
   `- Total banned: 0
root@ubuntu:/home/juan# 


La prueba:


Ahora volvemos a lanzar Nikto contra nuestro servidor para ver si funciona:

juan@moon:~/borrar/nikto-2.1.5$ ./nikto.pl -h 172.16.62.149
- Nikto v2.1.5
---------------------------------------------------------------------------
+ No web server found on 172.16.62.149:80
---------------------------------------------------------------------------
+ 0 host(s) tested
juan@moon:~/borrar/nikto-2.1.5$ 

Claramente esta vez nikto no hay podido hacer nada. Y a continuación podemos ver porque:

root@ubuntu:/home/juan# fail2ban-client status apache-badbots
Status for the jail: apache-badbots
|- filter
|  |- File list: /var/log/apache2/access.log /var/log/apache2/other_vhosts_access.log
|  |- Currently failed: 1
|  `- Total failed: 1784
`- action
   |- Currently banned: 1
   |  `- IP list: 172.16.62.1
   `- Total banned: 1
root@ubuntu:/home/juan#

La jaula nos indica que la IP 172.16.62.1 fue detectada y bloqueada, podemos verlo también directamente desde iptables:

root@ubuntu:/home/juan# iptables-save
# Generated by iptables-save v1.4.12 on Fri Mar 21 06:29:33 2014
*filter
:INPUT ACCEPT [100:6649]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [77:8884]
:fail2ban-apache-badbots - [0:0]
:fail2ban-ssh - [0:0]
-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-apache-badbots
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A fail2ban-apache-badbots -s 172.16.62.1/32 -j DROP
-A fail2ban-apache-badbots -j RETURN
-A fail2ban-ssh -j RETURN
COMMIT
# Completed on Fri Mar 21 06:29:33 2014
root@ubuntu:/home/juan#

Nikto fue completamente detenido por fail2ban!!! Como ven, el potencial de fail2ban es gigante.

No hay comentarios:

Publicar un comentario