HACKORY
Language · English
← All chapters
HACKORY / Open library

Cross-site scripting (XSS)

XSS (cross-site scripting) happens when text someone wrote, such as a comment, ends up working as code inside the page another person sees.

New here? Try the first lesson without an account

How it works

A page can paste a text in two ways. Pasting as text (textContent) shows the < and > signs as they are. Pasting as HTML (innerHTML) asks the browser to read tags and turn them into parts of the page, code included. The flaw appears when someone else’s data is pasted as HTML: in the same response (reflected), saved for later visits (stored), or built by JavaScript in the DOM.

Expected behavior

A comment containing < and > appears as text on the page.

What can go wrong

The same comment is pasted with innerHTML and the browser reads it as tags that can run code.

What to observe

With a test account, look at how the DOM ended up and where the text landed: as visible text or as tags.

Common false positive

Seeing the text in the response is not enough: it has to reach a place where the browser runs it.

Why it matters

That code runs as if it belonged to the site: it can change the page or send requests with the session of whoever is viewing it.

How to fix it

Display data as text, encode it for the place where it is inserted, do not paste as HTML what another person wrote, and add CSP, a header that tells the browser which origins it may load scripts from.

Understand it step by step

Context decides

Think about pasting into a document: “paste as plain text” keeps the signs as they are; “paste with formatting” interprets what they bring. The same happens in a page. With textContent, <b>hola</b> is shown literally. With innerHTML, the browser creates bold text and, if the text brings a tag with code, also makes it executable. The same input is safe in one case and dangerous in the other.

Three paths

In reflected XSS, the input comes back in the response to the same request. In stored XSS, it is saved and appears in other people’s visits. In DOM XSS, JavaScript takes data from the browser itself, such as what comes after # in the address, and modifies the page without the server returning that HTML. To investigate them, find where the data comes from and the exact point where it is interpreted.

The defense that fits the place

Displaying as text is the simple choice for data that does not need HTML. If a product accepts HTML, such as a note editor with bold text, it must clean it with a strict list of allowed tags. CSP is a response header with which the site tells the browser where it may load scripts from: it reduces the consequences, but it does not make inserting data as code safe. To confirm XSS you must show that something ran on the affected site, not just that the characters appear.

Recommend this chapter to a friend