Microsoft windows wmi activity

Shell is Only the Beginning

When getting shell is only the start of the journey.

WMI (Windows Management Instrumentation) has been part of the Windows Operating System since since Windows 2000 when it was included in the OS. The technology has been of great value to system administrators by providing ways to pull all types of information, configure components and take action based on state of several components of the OS. Due to this flexibility it has been abused by attackers that saw its potential since it early inclusion in the OS.

As security practitioners it is one of the technologies on Microsoft Windows that is of great importance to master. Until recently there was little to now logging of the actions one could take using WMI. Blue Teams where left leveraging third party tools or coding their own solution to cover gaps, this allowed for many year the abuse of WMI by Red Teams simulating the very actions that attackers of all kind have used in their day to day operation. We will take a look at how Microsoft improved the logging of WMI actions.

The WMI Activity Provider

The WMI Activity eventlog provider in Windows until 2012 was mostly for logging debug and trace information for WMI when it was enabled. It was expanded with this release of Windows to have an Operational log that logged several actions. Lets take a look at the provider it self and what does it offer. For this we will use PowerShell and in it the Get-WinEvent cmdlet to get the information.

We start by getting the object representing the provider:

PS C:\> $WmiProv = Get-WinEvent -ListProvider "Microsoft-Windows-WMI-Activity"
PS C:\> $WmiProv


Name     : Microsoft-Windows-WMI-Activity
LogLinks : {Microsoft-Windows-WMI-Activity/Trace, Microsoft-Windows-WMI-Activity/Operational, Microsoft-Windows-WMI-Activity/Debug}
Opcodes  : {}
Tasks    : {}

PowerShell formats the output of this object so we need to use the Format-List parameter to see all properties and which have values set on them.

PS C:\> $WmiProv | Format-List -Property *


ProviderName      : Microsoft-Windows-WMI-Activity
Name              : Microsoft-Windows-WMI-Activity
Id                : 1418ef04-b0b4-4623-bf7e-d74ab47bbdaa
MessageFilePath   : C:\WINDOWS\system32\wbem\WinMgmtR.dll
ResourceFilePath  : C:\WINDOWS\system32\wbem\WinMgmtR.dll
ParameterFilePath :
HelpLink          : https://go.microsoft.com/fwlink/events.asp?CoName=Microsoft Corporation&ProdName=Microsoft® Windows® Operating
                    System&ProdVer=10.0.15063.0&FileName=WinMgmtR.dll&FileVer=10.0.15063.0
DisplayName       : Microsoft-Windows-WMI-Activity
LogLinks          : {Microsoft-Windows-WMI-Activity/Trace, Microsoft-Windows-WMI-Activity/Operational, Microsoft-Windows-WMI-Activity/Debug}
Levels            : {win:Error, win:Informational}
Opcodes           : {}
Keywords          : {}
Tasks             : {}
Events            : {1, 2, 3, 11...}

Lets take a look at the LogLinks or where does the provider saves its events.

PS C:\> $WmiProv.LogLinks

LogName                                    IsImported DisplayName
-------                                    ---------- -----------
Microsoft-Windows-WMI-Activity/Trace            False
Microsoft-Windows-WMI-Activity/Operational      False
Microsoft-Windows-WMI-Activity/Debug            False

The one we are interested in is the Microsoft-Windows-WMI-Activity/Operational one. Now that we have identified the specific EventLog name for which we are interested in the events that will be saved there we can now take a look at the events the provider generates.

A event provider can generate from a few events to over a 100. So look at how many events the provider generates using the Measure-Object cmdlet

PS C:\> $WmiProv.Events | Measure-Object


Count    : 22
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

We see that the provider generates 22 events. We take a look at how each object is composed using the Get-Member cmdlet.

PS C:\> $WmiProv.Events | Get-Member


   TypeName: System.Diagnostics.Eventing.Reader.EventMetadata

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()
Description Property   string Description {get;}
Id          Property   long Id {get;}
Keywords    Property   System.Collections.Generic.IEnumerable[System.Diagnostics.Eventing.Reader.EventKeyword] Keywords {get;}
Level       Property   System.Diagnostics.Eventing.Reader.EventLevel Level {get;}
LogLink     Property   System.Diagnostics.Eventing.Reader.EventLogLink LogLink {get;}
Opcode      Property   System.Diagnostics.Eventing.Reader.EventOpcode Opcode {get;}
Task        Property   System.Diagnostics.Eventing.Reader.EventTask Task {get;}
Template    Property   string Template {get;}
Version     Property   byte Version {get;}

We can see that each event has a LogLink property and the value is of type System.Diagnostics.Eventing.Reader.EventLogLink. The value is an object of it self. We can quickly take a peak in to the object to see what the values are and how they are formated.

PS C:\> $WmiProv.Events[0].LogLink

LogName                              IsImported DisplayName
-------                              ---------- -----------
Microsoft-Windows-WMI-Activity/Trace      False


PS C:\> $WmiProv.Events[0].LogLink | gm


   TypeName: System.Diagnostics.Eventing.Reader.EventLogLink

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()
DisplayName Property   string DisplayName {get;}
IsImported  Property   bool IsImported {get;}
LogName     Property   string LogName {get;}

We can now filter for the events we want to take a look at.

PS C:\> $WmiProv.Events | Where-Object {$_.LogLink.LogName -eq "Microsoft-Windows-WMI-Activity/Operational"}


Id          : 5857
Version     : 0
LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink
Level       : System.Diagnostics.Eventing.Reader.EventLevel
Opcode      : System.Diagnostics.Eventing.Reader.EventOpcode
Task        : System.Diagnostics.Eventing.Reader.EventTask
Keywords    : {}
Template    : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">
                <data name="ProviderName" inType="win:UnicodeString" outType="xs:string"/>
                <data name="Code" inType="win:HexInt32" outType="win:HexInt32"/>
                <data name="HostProcess" inType="win:UnicodeString" outType="xs:string"/>
                <data name="ProcessID" inType="win:UInt32" outType="xs:unsignedInt"/>
                <data name="ProviderPath" inType="win:UnicodeString" outType="xs:string"/>
              </template>

Description : %1 provider started with result code %2. HostProcess = %3; ProcessID = %4; ProviderPath = %5

Id          : 5858
Version     : 0
LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink
Level       : System.Diagnostics.Eventing.Reader.EventLevel
Opcode      : System.Diagnostics.Eventing.Reader.EventOpcode
Task        : System.Diagnostics.Eventing.Reader.EventTask
Keywords    : {}
Template    : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">
                <data name="Id" inType="win:UnicodeString" outType="xs:string"/>
                <data name="ClientMachine" inType="win:UnicodeString" outType="xs:string"/>
                <data name="User" inType="win:UnicodeString" outType="xs:string"/>
                <data name="ClientProcessId" inType="win:UInt32" outType="xs:unsignedInt"/>
                <data name="Component" inType="win:UnicodeString" outType="xs:string"/>
                <data name="Operation" inType="win:UnicodeString" outType="xs:string"/>
                <data name="ResultCode" inType="win:HexInt32" outType="win:HexInt32"/>
                <data name="PossibleCause" inType="win:UnicodeString" outType="xs:string"/>
              </template>

Description : Id = %1; ClientMachine = %2; User = %3; ClientProcessId = %4; Component = %5; Operation = %6; ResultCode = %7; PossibleCause = %8

Id          : 5859
Version     : 0
LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink
Level       : System.Diagnostics.Eventing.Reader.EventLevel
Opcode      : System.Diagnostics.Eventing.Reader.EventOpcode
Task        : System.Diagnostics.Eventing.Reader.EventTask
Keywords    : {}
Template    : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">
                <data name="NamespaceName" inType="win:UnicodeString" outType="xs:string"/>
                <data name="Query" inType="win:UnicodeString" outType="xs:string"/>
                <data name="User" inType="win:UnicodeString" outType="xs:string"/>
                <data name="processid" inType="win:UInt32" outType="xs:unsignedInt"/>
                <data name="providerName" inType="win:UnicodeString" outType="xs:string"/>
                <data name="queryid" inType="win:UInt32" outType="xs:unsignedInt"/>
                <data name="PossibleCause" inType="win:UnicodeString" outType="xs:string"/>
              </template>

Description : Namespace = %1; NotificationQuery = %2; OwnerName = %3; HostProcessID = %4;  Provider= %5, queryID = %6; PossibleCause = %7

Id          : 5860
Version     : 0
LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink
Level       : System.Diagnostics.Eventing.Reader.EventLevel
Opcode      : System.Diagnostics.Eventing.Reader.EventOpcode
Task        : System.Diagnostics.Eventing.Reader.EventTask
Keywords    : {}
Template    : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">
                <data name="NamespaceName" inType="win:UnicodeString" outType="xs:string"/>
                <data name="Query" inType="win:UnicodeString" outType="xs:string"/>
                <data name="User" inType="win:UnicodeString" outType="xs:string"/>
                <data name="processid" inType="win:UInt32" outType="xs:unsignedInt"/>
                <data name="MachineName" inType="win:UnicodeString" outType="xs:string"/>
                <data name="PossibleCause" inType="win:UnicodeString" outType="xs:string"/>
              </template>

Description : Namespace = %1; NotificationQuery = %2; UserName = %3; ClientProcessID = %4, ClientMachine = %5; PossibleCause = %6

Id          : 5861
Version     : 0
LogLink     : System.Diagnostics.Eventing.Reader.EventLogLink
Level       : System.Diagnostics.Eventing.Reader.EventLevel
Opcode      : System.Diagnostics.Eventing.Reader.EventOpcode
Task        : System.Diagnostics.Eventing.Reader.EventTask
Keywords    : {}
Template    : <template xmlns="http://schemas.microsoft.com/win/2004/08/events">
                <data name="Namespace" inType="win:UnicodeString" outType="xs:string"/>
                <data name="ESS" inType="win:UnicodeString" outType="xs:string"/>
                <data name="CONSUMER" inType="win:UnicodeString" outType="xs:string"/>
                <data name="PossibleCause" inType="win:UnicodeString" outType="xs:string"/>
              </template>

Description : Namespace = %1; Eventfilter = %2 (refer to its activate eventid:5859); Consumer = %3; PossibleCause = %4

We can now see the events that are specific for that eventlog. We can also see the amount of details we can get for each event, including the XML template for the message. This will be useful when we write XPath filters.

We can save them to a variable and pull the IDs for the events.

PS C:\> $WmiEvents = $WmiProv.Events | Where-Object {$_.LogLink.LogName -eq "Microsoft-Windows-WMI-Activity/Operational"}
PS C:\> $WmiEvents | Select-Object -Property Id

  Id
  --
5857
5858
5859
5860
5861

Provider Loading

Every time WMI is initialized it loads providers that will build the classes and provide access to the OS and System components that it exposes as classes and its instances. This provides executes under the context of SYSTEM in the user, in other words they execute with a very high privilege in Windows. Several actors and Red Teams leverage malicious providers as backdoor so as as to keep persistent access on systems.  Many forensic and incident response team do not look for new providers being added on systems or for suspicious exiting ones. Some examples of malicious providers are:

  • https://gist.github.com/subTee/c6bd1401504f9d4d52a0 SubTee Shellcode Execution WMI Class
  • https://github.com/jaredcatkinson/EvilNetConnectionWMIProvider Jared Atkinson Evil WMI Provider Example

In the list of Event Id we saw this would be event 5857 and it’s structure we have some very useful information that is of great help when hunting. 

5857.png

As we can see in its structure we have information on the ProcessID and Thread that loaded the provider, we can also see the name of the host process name and the path to the DLL loaded. 

If we are using Windows Event Collector we can create an XML filter with known providers and filters those out so we only see new unseen providers . We can generate a quick list of the unique privider files with a bit of PowerShell

PS C:\> Get-WinEvent -FilterHashtable @{logname='Microsoft-Windows-WMI-Activity/Operational';Id=5857} | % {$_.properties[4].value} | select -unique
%SystemRoot%\system32\wbem\wbemcons.dll
%systemroot%\system32\wbem\wmipiprt.dll
%systemroot%\system32\wbem\wmiprov.dll
C:\Windows\System32\wbem\krnlprov.dll
%systemroot%\system32\wbem\wmipcima.dll
C:\Windows\System32\wbem\WmiPerfClass.dll
%SystemRoot%\system32\tscfgwmi.dll
%systemroot%\system32\wbem\cimwin32.dll
%systemroot%\system32\wbem\vdswmi.dll
%SystemRoot%\System32\sppwmi.dll
%systemroot%\system32\wbem\WMIPICMP.dll
%SystemRoot%\System32\Win32_DeviceGuard.dll
%SYSTEMROOT%\system32\PowerWmiProvider.dll
%SystemRoot%\System32\storagewmi.dll
%systemroot%\system32\wbem\stdprov.dll
%systemroot%\system32\profprov.dll
C:\Windows\System32\wbem\WmiPerfInst.dll
%systemroot%\system32\wbem\DMWmiBridgeProv.dll
C:\Windows\SysWOW64\wbem\WmiPerfClass.dll

We can turn this in to a XML Filter that we can use either with Get-WinEvent while hunting or WEC for collection

<QueryList>
  <Query Id="0" Path="Microsoft-Windows-WMI-Activity/Operational">
    <Select Path="Microsoft-Windows-WMI-Activity/Operational">*[System[(EventID=5857)]]
    </Select>
    <Suppress Path="Microsoft-Windows-WMI-Activity/Operational">
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\wmiprov.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\wmipcima.dll']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\System32\sppwmi.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\vdswmi.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\DMWmiBridgeProv.dll']) or
    (*[UserData/*/ProviderPath='C:\Windows\System32\wbem\WmiPerfClass.dll']) or
    (*[UserData/*/ProviderPath='C:\Windows\System32\wbem\krnlprov.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\wmipiprt.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\stdprov.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\profprov.dll']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\System32\Win32_DeviceGuard.dll']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\System32\smbwmiv2.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\cimwin32.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\wmiprvsd.dll']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\system32\wbem\scrcons.exe']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\system32\wbem\wbemcons.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\vsswmi.dll']) or
    (*[UserData/*/ProviderPath='%SystemRoot%\system32\tscfgwmi.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\ServerManager.DeploymentProvider.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\mgmtprovider.dll']) or
    (*[UserData/*/ProviderPath='%systemroot%\system32\wbem\ntevt.dll']) or
    (*[UserData/*/ProviderPath='%SYSTEMROOT%\System32\wbem\DnsServerPsProvider.dll'])
    </Suppress>
    <Suppress Path="Microsoft-Windows-WMI-Activity/Operational">
    (*[UserData/*/ProviderPath='%windir%\system32\wbem\servercompprov.dll']) or
    (*[UserData/*/ProviderPath='C:\Windows\System32\wbem\WmiPerfInst.dll'])
    </Suppress>
  </Query>
</QueryList>

WMI Query Errors

EventLog Id 5858 logs all query errors, the data include the error code in the element ResultCode and the Query that caused it under the element Operation. The Process Id is also included but in this event it is under the ClientProcessId element. 

5858.png

The error code is in hex format. Thankfully Microsoft has a list of WMI Error Constants in MSDN https://msdn.microsoft.com/en-us/library/aa394559(v=vs.85).aspx that we can use to figure what the specific error was. We can query easily for specific result codes using an XPathFilter. In the following exampled we are looking for queries that failed because the specified Class did not exist searching for ResultCode 0x80041010. This could useful if an attacker is looking for a specific class present on the systems. Like a permanent event consumer he can modify for persistence.

PS C:\> Get-WinEvent -FilterXPath "*[UserData/*/ResultCode='0x80041010']" -LogName "Microsoft-Windows-WMI-Activity/Operational"

We could also search for queries that failed due to insufficient permissions.

PS C:\> Get-WinEvent -FilterXPath "*[UserData/*/ResultCode='0x80041003']" -LogName "Microsoft-Windows-WMI-Activity/Operational"

Eventing

The way events operate by monitoring for specific events generated by the CIM Database in Windows. WMI Events are those events that happen when a specific Event Class instance is created or they are defined in the WMI Model. The way most event work is by the creation of a query that defines what we are looking for to happen, a action that will be taken once the event happens and both are registered together. There are 2 types of WMI Event Subscription:

  • Temporary – Subscription is active as long as the process that created the subscription is active. (They run under the privilege of the process)
  • Permanent – Subscription is stored in the CIM Database and are active until removed from it. (They always run as SYSTEM)

Temporary Events

One of the areas where some have moved to now that the detection of permanent WMI events is more common due to some tools is the use of temporary event consumers. This can be written in C++, .Net, WSH and PowerShell, they allow the use of WMI Event filters to trigger an action that is executed by the application it self. These are not common but easy to write and operate as long as the application is running. We can track this events with events with Id 5860. Once the application registers the Event Consumer the event is created. 

Here is an example in PowerShell of a temporary event consumer that simply writes the name of a process that has been launched. 

# Query for new process events 
$queryCreate = "SELECT * FROM __InstanceCreationEvent WITHIN 5" + 
    "WHERE TargetInstance ISA 'Win32_Process'" 

# Create an Action
$CrateAction = {
    $name = $event.SourceEventArgs.NewEvent.TargetInstance.name
    write-host "Process $($name) was created."
}

# Register WMI event 
Register-WMIEvent -Query $queryCreate -Action $CrateAction 

When the Event Consumer is registered with Register-WmiEvent we get the following event logged on the system.

5960.png

We can see that the Query being used to monitor for events is logged under UserData under the element Query and under the element PlaussibleCause we see that it is marked as Temporary. 

Permanent Events

When a __EventFilter, and any of the consumer type class objects are used in the creation of a Binder instance in the WMI CIM Database to create a permanent event a eventlog entry with Id 5861 is created. The event is also created in modification if any of the component class instances are modified. The event will contain all the information associated about the permanent even in the UserData element under the PossibleCause subelement.

5961.png

When __EventFilter or Consumer that make up a permanent event is modified it generates the same event but there is no field in the data to show if it was modified or not. 

The event says to look at Event Id 5859 for the __EventFilter class that makes up the permanent event but at the moment I have not seen a event created with this Id in all my testing. 

Conclusion

As you can see Microsoft has improved quiet a bit the natural logging capabilities in the latest version of Windows. Sadly this has not been back ported to Windows 7 and Windows 2008/2008 R2. We are able to track:

  • Query Errors.
  • Temporary Event Creation
  • Permanent Event Creation and Modification
  • Loading of Providers.

From a Red Team perspective this lets us know that our actions can be tracked and we should look if this events are collected when we measure the level of maturity of the target. From a Blue Team perspective these are events you should be collecting and analyzing in your enviroment for possible malicious actions. 

If WMI-Activity consumes more than usual resources and it displays an Event ID 5858 on a Windows 11/10 computer, these solutions are for you. You can find the CPU or Memory usage details about this activity in the Task Manager and find the Event ID in the Event Viewer. Either way, you can resolve the issue within moments using these instructions.

Event ID 5858, WMI-Activity high CPU

What is WMI used for?

WMI or Windows Management Instrumentation establishes a connection between your system and applications. Having said that, your installed apps require your system to run, and they fetch many things while running. If this utility has some issues or your apps come with some problems, the Task Manager flags this service immediately. As a result, Event Viewer logs the event as an error with an Event ID named 5858. If it is 5857, you should not have any issue since it denotes “Information” while 5858 denotes “Error.”

To fix Event ID 5858 or WMI-Activity’s high CPU usage issue on your Windows 11/10 computer, follow these instructions:

  1. Temporarily disable recently installed app
  2. Find the faulty app using PID
  3. Restart WMI service

Before heading towards the listed solutions, we suggest you restart your computer once. At times, a simple restart could fix this problem.

1] Temporarily disable recently installed app

First of all, it doesn’t resolve the problem permanently. However, by doing this, you would know whether your recently installed app is causing this issue or not. That way, you can act faster. As said earlier, apps use this service to fetch system information. That is why it is suggested to temporarily close or disable (for antivirus/firewall) any app you have recently installed.

However, if you haven’t installed any app recently, there is no need to go through this step.

Fix: Windows Management Instrumentation error 1083

2] Find the faulty app using PID

PID or Process ID gets assigned to each process or app you have run on your computer so far. Fortunately, both Task Manager and Event Viewer show this PID so that you can identify the faulty app or the app, which is affecting WMI-Activity and causing the high CPU usage problem.

To find the PID in Event Viewer, you need to open the utility first. Then, go to this path:

Applications and Services Logs > Microsoft > Windows > WMI-Activity > Operational

In the Operational section, several events are on the right-hand side. A few of them are marked as Error. You need to click on any Error-marked event, which also has the Event ID 5858.

Then, find the ClientProcessId in the General or Details tab and note it down.

Event ID 5858, WMI-Activity high CPU

Next, open the Task Manager and go to the Details tab. After that, search for the same PID.

Event ID 5858, WMI-Activity high CPU

It is the app that is causing the issue and being masked as WMI-Activity. Depending on the app, you need to close/repair/update the app or tweak some settings.

3] Restart WMI service

Event ID 5858, WMI-Activity high CPU

WMI service needs to run all the time to allow all apps to work smoothly. However, if there are some internal issues with this service, it could cause the aforementioned problem. That is why we suggest you restart the service. For that, do the following:

  • Search for services in the Taskbar search box and click on the individual search result.
  • Double-click on the Windows Management Instrumentation service.
  • Click the Stop button.
  • Expand the Starup type drop-down menu and select the Automatic option.
  • Click the Start button.
  • Click on the OK button.

However, it is also important to restart the RPM or Remote Procedure Call since the WMI service depends on it. You can repeat the same above-mentioned steps and restart the Remote Procedure Call (RPC) service.

Although these solutions should work, at times, this problem might occur due to a corrupt driver as well. In that case, you need to boot your computer in the Clean Boot state and troubleshoot the issue.

I hope these solutions worked for you.

Read: WMI Provider Host High CPU Usage in Windows

How do I fix a corrupted WMI?

If the WMI is corrupted, it is best to use the System Restore point. However, if there is a minor problem, you can reset the WMI repository first. Following that, you can force recovery of the Windows Management Instrumentation. You can go through this guide to learn how to repair corrupted WMI.

Read: Fix Event ID 55 or 35 (Kernel-Processor-Power) error.

Любой администратор Windows сталкивался с проблемами в работе службы WMI (Windows Management Instrumentation) и ее компонентах. WMI это одна из ключевых подсистем Windows, и если она неисправна, на компьютере могут наблюдаться проблемы с работой служб, получением системной информации от WMI провайдеров, выполнением скриптов и ошибки в работе сторонних приложений. В этой статье мы рассмотрим, как выполнить диагностику работоспособности WMI и исправить типовые проблемы, если WMI репозиторий поврежден.

Содержание:

  • Диагностика проблем с WMI
  • Исправление WMI репозитория, перерегистрация библиотек, перекомпиляция MOF файлов
  • Сброс и пересоздание WMI репозитория (хранилища)

О наличии проблем с WMI может свидетельствовать широкий спектр ошибок:

  • Ошибки обработки WMI запросов в системных журналах и логах приложений:
    0x80041002 - WBEM_E_NOT_FOUND
    ,
    WMI: Not Found
    ,
    0x80041010 WBEM_E_INVALID_CLASS
    ,
    Failed to initialize WMI classes
    ,
    Invalid class
    или
    Invalid namespace
  • Ошибки обработки GPO, связанные c WMI ( некорректная работа wmi фильтров групповых политик, и пр.);
  • Медленное выполнение WMI запросов;
  • Ошибки при установке или работе агентов SCCM/SCOM;
  • Ошибки скриптов (vbs или PowerShell), обращающихся к пространству имен WMI (скрипты с Get-WmiObject, Get-CimInstance и т.д.).

powershell Get-WmiObject wmi ошибка invalid class

Диагностика проблем с WMI

В первую очередь проверьте, что запущена служба Windows Management Instrumentation (Winmgmt). Вы можете проверить состояние службы в консоли
services.msc
или с помощью PowerShell:

Get-Service Winmgmt | Select DisplayName,Status,ServiceName

служба Windows Management Instrumentation (Winmgmt) работает

Если служба Winmgmt запущена, протестируйте работоспособность WMI, выполнив простой WMI-запроса. Вы можете выполнить wmi запрос из командной строки или из PowerShell. Например, следующая команда выведет список установленных в Windows программ:

wmic product get name,version

Простая PowerShell команда для получения информации о версии и билда Windows через WMI:

get-wmiobject Win32_OperatingSystem

powershell проверка работы wmi командой get-wmiobject

Как вы видите, служба WMI ответила на запрос корректно. Если при выполнении такого WMI-запроса Windows возвращает ошибку, скорее всего сервис WMI работает некорректно, поврежден WMI репозиторий или есть какие-то другие проблемы с WMI классами.

Включите логирование обращений к WMI в Event Viewer, выполнив команду:

wevtutil set-log Microsoft-Windows-WMI-Activity/Operational /enabled:true

Затем откройте консоль Event Viewer (
eventvwr.msc
) и перейдите в Applications and Service Logs -> Microsoft -> Windows -> WMI Activity. В описании событий ошибок в EventID 5858 будет указаны пространство имен WMI и класс, при обращении к которому происходит ошибка. Если это специальный WMI класс некой программы, возможно программа установлена некорректно, или ее файлы повреждены.

В нашем случае ошибка связана с общесистемным WMI классом root\cimv2 : Win32_OperatingSystem, что означает что база данных WMI повреждена.

Журнал событий и ошибок wmi-activity в Event Viewer

A Windows Management Instrumentation (WMI) query has failed. The WMI repository may be corrupted or it works incorrectly.

Откройте консоль свойств WMI Control в консоли управления компьютером (compmgmt.msc). В моем случае здесь присутствует ошибка:

Failed to initialize all required WMI classes
Win32_Processor. WMI: Invalid namespace
Win32_WMISetting. WMI: Invalid namespace
Win32_OperationSystem. WMI: Invalid namespace

ошибка Failed to initialize all required WMI classes

Ранее для диагностики WMI существовала официальная утилита от Microsoft – WMIDiag.vbs (Microsoft WMI Diagnosis), К сожалению, последняя версия WMIDiag 2.2 корректно работает только с версиями до Windows 8.1/Windows Server 2012 R2.

На данный момент Microsoft даже удалила ссылку на загрузку WMIDiag из центра загрузок. Но при желании, этот скрипт можно найти в сети. WMIDiag дает подробную информацию по исправлению частных ошибок в WMI, но в большинстве случаев процесс это довольно трудоемкий и стоит потраченного времени только при решении инцидентов в критичных системах (на продуктивных серверах).

Для массового сегмента рабочих станций пользователей обычно проще и быстрее сбросить и пересоздать WMI репозиторий в Windows.

Исправление WMI репозитория, перерегистрация библиотек, перекомпиляция MOF файлов

Проверьте целостность WMI репозитория в Windows с помощью команды:

winmgmt /verifyrepository

winmgmt-verifyrepository - проверка состояния репозитория wmi

Если команда возвращает, что база данных WMI находится в неконсистентном состоянии (INCONSISTENT или WMI repository verification failed), стоит попробовать выполнить “мягкое” исправление ошибок репозитория:

Winmgmt /salvagerepository

WMI repository has been salvaged.

Данная команда выполняет проверку согласованности хранилища WMI и перестраивает базу данных WMI при обнаружении несогласованности.

Перезапустите службу WMI:

net stop Winmgmt
net start Winmgmt

Если стандартный способ исправления ошибок в WMI не помог, попробуйте следующий скрипт. Данный скрипт представляет собой ”мягкий” вариант восстановления службы WMI на компьютере (выполняется перерегистрация dll библиотек и службы WMI, перекомпилируются mof файлы). Данная процедура является безопасной и ее выполнение не должно привести к новым проблемам.

sc config winmgmt start= disabled
net stop winmgmt
cd %windir%\system32\wbem
for /f %s in ('dir /b *.dll') do regsvr32 /s %s
wmiprvse /regserver
sc config winmgmt start= auto
net start winmgmt
for /f %s in ('dir /b *.mof ^| findstr /V /I "uninstall.mof"') do mofcomp %s

for /f %s in ('dir /b *.mfl ^| findstr /V /I "uninstall.mfl"') do mofcomp %s

Команды для мягкого сброса WMI и перекомпиляции MOF файлов mofcomp

При перекомпиляции MOF файлов мы исключили файлы

*uninstall.mof

и

*uninstall.mfl

, т.к. они нужны только для удаления программ/WMI классов.

На 64 битной версии Windows эти действия нужно также выполнить для каталога SysWOW64. Замените третью строку на

cd %windir%\SysWOW64\wbem

Указанные команды можно выполнить путем простой вставки в окно командой строки, либо сохранить код в bat файле wmi_soft_repair.bat и запустить его с правами администратора (замените в BAT файле %s на %%s). После окончания работы скрипта, перезагрузите Windows и проверьте работу WMI.

bat скрипт для перекомпиляции хранилища wmi в mof файлах

Сброс и пересоздание WMI репозитория (хранилища)

Если вам не помогли мягкие способ восстановления WMI, рассмотренные выше, придется перейти к более “жесткому” способу восстановления работоспособности службы WMI, заключающегося в пересоздании хранилища WMI.

Например, в моем случае команда mofcomp почти для всех MOF файлов вернула ошибку:

Microsoft (R) MOF Compiler Version 10.0.26100.1
Copyright (c) Microsoft Corp. 1997-2006. All rights reserved.
Parsing MOF file: xwizards.mof
xwizards.mof (1): error SYNTAX 0X8004400a: Unexpected token at file scope
Compiler returned error 0x8004400a

mofcomp ошибка 0x8004400a

WMI репозиторий (хранилище) находится в каталоге
%windir%\System32\Wbem\Repository
и представляет собой базу данных, в которой содержится информация о метаданных и определениях WMI классов. В некоторых случаях WMI репозиторий может содержать статическую информацию классов. При повреждении репозитория WMI, в работе службы Windows Management Instrumentation (Winmgmt) могут наблюдаться ошибки вплоть до полной невозможности ее запустить.

Если вы подозреваете, что репозиторий WMI поврежден, что его пересоздание — это последняя шаг, к которому нужно прибегнуть только тогда, когда другие операции не помогают реанимировать WMI.

Следующая команда выполнит сброс базы данных WMI к исходному состоянию (как после чистой установки Windows). Используйте эту команду для выполнения hard reset репозитория WMI, если параметре salvagerepository не исправил проблему:

Winmgmt /resetrepository

Совет. На практике бывают случаи, когда пересоздание хранилища WMI приводит к проблемам со сторонним софтом. Это связано с тем, что все записи в базе WMI обнуляются (до состояния чистой системы). Такие программы скорее всего, придется переустановить.

Если обе команды (
Winmgmt /salvagerepository
и
Winmgmt /resetrepository
) не восстановили консистентное состояние базы WMI, попробуйте выполнить “жесткое” пересоздание базы WMI вручную таким скриптом:

net stop winmgmt
cd %windir%\system32\wbem
winmgmt /resetrepository
winmgmt /resyncperf
if exist Repos_bakup rd Repos_bakup /s /q
rename Repository Repos_bakup
regsvr32 /s %systemroot%\system32\scecli.dll
regsvr32 /s %systemroot%\system32\userenv.dll
for /f %s in ('dir /b *.dll') do regsvr32 /s %s
for /f %s in ('dir /b *.mof ^| findstr /V /I "uninstall.mof"') do mofcomp %s
for /f %s in ('dir /b *.mfl ^| findstr /V /I "uninstall.mfl"') do mofcomp %s
sc config winmgmt start= auto
net start winmgmt
wmiprvse /regserver

сброс и восстановление хранилища wmi в windows 10

На 64 битной версии Windows нужно также перерегистрировать dll/exe и перекомпилировать mof файлы в каталоге %windir%\sysWOW64\wbem.

Данный скрипт полностью пересоздает хранилище WMI (старый репозиторий сохраняется в каталог Repos_bakup). После окончания работы скрипта нужно перезагрузить Windows. Затем протестируйте работу службы WMI простым запросом.

Проверьте состояние WMI репозитория. Если ошибки исправлены, команда
winmgmt /verifyrepository
должна вернуть:

WMI repository is consistent

WMI repository is consistent

В этой статье мы собрали основные способы, позволяющие продиагностировать и устранить неполадки службы и репозитория WMI.

Channels:

Security.
Event: 4688.

Microsoft-Windows-WMI-Activity/Operational.
Events: 5857, 5858, 5859, 5860, 5861.

Process execution

Tracking process execution is the only way to natively detect lateral movement
leveraging WMI. With out Audit process tracking enabled to log process
creation event 4688 (or a dedicated product tracking process creation, such
as Sysmon or an EDR), lateral movement over WMI cannot be reliably
detected or investigated.

Channel Conditions Events
Security Requires Audit Process Creation to be enabled.

Requires ProcessCreationIncludeCmdLine_Enabled to be enabled for the command line to be logged.

Event 4688: A new process has been created.

Refer to the ETW — Process creation page for more general information on the event.

The event can be used to track the execution of programs related to WMI. For instance, the execution of wmic [...] /node:<REMOTE_HOST> can be an indicator of outgoing lateral movement using WMI on the source host, and process with WmiPrvSE.exe as a parent-process can be an indicator of incoming lateral movement using WMI on the destination host.

WMI Event subscription

Channel Conditions Events
Microsoft-Windows-WMI-Activity/Operational Introduced in Windows Sever 2012R2.

Default configuration.

Event 5858: Operation_ClientFailure.

Logged for error in a WMI operation, such as, for example, a WMI query (IWbemServices::ExecQuery or IWbemServices::ExecNotificationQuery), an object retrieval (IWbemServices::GetObject), or a CIM-object exported method execution (IWbemServices::ExecMethod).

Information of interest:
— Domain and username of the user that conducted the WMI operation.
— The result code of the failed operation.
— The Process ID (PID) of the process that conducted the operation.
— Details on the operation that raised the error.

For WMI query, the query string is included.
For example: Start IWbemServices::ExecQuery - ROOT\CIMV2 : SELECT * FROM Win32_ComputerSystemProduct.

For method execution, the WMI namespace, the class, and the method called are included, in the following format
IWbemServices::ExecMethod - <NAMESPACE> : <CLASS>::<METHOD>.
For example: IWbemServices::ExecMethod - ROOT\Microsoft\Windows\Smb : MSFT_SmbShare::FireShareChangeEvent.

Microsoft-Windows-WMI-Activity/Operational Introduced in Windows Sever 2012R2.

Default configuration.

Event 5857: <PROVIDER_NAME> provider started with result code 0x0. HostProcess = wmiprvse.exe; ProcessID = <PID>; ProviderPath = <PROVIDER_DLL_PATH>.

Logged whenever a provider is loaded by WMI.

WMI uses providers to access system components (that it then exposes as classes). As providers are loaded under NT AUTHORITY\SYSTEM, they can be a way to maintain elevated persistence on the system.

Information of interest:
— Provider name and DLL full path.
— The Process ID (PID) of the wmiprvse.exe process that loaded the provided.

Microsoft-Windows-WMI-Activity/Operational Introduced in Windows Sever 2012R2.

Default configuration.

Event 5860: Operation_TemporaryEssStarted.

Logged whenever a temporary WMI Event Subscription is configured.

Information of interest:
— Domain and username of the user executing the temporary subscription.
Process ID (PID) of the process under which the subscription is executed.
WMI namespace and query of the temporary subscription.

Microsoft-Windows-WMI-Activity/Operational Introduced in Windows Sever 2012R2.

Default configuration.

Event 5861: Operation_ESStoConsumerBinding.

Logged whenever a permanent WMI Event Subscription is configured (more precisely when a filter to consumer binding is configured).

Information of interest:
— Details on the event filter: name, creator SID, WMI namespace, WMI query language and query.
— Details on the event consumer: name, type of consumer (such as CommandLineEventConsumer for program execution), creator SID, and consumer parameters (such as the program path and command line for CommandLineEventConsumer consumer).

Microsoft-Windows-WMI-Activity/Operational Introduced in Windows Sever 2012R2.

Default configuration.

Event 5859: Operation_EssStarted.

Appears to be logged in relation with some permanent WMI Event Subscriptions.

Information of interest:
WMI query assocatied with a permanent subscription.

References

  • darkoperator — Carlos PEREZ — Basics of Tracking WMI Activity

  • Network Security Ninja — WMI Forensics

  • SANS — Chad Tilbury — Investigating WMI Attacks


View on GitHub

  • Home
  • News
  • A Full Guide to Fixing the WMI-Activity Event ID 5858 – Fixed!

A Full Guide to Fixing the WMI-Activity Event ID 5858 – Fixed!

By Anna | Follow |
Last Updated

WMI-Activity Event ID 5858 causes troubles for some Windows users. In this post on the MiniTool Website, we will discuss the possible reasons and useful troubleshooting methods. If you are also struggling with this error, please go on with your reading.

What is the WMI-Activity Event ID 5858? First of all, we can learn something about Windows Management Instrumentation (WMI).

WMI comes pre-installed on the system and is used to consolidate the management of devices and applications in a network. It can provide information on the status of local or remote computer systems.

When the WMI-Activity Event ID 5858 appears, the related WMI files are corrupted, therefore, causing PC performance issues, or even system crashes. To fix this WMI-Activity Event 5858, you can try the following methods.

Tips:

It is highly recommended that you back up data when you encounter the WMI-Activity Event ID 5858. Some unexpected results caused by this system issue may cause data loss. In this way, you can try MiniTool ShadowMaker free to back up files, folders, partitions, disks, and your system.
This professional software can also perform file sync and disk cloning functions. For a better backup experience, users are allowed to use backup schemes and schedules to save resources.

MiniTool ShadowMaker TrialClick to Download100%Clean & Safe

Fix: WMI-Activity Event ID 5858

Fix 1: Update Windows

Outdated Windows can make WMI activity fail and lead to 5858 Event ID. To update your Windows, please do as follows.

Step 1: Open Settings by pressing Win + I and click Update & Security > Windows Update.

Step 2: Click Check for updates to search for available updates; then please follow to download and install them.

click Check for updates

Fix 2: Run SFC & DISM Scans

If your system files are corrupted, you can try SFC and DISM scans to fix that.

Step 1: Type Command Prompt in Search and choose Run as administrator.

Step 2: Type sfc /scannow in the window and press Enter to execute the command.

When the command finishes, check if your issue has been fixed or not; or you can execute the DISM command – DISM /Online /Cleanup-Image /RestoreHealth to proceed with the fix.

Fix 3: Update Your Graphics Drivers

If you have updated your Windows to the latest version but the WMI-Activity error 5858 persists, you can update your graphics drivers.

Step 1: Right-click on the Windows icon and click Device Manager.

Step 2: Expand Display adapters and right-click on your graphics driver to choose Update driver > Search automatically for drivers.

click Search automatically for drivers

Fix 4: Reset the WMI Repository

Sometimes, the WMI repository gets corrupted, which may result in the WMI-Activity error 5858. In this way, you can reset the WMI repository to fix the issue.

Step 1: Run Command Prompt as an administrator and copy and paste this command to press Enternet stop winmgmt.

Step 2: Then please execute this command to verify the consistency & integrity of the Windows Management Instrumentation repository.

winmgmt /verifyrepository

Step 3: If the result tells you that the WMI repository is inconsistent, please execute this command.

winmgmt /salvagerepository

Step 4: Then you can repair the corrupted repository by performing this command.

winmgmt /resetrepository

Step 5: Now, you can start the service by executing this command.

net start winmgmt

After all of that, please restart your computer.

Fix 5: Perform a System Restore

If all the above methods can’t resolve your problem, you can restore your system by performing a created system restore point. This tip is just available for those who have created the point before this issue happens.

Step 1: Open Run by pressing Win + R and type rstrui to press Enter.

Step 2: Click Next and choose a restore point to click Next > Finish.

Bottom Line:

Those introduced methods may have resolved your issue – WMI-Activity Event ID 5858. We highly recommend you back up your data regularly with MiniTool ShadowMaker, which can better protect your data from loss.

About The Author

Position: Columnist

Anna is an editor of the MiniTool Team. She worked in this big family since her graduation. Her articles mainly focus on data backup and recovery, disk cloning, and file syncing, committed to resolving the data loss issues users may encounter on their PCs. Besides, more related computer articles are shared here. In her leisure time, she enjoys reading and watching movies. Travel can also be a good choice for her.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не работает панель поиска windows 10 на панели задач
  • Как проверить программу на совместимость с windows 10
  • Windows не удалось применить параметры mdm policy
  • Horizon forbidden west windows
  • Windows 10 не снимается атрибут только для чтения windows