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:andhttps: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-htmland 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
<%- writes raw HTML. <%= escapes.
Vulnerable — HTML built by concatenation
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
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 %>"), andstyle— HTML escaping is not enough in any of these. javascript:,data:andvbscript:URLs inhref,src,formaction; filtering onlyjavascript:missesjava\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
decodeURIComponentcan 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 noContent-Type, so a JSON response is sniffed as HTML.- CSP weakened by
unsafe-inlineor a permissivescript-src.
What to grep for
<%-,{{{,dangerouslySetInnerHTML,v-htmlinnerHTML,insertAdjacentHTML,document.write,outerHTMLres.send(with backticks,res.write(,Content-Typehref="<%,src="<%,JSON.stringifyinside<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
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
| 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
'back to'before the JavaScript runs. dumpwithout| safeproduces broken JSON ("), so developers add| safe, and then</script>in any string closes the script element.
Mitigated — keep autoescape on
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,
})))
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>
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: falseinnunjucks.configure(...)ornew nunjucks.Environment(loader, {...}), orenv.opts.autoescape = falseset 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 inviews/.- Custom filters, globals and extensions that return
SafeString, or extensions registered withautoescape: false. - Context mismatch even with autoescape on: unquoted attributes,
href/src/formactionwithjavascript:ordata:,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]+="[^"]*\{\{| dumpinside<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
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
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
?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
'back to'before the JavaScript runs. - In a
.ftlhfile,?js_stringoutput is HTML-escaped again ("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
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
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())));
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>
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.ftlfile renders without escaping unless the configuration or the#ftlheader sets an HTML output format. Check emails, PDFs, reports and exports, not only views. spring.freemarker.suffixchanged to.ftl, or a secondFreeMarkerConfigurer/Configurationbean with different settings.?no_esc,<#noautoesc>,<#outputformat "plainText">,?markup_stringprinted back out, and Java code callingfromMarkup(…)or returningTemplateMarkupOutputModelfrom 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/formactionwithjavascript:ordata:,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-attributesputting 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_stringhref="${,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
|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
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 %}andEnvironment(autoescape=False)anywhere in the code.select_autoescape()with a custom extension list that misses the templates actually used, or a bareEnvironment()(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,srcandstyle, or inside<script>and event handlers. - Raw file endpoints served as
text/html, or withoutX-Content-Type-Options: nosniff.
What to grep for
|safe,Markup(,autoescape,render_template_string(,select_autoescapeMarkdownIt(,markdown.markdown(,bleach.,nh3.,highlight(href="{{,src="{{,<script>,onclick="