0

Given that Same Origin Policy prevents JavaScript from one origin from running in another origin and accessing another origin's cookies, why is CSP necessary?

Is it that CORS selectively removes some protections of SOP, and CSP is an attempt to add some of those protections back? I think I have a fundamental misunderstanding of how these elements interact.

1
  • 2
    Because I can inject my code into your DOM with XSS and SOP can't do anything against that. From the browser's point of view, it's your code.
    – user163495
    Mar 24, 2022 at 16:20

1 Answer 1

1

Suppose you have a website where people can post artwork. Artists who post their artwork on the site can also post their bitcoin address, so that people can send a donation to an artist if they like the artist's work. Users can also post comments about other users' artwork.

Now, suppose there is a piece of artwork that is really popular. The page on the site where this particular piece of artwork is hosted gets thousands of page views per day, and a fair number of people make donations to the artist by sending bitcoin to the artist's bitcoin address.

An attacker sees that the site is designed such that the author's bitcoin address is contained in a <div> element on the page, like so:

<div id=divbitcoinaddress>12mEaXDMYPTFTMkuraoTMk8zVEFrPvve7W</div>

where 12mEaXDMYPTFTMkuraoTMk8zVEFrPvve7W is the author's bitcoin address.

So, the attacker posts a comment that contains:

<script>divbitcoinaddress.innerText='1Jhr6tVXvEsdz6WKpbrG5BkD45BuNXWZB9';</script>

where 1Jhr6tVXvEsdz6WKpbrG5BkD45BuNXWZB9 is the attacker's bitcoin address.

The comment is stored in the site's database, along with all of the other comments. When a user surfs to the page, and the page loads, the server serves the page, including the comment, as it should. Then, the user's browser runs the scripting in the <script> tag, and now the author's bitcoin address has been replaced with the attacker's.

Same Origin Policy (SOP) will not stop this attack, because there is no cross-origin activity here. The malicious code was served from the same origin as the rest of the site.

However, Content Security Policy (CSP) could have prevented this attack. If the site has a strict CSP that prohibits inline scripting, then this would prevent the malicious script from running.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .