ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Cyber Security Tutorial• 7 min read

Cross-Site Scripting (XSS) & Content Security Policy

Stored vs Reflected vs DOM XSS, output encoding, and CSP headers

Cross-Site Scripting (XSS) enables attackers to inject malicious client-side JavaScript into web applications viewed by other users, stealing session cookies or impersonating accounts.

The Three Types of XSS Attacks

Stored XSS: The malicious script is permanently stored in the database (e.g. in a blog comment or user bio) and executed whenever other users view the page.

Reflected XSS: The malicious script is reflected off the web server in an immediate response (e.g. in search results: ?q=<script>...).

DOM-based XSS: The vulnerability exists purely in client-side JavaScript that writes untrusted input into the DOM (e.g. element.innerHTML = location.hash).

Defense: Context-aware HTML escaping, using textContent instead of innerHTML, and enforcing strict Content Security Policy (Content-Security-Policy: default-src 'self') headers.

Safe DOM Manipulation in JavaScript
const untrustedInput = "<img src=x onerror=alert('Stealing cookies!')>";

// VULNERABLE TO DOM XSS:
// document.getElementById("profile").innerHTML = untrustedInput;

// SECURE: textContent treats input strictly as harmless plain text!
document.getElementById("profile").textContent = untrustedInput;
// Renders the literal text on screen without executing the JavaScript!
textContent automatically escapes HTML characters, preventing script execution.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which HTTP response header tells the browser which external scripts, images, and styles are authorized to load, mitigating XSS attacks?