Cross-Site Scripting (XSS) allows attackers to inject and execute malicious scripts in a victim’s browser. This often happens when user input is not properly sanitized before being rendered on a webpage.
Reflected vs. Stored XSS
Reflected XSS: The payload is delivered via a crafted URL and reflected by the server in the response (e.g., search results).
Stored XSS: The payload is permanently stored on the server (e.g., in a comment or profile field) and served to all users who view that page.
Mitigation
Input Validation: Reject or sanitize unexpected input at server side.
Output Encoding: Encode data according to the HTML context (e.g., HTML, JavaScript, or URL attributes).
Content Security Policy (CSP): Restrict sources of scripts and inline execution.
Example Attack Vector
Example inline payload: <script>alert('XSS');</script>
Best Practice Summary
Always encode user input before rendering it in HTML.
Use frameworks that auto-escape output (e.g., React, Django).
Implement a strict Content Security Policy (CSP).
Regularly scan your site using tools like OWASP ZAP or Burp Suite.