ENES

Cross-site scripting

Sneaking code into a website so it runs in other visitors' browsers.

An attacker posts a comment with hidden code to a site; the site shows it to another visitor, whose browser runs it and sends their session cookie to the attacker

Websites constantly show text that someone else wrote: comments, product reviews, usernames, the words you searched for. Cross-site scripting, almost always called XSS, happens when a site shows that text without making sure it stays text. If an attacker writes a comment that contains a bit of JavaScript disguised inside HTML, and the site pastes it into the page as is, every visitor's web browser reads it as part of the page and runs it.

That code runs with the site's own identity. It can read what the page shows, act as the logged-in visitor (post, change settings, send messages), show a fake login box, or grab session cookies so the attacker can take over the account. The visitor did nothing wrong: they opened a trusted site. The flaw is in the site, which let an outsider's code into its pages.

There are a few versions. Stored XSS lives in the site's database, like the comment above, and hits everyone who views it. Reflected XSS bounces off a link: the malicious bit is in the URL and the page echoes it back to whoever clicks. DOM-based XSS happens entirely inside the browser, in the site's own JavaScript.

The defenses are well known. Developers escape or encode anything that came from outside before putting it in a page, so < shows up as the character instead of starting a tag; modern frameworks do this automatically. A Content Security Policy tells the browser which scripts the site actually expects, and marking session cookies as HttpOnly keeps scripts from reading them. OWASP's guidance covers all of this in detail.

Keep in mind

Go deeper

Related terms

More in Security