Skip to content

Cross-site scripting (XSS)

When is it relevant

A change that puts data into an HTML, attribute, URL or script context where users or third parties can influence that data. This covers server-rendered HTML and templates, frontend code (innerHTML, dangerouslySetInnerHTML, v-html, href or src from data), and rendering of rich text, Markdown or SVG.

Attack

The attacker stores or reflects a payload, such as <img src=x onerror=…> or a javascript: link, that the browser runs as code in the victim's session. It can read data, act as the victim or take over their account. The context matters: escaping for HTML text doesn't protect attributes, URLs or script blocks.

Mitigation

  • Render data with auto-escaping templates or textContent, never string-built HTML.
  • When rich text is needed, sanitize it with an allowlist sanitizer such as DOMPurify.
  • Allow only http: and https: in links and sources built from data.
  • Serve APIs as application/json, and add a Content Security Policy as defense in depth.

Test

  • Point-in-time: store a script, an event-handler attribute and a javascript: link in every field that is rendered, then view each page where it appears, including admin and organizer pages.
  • Continuous: a SAST rule for innerHTML, dangerouslySetInnerHTML, v-html and unescaped template output, a unit test on the sanitizer, and a CSP header check.

Examples

Mitigation options

Option When it fits Docs
Escape by default in the template Server-rendered HTML EJS
Sanitise, then insert as HTML Rich text that must keep markup DOMPurify
Return data, render in the client JSON APIs with a JS front end OWASP XSS
Content Security Policy Defence in depth, never the only control Helmet

Vulnerable — unescaped output in EJS

<div class="comment"><%- comment.body %></div>

<%- writes raw HTML. <%= escapes.

Vulnerable — HTML built by concatenation

res.send(`<h1>Results for ${req.query.q}</h1>`)

Vulnerable — escaped, but in the wrong context

<a href="../<%= profile.website %>">Website</a>
<script>const user = <%- JSON.stringify(user) %>;</script>

HTML escaping does not make a URL safe (javascript:alert(1) survives it), and JSON.stringify output inside <script> can be broken out of with </script>.

Mitigated — escape by default

<div class="comment"><%= comment.body %></div>

Docs: EJS tags

Mitigated — sanitise rich text

const window = new JSDOM('').window
const purify = DOMPurify(window)

const safeHtml = purify.sanitize(req.body.body, {
  ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'code'],
  ALLOWED_ATTR: ['href'],
  ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|#)/i,
})
await Comment.create({ body: safeHtml, authorId: req.user.id })

Sanitise on output, or on input and output; storing sanitised HTML alone means a later change to the allowlist can't be applied retroactively.

Docs: DOMPurify configuration · jsdom

Mitigated — safe URL and safe script data

function safeUrl(value) {
  try {
    const url = new URL(value, 'https://example.com')
    return ['http:', 'https:'].includes(url.protocol) ? url.href : '#'
  } catch { return '#' }
}
<a href="../<%= safeUrl(profile.website) %>">Website</a>
<script type="application/json" id="bootstrap"><%- safeJson(user) %></script>
<script>const user = JSON.parse(document.getElementById('bootstrap').textContent)</script>

where safeJson replaces <, >, &, U+2028 and U+2029 with escapes.

Bypasses to check

  • One <%- left among many <%=, or a helper that returns a pre-built HTML string which the template then prints escaped-looking but raw.
  • Attribute context without quotes (class=<%= x %>), event handlers (onclick="<%= x %>"), and style — HTML escaping is not enough in any of these.
  • javascript:, data: and vbscript: URLs in href, src, formaction; filtering only javascript: misses java\tscript: and case variants.
  • Client-side sinks: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, location =, dangerouslySetInnerHTML.
  • Check then change: input sanitised, then decoded, unescaped, truncated or concatenated afterwards — truncation can cut a tag open, and a second decodeURIComponent can revive an entity.
  • Stored XSS through fields nobody thinks of as HTML: filenames, user agents, error messages, PDF or email templates.
  • res.send() with a user-controlled string and no Content-Type, so a JSON response is sniffed as HTML.
  • CSP weakened by unsafe-inline or a permissive script-src.

What to grep for

  • <%-, {{{, dangerouslySetInnerHTML, v-html
  • innerHTML, insertAdjacentHTML, document.write, outerHTML
  • res.send( with backticks, res.write(, Content-Type
  • href="<%, src="<%, JSON.stringify inside <script>

Mitigation options

Option When it fits Docs
Autoescape on for the whole environment (the default) Every server-rendered page Nunjucks configure
Sanitise, then mark safe Rich text that must keep markup DOMPurify
Pass data to scripts through a data- attribute Page scripts that need server data Nunjucks dump
Content Security Policy Defence in depth, never the only control Helmet

Nunjucks escapes & " ' < > \ in every {{ }} when autoescape is on, and it is on unless someone turns it off. So the review question is less "is this value escaped?" and more "where was escaping switched off or opted out of?". That can happen in the environment config, a | safe filter, a SafeString built in route code, or a custom filter or extension. Nunjucks has no {% autoescape %} block tag, so it can't be switched off per template.

Vulnerable — autoescape turned off for the whole app

nunjucks.configure('views', {
  autoescape: false,
  express: app,
})
<td>{{ emp.name }}</td>
<input name="title" value="{{ emp.title }}">

One line in app.js makes every {{ }} in every template raw, in both text and attribute contexts. The templates themselves look normal, so reading only the views (or only a PR that touches a view) won't show it.

Vulnerable — opting out per value

<div class="bio">{{ user.bio | safe }}</div>
res.render('profile.html', { bio: new nunjucks.runtime.SafeString(user.bio) })

| safe, markSafe() and SafeString all say "this is already HTML". Moving the opt-out into route code hides it from anyone reading the template.

Vulnerable — custom filter that returns safe markup around raw input

env.addFilter('highlight', (text, term) =>
  new nunjucks.runtime.SafeString(text.replace(term, `<mark>${term}</mark>`)))

A filter's plain-string return value is escaped. A SafeString return value is not, including any user text it wraps.

Vulnerable — escaped, but in the wrong context

<a href="{{ profile.website }}">Website</a>
<a class={{ user.theme }}>Profile</a>
<button onclick="track('{{ query }}')">Search</button>
<script>const user = {{ user | dump | safe }};</script>

Autoescape is HTML escaping, and it fails here, even when it's on:

  • javascript:alert(1) contains no character it escapes.
  • An unquoted attribute ends at the first space.
  • Inside an event handler, the browser decodes &#39; back to ' before the JavaScript runs.
  • dump without | safe produces broken JSON (&quot;), so developers add | safe, and then </script> in any string closes the script element.

Mitigated — keep autoescape on

nunjucks.configure('views', {
  autoescape: true,
  express: app,
})
<td>{{ emp.name }}</td>
<input name="title" value="{{ emp.title }}">

Text and double-quoted attribute values are safe with no further work. Leave autoescape out entirely to get the same default, but writing it down stops a later "fix" from turning it off.

Docs: Nunjucks autoescaping · Nunjucks configure

Mitigated — sanitise rich text before marking it safe

const window = new JSDOM('').window
const purify = DOMPurify(window)

env.addFilter('richtext', (html) =>
  new nunjucks.runtime.SafeString(purify.sanitize(String(html ?? ''), {
    ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'code'],
    ALLOWED_ATTR: ['href'],
    ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|#)/i,
  })))
<div class="bio">{{ user.bio | richtext }}</div>

Make the sanitiser the only path to SafeString for user content, so a reviewer can grep for | safe and expect no hits on user data.

Docs: DOMPurify configuration · jsdom · Nunjucks custom filters

Mitigated — safe URL, quoted attributes and script data

env.addFilter('safeUrl', (value) => {
  try {
    const url = new URL(value, 'https://example.com')
    return ['http:', 'https:'].includes(url.protocol) ? url.href : '#'
  } catch { return '#' }
})
<a href="{{ profile.website | safeUrl }}">Website</a>
<a class="{{ user.theme }}">Profile</a>
<button data-query="{{ query }}" class="track">Search</button>
<div id="bootstrap" data-user="{{ user | dump }}"></div>
<script src="/js/page.js"></script>
// /js/page.js
const user = JSON.parse(document.getElementById('bootstrap').dataset.user)

The browser decodes the escaped attribute back into the exact JSON, and the JSON never sits inside a <script> element. Event handlers read the value from data- attributes instead of having it pasted into inline JavaScript, which also lets a CSP drop 'unsafe-inline'.

Docs: Nunjucks dump · MDN dataset

Bypasses to check

  • The switch, not the template. autoescape: false in nunjucks.configure(...) or new nunjucks.Environment(loader, {...}), or env.opts.autoescape = false set later. Check every environment: an app can create one for pages and another for emails, with different settings.
  • | safe, markSafe(), new SafeString() anywhere in the route, service or helper code that builds render data, not only in views/.
  • Custom filters, globals and extensions that return SafeString, or extensions registered with autoescape: false.
  • Context mismatch even with autoescape on: unquoted attributes, href/src/ formaction with javascript: or data:, on* handlers, style, and values inside <script> (dump | safe, or a value pasted into a JS string).
  • Check then change: a value is escaped or sanitised in code, then the template prints it with | safe, or a filter later truncates (| truncate), replaces or concatenates it. Truncating sanitised HTML can leave a tag open.
  • Stored XSS crossing privilege levels: fields a low-privilege user writes that an admin page renders. HttpOnly cookies and CSRF tokens don't help there, because the script runs on the app's own origin and can read the token from the page.
  • Nunjucks before 3.2.4 didn't escape \, so two values on one line inside a JavaScript string could combine into a breakout (CVE-2023-2142). Check the version in the lockfile.

What to grep for

  • autoescape, nunjucks.configure(, new nunjucks.Environment(, opts.autoescape
  • | safe, markSafe(, SafeString(
  • addFilter(, addGlobal(, addExtension(
  • href="{{, src="{{, =\{\{ (unquoted attribute), on[a-z]+="[^"]*\{\{
  • | dump inside <script>, <script> blocks containing {{

Mitigation options

Option When it fits Docs
.ftlh templates (HTML auto-escaping; Spring Boot's default suffix) Every server-rendered page Auto-escaping and output formats
output_format="HTML" set explicitly Templates not loaded by a .ftlh name: strings, .ftl files, emails #ftl directive
Sanitise, then output as markup Rich text that must keep its tags OWASP Java HTML Sanitizer
Pass data to scripts through a data- attribute Page scripts that need server data MDN dataset
Content Security Policy Defence in depth, never the only control Spring Security headers

FreeMarker escapes ${…} only when the template has an HTML output format. That comes from the template's name (.ftlh), the <#ftl output_format="HTML"> header, or the configuration's output_format setting. Spring Boot loads views with the .ftlh suffix, so normal pages are escaped. The review question is which templates aren't .ftlh, and where escaping was opted out of: ?no_esc, <#noautoesc>, <#outputformat "plainText">, or markup values built in Java.

Vulnerable — template built from a string has no output format

Template template = new Template("report", new StringReader(source), freemarker);
template.process(Map.of("project", project), out);       // ${project.name} is NOT escaped
mail.setText(render("welcome", model), true);             // HTML email, same problem

The name "report" has no .ftlh extension, so .output_format is undefined and every ${…} prints raw (verified with Spring Boot 3.3 and FreeMarker 2.3.33). The page that later shows this output may escape it again, which hides the problem in testing until someone prints it with ?no_esc or sends it as an email.

Vulnerable — .ftl views or a changed suffix

spring.freemarker.suffix=.ftl
<td>${employee.name}</td>

Renaming views to .ftl (common in apps started before Spring Boot 2.2, or copied from older examples) silently turns auto-escaping off for every page. The templates look the same.

Vulnerable — opting out per value or block

<div class="bio">${user.bio?no_esc}</div>

<#noautoesc>
  <p>${comment.body}</p>
</#noautoesc>
model.addAttribute("bio", HTMLOutputFormat.INSTANCE.fromMarkup(user.getBio()));

?no_esc, <#noautoesc> and a TemplateMarkupOutputModel built with fromMarkup all say "this is already HTML". The Java form hides the opt-out from anyone reading only the template.

Vulnerable — escaped, but in the wrong context

<a href="${profile.website}">Website</a>
<a class=${user.theme}>Profile</a>
<button onclick="track('${query}')">Search</button>
<script>const name = "${user.name?js_string?no_esc}";</script>

HTML escaping fails here even in a .ftlh file:

  • javascript:alert(1) contains nothing HTML escaping changes.
  • An unquoted attribute ends at the first space.
  • Inside an event handler, the browser decodes &#39; back to ' before the JavaScript runs.
  • In a .ftlh file, ?js_string output is HTML-escaped again (&quot; breaks the JavaScript), so developers add ?no_esc. That's right only inside a quoted string in a <script> element. Copied into an attribute or used with a different built-in, the value is raw.

Mitigated — .ftlh everywhere

spring.freemarker.suffix=.ftlh
<td>${employee.name}</td>
<input name="title" value="${employee.title}">

Text and double-quoted attribute values are escaped with no further work. .ftlh is Spring Boot's default since 2.2; writing it down stops a later change from switching it back.

Docs: Spring Boot FreeMarker properties · Auto-escaping

Mitigated — explicit output format for templates outside the views

Configuration mailCfg = new Configuration(Configuration.VERSION_2_3_33);
mailCfg.setOutputFormat(HTMLOutputFormat.INSTANCE);       // every template here auto-escapes
<#ftl output_format="HTML">
<p>Hello ${name},</p>

Set it on the configuration rather than relying on each template's header, so a new template can't forget it.

Docs: Configuration.setOutputFormat · #ftl directive

Mitigated — sanitise rich text before marking it as markup

private static final PolicyFactory RICH_TEXT = Sanitizers.FORMATTING.and(Sanitizers.LINKS).and(Sanitizers.BLOCKS);

model.addAttribute("bio", HTMLOutputFormat.INSTANCE.fromMarkup(RICH_TEXT.sanitize(user.getBio())));
<div class="bio">${bio}</div>

Make the sanitiser the only place that calls fromMarkup for user content, so a reviewer can grep for ?no_esc and fromMarkup and expect no hits on raw user data. Sanitizers.LINKS allows only http, https and mailto URLs.

Docs: OWASP Java HTML Sanitizer · HTMLOutputFormat

Mitigated — safe URL, quoted attributes and script data

static String safeUrl(String value) {
    try {
        URI uri = new URI(value);
        return "http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())
                ? uri.toString() : "#";
    } catch (URISyntaxException e) { return "#"; }
}
<a href="${websiteUrl}">Website</a>                       <#-- safeUrl applied in the controller -->
<a class="${user.theme}">Profile</a>
<button class="track" data-query="${query}">Search</button>
<div id="bootstrap" data-user="${userJson}"></div>        <#-- userJson = objectMapper.writeValueAsString(…) -->
<script src="/js/page.js"></script>
const user = JSON.parse(document.getElementById('bootstrap').dataset.user)

The browser decodes the escaped attribute back into the exact JSON, and the JSON never sits inside a <script> element. Handlers read values from data- attributes instead of inline JavaScript, which also lets a CSP drop 'unsafe-inline'.

Docs: Jackson ObjectMapper · MDN dataset

Bypasses to check

  • The name, not the template. Any new Template(name, reader, cfg), StringTemplateLoader, or .ftl file renders without escaping unless the configuration or the #ftl header sets an HTML output format. Check emails, PDFs, reports and exports, not only views.
  • spring.freemarker.suffix changed to .ftl, or a second FreeMarkerConfigurer / Configuration bean with different settings.
  • ?no_esc, <#noautoesc>, <#outputformat "plainText">, ?markup_string printed back out, and Java code calling fromMarkup(…) or returning TemplateMarkupOutputModel from a helper.
  • <#ftl output_format="plainText"> or "XML" on an HTML page: XML escaping is close but not identical, and plain text escapes nothing.
  • Context mismatch even with escaping on: unquoted attributes, href / src / formaction with javascript: or data:, on* handlers, style, and values inside <script>.
  • Check then change: a value is sanitised in Java, then the template truncates (?truncate, ?substring), replaces or concatenates it before printing with ?no_esc. Cutting sanitised HTML can leave a tag open.
  • Stored XSS crossing privilege levels: fields a project member writes that an owner or admin page renders. HttpOnly cookies don't help, because the script runs on the app's origin and can make requests with the victim's cookie and read the CSRF token from the page.
  • spring.freemarker.expose-request-attributes / expose-session-attributes putting request or session values into every view, so a value set from user input in one filter appears on pages that don't expect it.

What to grep for

  • spring.freemarker.suffix, .ftl", new Template(, StringTemplateLoader, setOutputFormat, output_format
  • ?no_esc, noautoesc, outputformat, fromMarkup(, markup_string
  • href="${, src="${, =${ (unquoted attribute), on[a-z]+="[^"]*\$\{
  • <script> blocks containing ${, ?js_string, ?json_string

Mitigation options

Option When it fits Docs
Jinja2 autoescaping (on by default in Flask for .html, .htm, .xml, .xhtml, .svg) Always; {{ value }} is HTML-escaped Flask templating, Jinja autoescaping
A Markdown renderer with raw HTML off, plus link checks Rich text from users markdown-it-py, Python-Markdown
An HTML sanitizer (nh3, bleach) When users must be allowed some HTML nh3, bleach (deprecated)
A strict CSP Defense in depth for any slip MDN CSP

Vulnerable — |safe or Markup() on user text

<div class="bio">{{ user.bio|safe }}</div>
return render_template('page.html', body=Markup(request.form['body']))

|safe and Markup tell Jinja the text is already HTML, so it's printed as-is.

Vulnerable — autoescape off for a whole block or file

{% autoescape false %}{{ comment.body }}{% endautoescape %}

Flask autoescapes render_template_string and templates ending in .html, .htm, .xml, .xhtml and .svg. A template with another extension, such as .j2 or .txt served as HTML, is not autoescaped, and neither is a plain jinja2.Environment() created without autoescape=.

Vulnerable — Markdown with HTML allowed, then marked safe

md = MarkdownIt('commonmark')                       # 'commonmark' allows raw HTML blocks
Markup(md.render(text))                              # <img src=x onerror=…> passes through

Vulnerable — escaped, but in the wrong context

<a href="../{{ user.website }}">site</a>                 {# javascript:alert(1) is not escaped away #}
<script>var name = "{{ user.name }}";</script>        {# HTML escaping is not JS escaping #}
<div onclick="go('{{ item.id }}')">                   {# event handler: JS context #}

Mitigated — autoescape, |tojson for scripts, schemes checked for URLs

<p>{{ comment.body }}</p>
<script type="application/json" id="data">{{ payload|tojson }}</script>
{% if user.website.startswith(('https://', 'http://')) %}<a href="../{{ user.website }}" rel="nofollow noopener">site</a>{% endif %}

|tojson escapes <, >, & and ' so the value can't close the script tag.

Docs: Jinja tojson

Mitigated — Markdown with raw HTML disabled

_md = MarkdownIt('js-default')        # CommonMark + tables, html=False, validateLink blocks javascript:/vbscript:/data:
def render_markdown(text):
    return Markup(_md.render(text or ''))

Docs: markdown-it-py presets

Mitigated — sanitize when HTML is a feature

clean = nh3.clean(user_html, tags={'b', 'i', 'a', 'p', 'ul', 'li'}, url_schemes={'https', 'mailto'})

Docs: nh3

Bypasses to check

  • |safe, Markup(, {% autoescape false %} and Environment(autoescape=False) anywhere in the code.
  • select_autoescape() with a custom extension list that misses the templates actually used, or a bare Environment() (autoescape is off by default outside Flask).
  • Syntax highlighters and Markdown output wrapped in Markup. Confirm the library escapes code and disables HTML.
  • Values put in href, src and style, or inside <script> and event handlers.
  • Raw file endpoints served as text/html, or without X-Content-Type-Options: nosniff.

What to grep for

  • |safe, Markup(, autoescape, render_template_string(, select_autoescape
  • MarkdownIt(, markdown.markdown(, bleach., nh3., highlight(
  • href="{{, src="{{, <script>, onclick="

Resources