Exploring the Relationship Between XSS, CSRF, and the Same-Origin Policy
This quick outline is meant to map how the three relate. Once the big picture is clear, you can dive into other resources for the finer points.
Overview
SOP
The browser’s same-origin policy is enforced by the browser itself, and every mainstream browser ships with it.
- What it protects: user data stored by a trusted site (for example, cookies after sign-in).
- How it protects: a malicious site cannot issue AJAX requests to a trusted site across origins, so the attacker site can’t retrieve responses that include a victim’s cookies. Although a malicious page can embed resources such as
<script>
tags from the trusted site, it is not allowed to read the returned data. - How attackers work around it: JSONP (the requesting page defines a callback ahead of time, tells the trusted site which callback to call, and the trusted site returns JavaScript that invokes it — this requires the trusted site to cooperate); the trusted site can also set
Access-Control-Allow-Origin
to list third-party origins that are allowed to make cross-origin requests (i.e., CORS).
CSRF
Cross-Site Request Forgery focuses on “forging a user’s actions on the trusted site from a malicious site.”
- What it protects: operations that manipulate a user’s data on the trusted site (for example, requests that delete user data).
- How the attack works: the malicious site sends a request to the trusted site; if that alone can trigger the unwanted action, it’s a CSRF attack.
- How to defend: use CSRF tokens.
XSS
Cross-Site Scripting focuses on “injecting JavaScript into the trusted site the user is viewing in order to launch an attack.”
- What it protects: user data on the trusted site.
- How the attack works: attackers inject JavaScript through vulnerabilities such as comment boards or crafted links on the trusted site. When the victim loads the page, the script can, for instance, read the user’s cookies and send them to the attacker’s server.
- How to defend: set cookies with
HttpOnly
so JavaScript cannot read them; define a Content Security Policy (CSP) so the trusted site explicitly whitelists which third-party origins it will load resources from.
Relationships
Why SOP Alone Can’t Stop CSRF
The same-origin policy only blocks JavaScript from reading the response of a cross-origin request, not from sending one. If the attack succeeds simply by sending the request, SOP does not stand in the way. SOP’s core goal is to stop an attacker-controlled site from retrieving data from a trusted origin.
Why XSS Can Still Send Data to a Malicious Origin Despite SOP
As long as the malicious site sets Access-Control-Allow-Origin
to permit requests, it can accept incoming data from the victim’s browser without restriction.