Server-Side Template Injection

User input is parsed as template source rather than passed as template data, so the server-side engine evaluates attacker expressions (CWE-1336; also CWE-94/95).

What it is

Template engines compile a template string into code, then execute it with a context of data. The trust boundary is template source vs context data: render(template, {name: input}) is safe, while render("Hello " + input) hands the attacker the compiler. Kettle’s 2015 Black Hat research framed the class and its key trait. It is easily mistaken for Cross-Site Scripting (the reflection looks identical) or missed entirely, but it executes on the server. The 2024 arXiv survey of 34 engines across eight languages found most have a reachable RCE path once source is attacker-controlled.

Modern variants: the “template” is often not a web view. It can be an email or notification body, a CMS theme, a report or doc template, a webhook payload, a config value, a data-format document, or an LLM prompt/chat template.

Why it matters

Impact ladder, from least to most severe:

  1. Template-context disclosure. Example: Flask config/SECRET_KEY and Django signing keys (XBEN-056) lead to session and cookie forgery. Arize Phoenix CVE-2026-53998 read os.environ via an unauthenticated GraphQL f-string template, which led to admin session forgery and decrypted LLM keys.
  2. Data access through exposed objects. Nautobot sandbox escapes reached arbitrary DB reads, API tokens and password hashes, then ATO.
  3. Authorization bypass inside the app. Shopware Twig App Scripts allowed admin takeover. FortiManager let a low-priv admin become super admin on managed FortiGates.
  4. RCE as the app user, often root in Docker (Tandoor, DataGerry). Cloud blast radius: the AWS VEW Lambda IAM role spanned tenants. Shared containers: the mailcow rspamd container, cross-tenant mail.

Severity drivers are pre-auth reachability (LMFDB, ServiceNow, Imperia), whether a sandbox is in place, and the privilege needed to author templates. Many 2026 CVEs need an editor or admin role, which still matters in multi-tenant SaaS. ServiceNow CVE-2024-4879/5217 were mass-exploited and are on CISA KEV.

How it works

Exploitation follows the engine’s object model:

  • Python (Jinja2 SSTI, Mako, Django): attribute access walks the Python class hierarchy and function globals to modules. Escapes overlap with Python Sandbox Escapes.
  • Java (Java Template Engine SSTI: FreeMarker, Thymeleaf, Velocity, Pebble, Jinjava, Jelly): class instantiation and reflection. Thymeleaf overlaps with Expression Language Injection.
  • PHP (Twig SSTI, Smarty, Blade): Twig’s sandbox and its CMS wrappers. Smarty exposes PHP functions and modifiers directly (THM: Form Tools second-order via a Smarty modifier). Imperia CMS converted the TEMPLATE param into PHP executed by a PHPExec plugin (CVE-2026-110355).
  • JavaScript (JavaScript Template Engine SSTI: Handlebars, Nunjucks, EJS, Pug, Vue SSR): reaching the Function constructor. Prototype pollution can inject compiler AST nodes.
  • Ruby (ERB, Slim): ERB tags are Ruby, so injection is direct code exec. TrustedSec used introspection (.methods, instance variables) to pull WEBrick’s @ssl_context private key even under a safe level. Elo’s Ruby backend emitted unescaped #{} interpolation (GHSA-7w38-ggh5-v542).
  • Go (Go Template SSTI): no generic escape. Impact depends on exported methods of the context (“method confusion”).
  • .NET/T4: .tt text templates embed C#/VB executed by TextTransform/MSBuild. It is a living-off-the-land execution vector more than a web sink (ipurple).

Where to find it

  • Code sinks: render_template_string, Template(...), Environment.from_string, Twig createTemplate / template_from_string, FreeMarker new Template(..., new StringReader(x)), Spring controllers returning user-influenced view names, Go Parse(userInput), Handlebars compile(userInput), Quest Foglight renderTemplateString.
  • Features: name/greeting fields, custom error pages, email and notification editors (Fides, OpenMetadata, Formie, Thelia), themes (Mautic), report/doc generators (DataGerry DocAPI, OFBiz), webhooks (NocoDB), wizard steps (Wizarr), message fields (Frappe CVE-2026-119144), knowledge-base renderers (LMFDB), contact forms (Batflat), user-permission email templates (Strapi CVE-2023-22621), mail footers rendered by a downstream filter (mailcow → rspamd), uploaded file content (CSV) rendered in a viewer.
  • Build and packaging artifacts: BentoML dockerfile_template inside an imported bento (BentoML).
  • Non-HTTP inputs: config (Dynaconf), data documents (fsspec Kerchunk JSON, OSCAL in Trestle), CloudFormation (AWS VEW), and LLM prompt/skill templates (Agenta, Opik, DB-GPT, llama-cpp-python pattern).
  • Headers: a Referer rendered into a Thymeleaf view (modzero).

How to test

Methodology (detail in SSTI Detection):

  1. Map sinks. List every field that is rendered later, including emails, PDFs and admin previews. Check for second-order rendering.
  2. Fuzz with a metacharacter polyglot (${{<%[%'"}}%\) and watch for 500s or engine stack traces.
  3. Confirm evaluation with arithmetic per syntax family ({{7*7}}, ${7*7}, <%= 7*7 %>, #{7*7}). Test plaintext and code contexts separately.
  4. Identify the engine with discriminators ({{7*'7'}}: Jinja2 vs Twig), error text and framework fingerprints.
  5. Read the engine docs and enumerate the context. List exposed objects, helpers and the sandbox configuration. The app’s own objects are often the gadget (Pydantic, ORM, framework context).
  6. Prove impact minimally. Prefer a context-object disclosure or a benign command/OOB callback over destructive actions. Use blind time/boolean/OOB techniques if output is not reflected.
  7. Check for incomplete fixes. Mautic, Trestle, Vvveb, Nautobot and NocoDB all shipped follow-up advisories.

Checklist:

  • Every user-influenced string reaching a compile/parse API identified
  • Stored fields tested for second-order rendering (email, export, preview)
  • Arithmetic evaluation confirmed and engine identified
  • Sandbox presence and policy determined; exposed objects enumerated
  • Template-authoring permissions mapped to roles (low-priv authoring = finding)
  • Blind variants tried where output isn’t reflected
  • Engine/library version checked against known sandbox CVEs

Exploitation and escalation

Paths to impact, without recipes:

  • Unsandboxed engine: an object-model walk to code exec (Jinja2 SSTI, Java Template Engine SSTI). Result: Remote Code Execution.
  • Secrets first: template context, then a signing key or env token, then forged sessions or tickets (Flask/Django, Arize Phoenix, Craft securityKey, HTB Takeoff).
  • Chains in: LFI to forged cookie to admin SSTI (Poet). A leaked JS source map revealing a hidden API leading to a profile SSTI (HackSmarter). Path traversal in Flask-Reuploaded (CVE-2026-27641) writing a template file. Missing authorization exposing an SSTI sink (Formie, Grav CVE-2025-66301).
  • Chains out: SSTI file write overwriting an interpreted source file (CSC payslip/yaegi). SSTI-to-XSS reflected through WAFs (SSTItoXSS).
  • Tooling: SSTImap/tplmap automate exploitation, and Metasploit has modules (Tactical RMM, Grav).

Bypassing defenses

  • Deny-list input filters (__, ., [], {{) are bypassed by alternate attribute access, string construction, encodings, statement tags and moving strings into other request params. See Jinja2 SSTI. FreeMarker ?lower_abc defeats word filters (Synack). Jinja \xNN string escapes are decoded after a raw-byte substring filter runs (FortiPy).
  • WAF/app parsing differentials: WAFs inspect raw bytes while the app dechunks first (aiohttp challenge). Payload size limits are worked around by staging in config.
  • Engine sandboxes fail through exposed app objects, compiler bugs (Twig {% use %} CVE-2026-46633), unexpected template loading (template_from_string, CVE-2026-46634), Unicode normalization (Jinja2 LetMeOut), classpath reflection helpers (Thymeleaf + commons-lang3), interpreter memory bugs (CPython, RunSybil) and custom verifier bugs (OpenCTI EJS).
  • App-level “dangerous template” regexes (Grav cleanDangerousTwig) and user-editable safe-function lists.

Real-world cases

  • ServiceNow CVE-2024-4879 / -5178 / -5217: Jelly template injection chain, unauth RCE, KEV, global recon campaign — Censys, Resecurity, Cyfirma
  • Confluence CVE-2022-26134: OGNL injection, actively exploited — Rapid7
  • Confluence CVE-2019-3396: Velocity template via Widget Connector — Exploit-DB
  • LMFDB CVE-2026-123198: unauth Jinja2 via GET — GHSA
  • Imperia CMS CVE-2026-110355: unauth TEMPLATE param → PHP exec — RCE Security
  • Arize Phoenix CVE-2026-53998: unauth f-string template env disclosure — Corgea
  • Quest Foglight ZDI-26-866: renderTemplateString → SYSTEM — ZDI
  • FortiManager GHSA-p5xc-69mw-v3hr: template neutralization → super admin on FortiGates — advisory
  • Strapi CVE-2023-22621: SSTI → RCE in Users-Permissions email templates — Strapi
  • mailcow CVE-2026-125757: cross-tenant Jinja in shared rspamd; a domain admin’s verbatim footer (POST /api/v1/edit/domain/footer) is rendered by the lupa engine, whose macro defaults are load()ed outside the sandbox env. Blind, so confirmation is out of band; unbounded commands stall all mail at DATA. Fixed in 2026-11 by replacing jinja_template with {= key =} placeholder substitution — GHSA, PoC, vuln.today
  • Craft CMS CVE-2026-130674 (5.0.0-5.11.3): incomplete blocklist fix; entry-type title-format authors reach ZipArchive/XMLWriter through the non-sandboxed renderObjectTemplate() and write into the docroot — GHSA-42hj-xv33-m6rg
  • WHMCS CVE-2026-93700: authenticated client template injection → config file read (DB credentials) and code execution; fixed 8.10.1/8.9.2 — advisory
  • Ghost Render CTF: sqlmap-dumped admin creds, then Jinja2 SSTI in rendered CSV upload content to a shell — walkthrough
  • Dataiku DSS DSA-2026-015 (8.8): authenticated Jinja2 code injection on render — Dataiku
  • BentoML GHSA-v959-cwq9-7hr6: malicious bento archive → host RCE via unsandboxed Jinja2 do extension — advisory
  • Twig CVE-2026-46633: {% use %} name breaks out of a single-quoted PHP literal in the compiled cache — Symfony
  • FortiPy (HackerDNA lab): blacklist-filtered Jinja2 behind /welcome?user=, \xNN bypass, root process — writeup
  • Frappe CVE-2026-119144: message-field SSTI — writeup
  • Jinja2 SSTI bounty, $9,000, found via broken error message — writeup
  • HackerOne #423541 (H1-514) and #164224 — H1 423541, H1 164224
  • Recent-CVE tracker (FortiManager, mailcow, OFBiz, Craft, Bricks) — vuln.today
  • Engine-specific case tables: Jinja2 SSTI, Twig SSTI, Java Template Engine SSTI, JavaScript Template Engine SSTI, Go Template SSTI

Prevention

  • Templates are code. Load them from the filesystem or build artifacts only. Pass user input exclusively as context data (render_template() not render_template_string(); fixed Spring view names).
  • If users must author templates: prefer logic-less engines (Mustache), or the engine’s sandbox with an allow-list policy and a minimal context. Expose no ORM, deserialization, framework-context or reflective objects. Assume the sandbox will be bypassed: isolate rendering in a low-privilege process or container with no secrets in its environment.
  • Engine hardening: Jinja2 SandboxedEnvironment without ext.do/ext.debug. FreeMarker ALLOWS_NOTHING_RESOLVER with ?api disabled. Twig ≥3.26.0 and no StringLoaderExtension under the sandbox. Thymeleaf ≥3.1.5. Handlebars prototype-access protections on.
  • Authorization: treat template, theme, email and prompt authoring as a privileged capability and audit who has it. It is the only workaround offered in many advisories.
  • Replace the engine with substitution when only placeholders are needed: mailcow’s fix swapped Jinja rendering of footers for a gsub over {= key =} keys, so footer content is pure data (vuln.today).
  • Don’t rely on character blacklists, regex sanitizers or WAFs as the control. Craft CMS’s class blocklist was bypassed again via ZipArchive/XMLWriter (CVE-2026-130674).
  • Detect: SAST rules for compile-from-string sinks, CI checks on template sources (Xygeni), and runtime template-aware monitoring (Oligo).

Tools

  • SSTImap — detection and exploitation, blind techniques, many engines
  • tplmap / tplmap-python3 — original automated tool
  • TInjA — polyglot scanner
  • Burp Scanner; Metasploit modules (Tactical RMM, Grav)
  • Labs: PortSwigger Academy, GoSecure workshop, Inj3ctlab, karczewski Flask lab

Sub-pages

  • SSTI Detection — finding sinks, confirming evaluation, fingerprinting engines, blind techniques
  • Jinja2 SSTI — Python object model, SandboxedEnvironment escapes, AI prompt-template CVEs
  • Java Template Engine SSTI — FreeMarker, Thymeleaf, Velocity, Jelly; denylist bypasses and enterprise CVEs
  • Twig SSTI — PHP Twig sandbox and CMS-wrapper bypasses (Grav, Craft, Mautic)
  • JavaScript Template Engine SSTI — Handlebars, Nunjucks, EJS, Vue SSR; Function-constructor escapes
  • Go Template SSTI — text/html template method confusion and context exposure

Sources