# XSS vs. CSRF

## Differences between XSS and CSRF

{% hint style="info" %}

* **XSS** allows an attacker to execute arbitrary JavaScript within the browser of a victim user.
* **CSRF** allows an attacker to induce a victim user to perform actions that they do not intend to.
  {% endhint %}

The consequences of XSS vulnerabilities are generally more serious than for CSRF vulnerabilities:

* **Different Scopes**
  * CSRF often only applies to a subset of actions that a user is able to perform. Many applications implement CSRF defenses in general but overlook one or two actions that are left exposed.
  * Conversely, a successful XSS exploit can normally induce a user to perform any action that the user is able to perform, regardless of the functionality in which the vulnerability arises.
* **One-way vs. Two-way**
  * CSRF can be described as a "one-way" vulnerability, in that while an attacker can induce the victim to issue an HTTP request, they cannot retrieve the response from that request.
  * Conversely, XSS is "two-way", in that the attacker's injected script can issue arbitrary requests, read the responses, and exfiltrate data to an external domain of the attacker's choosing.

## CSRF Tokens for XSS

{% hint style="info" %}
Some XSS attacks can be prevented through effective use of CSRF tokens.
{% endhint %}

Consider a simple reflected XSS vulnerability that can be trivially exploited like this:

```uri
https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>
```

Now, suppose that the vulnerable function includes a CSRF token:

```uri
https://insecure-website.com/status?csrf-token=CIwNZNlR4XbisJF39I8yWnWX9wX4WFoz&message=<script>/*+Bad+stuff+here...+*/</script>
```

Assuming that the server properly validates the CSRF token, and rejects requests without a valid token, then the token does prevent exploitation of the XSS vulnerability. The clue here is in the name: "cross-site scripting", at least in its reflected form, involves a **cross-site request**. By preventing an attacker from forging a cross-site request, the application prevents trivial exploitation of the XSS vulnerability.

## Reference

{% embed url="<https://portswigger.net/web-security/csrf/xss-vs-csrf>" %}
XSS vs CSRF - Web Security Academy
{% endembed %}
