Track 08 · Lesson 2 of 20Attacks and defenses

Track 08 · Attacks and defenses

The same-origin policy

Lesson 2 of 20· 6 min

An origin is scheme + host + port. By default, a page can only read data from its own origin. This rule is why a random site can’t read your email in another tab.

Same origin, same site?

Pick a pair or type your own URLs

PartPage APage BMatch
SchemehttpshttpsSame
Hostapp.example.comapi.example.comDifferent
Port443 (implied)443 (implied)Same
Same origin? No

The host differs. A can link to B, embed it or submit forms to it, but can’t read B’s responses unless B allows it with CORS.

Same site? Yes

Both belong to https://example.com, so SameSite cookies are sent between them.

Same-site is looser#

app.example.com and api.example.com are different origins but the same site. That matters for cookies: SameSite stops cookies being sent from other sites, but not from your own subdomains. Browsers decide what counts as a site with the Public Suffix List, which is why two github.io pages are separate sites.

Sending is allowed, reading is not#

The same-origin policy doesn’t stop another site from making your browser send requests to your app. Links, images and forms to other sites are the whole point of the web, and the browser attaches your cookies to them. What it blocks is reading the answer.

What can evil.example do to your bank?

Switch the cookie’s SameSite value

Your bank cookie:
  • A normal link to bank.example/statements

    <a href="https://bank.example/statements">
    Request sentCookie attachedCan’t read the answer

    The statements page opens in a new tab. evil.example can’t see it.

  • An image tag pointing at the bank

    <img src="https://bank.example/avatar.png">
    Request sentNo cookieCan’t read the answer

    The image shows, but evil.example can’t read its pixels: drawing it taints the canvas.

  • A hidden form that posts a transfer

    <form method="POST" action="https://bank.example/transfer">
    Request sentNo cookieCan’t read the answer

    No cookie goes along, so the bank sees a logged-out request and refuses.

  • fetch() of the balance, with credentials

    fetch("https://bank.example/api/balance", { credentials: "include" })
    Request sentNo cookieCan’t read the answer

    The request reaches the bank, but the browser hides the response: CORS error.

  • Frame the bank and read its page

    frame.contentDocument.body.innerText
    Request sentNo cookieCan’t read the answer

    The frame may show, but reading it throws SecurityError: Blocked a frame with origin “https://evil.example”.

Lax sends the cookie only when you follow a link. Requests other sites start in the background go without it. Reading is blocked either way.

So other sites can make your browser do things; they just can’t see the result. That gap is where CSRF lives, a few lessons from now.

Check yourself

evil.example submits a hidden form to your API. What does the same-origin policy stop?