XSS (Cross-Site Scripting): The Injection Attack

XSS (Cross-Site Scripting): The Injection Attack in JavaScript: Imagine a guest comes to your house and leaves a "Post-it" note on your fridge.

Concept Explanation

Imagine a guest comes to your house and leaves a "Post-it" note on your fridge. Normal Guest: Writes "Thanks for the coffee!" XSS Attacker: Writes a magic spell on the note that, when you read it, forces you to give them your house keys.

In JS, XSS happens when an attacker injects a <script> into your page. This script can steal the user's login cookies or redirect them to a fake bank website.


Syntax or Core Structure

The Danger

// DANGEROUS: If 'userInput' is " <script>steal()</script> ", it will run!
document.getElementById('welcome').innerHTML = userInput;

The Defense

// SAFE: This treats the input as literal text, not HTML
document.getElementById('welcome').innerText = userInput;

Best Practices

  • Sanitize: Use a library like DOMPurify if you absolutely MUST render HTML from a user.
  • Content Security Policy (CSP): This is a browser feature that tells the website: "Only run scripts that come from MY server. Ignore all others."
  • HttpOnly Cookies: Tell the browser: "Only the server can read this cookie. JavaScript is not allowed to touch it." This stops 90% of token theft.

Practice Exercises

  1. The Sanitizer: Write a small function that replaces < with &lt; and > with &gt; in a string.
  2. The CSP Explorer: Look at the "Network" tab on a site like Facebook. Find the content-security-policy header and try to understand one part of it.
  3. The Cookie Policy: Research what the SameSite=Strict flag does for cookies.