Saltar al contenido principal

Lab 8.4: Registro de Windows y Persistencia

Objetivos de Aprendizaje​

Al final de este laboratorio, usted será capaz de:

  • Navegar y manipular el registro de Windows
  • Comprender las claves importantes para la seguridad
  • Detectar modificaciones sospechosas en el registro
  • Identificar mecanismos de persistencia a través del registro

Duración Estimada​

50 minutos

Prerrequisitos​

  • VM Windows 10/11
  • Derechos de administrador
  • Lab 7.2 completado (persistencia)

Contexto Profesional​

El registro de Windows es:

  • La base de datos central de configuración
  • Un objetivo privilegiado para la persistencia de malware
  • Un elemento clave a vigilar en seguridad

Parte 1: Navegación en el Registro​

Paso 1.1: Estructura del registro​

El registro está organizado en colmenas (hives):

ColmenaAliasContenido
HKEY_LOCAL_MACHINEHKLMConfiguración del sistema
HKEY_CURRENT_USERHKCUConfiguración del usuario actual
HKEY_USERSHKUTodos los perfiles de usuario
HKEY_CLASSES_ROOTHKCRAsociaciones de archivos
HKEY_CURRENT_CONFIGHKCCConfiguración de hardware actual

Paso 1.2: Acceso vía PowerShell​

# Las colmenas son accesibles como unidades
Get-PSDrive -PSProvider Registry

# Navegación
Set-Location HKLM:\SOFTWARE
Get-ChildItem

# Regresar
Set-Location C:\

Paso 1.3: Leer valores​

# Leer una clave completa
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"

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

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

Paso 1.4: Modificar el registro​

# Crear una clave
New-Item -Path "HKCU:\Software\LabTest" -Force

# Crear/modificar un 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"

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

Pregunta 1: ¿Por qué se utiliza -Type DWord para los números?


Parte 2: Claves de Seguridad Importantes​

Paso 2.1: Claves Run (Autoarranque)​

Estas claves ejecutan programas automáticamente:

# Mostrar todas las claves Run
Write-Host "=== CLAVES 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 " (no existe)"
}
}

Paso 2.2: Claves de servicios​

# Servicios 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

Paso 2.3: Claves de seguridad​

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

# RunAsPPL (protección LSASS)
$runAsPPL = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RunAsPPL" -ErrorAction SilentlyContinue
if ($runAsPPL.RunAsPPL -eq 1) {
Write-Host "LSA Protection: ACTIVA" -ForegroundColor Green
} else {
Write-Host "LSA Protection: INACTIVA" -ForegroundColor Red
}

# WDigest (credenciales en 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 credenciales en claro: ACTIVO (¡PELIGRO!)" -ForegroundColor Red
} else {
Write-Host "WDigest credenciales en claro: DESACTIVADO" -ForegroundColor Green
}

Paso 2.4: Asociaciones de archivos​

# Verificar las asociaciones (utilizadas para hijacking)
Write-Host "=== Asociaciones peligrosas ===" -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: Detección de Persistencia​

Paso 3.1: Script de detección completo​

<#
.SYNOPSIS
Detección de mecanismos de persistencia vía registro
#>

Write-Host @"
==============================================
DETECCIÓN PERSISTENCIA REGISTRO
==============================================
"@ -ForegroundColor Cyan

$findings = @()

# 1. Claves 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álisis de claves 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

# Criterios de sospecha
$suspicious = $false
$reasons = @()

if ($value -match "\\Temp\\|\\AppData\\Local\\Temp") {
$suspicious = $true
$reasons += "Ruta Temp"
}
if ($value -match "-[Ee]ncoded|-[Ww]indowStyle\s+[Hh]idden") {
$suspicious = $true
$reasons += "Argumentos sospechosos"
}
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. Servicios en rutas sospechosas
Write-Host "[2/5] Análisis de servicios..." -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 = "Ruta sospechosa"
}
}
}

# 3. Shell Extensions
Write-Host "[3/5] Análisis de 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 si el 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 faltante"
}
}
}
}
}
}

# 4. AppInit_DLLs
Write-Host "[4/5] Verificación 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 = "Inyección de DLL al inicio"
}
}

# 5. Image File Execution Options (Debugger)
Write-Host "[5/5] Verificación 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"
}
}
}

# Reporte
Write-Host "`n==============================================`n" -ForegroundColor Cyan

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

if ($suspiciousFindings.Count -eq 0) {
Write-Host "[OK] No se detectó persistencia sospechosa" -ForegroundColor Green
} else {
Write-Host "[!] $($suspiciousFindings.Count) elemento(s) sospechoso(s) detectado(s):" -ForegroundColor Red
$suspiciousFindings | Format-Table Type, Name, Reasons -AutoSize

Write-Host "`nDetalles:" -ForegroundColor Yellow
$suspiciousFindings | ForEach-Object {
Write-Host "`n Tipo: $($_.Type)" -ForegroundColor Cyan
Write-Host " Nombre: $($_.Name)"
Write-Host " Valor: $($_.Value)"
Write-Host " Razones: $($_.Reasons)" -ForegroundColor Yellow
}
}

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

Pregunta 2: ¿El script detectó elementos sospechosos en su VM?


Parte 4: Ejercicio Práctico​

Paso 4.1: Crear una persistencia de prueba​

# ATENCIÓN: ¡Solo para fines de prueba!
# Cree una entrada Run para comprender el mecanismo

# Crear una entrada inofensiva
Set-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestPersistence" `
-Value "cmd.exe /c echo Test de persistencia > C:\Temp\persistence_test.txt"

Write-Host "Entrada de prueba creada" -ForegroundColor Yellow

Paso 4.2: Detectar la persistencia​

# Ejecute el script de detección
# Su entrada debería ser detectada

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

Paso 4.3: Limpiar​

# Eliminar la entrada de prueba
Remove-ItemProperty `
-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" `
-Name "LabTestPersistence" `
-ErrorAction SilentlyContinue

Write-Host "Limpieza terminada" -ForegroundColor Green

Parte 5: Respaldo y Restauración​

Paso 5.1: Exportar una clave​

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

Write-Host "Clave exportada a: $exportPath" -ForegroundColor Green

Paso 5.2: Script de respaldo automático​

# Respaldo de claves de seguridad importantes
$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 "[ERROR] $($key.Name)" -ForegroundColor Red
}
}

Write-Host "`nRespaldo terminado: $backupFolder" -ForegroundColor Cyan

Entregables​

  1. Respuestas a las 2 preguntas

  2. Capturas de pantalla:

    • Navegación en el registro
    • Script de detección ejecutado
    • Persistencia de prueba creada y detectada
  3. Script de detección personalizado

  4. Informe (1 página):

    • Claves de registro importantes
    • Riesgos identificados
    • Recomendaciones de monitoreo

Criterios de Evaluación​

CriterioPuntos
Navegación en el registro20%
Claves de seguridad25%
Script de detección35%
Ejercicio práctico20%

Comandos de Referencia​

# Lectura
Get-ItemProperty "HKLM:\ruta"
Get-ItemPropertyValue "HKLM:\ruta" -Name "valor"

# Escritura
Set-ItemProperty -Path "ruta" -Name "nombre" -Value "valor"
New-Item -Path "ruta" -Force

# Eliminación
Remove-ItemProperty -Path "ruta" -Name "nombre"
Remove-Item -Path "ruta" -Recurse

# Exportar (vía reg.exe)
reg export "HKLM\ruta" archivo.reg /y
reg import archivo.reg

Recursos​


Lab desarrollado en el marco del curso Sistemas Operativos - MÓDULO 8