The Same-Origin Policy
Your browser right now may hold a webmail tab, a bank tab and a page with adverts from a dozen companies. All of them run JavaScript, and all of that JavaScript can make requests with your cookies. What stops the advert from reading your email? The same-origin policy (SOP): script from one origin may not read data belonging to another origin. It is the browser's oldest and most important security rule, and the reason most web attacks try either to get inside an origin (XSS) or to make the origin send something without reading the answer (CSRF). This lesson shows the rule working inside a sandboxed frame on this page, then the sanctioned ways around it.
Definitions
- Origin: (scheme, host, port), as in the trust-model lesson.
- Same-origin policy: a script may read the DOM, storage and HTTP responses of its own origin only. Cross-origin, it may still write (navigate, submit forms, send
fetchrequests without credentials-reading), embed (<img>,<script>,<iframe>,<link rel=stylesheet>), but not read what comes back. - Opaque origin: a unique origin that equals no other, not even itself across documents. A
sandboxiframe withoutallow-same-origin, adata:URL document and some redirects get one; it serialises as the string"null". - postMessage: the sanctioned channel between windows of different origins. The sender names the target origin; the receiver must check
event.origin. - CORS: the server-side opt-in that lets a named origin read a response (next lesson).
What is allowed, at a glance
| Action from origin B on origin A | Allowed? | Why it matters |
|---|---|---|
| Link or navigate to A, submit a form to A | yes | CSRF uses this: the request happens |
<img src>, <script src>, <link> from A |
yes, embed only | B can't read the bytes, but a <script> from A runs in B's origin (so JSON that is valid JavaScript has leaked in the past) |
fetch(A) and read the body |
only if A sends CORS headers allowing B | the main thing SOP protects |
Read iframe.contentDocument of an A frame |
no | the frame is A's |
Read A's cookies or localStorage |
no | storage is per origin (cookies per site/host) |
frame.postMessage(data, "https://A") |
yes | the receiver decides whether to trust it |
The same-origin lab checks one request at a time against https://shop.example.com and lists every decision the browser makes. It starts with a page on https://blog.example.com that frames the shop's account page and tries to read the frame's DOM: not the same origin (the host differs), although it is the same site (example.com), and contentDocument is null. Switch the page to https://shop.example.com:8443: only the port differs, and the answer is the same. Only https://shop.example.com itself can read the frame. Try <img> too: the image is sent and shown, but its pixels stay unreadable (a tainted canvas).
The rule, running
The playground below is itself a sandboxed frame with an opaque origin. Inside it the script creates a child frame that holds a secret. Sandbox flags are inherited by nested frames, so the child gets its own opaque origin: to the playground it is a foreign origin, just as bank.lab.test would be to evil.example. The parent tries to read the child's secret and DOM, the child tries to read its parent, and finally the two talk the sanctioned way, with postMessage.
<!doctype html>
<style>body{font:14px system-ui;margin:8px} iframe{width:60%;height:50px;border:1px solid #999} pre{background:#8881;padding:6px}</style>
<iframe id="child"></iframe>
<pre id="log"></pre>
<script>
window.secret = 'parent-4410';
const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
const child = document.getElementById('child');
child.srcdoc = `<body>child frame, secret child-7731<script>
window.secret = 'child-7731';
let r;
try { r = 'read ' + parent.secret; } catch (e) { r = 'blocked, ' + e.name; }
parent.postMessage('child reading parent.secret: ' + r, '*');
addEventListener('message', (e) => {
// A careful receiver checks who is asking; here only the parent window is answered.
if (e.source === parent) parent.postMessage('reply: here is the public part only', '*');
});
<\/script></body>`;
addEventListener('message', (e) => log(`message from origin "${e.origin}": ${e.data}`));
log('own data: ' + window.secret);
setTimeout(() => {
try { log('parent reading child.secret: read ' + child.contentWindow.secret); }
catch (e) { log('parent reading child.secret: blocked, ' + e.name); }
log('parent reading child DOM: ' + child.contentDocument);
try { log('playground reading the lesson page: ' + window.parent.document.title); }
catch (e) { log('playground reading the lesson page: blocked, ' + e.name); }
child.contentWindow.postMessage('hello', '*');
}, 300);
</script>Every read across the boundary fails: contentWindow.secret throws a SecurityError and contentDocument is simply null, in both directions. The playground can't read the lesson page that contains it either, which is exactly why XSS demos in this course are harmless. In an ordinary page a child frame from the same origin would be fully readable; here even siblings are isolated because the sandbox makes every document a fresh origin. The only thing that crosses is postMessage, and the origin it reports is "null": opaque origins can't be told apart, so a receiver that must trust a sender should never accept "null".
How SOP bypasses are detected
Real applications rarely break SOP itself; they open holes in it and those holes are what you look for:
- postMessage handlers without an origin check: search the JavaScript for
addEventListener('message'and read the first lines of each handler.if (e.origin !== 'https://app.lab.test') return;should be there, compared exactly (not withindexOforendsWith, whichapp.lab.test.evil.examplepasses). postMessage(data, '*')with sensitive data: anyone who framed or opened the page receives it.- CORS headers that reflect any origin (next lesson), JSONP endpoints (
?callback=), anddocument.domainassignments in old code. - DevTools: the console shows
Blocked a frame with origin … from accessing a cross-origin frameand CORS errors; the Network panel'sOriginandAccess-Control-*headers show what the server allows.
How the holes are closed
- Check
event.originagainst an exact allow-list, and validateevent.dataas data (never pass it toinnerHTMLoreval). - Always name the target origin when sending:
win.postMessage(data, 'https://app.lab.test'). - Replace JSONP with CORS restricted to known origins; remove
document.domain(modern browsers are phasing it out behind origin-keyed agent clusters). - Put untrusted content (user uploads, previews, third-party widgets) on a separate origin or in a
sandboxframe, as this site does for every playground.
Pitfalls
- SOP does not stop requests, only reading. Anything that changes state on a simple request needs CSRF protection.
- Script includes run in the includer's origin.
<script src="https://cdn.example/lib.js">gives that CDN full power over your page; pin versions and use Subresource Integrity (integrity="sha384-…"). - Cookies are not origin-scoped: they follow host and site rules, so
http://andhttps://pages of a host share non-Securecookies.
Practice
1. A handler does if (e.origin.endsWith('lab.test')) { el.innerHTML = e.data }. Find two bugs.
endsWith('lab.test') also accepts evil-lab.test (and any subdomain an attacker controls); compare exactly with an allow-list. innerHTML with message data is a DOM XSS sink; use textContent or parse structured data.
2. Why can a page on evil.example embed <img src="https://shop.lab.test/logo.png"> but not read the image's pixels with a canvas?
Embedding is allowed cross-origin; reading is not. Drawing a cross-origin image without CORS "taints" the canvas, and getImageData then throws a SecurityError.
Test yourself
What does the same-origin policy prevent?
- Sending any request to another origin
- Script reading data (DOM, storage, responses) that belongs to another origin
- Loading images from other sites
- Following links
In the demo, what crossed between the playground and its child frame?
- The secret variables, in both directions
- Only the DOM
- Only postMessage messages, reported with origin "null"
- Nothing at all
Which postMessage receiver check is correct?
- e.origin.includes('app.lab.test')
- e.origin === 'https://app.lab.test'
- e.origin !== null
- No check is needed with HTTPS
In the same-origin lab, a page on https://shop.example.com:8443 frames https://shop.example.com/account. Can its script read the frame's DOM?
- Yes, the host is the same
- Yes, because it is the same site
- No: the port differs, so it is another origin, even though it is the same site
- Only with CORS headers