Pular para o conteúdo principal

Lab 8.4: Registro do Windows e Persistência

Objetivos de Aprendizagem​

Ao final deste laboratório, você será capaz de:

  • Navegar e manipular o registro do Windows
  • Compreender as chaves importantes para a segurança
  • Detectar modificações suspeitas no registro
  • Identificar mecanismos de persistência via registro

Duração Estimada​

50 minutos

Pré-requisitos​

  • VM Windows 10/11
  • Permissões de administrador
  • Lab 7.2 completo (persistência)

Contexto Profissional​

O registro do Windows é:

  • O banco de dados central de configuração
  • Um alvo privilegiado para persistência de malwares
  • Um elemento-chave a ser monitorado em segurança

Parte 1: Navegação no Registro​

Etapa 1.1: Estrutura do registro​

O registro é organizado em hives (colmeias):

HiveAliasConteúdo
HKEY_LOCAL_MACHINEHKLMConfiguração do sistema
HKEY_CURRENT_USERHKCUConfiguração do usuário atual
HKEY_USERSHKUTodos os perfis de usuários
HKEY_CLASSES_ROOTHKCRAssociações de arquivos
HKEY_CURRENT_CONFIGHKCCConfiguração de hardware atual

Etapa 1.2: Acesso via PowerShell​

# As hives são acessíveis como drives
Get-PSDrive -PSProvider Registry

# Navegação
Set-Location HKLM:\SOFTWARE
Get-ChildItem

# Voltar
Set-Location C:\

Etapa 1.3: Ler valores​

# Ler uma chave inteira
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"

# Ler um valor específico
(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ProductName

# Valor com Get-ItemPropertyValue
Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName

Etapa 1.4: Modificar o registro​

# Criar uma chave
New-Item -Path "HKCU:\Software\LabTest" -Force

# Criar/modificar um valor
Set-ItemProperty -Path "HKCU:\Software\LabTest" -Name "TestValue" -Value "Hello World"
Set-ItemProperty -Path "HKCU:\Software\LabTest" -Name "TestNumber" -Value 42 -Type DWord

# Verificar
Get-ItemProperty "HKCU:\Software\LabTest"

# Remover
Remove-ItemProperty -Path "HKCU:\Software\LabTest" -Name "TestValue"
Remove-Item -Path "HKCU:\Software\LabTest" -Recurse

Pergunta 1: Por que usamos -Type DWord para números?


Parte 2: Chaves de Segurança Importantes​

Etapa 2.1: Chaves Run (Inicialização automática)​

Essas chaves executam programas automaticamente:

# Exibir todas as chaves Run
Write-Host "=== CHAVES RUN ===" -ForegroundColor Cyan

$runKeys = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunServices",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce"
)

foreach ($key in $runKeys) {
Write-Host "`n$key" -ForegroundColor Yellow
if (Test-Path $key) {
Get-ItemProperty $key | Format-List
} else {
Write-Host " (não existe)"
}
}

Etapa 2.2: Chaves de serviços​

# Serviços registrados
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services" |
Select-Object -First 10 |
ForEach-Object {
$svc = Get-ItemProperty $_.PSPath
[PSCustomObject]@{
Name = $_.PSChildName
DisplayName = $svc.DisplayName
ImagePath = $svc.ImagePath
Start = $svc.Start
}
} | Format-Table -AutoSize

Etapa 2.3: Chaves de segurança​

# Parâmetros de segurança LSA
Write-Host "=== LSA Security ===" -ForegroundColor Cyan
Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -ErrorAction SilentlyContinue

# RunAsPPL (proteção LSASS)
$runAsPPL = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RunAsPPL" -ErrorAction SilentlyContinue
if ($runAsPPL.RunAsPPL -eq 1) {
Write-Host "LSA Protection: ATIVA" -ForegroundColor Green
} else {
Write-Host "LSA Protection: INATIVA" -ForegroundColor Red
}

# WDigest (credenciais em texto claro)
Write-Host "`n=== WDigest ===" -ForegroundColor Cyan
$wdigest = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" -Name "UseLogonCredential" -ErrorAction SilentlyContinue
if ($wdigest.UseLogonCredential -eq 1) {
Write-Host "WDigest credenciais em texto claro: ATIVO (PERIGO!)" -ForegroundColor Red
} else {
Write-Host "WDigest credenciais em texto claro: DESATIVADO" -ForegroundColor Green
}

Etapa 2.4: Associações de arquivos​

# Verificar associações (usadas para hijacking)
Write-Host "=== Associações perigosas ===" -ForegroundColor Cyan

$extensions = @(".exe", ".bat", ".cmd", ".ps1", ".vbs", ".js")

foreach ($ext in $extensions) {
$assoc = (Get-ItemProperty "HKCR:\$ext" -ErrorAction SilentlyContinue).'(default)'
if ($assoc) {
$command = (Get-ItemProperty "HKCR:\$assoc\shell\open\command" -ErrorAction SilentlyContinue).'(default)'
Write-Host "$ext -> $assoc -> $command"
}
}

Parte 3: Detecção de Persistência​

Etapa 3.1: Script de detecção completo​

<#
.SYNOPSIS
Detecção de mecanismos de persistência via registro
#>

Write-Host @"
==============================================
DETECÇÃO DE PERSISTÊNCIA NO REGISTRO
==============================================
"@ -ForegroundColor Cyan

$findings = @()

# 1. Chaves Run
$runKeys = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
)

Write-Host "`n[1/5] Análise das chaves Run..." -ForegroundColor Yellow

foreach ($key in $runKeys) {
if (Test-Path $key) {
$props = Get-ItemProperty $key -ErrorAction SilentlyContinue
$props.PSObject.Properties | Where-Object {
$_.Name -notmatch "^PS"
} | ForEach-Object {
$value = $_.Value

# Critérios de suspeita
$suspicious = $false
$reasons = @()

if ($value -match "\\Temp\\|\\AppData\\Local\\Temp") {
$suspicious = $true
$reasons += "Caminho Temp"
}
if ($value -match "-[Ee]ncoded|-[Ww]indowStyle\s+[Hh]idden") {
$suspicious = $true
$reasons += "Argumentos suspeitos"
}
if ($value -match "powershell.*-[Cc]ommand") {
$suspicious = $true
$reasons += "PowerShell inline"
}

$findings += [PSCustomObject]@{
Type = "Run Key"
Location = $key
Name = $_.Name
Value = $value.Substring(0, [Math]::Min(80, $value.Length))
Suspicious = $suspicious
Reasons = ($reasons -join ", ")
}
}
}
}

# 2. Serviços em caminhos suspeitos
Write-Host "[2/5] Análise dos serviços..." -ForegroundColor Yellow

Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services" -ErrorAction SilentlyContinue | ForEach-Object {
$svc = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
if ($svc.ImagePath -match "\\Temp\\|\\AppData\\|\\Downloads\\") {
$findings += [PSCustomObject]@{
Type = "Service"
Location = $_.PSPath
Name = $_.PSChildName
Value = $svc.ImagePath
Suspicious = $true
Reasons = "Caminho suspeito"
}
}
}

# 3. Shell Extensions
Write-Host "[3/5] Análise das Shell Extensions..." -ForegroundColor Yellow

$shellExt = @(
"HKCU:\Software\Classes\*\shellex\ContextMenuHandlers",
"HKLM:\Software\Classes\*\shellex\ContextMenuHandlers"
)

foreach ($key in $shellExt) {
if (Test-Path $key) {
Get-ChildItem $key -ErrorAction SilentlyContinue | ForEach-Object {
$handler = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
$clsid = $handler.'(default)'

if ($clsid -and $clsid -match "^\{") {
# Verificar se o CLSID existe
$clsidPath = "HKCR:\CLSID\$clsid"
if (-not (Test-Path $clsidPath)) {
$findings += [PSCustomObject]@{
Type = "Shell Extension"
Location = $_.PSPath
Name = $_.PSChildName
Value = $clsid
Suspicious = $true
Reasons = "CLSID ausente"
}
}
}
}
}
}

# 4. AppInit_DLLs
Write-Host "[4/5] Verificação AppInit_DLLs..." -ForegroundColor Yellow

$appInit = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "AppInit_DLLs" -ErrorAction SilentlyContinue
if ($appInit.AppInit_DLLs) {
$findings += [PSCustomObject]@{
Type = "AppInit_DLLs"
Location = "HKLM:\...\Windows"
Name = "AppInit_DLLs"
Value = $appInit.AppInit_DLLs
Suspicious = $true
Reasons = "Injeção de DLL na inicialização"
}
}

# 5. Image File Execution Options (Debugger)
Write-Host "[5/5] Verificação IFEO..." -ForegroundColor Yellow

Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" -ErrorAction SilentlyContinue | ForEach-Object {
$ifeo = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
if ($ifeo.Debugger) {
$findings += [PSCustomObject]@{
Type = "IFEO Debugger"
Location = $_.PSPath
Name = $_.PSChildName
Value = $ifeo.Debugger
Suspicious = $true
Reasons = "Debugger definido"
}
}
}

# Relatório
Write-Host "`n==============================================`n" -ForegroundColor Cyan

$suspiciousFindings = $findings | Where-Object { $_.Suspicious }

if ($suspiciousFindings.Count -eq 0) {
Write-Host "[OK] Nenhuma persistência suspeita detectada" -ForegroundColor Green
} else {
Write-Host "[!] $($suspiciousFindings.Count) elemento(s) suspeito(s) detectado(s):" -ForegroundColor Red
$suspiciousFindings | Format-Table Type, Name, Reasons -AutoSize

Write-Host "`nDetalhes:" -ForegroundColor Yellow
$suspiciousFindings | ForEach-Object {
Write-Host "`n Tipo: $($_.Type)" -ForegroundColor Cyan
Write-Host " Nome: $($_.Name)"
Write-Host " Valor: $($_.Value)"
Write-Host " Razões: $($_.Reasons)" -ForegroundColor Yellow
}
}

# Resumo das entradas normais
Write-Host "`n==============================================`n" -ForegroundColor Cyan
$normalFindings = $findings | Where-Object { -not $_.Suspicious }
Write-Host "Entradas normais detectadas: $($normalFindings.Count)"

Pergunta 2: O script detectou elementos suspeitos na sua VM?


Parte 4: Exercício Prático​

Etapa 4.1: Criar uma persistência de teste​

# ATENÇÃO: Apenas para fins de teste!
# Crie uma entrada Run para entender o mecanismo

# Criar uma entrada inofensiva
Set-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestPersistence" `
-Value "cmd.exe /c echo Teste de persistência > C:\Temp\persistence_test.txt"

Write-Host "Entrada de teste criada" -ForegroundColor Yellow

Etapa 4.2: Detectar a persistência​

# Execute o script de detecção
# Sua entrada deve ser detectada

# Verificar manualmente
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" | Select-Object LabTestPersistence

Etapa 4.3: Limpar​

# Remover a entrada de teste
Remove-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestPersistence" `
-ErrorAction SilentlyContinue

Write-Host "Limpeza concluída" -ForegroundColor Green

Parte 5: Backup e Restauração​

Etapa 5.1: Exportar uma chave​

# Exportar uma chave
$exportPath = "$env:USERPROFILE\Desktop\backup_run_keys.reg"
reg export "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" $exportPath /y

Write-Host "Chave exportada para: $exportPath" -ForegroundColor Green

Etapa 5.2: Script de backup automático​

# Backup das principais chaves de segurança
$backupFolder = "$env:USERPROFILE\Desktop\RegistryBackup_$(Get-Date -Format 'yyyyMMdd')"
New-Item -Path $backupFolder -ItemType Directory -Force | Out-Null

$keysToBackup = @(
@{Path = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; Name = "HKLM_Run"},
@{Path = "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; Name = "HKCU_Run"},
@{Path = "HKLM\SYSTEM\CurrentControlSet\Control\Lsa"; Name = "LSA"},
@{Path = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows"; Name = "Windows"}
)

foreach ($key in $keysToBackup) {
$file = Join-Path $backupFolder "$($key.Name).reg"
reg export $key.Path $file /y 2>$null
if ($?) {
Write-Host "[OK] $($key.Name)" -ForegroundColor Green
} else {
Write-Host "[ERRO] $($key.Name)" -ForegroundColor Red
}
}

Write-Host "`nBackup concluído: $backupFolder" -ForegroundColor Cyan

Entregáveis​

  1. Respostas às 2 perguntas

  2. Capturas de tela:

    • Navegação no registro
    • Script de detecção executado
    • Persistência de teste criada e detectada
  3. Script de detecção personalizado

  4. Relatório (1 página):

    • Chaves de registro importantes
    • Riscos identificados
    • Recomendações de monitoramento

Critérios de Avaliação​

CritérioPontos
Navegação no registro20%
Chaves de segurança25%
Script de detecção35%
Exercício prático20%

Comandos de Referência​

# Leitura
Get-ItemProperty "HKLM:\caminho"
Get-ItemPropertyValue "HKLM:\caminho" -Name "valor"

# Escrita
Set-ItemProperty -Path "caminho" -Name "nome" -Value "valor"
New-Item -Path "caminho" -Force

# Remoção
Remove-ItemProperty -Path "caminho" -Name "nome"
Remove-Item -Path "caminho" -Recurse

# Exportação (via reg.exe)
reg export "HKLM\caminho" arquivo.reg /y
reg import arquivo.reg

Recursos​


Lab desenvolvido no âmbito do curso Sistemas Operacionais - MÓDULO 8