Application security XSS 4 min read
What is XSS?
A comment box inserts each comment into the page as HTML. Someone posts a comment with a <script> tag in it. What happens when other people open the page?
-
Text inserted as HTML runs as code
The site stores the comment and serves it to everyone who opens the page. Because it’s inserted as HTML, the
<script>tag isn’t displayed. It runs.The browser can’t tell the site’s own code from code that arrived inside a comment. It all runs with the page’s permissions: it can read what’s on the page and make requests as whoever is signed in.
A commenter posts a comment containing a script tag. The site stores it and later serves the page to Priya with the comment inserted as HTML. Priya’s browser runs the script as part of the site.
The attacker never touched Priya’s browser directly. In short If untrusted text is inserted as HTML, it can run in other people’s browsers.
-
Show untrusted text as text
The fix is encoding on output. It turns
<into<, so the browser displays the characters instead of running them.element.textContent = commentdoes this;element.innerHTML = commentdoesn’t.Frameworks like React and most template engines encode by default. The danger is the escape hatches:
dangerouslySetInnerHTML,document.write, and links placed inhrefwithout checking they start withhttps:.Same comment, two outcomes. Encoded, it’s just characters on the screen. In short Encode on output, and be suspicious of every escape hatch.
What a Content Security Policy doesn’t replace
A Content Security Policy that only allows the site’s own scripts blocks many attacks. But policies have gaps, and they’re easy to loosen by accident.
Treat it as a safety net, not the fix. Encoding is the wall. HttpOnly cookies keep the session cookie out of a script’s reach, but the script can still act inside the page.
Keep this
Show untrusted text as text, never as HTML. Encoding on output is the fix.
Frameworks encode by default; the danger is the escape hatches like innerHTML. A Content Security Policy is a safety net, not the fix.- Cause
- Untrusted text inserted as HTML.
- Effect
- It runs as script, with the page’s permissions.
- Fix
- Encode output: show text as text.
- Safety net
- A Content Security Policy limits what runs.
Questions worth carrying
What are stored, reflected and DOM XSS?
Where the untrusted text comes from: saved on the server (stored), bounced back from the request (reflected), or read by page scripts from the URL or page (DOM). Same fix for all three.
What if I really need to show user HTML?
Run it through a well-maintained sanitiser library with a strict allow-list of tags, and keep a Content Security Policy as backup.