Template engines, such as Thymeleaf or Freemarker, provide automatic escaping of template variables to prevent cross-site scripting (XSS) attacks, but this protection can be explicitly disabled.

Why is this an issue?

Template engines provide auto-escaping as a safety mechanism that transforms HTML special characters in variable output before rendering, preventing user-controlled input from being interpreted as HTML or JavaScript by the browser. Disabling this protection — through settings like autoescape: false, escape-bypass filters like |safe, or equivalent configuration — allows untrusted input to pass through unmodified and be executed by the browser as markup or script.

What is the potential impact?

When auto-escaping is disabled, an attacker who can control the content of template variables can inject malicious HTML or JavaScript into pages served to other users. An attacker could steal session tokens, redirect users to phishing pages, or perform unauthorized actions on behalf of the victim.

How to fix it in JMustache

Code examples

The following examples configure the template engine to disable its auto-escaping feature, allowing template variables to be rendered without HTML encoding.

Noncompliant code example

Mustache.compiler().escapeHTML(false).compile(template).execute(context); // Noncompliant
Mustache.compiler().withEscaper(Escapers.NONE).compile(template).execute(context); // Noncompliant

Compliant solution

Mustache.compiler().compile(template).execute(context); // Compliant, auto-escaping is enabled by default
Mustache.compiler().escapeHTML(true).compile(template).execute(context); // Compliant

How to fix it in FreeMarker

Code examples

The following examples configure the template engine to disable its auto-escaping feature, allowing template variables to be rendered without HTML encoding.

Noncompliant code example

freemarker.template.Configuration configuration = new freemarker.template.Configuration();
configuration.setAutoEscapingPolicy(DISABLE_AUTO_ESCAPING_POLICY); // Noncompliant

Compliant solution

freemarker.template.Configuration configuration = new freemarker.template.Configuration();
configuration.setAutoEscapingPolicy(ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY); // Compliant

Resources

Documentation

Standards