Sign in to save

Bookmark this page so you can find it later.

Sign in to save

Bookmark this page so you can find it later.

Cross Site Scripting, or XSS, happens when an attacker gets a browser to run untrusted script as if it came from a trusted site. This cheat sheet helps students recognize where XSS enters an app, where it is rendered, and which defenses match each output context. It is organized as a printable reference with three sections: How XSS Happens, Context-Aware Output Encoding, and Browser & App Defenses.

Students need these rules because one unsafe template, URL, attribute, or DOM update can expose accounts and private data.

The most important idea is that output must be encoded for the exact place where it appears, such as HTML text, an HTML attribute, JavaScript, CSS, or a URL. Input validation helps reject unexpected data, but it does not replace output encoding. Strong browser and app defenses include Content Security Policy, HttpOnly cookies, SameSite cookies, safe DOM APIs, and trusted libraries.

Secure XSS defense uses layers, because no single rule catches every possible attack path.

Key Facts

  • Stored XSS occurs when malicious input is saved by the app and later displayed to users, such as a comment containing <script>alert(1)</script>.
  • Reflected XSS occurs when a request value is immediately included in a response, such as /search?q=<script>alert(1)</script>.
  • DOM-based XSS occurs when client-side JavaScript writes untrusted data into the page with unsafe sinks such as element.innerHTML = userInput.
  • For HTML text content, encode the characters & as &amp;, < as &lt;, > as &gt;, " as &quot;, and ' as &#x27; before output.
  • For HTML attributes, quote every attribute value and encode at least &, <, >, ", and ', such as <div title="encodedValue">.
  • For URLs, allow only safe schemes such as https and encode parameter values with encodeURIComponent(value), not by string concatenation.
  • Use safe DOM APIs when possible, such as element.textContent = userInput instead of element.innerHTML = userInput.
  • A strong Content Security Policy can reduce damage, such as Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-randomValue'; object-src 'none'.

Vocabulary

Cross Site Scripting
A web security flaw where untrusted input is executed by a browser as active script in a trusted page.
Output Encoding
The process of converting characters with special meaning into safe text for a specific output context.
Context
The location where data is inserted, such as HTML text, an attribute, a script block, CSS, or a URL.
Content Security Policy
A browser security policy that limits which scripts, styles, images, and other resources a page is allowed to load or run.
Safe Sink
A DOM property or method that treats input as text instead of executable markup, such as textContent.
HttpOnly Cookie
A cookie setting that prevents JavaScript from reading the cookie through document.cookie.

Common Mistakes to Avoid

  • Using the same encoding everywhere is wrong because HTML text, attributes, JavaScript, CSS, and URLs follow different parsing rules.
  • Relying only on input validation is wrong because valid-looking input can still become dangerous when placed in an unsafe output context.
  • Writing user input with innerHTML is wrong because the browser parses the input as markup and may execute scripts or event handlers.
  • Building links by string concatenation is wrong because attacker-controlled values can break out of parameters or introduce unsafe schemes such as javascript:.
  • Disabling CSP errors without fixing them is wrong because CSP warnings often reveal unsafe inline scripts, missing nonces, or overly broad sources.

Practice Questions

  1. 1 A profile page displays 3 user-controlled fields: display name in HTML text, website in an href attribute, and bio through innerHTML. List the correct defense for each field.
  2. 2 A form has 5 inputs, but only 2 are later shown on a page. How many outputs need context-aware encoding, and why?
  3. 3 Choose the safer line and explain why: element.innerHTML = comment; or element.textContent = comment;
  4. 4 Explain why a site should use both output encoding and a Content Security Policy instead of choosing only one defense.

Understanding Cross Site Scripting Defense Reference

Browsers do not see a page as one block of text. They parse it into separate languages and structures. HTML creates elements, attributes supply settings, URLs point to locations, and JavaScript gives instructions.

A dangerous value becomes a problem when the browser is tricked into treating data as part of one of those structures. This is why a value that is harmless in visible paragraph text may be unsafe inside a link, a style rule, or a script.

Developers need to know the destination of each value before they choose a defense. The important boundary is between data supplied by a person or another system and code or markup interpreted by the browser.

Modern template systems can reduce mistakes because many escape ordinary text by default. That protection can disappear when a developer uses a feature meant for raw HTML output. Raw output is sometimes needed for articles, formatted comments, or help pages, but it requires a different process.

The application must sanitize the allowed HTML with a well tested library and a strict list of permitted tags and attributes. Removing a few suspicious words is not enough. Attackers can use unexpected spacing, nested markup, encoded characters, or browser parsing quirks.

Input validation still has value because it keeps data predictable. For example, an age should be a number within a sensible range, while a username can follow a limited character set. Validation improves data quality, but it cannot predict every place that valid data may later appear.

Client side code creates its own risks after the server has finished its response. Data can arrive from a URL fragment, a query value, browser storage, a message from another window, or an application programming interface response. These are common sources of untrusted data.

The risky destinations are called sinks. A sink that parses HTML can turn a string into live page elements. A safer approach is to create elements through DOM methods and place plain user text into a text node.

Even methods that set attributes need care. A title attribute and a link destination follow different browser rules.

Link destinations should be checked against an allowlist of protocols before use. Treat every value from the page, storage, or network as untrusted unless the program has established otherwise.

Browser protections limit damage when a coding mistake survives. A Content Security Policy tells the browser where scripts may load from and can require a unique nonce for approved scripts. It works best when pages avoid inline script blocks, inline event handlers, and broad permissions.

The policy is not a repair for unsafe rendering, since a weak policy or an allowed script can still be abused. HttpOnly cookies make it harder for injected code to read session cookies. SameSite settings reduce some cross site request risks, though injected code running on the site may still perform actions as the signed in user.

Students should practice tracing data from its source to its final output. During reviews, pay close attention to template escape settings, DOM updates, URL construction, and any place that accepts formatted HTML.