80,443 - Metodología de Pentesting Web

Tip

Aprende y practica Hacking en AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica Hacking en GCP: HackTricks Training GCP Red Team Expert (GRTE) Aprende y practica Hacking en Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Apoya a HackTricks

Información Básica

El servicio web es el servicio más común y extenso y existen muchos tipos diferentes de vulnerabilidades.

Puerto por defecto: 80 (HTTP), 443 (HTTPS)

PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  ssl/https
nc -v domain.com 80 # GET / HTTP/1.0
openssl s_client -connect domain.com:443 # GET / HTTP/1.0

Guía para Web API

Web API Pentesting

Resumen de la metodología

En esta metodología vamos a suponer que vas a atacar un dominio (o subdomain) y solo ese. Por tanto, debes aplicar esta metodología a cada dominio, subdomain o IP descubierta con un servidor web no determinado dentro del alcance.

  • Empieza por identificar las tecnologías usadas por el servidor web. Busca trucos a tener en cuenta durante el resto del test si logras identificar la tecnología.
  • ¿Alguna vulnerabilidad conocida de la versión de la tecnología?
  • ¿Usando alguna well known tech? ¿Algún truco útil para extraer más información?
  • ¿Algún specialised scanner para ejecutar (como wpscan)?
  • Lanza general purposes scanners. Nunca sabes si van a encontrar algo o si van a encontrar información interesante.
  • Comienza con las initial checks: robots, sitemap, 404 error y SSL/TLS scan (si HTTPS).
  • Comienza a spidering la página web: es momento de encontrar todos los posibles files, folders y parameters being used. También, revisa por special findings.
  • Nota que cada vez que se descubra un nuevo directorio durante brute-forcing o spidering, este debe ser spidered.
  • Directory Brute-Forcing: Intenta brute force en todas las carpetas descubiertas buscando nuevos files y directories.
  • Nota que cada vez que se descubra un nuevo directorio durante brute-forcing o spidering, este debe ser Brute-Forced.
  • Backups checking: Prueba si puedes encontrar backups de discovered files añadiendo extensiones de backup comunes.
  • Brute-Force parameters: Intenta encontrar parámetros ocultos.
  • Una vez que hayas identificado todos los posibles endpoints que aceptan user input, revisa todo tipo de vulnerabilidades relacionadas con ellos.
  • Sigue esta lista de verificación

Versión del servidor (¿Vulnerable?)

Identificar

Comprueba si hay vulnerabilidades conocidas para la versión del servidor que está corriendo.
Las HTTP headers y cookies de la respuesta pueden ser muy útiles para identificar las tecnologías y/o la versión empleada. Un escaneo con Nmap puede identificar la versión del servidor, pero también pueden ser útiles las herramientas whatweb, webtech o https://builtwith.com/:

whatweb -a 1 <URL> #Stealthy
whatweb -a 3 <URL> #Aggresive
webtech -u <URL>
webanalyze -host https://google.com -crawl 2

Buscar por vulnerabilidades de la versión de la aplicación web

Check if any WAF

Web tech tricks

Algunos trucos para encontrar vulnerabilidades en diferentes tecnologías bien conocidas que se estén usando:

Ten en cuenta que el mismo dominio puede estar usando diferentes tecnologías en distintos puertos, carpetas y subdominios.
Si la aplicación web está usando alguna tecnología/plataforma listada antes o cualquier otra, no olvides buscar en Internet nuevos trucos (¡y avísame!).

Source Code Review

Si el código fuente de la aplicación está disponible en github, además de realizar por tu cuenta un White box test de la aplicación, hay alguna información que podría ser útil para el actual Black-Box testing:

  • ¿Existe un Change-log or Readme or Version file o cualquier cosa con version info accesible vía web?
  • ¿Cómo y dónde se guardan las credenciales? ¿Hay algún (¿accesible?) file con credenciales (usernames o passwords)?
  • ¿Las passwords están en plain text, encrypted o qué hashing algorithm se usa?
  • ¿Está usando alguna master key para encriptar algo? ¿Qué algorithm se usa?
  • ¿Puedes acceder a alguno de estos archivos explotando alguna vulnerabilidad?
  • ¿Hay alguna información interesante en el github (issues resueltos y no resueltos)? ¿O en el commit history (quizá alguna password introducida en un commit antiguo)?

Source code Review / SAST Tools

Automatic scanners

General purpose automatic scanners

nikto -h <URL>
whatweb -a 4 <URL>
wapiti -u <URL>
W3af
zaproxy #You can use an API
nuclei -ut && nuclei -target <URL>

# https://github.com/ignis-sec/puff (client side vulns fuzzer)
node puff.js -w ./wordlist-examples/xss.txt -u "http://www.xssgame.com/f/m4KKGHi2rVUN/?query=FUZZ"

Escáneres de CMS

Si se utiliza un CMS, no olvides ejecutar un scanner, quizá se encuentre algo jugoso:

Clusterd: JBoss, ColdFusion, WebLogic, Tomcat, Railo, Axis2, Glassfish
CMSScan: WordPress, Drupal, Joomla, vBulletin sitios web en busca de problemas de seguridad. (GUI)
VulnX: Joomla, Wordpress, Drupal, PrestaShop, Opencart
CMSMap: (W)ordpress, (J)oomla, (D)rupal o (M)oodle
droopscan: Drupal, Joomla, Moodle, Silverstripe, Wordpress

cmsmap [-f W] -F -d <URL>
wpscan --force update -e --url <URL>
joomscan --ec -u <URL>
joomlavs.rb #https://github.com/rastating/joomlavs

En este punto ya deberías tener algo de información sobre el servidor web que usa el cliente (si se dio algún dato) y algunos trucos para tener en cuenta durante la prueba. Si tienes suerte, incluso habrás encontrado un CMS y ejecutado algún scanner.

Descubrimiento paso a paso de la aplicación web

Desde este punto vamos a empezar a interactuar con la aplicación web.

Comprobaciones iniciales

Páginas por defecto con información interesante:

  • /robots.txt
  • /sitemap.xml
  • /crossdomain.xml
  • /clientaccesspolicy.xml
  • /.well-known/
  • También revisa los comentarios en la página principal y en las páginas secundarias.

Provocar errores

Los servidores web pueden comportarse de manera inesperada cuando se les envían datos extraños. Esto puede exponer vulnerabilidades o revelar información sensible.

  • Accede a páginas falsas como /whatever_fake.php (.aspx,.html,.etc)
  • Añade “[]”, “]]” y “[[” en cookie values y parameter values para provocar errores
  • Genera un error dando como entrada /~randomthing/%s al final de la URL
  • Prueba different HTTP Verbs como PATCH, DEBUG o incluso incorrectos como FAKE

Comprueba si puedes subir archivos (PUT verb, WebDav)

Si descubres que WebDav está habilitado pero no tienes permisos suficientes para subir archivos en la carpeta raíz, intenta:

  • Realizar Brute Force sobre las credenciales
  • Subir archivos vía WebDav al resto de las carpetas encontradas dentro de la página web. Puede que tengas permisos para subir archivos en otras carpetas.

Vulnerabilidades SSL/TLS

  • Si la aplicación no obliga al uso de HTTPS en ninguna parte, entonces es vulnerable a MitM
  • Si la aplicación envía datos sensibles (contraseñas) usando HTTP, entonces es una vulnerabilidad alta.

Usa testssl.sh para comprobar vulnerabilidades (en los programas de Bug Bounty probablemente este tipo de vulnerabilidades no serán aceptadas) y usa a2sv para volver a comprobar las vulnerabilidades:

./testssl.sh [--htmlfile] 10.10.10.10:443
#Use the --htmlfile to save the output inside an htmlfile also

# You can also use other tools, by testssl.sh at this momment is the best one (I think)
sslscan <host:port>
sslyze --regular <ip:port>

Information about SSL/TLS vulnerabilities:

Spidering

Lanza algún tipo de spider dentro de la web. El objetivo del spider es encontrar la mayor cantidad de rutas posible desde la aplicación testeada. Por lo tanto, se debe usar web crawling y fuentes externas para localizar la mayor cantidad de rutas válidas posible.

  • gospider (go): HTML spider, LinkFinder en archivos JS y fuentes externas (Archive.org, CommonCrawl.org, VirusTotal.com).
  • hakrawler (go): HML spider, con LinkFider para archivos JS y Archive.org como fuente externa.
  • dirhunt (python): HTML spider, también indica “juicy files”.
  • evine (go): CLI interactivo HTML spider. También busca en Archive.org
  • meg (go): Esta herramienta no es un spider pero puede ser útil. Puedes indicar un archivo con hosts y un archivo con paths y meg hará fetch de cada path en cada host y guardará la respuesta.
  • urlgrab (go): HTML spider con capacidades de renderizado JS. Sin embargo, parece estar sin mantenimiento, la versión precompilada es antigua y el código actual no compila
  • gau (go): HTML spider que usa proveedores externos (wayback, otx, commoncrawl)
  • ParamSpider: Este script encontrará URLs con parámetros y las listará.
  • galer (go): HTML spider con capacidades de renderizado JS.
  • LinkFinder (python): HTML spider, con capacidades de JS beautify capaz de buscar nuevas rutas en archivos JS. También puede valer la pena mirar JSScanner, que es un wrapper de LinkFinder.
  • goLinkFinder (go): Para extraer endpoints tanto del source HTML como de archivos javascript embebidos. Útil para bug hunters, red teamers, infosec ninjas.
  • JSParser (python2.7): Un script python 2.7 que usa Tornado y JSBeautifier para parsear URLs relativas desde archivos JavaScript. Útil para descubrir fácilmente peticiones AJAX. Parece estar sin mantenimiento.
  • relative-url-extractor (ruby): Dado un archivo (HTML) extraerá URLs usando una expresión regular ingeniosa para encontrar y extraer URLs relativas de archivos “feos” (minificados).
  • JSFScan (bash, varias herramientas): Recolecta información interesante de archivos JS usando varias herramientas.
  • subjs (go): Encuentra archivos JS.
  • page-fetch (go): Carga una página en un headless browser e imprime todas las urls que se cargaron para renderizar la página.
  • Feroxbuster (rust): Herramienta de discovery de contenido que mezcla varias opciones de las herramientas anteriores
  • Javascript Parsing: Una extensión de Burp para encontrar paths y params en archivos JS.
  • Sourcemapper: Una herramienta que, dado el .js.map URL, te obtiene el código JS beautified
  • xnLinkFinder: Herramienta usada para descubrir endpoints para un target dado.
  • waymore: Descubre links desde la wayback machine (también descargando las respuestas en la wayback y buscando más links)
  • HTTPLoot (go): Crawl (incluso rellenando forms) y también encuentra info sensible usando regexes específicas.
  • SpiderSuite: Spider Suite es un avanzado crawler/spider GUI multifunción diseñado para profesionales de ciberseguridad.
  • jsluice (go): Es un paquete Go y una herramienta de línea de comandos para extraer URLs, paths, secrets y otros datos interesantes del código fuente JavaScript.
  • ParaForge: ParaForge es una simple Burp Suite extension para extraer los parámetros y endpoints de las requests para crear wordlists personalizadas para fuzzing y enumeración.
  • katana (go): Excelente herramienta para esto.
  • Crawley (go): Imprime cada link que es capaz de encontrar.

Brute Force directories and files

Start brute-forcing from the root folder and be sure to brute-force all the directories found using this method and all the directories discovered by the Spidering (you can do this brute-forcing recursively and appending at the beginning of the used wordlist the names of the found directories).
Tools:

  • Dirb / Dirbuster - Included in Kali, old (and slow) but functional. Allow auto-signed certificates and recursive search. Too slow compared with th other options.
  • Dirsearch (python): It doesn’t allow auto-signed certificates but allows recursive search.
  • Gobuster (go): It allows auto-signed certificates, it doesn’t have recursive search.
  • Feroxbuster - Fast, supports recursive search.
  • wfuzz wfuzz -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt https://domain.com/api/FUZZ
  • ffuf - Fast: ffuf -c -w /usr/share/wordlists/dirb/big.txt -u http://10.10.10.10/FUZZ
  • uro (python): This isn’t a spider but a tool that given the list of found URLs will to delete “duplicated” URLs.
  • Scavenger: Burp Extension to create a list of directories from the burp history of different pages
  • TrashCompactor: Remove URLs with duplicated functionalities (based on js imports)
  • Chamaleon: It uses wapalyzer to detect used technologies and select the wordlists to use.

Recommended dictionaries:

Note that anytime a new directory is discovered during brute-forcing or spidering, it should be Brute-Forced.

What to check on each file found

Special findings

While performing the spidering and brute-forcing you could find interesting things that you have to notice.

Interesting files

403 Forbidden/Basic Authentication/401 Unauthorized (bypass)

403 & 401 Bypasses

502 Proxy Error

If any page responds with that code, it’s probably a bad configured proxy. If you send a HTTP request like: GET https://google.com HTTP/1.1 (with the host header and other common headers), the proxy will try to access google.com and you will have found a SSRF.

NTLM Authentication - Info disclosure

If the running server asking for authentication is Windows or you find a login asking for your credentials (and asking for domain name), you can provoke an information disclosure.
Send the header: “Authorization: NTLM TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=” and due to how the NTLM authentication works, the server will respond with internal info (IIS version, Windows version…) inside the header “WWW-Authenticate”.
You can automate this using the nmap pluginhttp-ntlm-info.nse”.

HTTP Redirect (CTF)

It is possible to put content inside a Redirection. This content won’t be shown to the user (as the browser will execute the redirection) but something could be hidden in there.

Web Vulnerabilities Checking

Now that a comprehensive enumeration of the web application has been performed it’s time to check for a lot of possible vulnerabilities. You can find the checklist here:

Web Vulnerabilities Methodology

Find more info about web vulns in:

Monitor Pages for changes

You can use tools such as https://github.com/dgtlmoon/changedetection.io to monitor pages for modifications that might insert vulnerabilities.

HackTricks Automatic Commands

HackTricks Automatic Commands ```yaml Protocol_Name: Web #Protocol Abbreviation if there is one. Port_Number: 80,443 #Comma separated if there is more than one. Protocol_Description: Web #Protocol Abbreviation Spelled out

Entry_1: Name: Notes Description: Notes for Web Note: | https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-web/index.html

Entry_2: Name: Quick Web Scan Description: Nikto and GoBuster Command: nikto -host {Web_Proto}://{IP}:{Web_Port} &&&& gobuster dir -w {Small_Dirlist} -u {Web_Proto}://{IP}:{Web_Port} && gobuster dir -w {Big_Dirlist} -u {Web_Proto}://{IP}:{Web_Port}

Entry_3: Name: Nikto Description: Basic Site Info via Nikto Command: nikto -host {Web_Proto}://{IP}:{Web_Port}

Entry_4: Name: WhatWeb Description: General purpose auto scanner Command: whatweb -a 4 {IP}

Entry_5: Name: Directory Brute Force Non-Recursive Description: Non-Recursive Directory Brute Force Command: gobuster dir -w {Big_Dirlist} -u {Web_Proto}://{IP}:{Web_Port}

Entry_6: Name: Directory Brute Force Recursive Description: Recursive Directory Brute Force Command: python3 {Tool_Dir}dirsearch/dirsearch.py -w {Small_Dirlist} -e php,exe,sh,py,html,pl -f -t 20 -u {Web_Proto}://{IP}:{Web_Port} -r 10

Entry_7: Name: Directory Brute Force CGI Description: Common Gateway Interface Brute Force Command: gobuster dir -u {Web_Proto}://{IP}:{Web_Port}/ -w /usr/share/seclists/Discovery/Web-Content/CGIs.txt -s 200

Entry_8: Name: Nmap Web Vuln Scan Description: Tailored Nmap Scan for web Vulnerabilities Command: nmap -vv –reason -Pn -sV -p {Web_Port} –script=banner,(http* or ssl*) and not (brute or broadcast or dos or external or http-slowloris* or fuzzer) {IP}

Entry_9: Name: Drupal Description: Drupal Enumeration Notes Note: | git clone https://github.com/immunIT/drupwn.git for low hanging fruit and git clone https://github.com/droope/droopescan.git for deeper enumeration

Entry_10: Name: WordPress Description: WordPress Enumeration with WPScan Command: | ?What is the location of the wp-login.php? Example: /Yeet/cannon/wp-login.php wpscan –url {Web_Proto}://{IP}{1} –enumerate ap,at,cb,dbe && wpscan –url {Web_Proto}://{IP}{1} –enumerate u,tt,t,vp –passwords {Big_Passwordlist} -e

Entry_11: Name: WordPress Hydra Brute Force Description: Need User (admin is default) Command: hydra -l admin -P {Big_Passwordlist} {IP} -V http-form-post ‘/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log In&testcookie=1:S=Location’

Entry_12: Name: Ffuf Vhost Description: Simple Scan with Ffuf for discovering additional vhosts Command: ffuf -w {Subdomain_List}:FUZZ -u {Web_Proto}://{Domain_Name} -H “Host:FUZZ.{Domain_Name}” -c -mc all {Ffuf_Filters}

</details>

> [!TIP]
> Aprende y practica Hacking en AWS:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Aprende y practica Hacking en GCP: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Aprende y practica Hacking en Azure: <img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training Azure Red Team Expert (AzRTE)**](https://training.hacktricks.xyz/courses/azrte)<img src="../../../../../images/azrte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <details>
>
> <summary>Apoya a HackTricks</summary>
>
> - Revisa los [**planes de suscripción**](https://github.com/sponsors/carlospolop)!
> - **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos en** **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Comparte trucos de hacking enviando PRs a los** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositorios de github.
>
> </details>