Hardening avanzado de Windows Server: LAPS, AppLocker y auditoría de eventos
15.1 Introducción: por qué Windows Server merece un módulo propio de hardening
es el de directorio, y archivos en la mayoría de las redes corporativas. Un mal endurecido equivale a dar las llaves del reino a cualquier atacante que obtenga acceso local. Este módulo cubre las capas de defensa que van más allá de la configuración básica y que, en la práctica, marcan la diferencia entre un entorno auditable y uno que se compromete por completo en minutos.
15.2 LAPS: contraseñas únicas para cada administrador local
15.2.1 El problema que resuelve LAPS
Sin Local Administrator Password Solution (LAPS), todas las estaciones de trabajo y servidores de un dominio suelen compartir la misma contraseña del administrador local — la que se configuró en la imagen base. Si un atacante extrae esa contraseña de una sola máquina (por ejemplo con mimikatz sekurlsa::logonpasswords), puede usarla en todas las demás (Pass-the- lateral).
15.2.2 Cómo funciona
LAPS extiende el esquema de con dos atributos nuevos en cada objeto de equipo:
| Atributo | Contenido |
|---|---|
ms-Mcs-AdmPwd | Contraseña en texto (protegida por de AD, legible solo para roles autorizados) |
ms-Mcs-AdmPwdExpirationTime | Fecha de expiración — la contraseña se rota automáticamente al vencer |
Un agente (CSE de Group Policy) en cada máquina genera una contraseña aleatoria, la escribe en AD y la rota según la política.
15.2.3 Windows LAPS (la versión moderna)
A partir de Windows Server 2019 con actualizaciones recientes y 11, Microsoft integró LAPS de forma nativa. La versión moderna añade:
- Cifrado de la contraseña en AD (la versión legacy la almacenaba en texto, protegida solo por ACL)
- Historial de contraseñas — se conservan las anteriores durante un período configurable
- Soporte para DSRM — también rota la contraseña del modo de restauración de servicios de directorio
15.2.4 Configuración completa
Legacy LAPS (agente MSI):
# Paso 1: Extender el esquema de AD (una sola vez, como Schema Admin)
Import-Module AdmPwd.PS
Update-AdmPwdADSchema
# Paso 2: Dar permiso a las máquinas para escribir su contraseña
Set-AdmPwdComputerSelfPermission -OrgUnit "OU=Servers,DC=corp,DC=local"
# Paso 3: Dar permiso de lectura al grupo de Service Desk
Set-AdmPwdReadPasswordPermission -OrgUnit "OU=Servers,DC=corp,DC=local" `
-AllowedPrincipals "ServiceDesk"
# Paso 4: Consultar la contraseña de una máquina
Get-AdmPwdPassword -ComputerName servidor01
Windows LAPS (nativo, Windows Server 2022+):
# Verificar soporte
Get-LapsADSchema
# Leer la contraseña almacenada (requiere permiso en AD)
Get-LapsADPassword -Identity servidor01 -AsPlainText
# Forzar rotación inmediata
Reset-LapsPassword -Identity servidor01
# Auditar qué máquinas NO tienen contraseña LAPS
Get-ADComputer -Filter * -Properties ms-LAPS-Password |
Where-Object { $_."ms-LAPS-Password" -eq $null } |
Select-Object Name
# Auditar expiración de contraseñas LAPS
Get-ADComputer -Filter * -Properties ms-LAPS-PasswordExpirationTime |
Select-Object Name, @{N='Expira';E={
[datetime]::FromFileTime($_."ms-LAPS-PasswordExpirationTime")
}} | Sort-Object Expira
Política de típica:
Computer Configuration → Policies → Administrative Templates → LAPS
├── Enable local admin password management: Enabled
├── Password Settings:
│ Complexity: Large letters + small letters + numbers + specials
│ Length: 20 characters
│ Age (days): 30
├── Name of administrator account to manage: Administrator
├── Do not allow password expiration time longer than policy: Enabled
└── Enable password encryption: Enabled (solo Windows LAPS)
15.2.5 Verificación de auditoría
# Verificar que ms-Mcs-AdmPwd NO es legible por Authenticated Users
# (error de configuración muy frecuente)
Import-Module ActiveDirectory
$OU = "OU=Servers,DC=corp,DC=local"
(Get-Acl "AD:\$OU").Access |
Where-Object { $_.ObjectType -eq "GUID_de_ms-Mcs-AdmPwd" } |
Select-Object IdentityReference, AccessControlType
# Comprobar que la GPO está vinculada a TODAS las OUs con equipos
Get-GPInheritance -Target "OU=Servers,DC=corp,DC=local" |
Select-Object -ExpandProperty InheritedGpoLinks
# Verificar que el agente funciona: si el atributo está vacío, LAPS no funciona
Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd |
Where-Object { $_."ms-Mcs-AdmPwd" -eq $null } |
Measure-Object | Select-Object Count
15.3 Group Policy: baselines de seguridad CIS
Los son la referencia de la industria para configurar Windows Server de forma segura. Se implementan mediante GPOs.
15.3.1 Políticas de cuentas
Computer Configuration → Policies → Windows Settings → Security Settings
→ Account Policies → Password Policy:
├── Enforce password history: 24 passwords remembered
├── Maximum password age: 365 days (con MFA activo)
├── Minimum password age: 1 day
├── Minimum password length: 14 characters
├── Password must meet complexity requirements: Enabled
└── Store passwords using reversible encryption: Disabled
→ Account Lockout Policy:
├── Account lockout duration: 15 minutes
├── Account lockout threshold: 5 invalid logon attempts
└── Reset account lockout counter after: 15 minutes
15.3.2 Políticas de auditoría avanzada
Computer Configuration → Policies → Windows Settings → Security Settings
→ Advanced Audit Policy Configuration:
Account Logon:
├── Audit Credential Validation: Success, Failure
└── Audit Kerberos Authentication Service: Success, Failure
Account Management:
├── Audit Security Group Management: Success
├── Audit User Account Management: Success, Failure
└── Audit Computer Account Management: Success
Detailed Tracking:
├── Audit Process Creation: Success
└── Audit DPAPI Activity: Success, Failure
Logon/Logoff:
├── Audit Logon: Success, Failure
├── Audit Logoff: Success
├── Audit Special Logon: Success
└── Audit Other Logon/Logoff Events: Success, Failure
Object Access:
├── Audit File System: Success, Failure
├── Audit Registry: Success, Failure
└── Audit SAM: Success
Policy Change:
├── Audit Audit Policy Change: Success, Failure
└── Audit Authentication Policy Change: Success
Privilege Use:
└── Audit Sensitive Privilege Use: Success, Failure
System:
├── Audit Security State Change: Success, Failure
├── Audit Security System Extension: Success, Failure
└── Audit System Integrity: Success, Failure
15.3.3 Derechos de usuario (User Rights Assignment)
Computer Configuration → Policies → Windows Settings → Security Settings
→ Local Policies → User Rights Assignment:
# Acceso local: solo administradores
Allow log on locally: Administrators
# Acceso remoto por RDP
Allow log on through Remote Desktop Services: Remote Desktop Users
# Denegaciones críticas (protegen contra escalada)
Deny access to this computer from the network: Guests, Local account
Deny log on as a batch job: Guests
Deny log on as a service: Guests
Deny log on locally: Guests
Deny log on through Remote Desktop Services: Guests, Local account
# Debug: SOLO administradores (mimikatz necesita SeDebugPrivilege)
Debug programs: Administrators
# En DCs: dejar vacío — nadie debe debuggear un DC
para auditar las GPOs de seguridad:
# Exportar todas las GPOs a HTML para revisión
Get-GPO -All | ForEach-Object {
$nombre = $_.DisplayName -replace '[\\/:*?"<>|]', '_'
Get-GPOReport -Guid $_.Id -ReportType Html -Path "C:\AuditGPO\$nombre.html"
}
# Verificar una política específica contra CIS benchmark
# Ejemplo: verificar que lockout está configurado
$gpo = Get-GPO -Name "CIS Baseline - Windows Server 2022"
$report = Get-GPOReport -Guid $gpo.Id -ReportType Xml
$xml = [xml]$report
# Buscar la configuración de lockout
$xml.GPO.Computer.ExtensionData.Extension.Account |
Where-Object { $_.Name -like "*Lockout*" }
15.4 AppLocker y WDAC: control de aplicaciones
15.4.1 Por qué limitar qué se ejecuta
El 90 % del y del tooling ofensivo depende de ejecutar un o script que no existía antes en la máquina. Si solo se permite ejecutar lo que está firmado o en una ruta aprobada, la mayoría de los ataques se bloquean antes de empezar — incluyendo macros de Office, scripts de descargados y de C2.
15.4.2 AppLocker
AppLocker permite crear reglas basadas en ruta, editor () y hash:
| Tipo de regla | Qué controla | Ejemplo |
|---|---|---|
| Ruta | Ubicación del archivo | Permitir solo C:\Program Files\* y C:\Windows\* |
| Editor (publisher) | Firma digital | Permitir todo lo firmado por Microsoft |
| Hash | Hash del binario | Permitir un binario específico por su SHA-256 |
Categorías de AppLocker (cada una independiente):
- Executables (
.exe,.com) - Windows Installer (
.msi,.msp) - Scripts (
.ps1,.bat,.cmd,.vbs,.js) - DLLs (
.dll,.ocx) — deshabilitada por defecto por impacto en rendimiento - Packaged apps (apps de la Store)
Configuración paso a paso:
# Paso 1: Generar reglas automáticas basadas en el software instalado
# (crea reglas por publisher para todo lo que ya está instalado)
Get-AppLockerFileInformation -Directory "C:\Program Files" -Recurse |
New-AppLockerPolicy -RuleType Publisher -User Everyone |
Set-AppLockerPolicy -Merge
# Paso 2: Crear reglas por defecto (permiten Windows y Program Files)
# GPO → Computer Configuration → Windows Settings → Security Settings
# → Application Control Policies → AppLocker
# → Click derecho en cada categoría → "Create Default Rules"
# Paso 3: Modo auditoría (NO bloquea, solo registra)
# En cada categoría: Properties → Configured → Audit only
# Paso 4: Revisar los eventos de auditoría después de 2-4 semanas
Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL" -MaxEvents 100 |
Where-Object { $_.Id -eq 8003 } | # 8003 = "would have been blocked"
Select-Object TimeCreated, Message |
Format-Table -Wrap
# Paso 5: Añadir excepciones para software legítimo que se bloquearía
# Ejemplo: permitir una aplicación interna por publisher
$rule = New-Object Microsoft.Security.ApplicationId.PolicyManagement.PolicyModel.PublisherRule
# ... o por hash para binarios sin firma
# Paso 6: Cambiar a modo Enforce cuando se confirma que no rompe nada
# Properties → Enforce rules
# Paso 7: Verificar que el servicio AppIDSvc está en automático
Set-Service -Name AppIDSvc -StartupType Automatic
Start-Service AppIDSvc
15.4.3 WDAC: Windows Defender Application Control
WDAC opera a nivel de — es más robusto que AppLocker porque un administrador local no puede desactivarlo sin reiniciar con una nueva política.
Diferencias clave:
| Aspecto | AppLocker | WDAC |
|---|---|---|
| Nivel | Servicio de usuario | de kernel |
| ¿Admin local lo elude? | Sí (puede parar el servicio) | No (requiere reinicio) |
| Gestión | GPO | GPO, MDM, ConfigCI |
| Ediciones de Windows | Enterprise/Education | Todas (incluso Pro) |
Creación de política WDAC paso a paso:
# Paso 1: Crear una política base escaneando el sistema actual
# Captura todo el software instalado como "permitido"
New-CIPolicy -Level Publisher -FilePath "C:\WDAC\BasePolicy.xml" `
-ScanPath "C:\" -UserPEs
# Paso 2: Crear una política restrictiva (solo Microsoft)
New-CIPolicy -Level Publisher -FilePath "C:\WDAC\MicrosoftOnly.xml" `
-ScanPath "C:\Windows" -UserPEs
# Paso 3: Fusionar las políticas
Merge-CIPolicy -PolicyPaths "C:\WDAC\BasePolicy.xml","C:\WDAC\MicrosoftOnly.xml" `
-OutputFilePath "C:\WDAC\MergedPolicy.xml"
# Paso 4: Configurar la política en modo auditoría primero
Set-RuleOption -FilePath "C:\WDAC\MergedPolicy.xml" -Option 3
# Opción 3 = "Enabled:Audit Mode"
# Paso 5: Convertir a binario
ConvertFrom-CIPolicy -XmlFilePath "C:\WDAC\MergedPolicy.xml" `
-BinaryFilePath "C:\WDAC\MergedPolicy.p7b"
# Paso 6: Desplegar la política
# Copiar a la carpeta de políticas de CI:
Copy-Item "C:\WDAC\MergedPolicy.p7b" `
"C:\Windows\System32\CodeIntegrity\SIPolicy.p7b"
# Reiniciar para aplicar
# Paso 7: Revisar eventos de auditoría
Get-WinEvent -LogName "Microsoft-Windows-CodeIntegrity/Operational" `
-MaxEvents 50 |
Where-Object { $_.Id -eq 3076 } | # 3076 = audit block
Select-Object TimeCreated, Message
# Paso 8: Cuando sea seguro, desactivar modo auditoría
Set-RuleOption -FilePath "C:\WDAC\MergedPolicy.xml" -Option 3 -Delete
# Reconvertir y redesplegar
15.5 Auditoría avanzada de eventos
15.5.1 Las categorías que importan
| Subcategoría | Event ID clave | Qué detecta |
|---|---|---|
| Logon/Logoff | 4624, 4625, 4648 | Logins exitosos, fallidos, credenciales explícitas (runas) |
| Account Logon | 4768, 4769, 4771 | TGT, TGS y preauth failures (AS-REP roasting) |
| Object Access | 4663 | Acceso a archivos y carpetas sensibles |
| Privilege Use | 4672 | con privilegios especiales (admin logon) |
| Process Creation | 4688 | Creación de procesos (con command line si se habilita) |
| Policy Change | 4719 | Cambios en la política de auditoría (tampering) |
| Account Management | 4720, 4728, 4732 | Creación de usuarios, cambios de grupo |
| Scheduled Task | 4698, 4702 | Creación/modificación de tareas programadas (persistencia) |
| Service Install | 7045 | Nuevo servicio instalado (, persistencia) |
15.5.2 Habilitar el registro de línea de comando
Por defecto, el evento 4688 registra que se creó un proceso pero NO qué argumentos recibió:
GPO: Computer Configuration → Administrative Templates → System
→ Audit Process Creation → Include command line in process creation events
→ Enabled
Sin command line: "4688: Process svchost.exe created" — inútil
Con command line: "4688: Process powershell.exe created,
CommandLine: powershell -enc SQBFAFgAIAAo..." — detecta PS codificado
15.5.3 Eventos de seguridad críticos para detección
# Script de monitorización de eventos críticos en tiempo real
$eventos_criticos = @{
# Credential access
4625 = "Login fallido (posible brute force)"
4648 = "Login con credenciales explícitas (runas)"
4768 = "Kerberos TGT request (monitorizar servicios)"
4771 = "Kerberos preauth failure (AS-REP roasting)"
# Persistence
4698 = "Tarea programada creada (posible persistencia)"
7045 = "Servicio instalado (posible persistencia/lateral)"
4720 = "Cuenta de usuario creada"
# Privilege escalation
4672 = "Privilegios especiales asignados (admin logon)"
4728 = "Miembro añadido a grupo con privilegios"
4732 = "Miembro añadido a grupo local de administradores"
# Defense evasion
4719 = "Política de auditoría modificada"
1102 = "Log de seguridad limpiado"
}
# Consultar eventos de las últimas 24 horas
$inicio = (Get-Date).AddHours(-24)
foreach ($id in $eventos_criticos.Keys) {
$count = (Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = $id
StartTime = $inicio
} -ErrorAction SilentlyContinue | Measure-Object).Count
if ($count -gt 0) {
Write-Host "[$id] $($eventos_criticos[$id]): $count eventos" -ForegroundColor Yellow
}
}
# Detectar brute force: >10 login fallidos en 5 minutos desde la misma IP
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=$inicio} |
Group-Object { $_.Properties[19].Value } | # IpAddress
Where-Object { $_.Count -gt 10 } |
Select-Object Name, Count
15.6 Sysmon: el complemento imprescindible
15.6.1 Instalación y configuración
Sysmon genera eventos que Windows no registra de forma nativa:
| Sysmon Event ID | Qué registra | Detección |
|---|---|---|
| 1 | Creación de proceso (con hash y padre) | LOLBins, malware |
| 3 | Conexión de red (proceso → IP:puerto) | C2, exfiltración |
| 7 | Carga de DLL (image loaded) | DLL injection, hijacking |
| 8 | CreateRemoteThread | Inyección de código |
| 10 | ProcessAccess | mimikatz abriendo lsass.exe |
| 11 | Creación de archivo | Dropper escribiendo payload |
| 12/13/14 | Cambios en registro | Persistencia por Run keys |
| 22 | Consulta por proceso | C2 por DNS, beaconing |
| 23 | Archivo eliminado (con contenido) | Anti-forense |
| 25 | Process Tampering | Hollowing, herpaderping |
# Descargar Sysmon
# https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon
# Instalar con la configuración de SwiftOnSecurity como base
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml" `
-OutFile "C:\Sysmon\sysmonconfig.xml"
# Instalar Sysmon con la configuración
.\Sysmon64.exe -accepteula -i C:\Sysmon\sysmonconfig.xml
# Verificar que está corriendo
Get-Service Sysmon64
# Actualizar la configuración sin reinstalar
.\Sysmon64.exe -c C:\Sysmon\sysmonconfig_nueva.xml
# Ver la configuración actual
.\Sysmon64.exe -c
15.6.2 Configuración personalizada para detección avanzada
<Sysmon schemaversion="4.90">
<HashAlgorithms>SHA256,IMPHASH</HashAlgorithms>
<EventFiltering>
<!-- ===== Evento 1: Creación de proceso ===== -->
<!-- Registrar TODOS los procesos (el filtro se hace en el SIEM) -->
<ProcessCreate onmatch="exclude">
<!-- Excluir solo el ruido más extremo -->
<Image condition="is">C:\Windows\System32\conhost.exe</Image>
</ProcessCreate>
<!-- ===== Evento 3: Conexiones de red ===== -->
<NetworkConnect onmatch="exclude">
<!-- Excluir navegadores y procesos de sistema conocidos -->
<Image condition="end with">chrome.exe</Image>
<Image condition="end with">firefox.exe</Image>
<Image condition="end with">msedge.exe</Image>
<Image condition="is">C:\Windows\System32\svchost.exe</Image>
</NetworkConnect>
<!-- ===== Evento 7: Carga de DLL (alto volumen, filtrar) ===== -->
<ImageLoad onmatch="include">
<!-- Solo DLLs cargadas desde ubicaciones sospechosas -->
<ImageLoaded condition="contains">\Users\</ImageLoaded>
<ImageLoaded condition="contains">\Temp\</ImageLoaded>
<ImageLoaded condition="contains">\AppData\</ImageLoaded>
<ImageLoaded condition="contains">\Downloads\</ImageLoaded>
</ImageLoad>
<!-- ===== Evento 8: CreateRemoteThread (inyección) ===== -->
<CreateRemoteThread onmatch="exclude">
<!-- Excluir inyecciones legítimas conocidas -->
<SourceImage condition="is">C:\Windows\System32\csrss.exe</SourceImage>
</CreateRemoteThread>
<!-- ===== Evento 10: ProcessAccess — LSASS ===== -->
<!-- CRÍTICO: detecta mimikatz, procdump, credential dumping -->
<ProcessAccess onmatch="include">
<TargetImage condition="end with">lsass.exe</TargetImage>
</ProcessAccess>
<!-- ===== Evento 11: Creación de archivos ===== -->
<FileCreate onmatch="include">
<!-- Archivos ejecutables creados en ubicaciones de usuario -->
<TargetFilename condition="contains">\Users\</TargetFilename>
<TargetFilename condition="end with">.exe</TargetFilename>
<TargetFilename condition="end with">.dll</TargetFilename>
<TargetFilename condition="end with">.ps1</TargetFilename>
<TargetFilename condition="end with">.bat</TargetFilename>
<TargetFilename condition="end with">.hta</TargetFilename>
<TargetFilename condition="end with">.vbs</TargetFilename>
</FileCreate>
<!-- ===== Evento 13: Cambios de registro (persistencia) ===== -->
<RegistryEvent onmatch="include">
<TargetObject condition="contains">CurrentVersion\Run</TargetObject>
<TargetObject condition="contains">CurrentVersion\RunOnce</TargetObject>
<TargetObject condition="contains">\Services\</TargetObject>
<TargetObject condition="contains">Windows\CurrentVersion\Explorer\Shell Folders</TargetObject>
<TargetObject condition="contains">\Software\Microsoft\Windows\CurrentVersion\Policies</TargetObject>
</RegistryEvent>
<!-- ===== Evento 22: DNS (C2 por DNS, DGA) ===== -->
<DnsQuery onmatch="exclude">
<!-- Registrar TODAS las consultas DNS excepto las más ruidosas -->
<QueryName condition="end with">.microsoft.com</QueryName>
<QueryName condition="end with">.windowsupdate.com</QueryName>
</DnsQuery>
<!-- ===== Evento 25: Process Tampering ===== -->
<ProcessTampering onmatch="exclude" />
</EventFiltering>
</Sysmon>
15.6.3 Reglas de detección específicas
Detectar credential dumping (acceso a LSASS — Sysmon Event 10):
La técnica más común de los atacantes es extraer credenciales de la memoria del proceso lsass.exe. Sysmon Event 10 registra cada vez que un proceso abre otro:
Alerta si:
Sysmon Event 10
AND TargetImage contiene "lsass.exe"
AND SourceImage NO es:
- C:\Windows\System32\lsass.exe (self)
- C:\Windows\System32\csrss.exe
- C:\Windows\System32\wininit.exe
- C:\Program Files\Windows Defender\MsMpEng.exe
AND GrantedAccess contiene 0x1010 o 0x1FFFFF
(PROCESS_QUERY_LIMITED_INFORMATION + PROCESS_VM_READ = mimikatz)
Detectar movimiento lateral por servicio remoto (Event 7045):
Alerta si:
Windows Security Event 7045 (nuevo servicio instalado)
AND ServiceFileName contiene:
- "cmd.exe" / "powershell.exe" (PsExec pattern)
- "\\\\<ip>\" (ruta UNC = ejecución remota)
- "COMSPEC" (variable de entorno en service binary path)
PsExec crea un servicio temporal llamado PSEXESVC con un binario
copiado a \\target\ADMIN$\. El Event 7045 captura exactamente esto.
Detectar persistencia por tareas programadas (Event 4698):
Alerta si:
Windows Security Event 4698 (tarea programada creada)
AND TaskContent contiene:
- "powershell" / "cmd" / "wscript" / "cscript" / "mshta"
- Ruta en %TEMP% o %APPDATA%
- Encoded command (-enc / -e)
- URL (http:// o https://)
AND Creator NO es un administrador conocido
AND TaskName NO coincide con tareas legítimas documentadas
15.7 Windows Event Forwarding (WEF) — configuración completa
En un entorno con más de unas pocas máquinas, revisar uno por uno no escala. WEF centraliza eventos de todas las estaciones en un servidor recolector.
15.7.1 Preparar el collector
# En el servidor collector:
# Paso 1: Habilitar el servicio Windows Event Collector
wecutil qc /q
# Paso 2: Crear un log personalizado para recibir los eventos
# (evita mezclarlos con los eventos locales del collector)
wevtutil cl "ForwardedEvents"
# Paso 3: Configurar el tamaño del log de eventos reenviados
wevtutil sl "ForwardedEvents" /ms:4294967296
# 4 GB — ajustar según volumen de endpoints
15.7.2 Preparar los source computers (por GPO)
Computer Configuration → Policies → Administrative Templates
→ Windows Components → Event Forwarding:
Configure target Subscription Manager:
Server=http://collector.corp.local:5985/wsman/SubscriptionManager/WEC,
Refresh=60
Computer Configuration → Policies → Windows Settings → Security Settings
→ System Services:
Windows Remote Management (WS-Management): Automatic
# En cada source computer (o por GPO startup script):
winrm quickconfig -q
# Añadir la cuenta del collector al grupo local Event Log Readers
net localgroup "Event Log Readers" "CORP\CollectorSvc$" /add
# Verificar conectividad WinRM
Test-WSMan -ComputerName collector.corp.local
15.7.3 Crear la suscripción
<!-- SecurityEvents.xml — suscripción de eventos de seguridad -->
<Subscription xmlns="http://schemas.microsoft.com/2006/03/windows/events/subscription">
<SubscriptionId>SecurityEvents</SubscriptionId>
<SubscriptionType>SourceInitiated</SubscriptionType>
<Description>Eventos de seguridad críticos de todos los endpoints</Description>
<Enabled>true</Enabled>
<Uri>http://schemas.microsoft.com/wbem/wsman/1/windows/EventLog</Uri>
<ConfigurationMode>MinLatency</ConfigurationMode>
<Delivery Mode="Push">
<Batching>
<MaxLatencyTime>1000</MaxLatencyTime>
</Batching>
</Delivery>
<Query>
<![CDATA[
<QueryList>
<Query Id="0" Path="Security">
<!-- Logon events -->
<Select Path="Security">
*[System[(EventID=4624 or EventID=4625 or EventID=4648)]]
</Select>
<!-- Kerberos -->
<Select Path="Security">
*[System[(EventID=4768 or EventID=4769 or EventID=4771)]]
</Select>
<!-- Account management -->
<Select Path="Security">
*[System[(EventID=4720 or EventID=4728 or EventID=4732)]]
</Select>
<!-- Process creation (con command line) -->
<Select Path="Security">
*[System[(EventID=4688)]]
</Select>
<!-- Scheduled tasks -->
<Select Path="Security">
*[System[(EventID=4698 or EventID=4702)]]
</Select>
<!-- Service install -->
<Select Path="System">
*[System[(EventID=7045)]]
</Select>
<!-- Audit policy changes / log cleared -->
<Select Path="Security">
*[System[(EventID=4719 or EventID=1102)]]
</Select>
</Query>
<!-- Sysmon events -->
<Query Id="1" Path="Microsoft-Windows-Sysmon/Operational">
<Select Path="Microsoft-Windows-Sysmon/Operational">*</Select>
</Query>
</QueryList>
]]>
</Query>
<ReadExistingEvents>false</ReadExistingEvents>
<TransportName>HTTP</TransportName>
<AllowedSourceNonDomainComputers />
<AllowedSourceDomainComputers>
O:NSG:NSD:(A;;GA;;;DC)(A;;GA;;;NS)
</AllowedSourceDomainComputers>
</Subscription>
# Crear la suscripción
wecutil cs SecurityEvents.xml
# Verificar el estado
wecutil gs SecurityEvents
wecutil gr SecurityEvents
# Listar suscripciones activas
wecutil es
15.8 PowerShell Constrained Language Mode
Constrained Language Mode (CLM) limita PowerShell para que solo pueda ejecutar cmdlets aprobados, bloqueando el acceso a .NET Framework, COM objects y Add-Type — las técnicas que usa el malware fileless.
GPO: Computer Configuration → Policies → Administrative Templates
→ Windows Components → Windows PowerShell:
Turn on Script Block Logging: Enabled
Turn on PowerShell Transcription: Enabled
(Transcript output directory: \\collector\PSTranscripts$)
Para forzar CLM en todas las sesiones:
Implementar con una política WDAC que restrinja scripts no firmados
→ PowerShell detecta automáticamente WDAC y entra en CLM
Alternativa (menos robusta): variable de entorno
__PSLockdownPolicy = 4 (vía GPO → Environment Variables)
# Verificar el modo actual
$ExecutionContext.SessionState.LanguageMode
# Debe devolver: ConstrainedLanguage
# En CLM, esto FALLA (bloquea .NET directo):
[System.IO.File]::ReadAllText("C:\secret.txt") # ERROR
Add-Type -TypeDefinition "..." # ERROR
New-Object -ComObject WScript.Shell # ERROR
# Pero esto SÍ funciona (cmdlets aprobados):
Get-Content "C:\archivo.txt" # OK
Get-Process # OK
15.9 Just Enough Administration (JEA)
JEA permite dar a los administradores exactamente los que necesitan — ni más, ni menos. En vez de dar Domain Admin a un técnico de DNS, se crea un rol JEA que solo permite ejecutar cmdlets de DNS.
15.9.1 Crear un rol JEA para administración de DNS
# Paso 1: Crear el archivo de Role Capability (.psrc)
New-PSRoleCapabilityFile -Path "C:\JEA\DnsAdmin.psrc"
# DnsAdmin.psrc — editar el contenido:
@{
# Cmdlets permitidos
VisibleCmdlets = @(
'DnsServer\*', # Todos los cmdlets de DNS
'Get-Service', # Ver estado de servicios
'Restart-Service' # Reiniciar servicios (solo DNS)
)
# Funciones visibles
VisibleFunctions = @(
'Get-DnsZoneStatus' # Función personalizada (definida abajo)
)
# Parámetros restringidos en Restart-Service
# Solo permite reiniciar el servicio DNS, no otros
VisibleCmdlets = @{
Name = 'Restart-Service'
Parameters = @{
Name = 'Name'
ValidateSet = 'DNS'
}
}
# Comandos externos permitidos
VisibleExternalCommands = @(
'C:\Windows\System32\nslookup.exe',
'C:\Windows\System32\ipconfig.exe'
)
# Funciones personalizadas disponibles en la sesión
FunctionDefinitions = @{
Name = 'Get-DnsZoneStatus'
ScriptBlock = {
Get-DnsServerZone | Select-Object ZoneName, ZoneType, IsReverseLookupZone
}
}
}
# Paso 2: Crear la configuración de sesión (.pssc)
New-PSSessionConfigurationFile -Path "C:\JEA\DnsAdmin.pssc" `
-SessionType RestrictedRemoteServer `
-RunAsVirtualAccount `
-RoleDefinitions @{
'CORP\DNS-Operators' = @{ RoleCapabilities = 'DnsAdmin' }
} `
-TranscriptDirectory "C:\JEA\Transcripts"
# Paso 3: Registrar el endpoint JEA
Register-PSSessionConfiguration -Name "DnsAdmin" `
-Path "C:\JEA\DnsAdmin.pssc" -Force
# Paso 4: Conectar al endpoint JEA
Enter-PSSession -ComputerName dc01 -ConfigurationName DnsAdmin
# El técnico solo ve los cmdlets de DNS — nada más
15.10 Attack Surface Reduction (ASR)
Las reglas ASR son mitigaciones integradas en que bloquean comportamientos concretos de malware sin necesidad de firmas.
15.10.1 Reglas ASR críticas
| GUID de la regla | Qué bloquea | Prioridad |
|---|---|---|
BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550 | Contenido ejecutable de email/webmail | Crítica |
D4F940AB-401B-4EFC-AADC-AD5F3C50688A | Office creando procesos hijo (macro → .exe) | Crítica |
9E6C4E1F-7D60-472F-BA1A-A39EF669E4B2 | Credential stealing desde LSASS | Crítica |
D1E49AAC-8F56-4280-B9BA-993A6D77406C | Creación de procesos desde PsExec/WMI | Alta |
C1DB55AB-C21A-4637-BB3F-A12568109D35 | Protección avanzada anti- | Alta |
3B576869-A4EC-4529-8536-B80A7769E899 | Office creando contenido ejecutable | Alta |
75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84 | Office inyectando código en otros procesos | Alta |
56A863A9-875E-4185-98A7-B882C64B5CE5 | Bloquear procesos no confiables de USB | Media |
15.10.2 Configuración de reglas ASR
# Habilitar reglas ASR en modo auditoría primero (valor 2)
# Modo: 0 = deshabilitado, 1 = bloquear, 2 = auditoría
# Block Office from creating child processes
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"D4F940AB-401B-4EFC-AADC-AD5F3C50688A" `
-AttackSurfaceReductionRules_Actions 2
# Block credential stealing from LSASS
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"9E6C4E1F-7D60-472F-BA1A-A39EF669E4B2" `
-AttackSurfaceReductionRules_Actions 2
# Block process creations from PsExec and WMI
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"D1E49AAC-8F56-4280-B9BA-993A6D77406C" `
-AttackSurfaceReductionRules_Actions 2
# Block executable content from email
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550" `
-AttackSurfaceReductionRules_Actions 2
# Block Office from creating executable content
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"3B576869-A4EC-4529-8536-B80A7769E899" `
-AttackSurfaceReductionRules_Actions 2
# Verificar estado de todas las reglas ASR
Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Ids
Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Actions
# Revisar eventos de auditoría ASR
Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" |
Where-Object { $_.Id -in @(1121, 1122) } | # 1121=blocked, 1122=audit
Select-Object TimeCreated, Message -First 20
# Cuando sea seguro, cambiar a modo bloqueo (valor 1)
Set-MpPreference -AttackSurfaceReductionRules_Ids `
"D4F940AB-401B-4EFC-AADC-AD5F3C50688A" `
-AttackSurfaceReductionRules_Actions 1
Configuración por GPO (recomendado para despliegue masivo):
Computer Configuration → Policies → Administrative Templates
→ Windows Components → Microsoft Defender Antivirus
→ Microsoft Defender Exploit Guard → Attack Surface Reduction:
Configure Attack Surface Reduction rules: Enabled
Set the state for each ASR rule:
D4F940AB-401B-4EFC-AADC-AD5F3C50688A = 1 (Block)
9E6C4E1F-7D60-472F-BA1A-A39EF669E4B2 = 1 (Block)
...
15.11 Credential Guard
Credential Guard aísla los secretos de LSASS en una protegida por el (Virtualization Based Security, VBS). Aunque un atacante obtenga SYSTEM, no puede extraer hashes NTLM ni tickets TGT de la memoria.
15.11.1 Requisitos
- UEFI con habilitado
- 2.0
- Virtualización de hardware (VT-x o AMD-V) habilitada en BIOS
- Windows Server 2016+ o Windows 10/11 Enterprise/Education
- Hyper-V no necesita estar instalado como rol (VBS usa el hipervisor directamente)
15.11.2 Habilitación por GPO
Computer Configuration → Policies → Administrative Templates
→ System → Device Guard:
Turn On Virtualization Based Security: Enabled
Platform Security Level: Secure Boot and DMA Protection
Virtualization Based Protection of Code Integrity: Enabled with UEFI lock
Credential Guard Configuration: Enabled with UEFI lock
Secure Launch Configuration: Enabled
# Verificar que Credential Guard está activo
Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard |
Select-Object VirtualizationBasedSecurityStatus,
SecurityServicesConfigured, SecurityServicesRunning
# VirtualizationBasedSecurityStatus:
# 0 = VBS no está corriendo
# 1 = VBS habilitado pero no corriendo
# 2 = VBS corriendo ✓
# SecurityServicesRunning debe incluir:
# 1 = Credential Guard
# 2 = HVCI (Hypervisor-enforced Code Integrity)
# Alternativa: msinfo32 → "Credential Guard" debe decir "Running"
systeminfo | findstr /i "credential guard"
Lo que protege: hashes NTLM derivados y tickets TGT en caché. Lo que NO protege: credenciales tecleadas activamente (), tickets de servicio ( sigue siendo posible), contraseñas en texto en memoria de aplicaciones.
15.12 Lab de detección con Elastic SIEM
Un laboratorio completo de detección conecta Sysmon + Winlogbeat al stack Elastic para visualizar alertas.
15.12.1 Docker Compose para Elastic SIEM
# docker-compose.yml
version: '3.8'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.12.0
environment:
- discovery.type=single-node
- xpack.security.enabled=false
- "ES_JAVA_OPTS=-Xms2g -Xmx2g"
ports:
- "9200:9200"
volumes:
- esdata:/usr/share/elasticsearch/data
kibana:
image: docker.elastic.co/kibana/kibana:8.12.0
ports:
- "5601:5601"
environment:
- ELASTICSEARCH_HOSTS=http://elasticsearch:9200
depends_on:
- elasticsearch
volumes:
esdata:
15.12.2 Configuración de Winlogbeat
# winlogbeat.yml — en cada endpoint Windows
winlogbeat.event_logs:
- name: Security
processors:
- drop_event.when.not.or:
- equals.winlog.event_id: 4624
- equals.winlog.event_id: 4625
- equals.winlog.event_id: 4648
- equals.winlog.event_id: 4672
- equals.winlog.event_id: 4688
- equals.winlog.event_id: 4698
- equals.winlog.event_id: 4720
- equals.winlog.event_id: 4728
- equals.winlog.event_id: 4732
- equals.winlog.event_id: 4768
- equals.winlog.event_id: 4769
- equals.winlog.event_id: 4771
- equals.winlog.event_id: 1102
- name: Microsoft-Windows-Sysmon/Operational
- name: System
processors:
- drop_event.when.not.or:
- equals.winlog.event_id: 7045
- name: Microsoft-Windows-Windows Defender/Operational
processors:
- drop_event.when.not.or:
- equals.winlog.event_id: 1121
- equals.winlog.event_id: 1122
- equals.winlog.event_id: 5007
output.elasticsearch:
hosts: ["http://siem.corp.local:9200"]
index: "winlogbeat-%{+yyyy.MM.dd}"
setup.kibana:
host: "http://siem.corp.local:5601"
setup.dashboards.enabled: true
# Instalar Winlogbeat como servicio
.\winlogbeat.exe setup
.\install-service-winlogbeat.ps1
Start-Service winlogbeat
15.12.3 Reglas de detección en Kibana
Una vez los datos fluyen, crear reglas de detección en Kibana → Security → Rules:
Regla 1: Credential Dumping (Sysmon Event 10 → lsass.exe)
KQL: event.code: "10" AND winlog.event_data.TargetImage: *lsass.exe
AND NOT winlog.event_data.SourceImage: (*csrss.exe OR *MsMpEng.exe)
Severidad: Critical
Acción: Alerta + email al SOC
Regla 2: Nuevo servicio sospechoso (Event 7045)
KQL: event.code: "7045"
AND winlog.event_data.ServiceFileName: (*cmd* OR *powershell* OR *\\\\*)
Severidad: High
Acción: Alerta
Regla 3: Tarea programada sospechosa (Event 4698)
KQL: event.code: "4698"
AND message: (*powershell* OR *cmd* OR *http* OR *-enc*)
Severidad: High
Acción: Alerta
Regla 4: Brute Force (>5 Event 4625 en 5 minutos)
KQL: event.code: "4625"
Threshold: >5 by source.ip per 5 minutes
Severidad: Medium
Acción: Alerta
15.13 Windows Firewall con seguridad avanzada
# Bloquear toda conexión entrante no autorizada explícitamente
Set-NetFirewallProfile -Profile Domain,Public,Private `
-DefaultInboundAction Block -DefaultOutboundAction Allow
# Permitir solo RDP desde la red de administración
New-NetFirewallRule -DisplayName "RDP - Admin Only" `
-Direction Inbound -Protocol TCP -LocalPort 3389 `
-RemoteAddress 10.0.100.0/24 -Action Allow
# Bloquear SMB desde fuera de la red corporativa
New-NetFirewallRule -DisplayName "Block SMB External" `
-Direction Inbound -Protocol TCP -LocalPort 445 `
-RemoteAddress "0.0.0.0/0" -Action Block
New-NetFirewallRule -DisplayName "Allow SMB Internal" `
-Direction Inbound -Protocol TCP -LocalPort 445 `
-RemoteAddress 10.0.0.0/8 -Action Allow
# Bloquear PowerShell Remoting desde fuera de la red de gestión
New-NetFirewallRule -DisplayName "Block WinRM External" `
-Direction Inbound -Protocol TCP -LocalPort 5985,5986 `
-RemoteAddress "0.0.0.0/0" -Action Block
# Habilitar logging del firewall
Set-NetFirewallProfile -Profile Domain `
-LogAllowed True -LogBlocked True `
-LogFileName "C:\Windows\System32\LogFiles\Firewall\pfirewall.log" `
-LogMaxSizeKilobytes 32768
# Exportar las reglas actuales para auditoría
Get-NetFirewallRule | Where-Object { $_.Enabled -eq 'True' } |
Select-Object DisplayName, Direction, Action, Profile |
Export-Csv "C:\Audit\firewall_rules.csv" -NoTypeInformation
15.14 Hardening de SMB
| Configuración | Valor seguro | Por qué |
|---|---|---|
SMB1Protocol | Deshabilitado | EternalBlue, WannaCry |
RequireSecuritySignature | True | Previene relay |
EncryptData | True | Cifrado del tráfico SMB 3.0+ |
EnableInsecureGuestLogons | False | Impide fallback a guest |
# Verificar configuración actual
Get-SmbServerConfiguration | Select-Object `
EnableSMB1Protocol, RequireSecuritySignature, EncryptData,
EnableInsecureGuestLogons
# Aplicar hardening
Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force
Set-SmbServerConfiguration -RequireSecuritySignature $true -Force
Set-SmbServerConfiguration -EncryptData $true -Force
Set-SmbServerConfiguration -EnableInsecureGuestLogons $false -Force
# Verificar que SMBv1 está completamente eliminado
Get-WindowsOptionalFeature -Online -FeatureName "SMB1Protocol"
# Si State = Enabled, desinstalar:
Disable-WindowsOptionalFeature -Online -FeatureName "SMB1Protocol" -NoRestart
15.15 Protected Users: el grupo que limita la superficie
El grupo (Server 2012 R2+) aplica restricciones automáticas:
- No se cachean credenciales en texto ni hashes NTLM — protege contra mimikatz
- No se permite autenticación NTLM — fuerza Kerberos
- TGT de vida corta (4 horas vs. 10) — limita Pass-the-Ticket
- No se permite delegación — previene por servicios intermedios
# Añadir cuentas privilegiadas
Add-ADGroupMember -Identity "Protected Users" -Members "admin-t0","admin-t1"
# Verificar membresía
Get-ADGroupMember -Identity "Protected Users" | Select-Object Name, ObjectClass
# Precaución: verificar que ningún servicio depende de NTLM
# para estas cuentas antes de añadirlas
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624} -MaxEvents 1000 |
Where-Object { $_.Properties[8].Value -eq 'NTLM' } |
Group-Object { $_.Properties[5].Value } |
Select-Object Name, Count | Sort-Object Count -Descending
15.16 Checklist de hardening de Windows Server
- LAPS desplegado y verificado en TODAS las OUs con equipos
- Baselines CIS aplicadas por GPO (cuentas, auditoría, derechos)
- AppLocker o WDAC en modo enforce (al menos scripts y ejecutables)
- Auditoría avanzada habilitada (4688 con command line, Kerberos, logon)
- Sysmon instalado con configuración personalizada
- WEF configurado para centralizar eventos en collector
- Reglas ASR habilitadas (Office, LSASS, PsExec, ransomware)
- Credential Guard activo en DCs y servidores críticos
- PowerShell en Constrained Language Mode
- JEA configurado para administración delegada
- SMBv1 deshabilitado, signing obligatorio, cifrado habilitado
- Windows con reglas restrictivas y logging
- Grupo "Protected Users" con cuentas privilegiadas
- Cuentas de servicio sin Domain Admin (usar )
- recibiendo eventos con reglas de detección activas
15.17 Herramientas y fuentes
| Herramienta | Propósito | Fuente |
|---|---|---|
| Sysmon | Monitorización avanzada de procesos | https://learn.microsoft.com/sysinternals/downloads/sysmon |
| SwiftOnSecurity sysmon-config | Configuración de referencia | https://github.com/SwiftOnSecurity/sysmon-config |
| Olaf Hartong sysmon-modular | Config modular avanzada | https://github.com/olafhartong/sysmon-modular |
| CIS Benchmarks | Baselines de seguridad | https://www.cisecurity.org/cis-benchmarks |
| Microsoft Security Baselines | GPOs oficiales de Microsoft | https://www.microsoft.com/security/blog/baseline/ |
| Elastic SIEM | Plataforma de detección | https://www.elastic.co/security |
| Winlogbeat | Envío de eventos a Elastic | https://www.elastic.co/beats/winlogbeat |
| Rules | Reglas de detección universales | https://github.com/SigmaHQ/sigma |
| WDAC Wizard | GUI para crear políticas WDAC | https://webapp-wdac-wizard.azurewebsites.net |
| PingCastle | Auditoría de seguridad de AD | https://www.pingcastle.com |
referencias de este módulo:
- T1003.001: OS Credential Dumping: LSASS Memory (→ Sysmon Event 10, ASR, Credential Guard)
- T1053.005: Scheduled Task (→ Event 4698, Sysmon Event 11)
- T1543.003: Create or Modify System Process: Windows Service (→ Event 7045)
- T1059.001: Command and Scripting Interpreter: PowerShell (→ CLM, Script Block Logging)
- T1021.002: Remote Services: SMB (→ SMB , signing)
- T1550.002: Use Alternate Authentication Material: Pass the Hash (→ LAPS, Protected Users)
- T1562.001: Impair Defenses: Disable or Modify Tools (→ Event 4719, tamper protection)