Skip to content
Back to skills

Khaos Htmx Security

ASecurity

Security testing methodology for HTMX-powered applications — CSP bypass via hx-* attributes, fragment injection, event handler abuse, and header leakage

  • 6 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 5, 2026
ai-agentsgotestinggitsecuritydocumentation

Works with

  • cli

Security analysis

A100/100

Scanned December 5, 2026

npx -y skills add henriqqw/Khaos-Pentester-Agent --skill khaos-htmx-security --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Khaos Htmx Security?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Khaos Htmx Security
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/henriqqw-khaos-htmx-security-khaos-pentester-agent/badge)](https://www.skillsdirectory.com/skills/henriqqw-khaos-htmx-security-khaos-pentester-agent)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: khaos-htmx-security
description: Security testing methodology for HTMX-powered applications — CSP bypass via hx-* attributes, fragment injection, event handler abuse, and header leakage
metadata:
  khaos:
    tool_ids: [httpx, katana]
    wordlist_ids: []
    stages: [enumeration, vuln, validation]
    source_type: original
    source:
      repository: https://github.com/henriqqw/Khaos
      revision: internal
      path: internal/skillseed/catalog/khaos-htmx-security/SKILL.md
      license: MIT
      reviewed_by: Khaos maintainers
      review_note: Skill original escrita pela equipa Khaos para assessments autorizados.
---

# HTMX Security Testing

## Objetivo

Identificar vulnerabilidades específicas de aplicações que usam HTMX (biblioteca de hipermídia para interações Ajax via atributos HTML), com foco em bypass de CSP, injeção de fragmentos, manipulação de eventos e headers expostos.

## Contexto Técnico

HTMX 2.x usa `hx-get`, `hx-post`, `hx-swap`, `hx-target`, `hx-trigger`, `hx-vals`, `hx-headers` e outros atributos para substituir parcialmente o DOM com respostas do servidor. Cada requisição inclui headers especiais:
- `HX-Request: true`
- `HX-Trigger`, `HX-Target`, `HX-Current-URL`
- `HX-Prompt` (para diálogos `hx-prompt`)
- `HX-Boosted` (para `hx-boost`)

HTMX processa **HTML cru do servidor** e o injeta no DOM via `innerHTML`/`outerHTML`. Isso torna XSS via fragmento HTML extremamente efetivo se o servidor reflete input sem sanitização.

## Vetores de Ataque

### 1. Fragment Injection / XSS via HTMX Swap

HTMX insere a resposta diretamente no DOM sem sanitização por padrão (antes do HTMX 1.9.3+). Se o servidor reflete qualquer parâmetro na resposta HTML parcial:

```
GET /search?q=<img src=x onerror=alert(1)> HTTP/1.1
HX-Request: true
HX-Target: #results
```

**Teste**: Envie requisição com `HX-Request: true` + payload XSS no parâmetro refletido. Se a resposta contiver o payload e HTMX processar o fragmento sem sanitização → XSS.

**Mitigação ausente**: Ausência de `htmx.config.allowScriptTags = false` e `htmx.config.allowEval = false` indica superfície ampla.

### 2. CSP Bypass via hx-on e eval()

HTMX 1.9.x+ suporta `hx-on:event="JS"` que chama `new Function()` / `eval()` internamente para executar handlers inline. Se o CSP não inclui `'unsafe-eval'` mas inclui `'unsafe-inline'`:

```html
<button hx-get="/endpoint" hx-on::after-request="alert(document.cookie)">Click</button>
```

Em HTMX ≥ 2.0, `hx-on:` foi adicionado como alternativa explícita. Verifica:
1. A resposta do servidor inclui elementos com `hx-on`?
2. O CSP permite `unsafe-eval`?
3. A versão do HTMX (via `<meta name="htmx-config">` ou header) é vulnerável?

### 3. Server-Side Template Injection via HX-Prompt

O header `HX-Prompt` é enviado quando o usuário responde a um diálogo `hx-prompt`. Se o servidor usa esse valor em template sem sanitização:

```
POST /action HTTP/1.1
HX-Prompt: {{7*7}}
```

Teste com payloads de SSTI: `{{config}}`, `${7*7}`, `<%= 7*7 %>`.

### 4. CSRF via hx-headers e hx-vals

`hx-vals` injeta parâmetros extras no corpo da requisição; `hx-headers` adiciona headers customizados. Se um formulário controlável pelo usuário aceita `hx-vals` via atributo data:

```html
<form hx-post="/transfer" hx-vals='{"amount": "9999"}'>
```

Verifica se existe validação CSRF independente do token HTMX.

### 5. Open Redirect via HX-Redirect

HTMX processa o header de resposta `HX-Redirect` para navegação client-side. Se o servidor reflete um parâmetro URL no `HX-Redirect`:

```
GET /go?next=https://evil.com HTTP/1.1
HX-Request: true
→ HX-Redirect: https://evil.com
```

Verifica o comportamento de redirect em respostas HTMX parciais.

### 6. Information Disclosure via Headers HTMX

Requisições HTMX expõem `HX-Current-URL` (URL atual do navegador) e `HX-Trigger` (ID do elemento clicado) ao servidor. Confirma se esses headers aparecem em logs ou respostas de erro.

## Procedimento de Teste

1. **Identificação**: Procure `<script src="...htmx...">` ou `hx-get`/`hx-post` no HTML. Confirme versão via `htmx.version` no console ou atributo de meta.
2. **Mapeie endpoints HTMX**: Requisições com `HX-Request: true` retornam fragmentos diferentes; catalogue-os com katana usando header customizado.
3. **Teste injeção de fragmento**: Para cada parâmetro refletido em resposta parcial, teste XSS.
4. **Analise CSP**: Verifique se `Content-Security-Policy` bloqueia `unsafe-eval` e `unsafe-inline`. HTMX 2.x requer configuração explícita para remover eval.
5. **Teste hx-on handlers**: Inspecione HTML de respostas parciais por `hx-on:` ou `hx-trigger="js:..."`.
6. **Verifique HX-Redirect**: Tente controlar parâmetro de redirect; use `HX-Request: true` para obter resposta fragmentada.
7. **Documente versão e configuração**: `htmx.config` exposto no JS indica configuração permissiva.

## Indicadores de Vulnerabilidade

| Observação | Vulnerabilidade Potencial |
|---|---|
| `hx-on:` no HTML servido pelo servidor | CSP bypass / XSS via handler inline |
| Parâmetro refletido em fragmento HTML | XSS via fragment injection |
| Header `HX-Redirect` com valor controlável | Open redirect |
| `HX-Prompt` value usado em template | SSTI |
| CSP ausente ou com `unsafe-eval` | XSS amplificado |
| `htmx.config.allowScriptTags = true` (default pré-2.0) | XSS via `<script>` em fragmento |

## Evidência Mínima para Finding

- Request/response mostrando o parâmetro controlável e sua reflexão no fragmento.
- Confirmação de qual mecanismo de swap processa o fragmento (`innerHTML`, `outerHTML`, `beforeend`, etc.).
- Versão do HTMX e configuração de segurança ativa.

## Referências

- HTMX Security documentation: https://htmx.org/docs/#security
- OWASP XSS Prevention Cheat Sheet
- PortSwigger: DOM-based XSS
- HTMX 2.0 Breaking Changes (eval removal): https://htmx.org/migration-guide-htmx-2/

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.