Monitoriza la actividad WMI con WMIMon

Cada vez es más y más común el malware "fileless" que no requiere a un atacante instalar ninguna pieza de software en el equipo de la víctima si no que se se apoya en el uso de herramientas presentes en el sistema operativo como WMI (Windows Management Infrastructure). 


WMI permite a los administradores realizar tareas muy rápidamente, pero puede convertirse también en algo muy peligroso cuando se usa de forma malintencionada. Es decir, de la misma forma que un administrador usa WMI para consultar métricas y ejecutar programas, un atacante puede usarlo para ejecutar de forma silenciosa código malicioso en toda una red de máquinas. WMI también permite la persistencia de programas al inicio o en función de eventos específicos.

WMI no se puede desinstalar, pero se puede deshabilitar. Sin embargo, hacerlo perjudica y limita lo que un administrador puede hacer, como actualizar software en múltiples máquinas. Por ello, la alternativa quizás más equilibrada es monitorizar su uso y una de las herramientas en la que podemos apoyarnos es la que hoy os traemos: WMIMon.

WMIMon del francés luctalpe de Microsoft permite monitorizar la actividad WMI en plataformas Windows. Puedes compilar tú mismo la herramienta o, si no tienes Visual Studio, descargarte directamente los binarios aquí.

WMIMon realmente un consumidor de ETL (Extract, Transform, Load) en tiempo real para el event log de WMI-Activity. Permitirá también obtener información sobre el proceso del cliente de WMI (ejecutable). Puede especificar una expresión regular para filtrar y limitar la salida a un ejecutable específico, nombre de usuario, nombre de equipo del cliente, ID de proceso o consulta.

Esta herramienta puede ser útil para varios escenarios:

- Encontrar qué ejecutable/equipo/usuario está ejecutando consultas específicas y cargando el sistema
- Aprender las consultas de WMI realizadas por sus componentes o un componente al que se necesite hacer un troubleshooting
-  Ejecutar un script específico cuando se devuelve un código de error WMI a un cliente

Ejemplo 1:

Ver todas la actividad WMI
C:\Temp> WMIMOn
***** *** Successfully Created ETW Session WMITrace_{1B701051-0E73-4EEE-85B7-567AC21B1E55}

***** *** Successfully Added Provider to  ETW Session

***** 14:38:22.372 Grp=125426 _ClientProcessId=3092 [MsMpEng.exe] LUCT10 NT AUTHORITY\SYSTEM
        IWbemServices::Connect
***** 14:38:22.376 Grp=125427 Op=125428 _ClientProcessId=3092 [MsMpEng.exe] LUCT10 NT AUTHORITY\SYSTEM
        Start IWbemServices::CreateInstanceEnum - root\SecurityCenter2 : AntiVirusProduct
***** 14:38:22.380 Stop Op=125426 0x0
***** 14:38:22.380 Stop Op=125428 0x0

Ejemplo 2:

Monitorizar todas las queries que contiene CreateSnaphost. Cuando esta query es ejecutada, se ejecuta también el script en powershell listvar.ps1 que muestra todas las variables de WMIMon y la info del proceso WMI actual (variable $WMIMOM_PID).
PS C:\temp\WMIMon> type .\listvar.ps1
ls variable:WMI*
get-process -ID $WMIMON_PID


PS C:\temp\WMIMon> .\WMIMon.exe "-filter=.*Virtual.*CreateSnapshot" "-action=.\listvar.ps1"
Parsing:        filtering on .*virtual.*createsnapshot
Parsing:        Powershell action when filter is found : .\listvar.ps1
***** *** Successfully Created ETW Session WMITrace_{81830E71-72D7-4228-94CE-A02FE99A01B8}

***** *** Successfully Added Provider to  ETW Session

***** 14:46:46.615 Grp=12388022 Op=12388023 _ClientProcessId=3448 [mmc.exe] LUCT2016 LUCT2016\luct
        Start IWbemServices::ExecMethod - root\virtualization\v2 : \\.\ROOT\virtualization\v2:Msvm_VirtualSystemSnapshot
Service.CreationClassName="Msvm_VirtualSystemSnapshotService",Name="vssnapsvc",SystemCreationClassName="Msvm_ComputerSys
tem",SystemName="LUCT2016"::CreateSnapshot

Name                           Value
----                           -----
WMIMON_PID                     3448
WMIMON_EXECUTABLE              mmc.exe
WMIMON_COMPUTER                LUCT2016
WMIMON_USER                    LUCT2016\luct
WMIMON_STOPSTATUS              0
WMIMON_ACTIVITY                14:46:46.615 Grp=12388022 Op=12388023 _ClientProcessId=3448 [mmc.exe] LUCT2016 LUCT201...
WMIMON_RELATEDACTIVITY

Id      : 3448
Handles : 1715
CPU     : 17070.078125
SI      : 2
Name    : mmc

***** 14:46:46.659 Stop Op=12388023 0x0

Uso:

- WMITrace.exe es una versión básica en C++ sin ninguna característica de filtrado
- WMIMON.exe es una herramienta en .Net con todas las características. Necesitarás copiar WMIMonC.dll en el mismo directorio.
c:\Temp> WMImon /?
Parsing:        Invalid argument /?


Usage:  WmiMon [-filter=regular_expression_string] [-stop=start|end|none] [-ifstopstatus=hexadecimal_value] [-log=all|filter] [action=pipeline]
                  default WmiMon [-filter=.*] [-stop=none] [-log=all]
will monitor WMI activity. By default all WMI activities are displayed.

You can filter the output with the -filter switch.
You can stop the application :
- if the filtering is successfull. Stop will occur at activity startup  if -stop=start is specified.
      If -stop=end is specified we will wait for the end of the activity to stop the monitoring
        Warning : if many records match the filtering pattern , memory usage  may increase
- if the filtering is successfull and _ifstopstatus condition is meet
    Warning : if many records match the filtering pattern , memory usage for this query may be hudge

For all filtered items or if a stop condition is meet , the pipeline action will be executed
Powershell variables WMIMON_* will be set in Powershell runspace to reflect the current WMI activity.
Your Powershell actions may use these variables (client PID, client computer, client user, stop status, WMI query,...)  

N.B: WMIMon is based on RealTime ETL notification. ETL infrastructure doesn't guarantee that all events will be received.
N.B: WMI Stop operation logging may occur after a delay based on client (get-cim* cmdlets cleanup occurs immediately
     This is not true with get-wmiobject cmdlet).

Repositorio: https://github.com/luctalpe/WMIMon

Comentarios