TExcelTAD

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 fetch requests 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 sandbox iframe without allow-same-origin, a data: 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).

<iframe src="https://shop.example.com/account">; frame.contentDocumentpage (script runs here)https://blog.example.comhttps://shop.example.comcookie session: SameSite=LaxSecure; HttpOnlyGET + cookie session200✕same origin: no (host differs)✓same site: yes (same scheme and registrable domain example.com)✓preflight: none (simple request, navigation or same origin)✓request sent: yes✓cookie attached: yes (same-site: SameSite=Lax allows it)✕script reads the response: no (cross-origin frame: contentDocument is null)

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.

html · try it yourself
<!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 with indexOf or endsWith, which app.lab.test.evil.example passes).
  • 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=), and document.domain assignments in old code.
  • DevTools: the console shows Blocked a frame with origin … from accessing a cross-origin frame and CORS errors; the Network panel's Origin and Access-Control-* headers show what the server allows.

How the holes are closed

  • Check event.origin against an exact allow-list, and validate event.data as data (never pass it to innerHTML or eval).
  • 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 sandbox frame, 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:// and https:// pages of a host share non-Secure cookies.

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?

  1. Sending any request to another origin
  2. Script reading data (DOM, storage, responses) that belongs to another origin
  3. Loading images from other sites
  4. Following links

In the demo, what crossed between the playground and its child frame?

  1. The secret variables, in both directions
  2. Only the DOM
  3. Only postMessage messages, reported with origin "null"
  4. Nothing at all

Which postMessage receiver check is correct?

  1. e.origin.includes('app.lab.test')
  2. e.origin === 'https://app.lab.test'
  3. e.origin !== null
  4. 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?

  1. Yes, the host is the same
  2. Yes, because it is the same site
  3. No: the port differs, so it is another origin, even though it is the same site
  4. Only with CORS headers