Cross-Site Scripting (XSS) occurs when an application includes malicious script code in web pages sent to visitors without proper sanitization, allowing attackers to hijack sessions.
1. Main XSS Types
- Stored XSS: The exploit payload is permanently saved in database tables (like user comments) and executed every time users load the page.
- Reflected XSS: The payload is passed via parameter URLs and executed immediately when the page reflects the parameters back.
- DOM-based XSS: The vulnerability is entirely client-side, executing when JavaScript updates page contents dynamically based on user parameters.
2. Mitigation: Context-Aware Output Encoding
To secure pages, treat all dynamic text variables as plain text rather than active HTML. Use HTML sanitization libraries and output encoding methods before rendering variables.
Vulnerable JavaScript code:
document.getElementById("output").innerHTML = userInput;
Secure JavaScript code:
document.getElementById("output").textContent = userInput;
Defensive Tip: Set up strict Content Security Policies (CSP) headers to block unauthorized external script loading.