Comprobación de la vulnerabilidad de cualquier sitio que use Nikto

¡Hola a todos! En marzo, OTUS lanza un nuevo Kali Linux Workshop . En previsión del inicio del curso, hemos preparado una traducción de material útil para usted. También queremos invitar a todos a una lección gratuita sobre el tema: "Ataques de denegación de servicio y defensa contra ellos" .





Antes de atacar cualquier sitio, un hacker o un pentester primero elabora una lista de objetivos. Después de hacer un buen reconocimiento y encontrar puntos débiles para "apuntar", necesitará una herramienta de escaneo del servidor web como Nikto, que lo ayudará a encontrar vulnerabilidades, posibles vectores de ataque.

Nikto es un simple escáner de servidor web de código abierto que escanea un sitio web e informa vulnerabilidades encontradas que pueden ser explotadas o pirateadas. También es una de las herramientas más utilizadas para escanear sitios web en busca de vulnerabilidades en toda la industria, y en muchos círculos se considera el estándar de la industria.

A pesar de que esta herramienta es extremadamente efectiva, no actúa de manera encubierta. Cualquier sitio con un sistema de detección de intrusos u otras medidas de seguridad comprenderá que se está escaneando. Nikto fue diseñado para probar la seguridad, y nadie pensó en el secreto de su trabajo.

Cómo usar Nikto


Si simplemente ejecuta Nikto en el sitio web de destino, es posible que no entienda qué hacer con la información obtenida después del escaneo. Nikto es en realidad más como un puntero láser, lo que implica un disparo, y después de un tiempo verá cómo funciona.

Para empezar, hablemos de objetivos. El objetivo puede ser casi cualquier lugar donde un hacker pueda atacar, como impresoras de red o un servidor web. Cuando pasemos a usar Nikto un poco más tarde, tendremos que proporcionarle uno de los tres tipos de información: la dirección IP del servicio local, el dominio de ataque o el sitio web SSL / HTTPS.

Antes de comenzar a escanear con Nikto, es mejor realizar una exploración preliminar con una herramienta abierta como Maltego. Dichas herramientas pueden ser útiles para crear un perfil y formar una lista más específica de objetivos en los que centrarse. Una vez que haga esto, puede usar Nikto para buscar posibles vulnerabilidades para los objetivos de su lista.

Si tiene suerte, se encontrará una vulnerabilidad con un exploit conocido, lo que significa que ya existe una herramienta que ayudará a explotar este punto débil. Usando una herramienta apropiada que explota automáticamente la vulnerabilidad, un hacker puede obtener acceso al objetivo para llevar a cabo cualquier cantidad de ataques ocultos, como, por ejemplo, agregar código malicioso.

Paso 1: instalar Nikto


Si usa Kali Linux, Nikto estará preinstalado, por lo que no tiene que descargar ni instalar nada. Se ubicará en la categoría Análisis de vulnerabilidad. Si por alguna razón no lo tiene, puede descargar Nikto desde su repositorio en GitHub o simplemente usar el comando apt install.

apt install nikto

Si está utilizando una Mac, puede usar Homebrew para instalar Nikto.

brew install nikto

Paso 2: Conozca a Nikto


Antes de escanear servidores web con Nikto, use el parámetro -Help para ver todo lo que puede hacer con esta herramienta:

nikto -Help

Options:
       -ask+               Whether to ask about submitting updates
                               yes   Ask about each (default)
                               no    Don't ask, don't send
                               auto  Don't ask, just send
       -Cgidirs+           Scan these CGI dirs: "none", "all", or values like "/cgi/ /cgi-a/"
       -config+            Use this config file
       -Display+           Turn on/off display outputs:
                               1     Show redirects
                               2     Show cookies received
                               3     Show all 200/OK responses
                               4     Show URLs which require authentication
                               D     Debug output
                               E     Display all HTTP errors
                               P     Print progress to STDOUT
                               S     Scrub output of IPs and hostnames
                               V     Verbose output
       -dbcheck           Check database and other key files for syntax errors
       -evasion+          Encoding technique:
                               1     Random URI encoding (non-UTF8)
                               2     Directory self-reference (/./)
                               3     Premature URL ending
                               4     Prepend long random string
                               5     Fake parameter
                               6     TAB as request spacer
                               7     Change the case of the URL
                               8     Use Windows directory separator (\)
                               A     Use a carriage return (0x0d) as a request spacer
                               B     Use binary value 0x0b as a request spacer
        -Format+           Save file (-o) format:
                               csv   Comma-separated-value
                               htm   HTML Format
                               nbe   Nessus NBE format
                               sql   Generic SQL (see docs for schema)
                               txt   Plain text
                               xml   XML Format
                               (if not specified the format will be taken from the file extension passed to -output)
       -Help              Extended help information
       -host+             Target host
       -404code           Ignore these HTTP codes as negative responses (always). Format is "302,301".
       -404string         Ignore this string in response body content as negative response (always). Can be a regular expression.
       -id+               Host authentication to use, format is id:pass or id:pass:realm
       -key+              Client certificate key file
       -list-plugins      List all available plugins, perform no testing
       -maxtime+          Maximum testing time per host (e.g., 1h, 60m, 3600s)
       -mutate+           Guess additional file names:
                               1     Test all files with all root directories
                               2     Guess for password file names
                               3     Enumerate user names via Apache (/~user type requests)
                               4     Enumerate user names via cgiwrap (/cgi-bin/cgiwrap/~user type requests)
                               5     Attempt to brute force sub-domain names, assume that the host name is the parent domain
                               6     Attempt to guess directory names from the supplied dictionary file
       -mutate-options    Provide information for mutates
       -nointeractive     Disables interactive features
       -nolookup          Disables DNS lookups
       -nossl             Disables the use of SSL
       -no404             Disables nikto attempting to guess a 404 page
       -Option            Over-ride an option in nikto.conf, can be issued multiple times
       -output+           Write output to this file ('.' for auto-name)
       -Pause+            Pause between tests (seconds, integer or float)
       -Plugins+          List of plugins to run (default: ALL)
       -port+             Port to use (default 80)
       -RSAcert+          Client certificate file
       -root+             Prepend root value to all requests, format is /directory
       -Save              Save positive responses to this directory ('.' for auto-name)
       -ssl               Force ssl mode on port
       -Tuning+           Scan tuning:
                               1     Interesting File / Seen in logs
                               2     Misconfiguration / Default File
                               3     Information Disclosure
                               4     Injection (XSS/Script/HTML)
                               5     Remote File Retrieval - Inside Web Root
                               6     Denial of Service
                               7     Remote File Retrieval - Server Wide
                               8     Command Execution / Remote Shell
                               9     SQL Injection
                               0     File Upload
                               a     Authentication Bypass
                               b     Software Identification
                               c     Remote Source Inclusion
                               d     WebService
                               e     Administrative Console
                               x     Reverse Tuning Options (i.e., include all except specified)
       -timeout+          Timeout for requests (default 10 seconds)
       -Userdbs           Load only user databases, not the standard databases
                               all   Disable standard dbs and load only user dbs
                               tests Disable only db_tests and load udb_tests
       -useragent         Over-rides the default useragent
       -until             Run until the specified time or duration
       -update            Update databases and plugins from CIRT.net
       -useproxy          Use the proxy defined in nikto.conf, or argument http://server:port
       -Version           Print plugin and database versions
       -vhost+            Virtual host (for Host header)
   		+ requires a value

Paso 3: usa la sintaxis básica


Como puede ver en el paso anterior, Nikto tiene muchos casos de uso, pero para nuestros propósitos usaremos la sintaxis básica <IP o nombre de host> con la dirección IP real o el nombre de host sin corchetes angulares.

nikto -h <IP or hostname>

Sin embargo, Nikto puede escanear SSL y el puerto 443, que usan los sitios HTTPS (HTTP usa el puerto 80 por defecto). Por lo tanto, no estamos limitados solo a rastrear sitios antiguos, podemos evaluar las vulnerabilidades de los sitios que usan SSL, que hoy es un requisito casi obligatorio para la indexación en los resultados de búsqueda.

Si sabemos que el sitio de destino tiene SSL, podemos especificar esto en Nikto para ahorrar tiempo en el rastreo agregando -ssl al final del comando.

nikto -h <IP or hostname> -ssl

Paso 4: escanee sitios con SSL


Por ejemplo, comencemos escaneando el sitio pbs.orgpara ver los tipos de información que Nikto crawls puede proporcionar. Después de que se conecta al puerto 443, vemos información útil sobre el cifrado y otros detalles, como, por ejemplo, que el servidor se está ejecutando en nginx, pero aquí no hay mucho interés para nosotros.

nikto -h pbs.org -ssl

- Nikto v2.1.6
------------------------------------------------------------------------------
- STATUS: Starting up!
+ Target IP:			54.225.198.196
+ Target Hostname:		pbs.org
+ Traget Port:			443
------------------------------------------------------------------------------
+ SSl Info:			Subject:	/CN=www.pbs.org
					Altnames:	account.pbs.org, admin.pgs.org, dipsy-tc.pbs.org, docs.pbs.org, ga.video.cdn.pbs.org, git.pbs.org, heart.ops.pbs.org, hub-dev.pbs.org, image.pbs.org,
                    			jaws..pbs.org, kids.pbs.org, koth-qa.svp.pbs.org, login.pbs.org, ops.pbs.org, pbs.org, player.pbs.org, projects.pbs.org, sentry.pbs.org, teacherline.pbs.org,
                                urs.pbs.org, video.pbs.org, weta-qa.svp.pbs.org, whut-qa.svp.pbs.org, wnet.video-qa.pbs.org, wnet.video-staging.pbs.org, www-cache.pbs.org, www.pbs.org
                    Ciphers:	ECDHE-RSA-AES128-GCM-SHA256
                    Issuer:		/C-US/0=Let's Encrypt/CN=Let's Encrypt Authority X3
+ Start Time:			2018-12-05 23:34:06 (GMT-8)
------------------------------------------------------------------------------
+ Server: nginx
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'x-pbs-fwsrvname' found, with contents: fwcacheproxy1
+ The site uses SSL and the Strict-Transport-Security HTTP header is not defined.
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Root page / redirects to: https://www.pbs.org/
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ RC-1918 IP address found in the 'x-pbs-appsvrip' header: The IP is "10.137.181.52".
+ Uncommon header 'x-cache-fs-status' found, with contents: EXPIRED
+ Uncommon header 'x-pbs-appsvrname' found, with contents: fwcacheproxy1
+ Uncommon header 'x-pbs-appsvrip' found, with contents: 10.137.181.52
+ Server leaks inodes via ETags, header found with file /pbs.org.zip, fields: 0x5b96537e 0x1678
+ 7446 requests: 0 error(s) and 10 item(s) reported on remote host
+ End Time:				2018-12-06 00:30:29 (GMT-8) (3383 seconds)
------------------------------------------------------------------------------
+ 1 host(s) tested

Paso 5: Escanee la dirección IP


Ahora que hemos hecho un escaneo rápido del sitio web, podemos intentar usar Nikto en la red local para encontrar servidores integrados, como la página de inicio de sesión del enrutador o el servicio HTTP en otra máquina, que es simplemente un servidor sin un sitio web. Para averiguar la dirección IP que utilizaremos ifconfig.

La dirección IP que necesitamos se refiere a inet. En él podemos usar ipcalcpara obtener el rango de red. Si no tiene ipcalc, puede instalarlo con el comando apt install ipcalcy luego intentarlo de nuevo. El rango será después de "Red", en mi caso es 192.168.0.0/24.

ifconfig

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST>  mtu 1500
        inet 192.168.0.48  netmask 0xffffff00  broadcast 192.168.0.255
        inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0  prefixlen 64  secured scopeid 0x8
        ether XX:XX:XX:XX:XX:XX  txqueuelen 1000  (Ethernet)
        inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0  prefixlen 64 autoconf secured
        inet6 XXXX::XXX:XXXX:XXXX:XXXX%en0  prefixlen 64 autoconf temporary
        nd6 options=201<PERFORMNUD,DAD>
        media: autoselect
        status: active

en2: flags=8863<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST>  mtu 1500
        options=60<TS04,TS06>
        ether XX:XX:XX:XX:XX:XX
        media: autoselect <full-duplex>
        status: inactive

Ahora queremos iniciar Nmap para encontrar servicios que funcionen en este rango de red. Analicemos el puerto 80 usando nuestro rango, para esto agregaremos -oG (salida grepable) para obtener solo aquellos hosts que están en funcionamiento, es decir, aquellos que responden diciendo que el puerto 80 está abierto. Luego guardaremos todo esto en un archivo, que nombraré nullbyte.txt, usted, a su vez, puede nombrarlo como quiera.

ipcalc 192.168.0.48

Address:   192.168.0.48         11000000.10101000.00000000. 00110000
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   192.168.0.0/24       11000000.10101000.00000000. 00000000
HostMin:   192.168.0.1          11000000.10101000.00000000. 00000001
HostMax:   192.168.0.254        11000000.10101000.00000000. 11111110
Broadcast: 192.168.0.255        11000000.10101000.00000000. 11111111
Hosts/Net: 254                   Class C, Private Internet

Hay un pequeño truco que ayudará a enviar todos los hosts directamente a Nikto para su escaneo. Usamos catpara leer la entrada almacenada en nuestro documento nullbyte.txt(o como lo llamó usted mismo). Después de eso, usamos awk , una herramienta especial en Linux que lo ayudará a encontrar la siguiente plantilla, donde Arriba significa que el host está activo, e imprimir $ 2 significa que necesita imprimir la segunda palabra en cada línea, es decir, solo la dirección IP. Luego, enviaremos los datos recibidos a un archivo llamado targetIP.txt(o lo que desee).

cat nullbyte.txt | awk '/Up$/{print $2}' | cat >> targetIP.txt

Ahora podemos ver el contenido de nuestro nuevo archivo con cat para ver todas las direcciones IP que tienen abierto el puerto 80.

cat targetIP.txt

192.168.0.1
192.168.0.2
192.168.0.4
192.168.0.5
192.168.0.11
192.168.0.24
192.168.0.31
192.168.0.48
192.168.0.60

Este formato es ideal para Nikto, ya que puede interpretar fácilmente dichos archivos. Por lo tanto, podemos enviar esta salida a Nikto con el siguiente comando.

nikto -h targetIP.txt

Los resultados serán similares a los que obtuvimos al escanear con SSL.

Paso 6: escanee el sitio HTTP


Escaneamos un sitio web seguro y una dirección IP en la red local, ahora es el momento de buscar un dominio web inseguro que use el puerto 80. Para este ejemplo, estoy usando afl.com.au , que no tenía SSL en el momento en que estaba escaneando esto.

nikto -h www.afl.com.au

- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          159.180.84.10
+ Target Hostname:    www.afl.com.au
+ Target Port:        80
+ Start Time:         2018-12-05 21:48:32 (GMT-8)
---------------------------------------------------------------------------
+ Server: instart/nginx
+ Retried via header: 1.1 varnish (Varnish/6.1), 1.1 e9ba0a9a729ff2960a04323bf1833df8.cloudfront.net (CloudFront)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'x-cache' found, with contents: Miss from cloudfront
+ Uncommon header 'x-instart-cache-id' found, with contents: 17:12768802731504004780::1544075250
+ Uncommon header 'v-cache-hit' found, with contents: Hit
+ Uncommon header 'x-amz-cf-id' found, with contents: Dr-r6OwO5kk9ABt4ejzpc7R7AIF6SuH6kfJHQgP0v6xZoHwMLE55rQ==
+ Uncommon header 'x-instart-request-id' found, with contents: 12814413144077601501:BEQ01-CPVNPPRY18:1552504721:0
+ Uncommon header 'x-oneagent-js-injection' found, with contents: true
+ Uncommon header 'grace' found, with contents: cache
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Uncommon header 'x-ruxit-js-agent' found, with contents: true
+ Cookie dtCookie created without the httponly flag
+ Server banner has changed from 'instart/nginx' to 'nginx' which may suggest a WAF, load balancer or proxy is in place
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Entry '/sites/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ Entry '/search/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ Entry '*.mobileapp' in robots.txt returned a non-forbidden or redirect HTTP code (400)
+ Entry '*.liveradio' in robots.txt returned a non-forbidden or redirect HTTP code (400)
+ Entry '*.smartmobile' in robots.txt returned a non-forbidden or redirect HTTP code (400)
+ Entry '*.responsive' in robots.txt returned a non-forbidden or redirect HTTP code (400)
+ Entry '/stats?*/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 8 entries which should be manually viewed.
+ OSVDB-3092: /sitemap.xml: This gives a nice listing of the site content.
+ OSVDB-3092: /psql_history: This might be interesting...
+ OSVDB-3092: /global/: This might be interesting...
+ OSVDB-3092: /home/: This might be interesting...
+ OSVDB-3092: /news: This might be interesting...
+ OSVDB-3092: /search.vts: This might be interesting...
+ OSVDB-3092: /stats.htm: This might be interesting...
+ OSVDB-3092: /stats.txt: This might be interesting...
+ OSVDB-3092: /stats/: This might be interesting...
+ OSVDB-3092: /Stats/: This might be interesting...
+ OSVDB-3093: /.wwwacl: Contains authorization information
+ OSVDB-3093: /.www_acl: Contains authorization information
+ OSVDB-3093: /.htpasswd: Contains authorization information
+ OSVDB-3093: /.access: Contains authorization information
+ OSVDB-3093: /.addressbook: PINE addressbook, may store sensitive e-mail address contact information and notes
+ OSVDB-3093: /.bashrc: User home dir was found with a shell rc file. This may reveal file and path information.
+ OSVDB-3093: /.bash_history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web.
+ OSVDB-3093: /.forward: User home dir was found with a mail forward file. May reveal where the user's mail is being forwarded to.
+ OSVDB-3093: /.history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web.
+ OSVDB-3093: /.htaccess: Contains configuration and/or authorization information
+ OSVDB-3093: /.lynx_cookies: User home dir found with LYNX cookie file. May reveal cookies received from arbitrary web sites.
+ OSVDB-3093: /.mysql_history: Database SQL?
+ OSVDB-3093: /.passwd: Contains authorization information
+ OSVDB-3093: /.pinerc: User home dir found with a PINE rc file. May reveal system information, directories and more.
+ OSVDB-3093: /.plan: User home dir with a .plan, a now mostly outdated file for delivering information via the finger protocol
+ OSVDB-3093: /.proclog: User home dir with a Procmail rc file. May reveal mail traffic, directories and more.
+ OSVDB-3093: /.procmailrc: User home dir with a Procmail rc file. May reveal subdirectories, mail contacts and more.
+ OSVDB-3093: /.profile: User home dir with a shell profile was found. May reveal directory information and system configuration.
+ OSVDB-3093: /.rhosts: A user's home directory may be set to the web root, a .rhosts file was retrieved. This should not be accessible via the web.
+ OSVDB-3093: /.sh_history: A user's home directory may be set to the web root, the shell history was retrieved. This should not be accessible via the web.
+ OSVDB-3093: /.ssh: A user's home directory may be set to the web root, an ssh file was retrieved. This should not be accessible via the web.
+ OSVDB-5709: /.nsconfig: Contains authorization information
+ /portal/changelog: Vignette richtext HTML editor changelog found.
+ 7587 requests: 4 error(s) and 55 item(s) reported on remote host
+ End Time:           2018-12-05 22:42:41 (GMT-8) (3249 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested

De la información anterior, entendemos que hay un servidor Varnish y algunos encabezados que pueden indicar cómo está configurado el sitio web. Sin embargo, se encuentra información más útil en directorios descubiertos que pueden ayudar a capturar archivos de configuración que contienen credenciales u otras cosas que no se configuraron correctamente y estuvieron disponibles de forma no intencional.

Los elementos con el prefijo OSVDB son vulnerabilidades reportadas en la Base de datos de vulnerabilidad de código abierto (un sitio que cerró en 2016). Es similar a otras bases de datos de vulnerabilidades como SecurityFocus , Microsoft Technet y Vulnerabilities and Exposures (https://cve.mitre.org/). Personalmente, la Base de Datos Nacional de Vulnerabilidad está más cerca de mí .

Aunque nuestro análisis no reveló ninguna vulnerabilidad crítica que pudiera ser explotada, puede usar la herramienta de ayuda CVE para traducir el identificador OSVDB en un registro CVE para que pueda usar uno de los sitios mencionados anteriormente.

Suponga que encuentra algo que vale la pena explorar, por ejemplo CVE-2018-10933 , la vulnerabilidad Libssh, que discutimos con más detalle anteriormente . El CVE contiene información sobre cómo explotarlo, la gravedad de la vulnerabilidad (por ejemplo, una vulnerabilidad crítica) y otra información que puede ayudar a determinar el vector de ataque. Si esto es algo que vale la pena, puede buscar con Metasploit, ya que es muy probable que alguien ya haya desarrollado un módulo que ayudará a explotar fácilmente esta vulnerabilidad.



Paso 7: escanee con Metasploit


Una de las mejores cosas de Nikto es que simplemente puede exportar la información que recibió del escaneo a un formato que Metasploit pueda leer. Para hacer esto, simplemente use los comandos para realizar el escaneo anterior, pero agregue los indicadores -Format msf + al final . Este formato puede ayudarlo a hacer coincidir rápidamente los datos obtenidos a través del exploit.

nikto -h <IP or hostname> -Format msf+

Entonces, en la guía de hoy, pasamos de definir un objetivo a encontrar vulnerabilidades en él, y luego asociamos las vulnerabilidades con el exploit para que no tuviéramos que hacer todo el trabajo manualmente. Dado que Nikto no funciona de forma encubierta, es aconsejable realizar estos escaneos a través de una VPN, Tor u otro tipo de servicio para que su dirección IP no se marque como sospechosa.

→  Regístrese para una lección gratis

All Articles