XSS from bypassing template escaping

Bypassing template escaping protections

Description

Cross-site scripting can occur when a template outputs user input without appropriate escaping, or when escaped data is later interpreted as HTML.

Potential impact

  • Attackers may execute JavaScript in the browser.
  • This can lead to session theft, phishing, actions performed as the user, or disclosure of sensitive information.

Remediation

  • Keep the template engine's default automatic escaping enabled.
  • Do not put user input directly into innerHTML or unsafe/raw output blocks.
  • If HTML is necessary, allow only restricted markup processed by a trusted sanitizer.

Examples

These examples output an ordinary string in Handlebars. For other template engines, check their escaping rules.

Before

html
<div>{{{ userContent }}}</div>

After

html
<div>{{ userContent }}</div>

Explanation:

  • Before: Disabling automatic escaping or marking data as trusted with a safe filter can let user-controlled HTML or scripts run in the browser.
  • After: {{ userContent }} escapes an ordinary string as HTML text. The same approach does not automatically suit every JavaScript, URL, or other output context.

References