# Cross Site Request Forgery (CSRF)

## Overview

Cross Site Request Forgery (CSRF) occurs when a malicious payload causes the victim's browser to send an HTTP request on behalf of the victim without their knowledge/consent to the targeted application. CSRF attack vectors most often involve convincing a user to visit an attacker controlled website. However, if the targeted route accepts HTTP GET requests to change data then a payload can potentially be self contained on the targeted website. Most often a CSRF exploit is contained on an attacker controlled website and upon the targeted user visiting this website, the JavaScript payload automatically triggers without user interaction and sends a HTTP request on the user's behalf. This HTTP request targets functionality to modify data. Common targets include user settings, password change functionality and email change functionality.&#x20;

The most common defense against this attack is to have the backend send an anti-forgery token (a long random Nonce) to the front end for any future HTTP POST/PUT requests such as a web form. This token is then contained on the user's front-end until it is used in a HTTP request to the backend which verifies the token for the request, proving the authenticity of the request.&#x20;

## Example&#x20;

This example is from Appsecco's DVNA. The route which handles modifying products at `http://127.0.0.1:9090/app/modifyproduct` is vulnerable to CSRF, it does not have an anti-CSRF token.&#x20;

If a victim user browses to a malicious webpage that contains the code below, it will add a new product to the application as that victim user.&#x20;

```
<html>
    <body onload='document.hidden_form.submit()'>
        <form name="hidden_form" method="POST" action="http://127.0.0.1:9090/app/modifyproduct">
            <input type="hidden" name="name" value="Hacked">
            <input type="hidden" name="code" value="hacked">
            <input type="hidden" name="tags" value="hack">
            <input type="hidden" name="description" value="This is a hacked product">
        </form>
    </body>
</html>
```

The code is a simple form that executes on the webpage loading, sending a HTTP POST request to the _modifyproduct_ route to upload a new product as the victim user.&#x20;

The remediation to this vulnerability is to implement anti-CSRF tokens in the application. This could be done by adding custom middleware to the functions that handle each route or by using a pre-existing NPM module like [csurf](https://www.npmjs.com/package/csurf). In Appsecco's DVNA case they implemented the csurf module to protect the entirety of the application.&#x20;

For CSRF remediation check out the OWASP cheat sheet series below.&#x20;





{% embed url="https://portswigger.net/web-security/csrf" %}

{% embed url="https://owasp.org/www-community/attacks/csrf" %}

{% embed url="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" %}

