Cross-site scripting and where tokens live
The browser keeps sites apart, but it trusts every script running inside a page. If someone else's script gets in, the application's tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret. storage determines what that script can steal and use elsewhere.
A script that is not yours
The same-origin policy from What browsers add judges code by the origin of the page it runs in, not by who wrote the code. If someone else's script gets into your page, the browser treats it exactly like your own.
Picture the comments under a photo in the photo app Ava uses. The page loads each comment from the server and adds it to a list with a line of JavaScript like this:
list.innerHTML += '<li>' + comment.text + '</li>';A page's script changes the page through objects the browser hands it, one for each part of the page. Here list is the comment list, which the script found earlier, and comment.text is one comment's text as the server sent it. + joins pieces of text, and += adds the result to what is already there. innerHTML is the list's content written as HTML, so whatever the script adds is read as HTML too.
A comment of Great shot! becomes a list item, as intended. A comment of <b>Great</b> shot! turns bold, which shows that the comment's text became part of the page's markup. Markup can carry code, so a comment written as markup can do much more:
<li><img src="x" onerror="sendSomewhere(localStorage)"></li>An onerror attribute holds JavaScript for the browser to run if the image fails to load. The image x does fail, so the browser runs that code in the photo app's origin, for every person who opens that photo. Running someone else's script inside a page this way is called cross-site scripting, or XSS.
XSS arrives by three routes, with one cause. In stored XSS, as here, the server saves the input and serves it to everyone who views it. In reflected XSS, the server copies a value from the request into its response, such as a search page that shows "Results for" and the search terms from the URLA web address, such as https://photos.example/api/albums/42?limit=10. It names how to connect (https), the domain, the path to a particular page or resource, and any extra parameters after the question mark., so a crafted link runs the script in the browser of whoever follows it. In DOM-based XSS, the page's own JavaScript reads a value, such as part of the URL, and writes it into the page as HTML. In each case, text that should have stayed data was treated as code.
What an injected script can reach
Browsers give each origin a small store of named values that its page scripts can read and write, called Web Storage. It comes in two kinds: localStorage keeps values until a script or the person deletes them, across restarts, and sessionStorage keeps them until the tab closes. The browser never sends either with a request on its own; a script has to read a value and put it in the request itself.
An injected script runs with the page's origin, so it can do anything the page's own scripts can:
- Read and change the page, including what the person types into it. It can add a convincing sign-in form, or read a password field.
- Read everything in
localStorageandsessionStorage. - Read every cookieA small value that a website asks the browser to store and send back with later matching requests. Cookies commonly carry a session identifier, so the site can recognize an ongoing sign-in without your password. that is not
HttpOnly, throughdocument.cookie. - Send requests to the page's own origin. The browser attaches the site's cookies,
HttpOnlyones included, and because the request is same-origin, the script reads the responses. - Send whatever it found to any other server. The same-origin policy limits reading responses, not sending requests.
It still cannot read the value of an HttpOnly cookie, or read responses from other origins that do not allow it with CORS. That leaves an important distinction. HttpOnly stops a script from taking a sessionThe ongoing connection between later requests and an earlier sign-in, so you are not asked for your password on every click. It is often tracked with a cookie holding an unpredictable session identifier. cookie away, but not from using the session through the page while the page is open. Once the person closes the page, the script stops, unless stored XSS brings it back on their next visit.
Where tokens can live
An application that calls APIs from the browser needs somewhere to keep its tokens, and each choice changes what an injected script can take. A token in localStorage lasts until something deletes it, and one in sessionStorage until the tab closes; a script can read either and send it away. A token kept only in a variable in the page's memory is gone when the page reloads, and a script cannot read it from storage, but it can change the page's code, for example its function for sending requests, and see the token the next time the page uses it. A token in an HttpOnly cookie cannot be read at all, yet the browser sends it with every matching request, including the script's. And when the application's server keeps the tokens, with only a session cookie in the browser, the tokens never reach the browser.
In localStorage
- A script can read it
- Sent with requests on its own
- Survives a reload
Read it and send it away
In sessionStorage
- A script can read it
- Sent with requests on its own
- Survives a reload
Read it and send it away
A variable in the page's memory
- A script can read it
- Sent with requests on its own
- Survives a reload
See the token the next time the page uses it
In an HttpOnly cookie
- A script can read it
- Sent with requests on its own
- Survives a reload
Send requests that carry it, including the script's
On the application's server
- A script can read it
- Sent with requests on its own
- Survives a reload
The tokens never reach the browser
No choice makes XSS harmless. While a hostile script runs in the page, it acts as the person.
No choice makes XSS harmless. While a hostile script runs in the page, it acts as the person. What the choice changes is what the attacker can carry away and use later from their own computer. A token read from storage works anywhere until it expires or is revoked, and a refresh tokenA longer-lived credential that a client sends to the authorization server, never to an API, to get new access tokens without asking the person again. taken this way can keep minting new access tokens. A token that never reaches the browser cannot be copied out of it.
That is why identity systems combine several measures: short token lifetimes, refresh tokens that are replaced each time they are used, tokens bound to a key the browser cannot export, and designs that keep tokens on a server. Browser applications and Backends for frontends compare these designs in detail. All of them start from the same place: keeping hostile scripts out of the page.
Keeping scripts out
The main defense is to keep data as data. The comment list above is safe when it sets the text instead of the HTML:
const item = document.createElement('li');
item.textContent = comment.text;
list.append(item);document is the whole page. createElement('li') makes a new, empty list item, which const item names. textContent sets the item's text, and list.append adds the item to the list. textContent never reads its value as markup, so <b> appears as the three characters you typed.
Server-side templates and modern front-end frameworks escape values by default for the same reason: < is written as <, so the browser shows it instead of starting a tag. The escaping must suit where the value lands, because HTML text, an attribute, a URL and a script each have their own special characters. Avoid the features that turn text into code, such as JavaScript's eval, inline onclick attributes and links that start with javascript:. When an application really must accept HTML from users, it passes that HTML through a sanitizer that keeps only an allowed list of harmless elements.
A second layer limits the damage when a mistake slips through. The Content-Security-Policy response header tells the browser what the page may load and run, as a list of directives separated by semicolons:
Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'none'With this policy the browser runs scripts only from files on the page's own origin ('self'). Inline code, including an onerror attribute that a comment smuggled in, does not run, and neither do scripts from other origins. object-src 'none' refuses old browser plugins, and base-uri 'none' stops injected markup from changing the address that relative links start from. Pages that need a little inline script can allow exactly those blocks with a fresh random value, called a nonceA random value used for one attempt only. In OpenID Connect, the client sends one in its sign-in request and checks that the same value comes back inside the ID token, showing the token answers this attempt., in the policy and on each block.
A response that is never meant to be a page, such as JSONA text format for structured information, written as named values inside curly braces. APIs, tokens, and discovery documents all use it. from an APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests., can carry a stricter policy:
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandboxdefault-src 'none' allows nothing to load or run. frame-ancestors 'none' stops any other page from showing this one inside a frame, the embedded window from Third-party cookies. sandbox makes the browser treat the response as an origin of its own, with scripts and forms switched off, so even if it were opened as a page it could not reach the real origin's cookies or storage.
Scripts you include on purpose run with your origin too, so every analytics or widget script from another company holds the same power as your own code. Include as few as you can. For a fixed file loaded from someone else's server, the integrity attribute on the script tag holds the file's digest, and the browser refuses the file if its bytes have changed.
Finally, an endpoint that returns data should label it honestly. A JSON response sent with Content-Type: application/json and X-Content-Type-Options: nosniff is never treated as a page or a script, even when it echoes text that looks like HTML: nosniff tells the browser to trust the label instead of guessing from the content.
Checking from the terminal
To see how a service handles input it echoes, send some markup and read where it comes back. --data-urlencode with -G puts it in the query, encoded:
curl -sS -G --data-urlencode 'name=<b>Ava</b>' https://api.example.com/echoAn echo inside a JSON string, labeled as JSON with nosniff, stays data whatever it contains. The same text copied into an HTML page without escaping would turn bold, and a comment written like the onerror example would run.
You can read the headers that limit scripts with the curl options from Sending requests with curl. -D - prints the response headers and -o /dev/null discards the body, so grep can pick out the ones that matter:
curl -sS -D - -o /dev/null https://app.example.com/ | grep -iE '^(content-type|content-security-policy|x-content-type-options):'A missing content-security-policy line does not prove a page has XSS, and a present one does not prove it is safe. It tells you whether the second layer exists, and exactly what it allows: a policy with 'unsafe-inline' in its script-src, for example, lets inline code such as that onerror attribute run again.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Read the headers that limit scripts and find what an injected script could takeRead the response headers that keep scripts out, watch echoed markup stay data, then write and test a function that finds which items in a browser's storage a script injected into the page could read.