OWASP XSS Cheat Sheet

Cross-Site Scripting (XSS) is a common web application security vulnerability. The Open Web Application Security Project (OWASP) provides a comprehensive XSS Cheat Sheet that developers and security professionals can use to understand, prevent, and mitigate XSS attacks.

Below is an overview of some key points from the OWASP XSS Cheat Sheet:

Contexts

  • HTML Context:
    • <div>, <span>, <p>, etc.
    • <body>, <head>, etc.
    • Attributes: onclick, onload, etc.
  • Attribute Context:
    • <img src="...">, <a href="...">, etc.
    • Attributes: src, href, onerror, etc.
  • JavaScript Context:
    • <script>, <a href="javascript:...">, etc.
  • CSS Context:
    • <style>, style attributes, etc.

Payloads

Classic XSS Payloads:

<script>alert('XSS')</script>

IMG Tag Payloads:

<img src="x" onerror="alert('XSS')">

Attribute Payloads:

<a href="javascript:alert('XSS')">Click me</a>

JavaScript Execution Context Payloads:

<a href="javascript:alert('XSS')">Click me</a>

Protection

  • Output Encoding:
    • Use proper output encoding functions based on the context.
    • For HTML, use &lt; instead of <.
  • Context-Aware Auto-Escaping Libraries:
    • Use libraries that automatically escape content based on its context.
  • Content Security Policy (CSP):
    • Implement and enforce a strong Content Security Policy.
    • Define allowed sources for scripts, styles, etc.
  • HTTP-Only Cookies:
    • Set the HTTP-Only flag on cookies to prevent JavaScript access.
  • X-XSS-Protection Header:
    • Enable the browser’s XSS protection feature using the X-XSS-Protection header.

DOM-Based XSS

  • Document.URL:
    • Extract data from the URL, but be cautious about user-controlled data.
  • Document.Write:
    • Avoid using user-controlled data directly in document.write().
  • Inner HTML:
    • Be cautious when using innerHTML with user input.

Prevention Cheat Sheet

HTML Escape Before Inserting Untrusted Data into HTML Element Content:

var div = document.createElement('div');
div.appendChild(document.createTextNode(untrustedData));

Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes:

element.setAttribute('attribute', untrustedData);

JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values:

var script = document.createElement('script');
script.text = 'var data = ' + JSON.stringify(untrustedData);

URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values:

var url = 'example.com/?param=' + encodeURIComponent(untrustedData);

CSS Escape and Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values:

  • Be cautious and consider using context-aware libraries.

Remember that the effectiveness of these measures depends on proper implementation and staying informed about the latest security best practices.