Lars-Erik Østerud
-
-
#1
Subject says it all, what is this stuff. Is it in use, or leftover
from something I once had installed (files not used for a while)?
-
-
#2
Web-Based Enterprise Management, actually more accurately WMI,
Windows Management Instrumentation.
-Core component of Windows XP, Service(s) — self maintaining.
Detlev Dreyer
Tom Porterfield
-
-
#4
Lars-Erik Østerud said:
Subject says it all, what is this stuff. Is it in use, or leftover
from something I once had installed (files not used for a while)?
These are the files used for Windows Management Instrumentation, or WMI,
which is Microsoft’s implementation of Web-based Enterprise Management
(WBEM). Those files are part of Windows and are used to query the state of
the machine and other information. You should leave them where they are so
that any program you have that uses WMI to query for information will
continue to work properly.
Lars-Erik Østerud
-
-
#5
R. McCarty said:
Web-Based Enterprise Management, actually more accurately WMI,
Windows Management Instrumentation.
-Core component of Windows XP, Service(s) — self maintaining.
What does it do? What processes need it?
R. McCarty
Rock
The Web-Based Enterprise Management(WBEM) repository contains the Windows Management Instrumentation (WMI) files. WBEM is an industry initiative to develop a standard technology for accessing management information in an enterprise environment.
What is C :\ Windows System32 wbem repository?
The WMI Repository “%windir%System32\Wbem\Repository” is the database that stores meta-information and definitions for WMI classes; in some cases the repository also stores static class data as well. If the Repository becomes corrupted, then the WMI service will not be able to function correctly.
What is Systemroot System32 wbem?
%SYSTEMROOT%\System32\wbem
wbem: web based enterprise management. Although called web based, this directory contains WMIC.exe , the WMI Commandline Utility. This directory is specified by the value of Installation Directory under the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM .
How do I rename a folder in wbem?
Question
- C:\Windows\system32>net stop winmgmt – STOP WMI.
- C: \ Windows \ system32 \ wbem \ repository– rename folder (C: \ Windows \ system32> rename% systemroot% \ system32 \ wbem \ repository repository.old)
- restart–C: \ windows \ system32> net start winmgmt.
How do I reset my WMI repository?
Type net stop winmgmt into the command prompt and press enter. When prompted if you wish to continue, type Y and press enter. Type winmgmt /resetrepository into the command prompt and press enter. Restart your computer to pick up the changes.
What is WBEM protocol?
Web-Based Enterprise Management (WBEM) is a set of industry standards that an enterprise can use to manage its information operations in the distributed computing environment of the Internet.
How do I reset my WMI?
How do you clean WMI?
Try the following steps:
- Disable and stop the WMI service. sc config winmgmt start= disabled. net stop winmgmt.
- Run the following commands. Winmgmt /salvagerepository C:\WINDOWS\System32\wbem. Winmgmt /resetrepository C:\WINDOWS\System32\wbem.
- Re-enable the WMI service and then reboot the server to see how it goes.
How do I know if my WMI is corrupted?
Confirm WMI is broken
- Launch the WMI MMC snapin: go to Start -> Run -> type wmimgmt.msc.
- Right click WMI Control (Local) and click Properties.
- If WMI is working correctly, you will see Successfully connected window as shown below.
- If you see Invalid class or any other error message then WMI is not working properly.
How do I fix a corrupted WMI file?
How do I delete a WMI repository in Windows 10?
How do I fix WMI issues?
If the problem remains after consistency check, rebuild the WMI repository:
- Disable and stop the WMI service.
- Rename the repository folder located at %windir%\System32\wbem\repository to repository.
- Re-enable the WMI service.
- To recreate the repository, you need to run a WMI-using application.
What is WBEM used for?
What is Web enabled business management?
WBMS – (Web Business Management System) – is a web-based software that manages or runs a website with specific business functions or requirements. These web-based tools allows business owners to run their website with a business mindset.
What causes WMI corruption?
If you’re getting that error this means that part of the operating system is broken. This is usually caused by partial (and failed) driver installation and/or “cleaner utilities”.
How do I check my WMI repository?
- Open an elevated command prompt.
- Verify the WMI repository is not corrupt by running the following command: winmgmt /verifyrepository. If the repository is not corrupted, a “WMI Repository is consistent” message will be returned. If you get something else, go to step 3.
- Run the following commands to repair WMI:
How do I fix WMI corruption?
What is a web enabled device?
What Does Web Enabled Mean? Web enabled refers to a product or service that can be used through, or in conjunction with, the World Wide Web. A Web-enabled product may be accessed through a Web browser or be able to connect to other Web-based applications in order to synchronize data.
What is web enabled database?
A web database is essentially a database that can be accessed from a local network or the internet instead of one that has its data stored on a desktop or its attached storage.
What are web services examples?
Here are some well-known web services that use markup languages:
- Web template.
- JSON-RPC.
- JSON-WSP.
- Web Services Description Language (WSDL)
- Web Services Conversation Language (WSCL)
- Web Services Flow Language (WSFL)
- Web Services Metadata Exchange (WS-MetadataExchange)
- XML Interface for Network Services (XINS)
What are the 4 types of database?
Four types of database management systems
hierarchical database systems. network database systems. object-oriented database systems.
Why is web database needed?
As mentioned, web databases can be used for professional and personal purposes. Common ways businesses use web databases are for customer feedback forms, website polls, and inventory lists. Personal web databases are a useful way to store email addresses, or even for a home inventory list.
What is a web service used for?
Web services allow different organizations or applications from multiple sources to communicate without the need to share sensitive data or IT infrastructure. Instead, all information is shared through a programmatic interface across a network.
What are the three kinds of data that web services have?
Web Services Metadata Exchange (WS-MetadataExchange) XML Interface for Network Services (XINS)
What are types of SQL?
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
…
Types of SQL Commands
- Data Definition Language (DDL)
- Data Manipulation Language.
- Data Control Language.
- Transaction Control Language.
- Data Query Language.
В операционных системах Windows поддерживаются различные объектные инфраструктуры. Для доступа к ним можно использовать интерфейсы прикладного программирования (API), но разработка полноценных приложений не всегда оправдана. В PowerShell существуют специальные командлеты, позволяющие обращаться к объектам .NET, COM, WMI (CIM) и ADSI в интерактивном режиме. В четвертой части цикла мы изучили основы с упором на классы .NET Core, а сейчас хотим углубить тему и разобрать особенности взаимодействия PowerShell с внешними объектами.
Оглавление:
Работа с JSON, XML и CSV
Работа с WMI и CIM
Работа с COM-объектами
Работа со службой каталогов ADSI
Форматирование вывода
Работа с JSON, XML и CSV
В сценариях PowerShell довольно часто приходится разбирать данные в форматах JSON, XML и CSV. Обычно такая необходимость возникает при работе с интернет-сервисами или с конфигурационными файлами. Некоторые администраторы пытаются парсить данные с помощью регулярных выражений, но идти на такие жертвы необязательно: в PowerShell есть специальные командлеты для конвертации, притом в обе стороны.
Формат JSON позволяет описывать разнообразные объекты и по сути представляет собой допускающую вложенность хэш-таблицу. Соответственно преобразовать объект JSON в объект .NET при помощи PowerShell несложно. Поскольку интернет-сервисы обычно отдают вместо красиво отформатированного файла очень длинную строку, это преобразование может пригодиться и для работы в интерактивном режиме. В примере ниже для описания объекта JSON мы использовали многострочную текстовую переменную:
$user = @"
{
"firstName": "Ivan",
"lastName": "Danko",
"address": {
"streetAddress": "Kremlin",
"city": "Moscow"
},
"phoneNumbers": [
"+7 495 1234567",
"+7 499 1234567"
]
}
"@ | ConvertFrom-Json
Обратная задача решается сходным образом:
$file = Get-ChildItem C:\Windows\System32\notepad.exe
$file.VersionInfo | ConvertTo-Json
Полученную строку в формате JSON нетрудно отправить другому приложению по сети. Это может быть, например, некий RESTful сервис. Работа с командлетами ConvertFrom-Csv, ConvertTo-Csv и ConvertTo-Xml строится примерно так же, предлагаем читателям изучить ее самостоятельно.
Для работы с XML и CSV нам потребуются и другие командлеты:
Используя эти инструменты нужно понимать, что преобразование бинарного объекта в текстовый формат сохраняет только значение его свойств, но не методы. Преобразование данных в формате JSON, XML или CSV в объект .NET с помощью PowerShell возможно, только если они валидны.
Работа с WMI и CIM
Windows Management Instrumentation (WMI) — это разработанная в Microsoft и адаптированная под Windows реализация стандарта WBEM (Web-Based Enterprise Management). В его основе лежит идея создания универсального решения для мониторинга распределенной информационной среды предприятия и управления ее компонентами. Структура данных WBEM в свою очередь основана на Common Information Model (CIM), реализующей объектно-ориентированный подход к представлению компьютерных систем. Дальнейшая разработка и поддержка WMI в Windows прекращена, Microsoft рекомендует использовать для управления инфраструктурой сходный механизм — объекты CIM. Для работы ними в PowerShell 3.0 появились специальные командлеты, которые мы будем рассматривать параллельно с аналогами для WMI. Если в коде есть вызовы командлетов для работы с WMI, его по возможности стоит переписать.
В рамках модели CIM (она же используется в WMI) данные операционной системы представлены в виде классов со свойствами и методами. Классы группируются в иерархически упорядоченные и логически связанные по технологии или области управления пространства имен. Существует корневое пространство имен Root, в котором имеются подпространства: CIMv2, Default, Secutiry и WMI. Для однозначной идентификации экземпляра класса (объекта) и описания состояния соответствующего ему ресурса используются свойства класса, которые обычно доступны только для чтения. Для управления ресурсом используются методы.
К экземпляру класса можно обратиться по полному пути, который имеет следующий вид:
[\\ComputerName\NameSpace][:ClassName][.KeyProperty1=Value1][,KeyProperty2=Value2]…]
где
ComputerName — имя компьютера;
NameSpace — пространство имен;
ClassName — имя класса;
KeyProperty1=Value1, KeyProperty2=Value2 — свойства объекта и значения, по которым он идентифицируется.
До появления PowerShell простого инструмента работы с WMI не существовало. Для доступа к объектам приходилось писать довольно сложные программы на высокоуровневых языках (C++, Visual Basic, Java Script) либо изучать оболочку WMIC (WMI Command Line, поддержка которой также прекращена) с собственным языком. Через PowerShell объекты WMI доступны рядовому пользователю из командной строки или в сценариях. Для начала подключимся к подсистеме WMI и получим список доступных классов с помощью командлета Get-WmiObject (псевдоним gwmi). Чтобы получить список классов CIM, используйте командлет Get-CimClass.
Get-CimClass
Get-WmiObject -List
Мы вывели список классов на локальном компьютере, но можно подключиться и к удаленному:
Get-CimClass -ComputerName IP-адрес
Get-CimClass -ComputerName Имя_компьютера
или
Get-WmiObject -ComputerName IP-адрес -List
Get-WmiObject -ComputerName Имя_компьютера -List
По умолчанию командлеты Get-CimClass и Get-WmiObject подключаются к пространству имен Root\CIMV2, в котором хранится большое количество классов для управления системой. Для смены пространства имен применяется параметр -Namespace:
Get-CimClass -Namespace Root
Get-WmiObject -Namespace Root -List
Зная имя класса, нетрудно получить его экземпляры. Следующая команда возвращает все экземпляры Win32_Service, т.е. зарегистрированные на локальной машине службы:
Get-WmiObject Win32_Service
Как и в случае с объектами других типов, список свойств и методов выводится при помощи Get-Member. К методам объекта WMI можно обращаться напрямую или с помощью командлета Invoke-WmiMethod. Также к объектам WMI можно применять командлеты для сортировки, фильтрации, группировки и т.д.
Get-WmiObject Win32_Service | Get-Member
Для получения объектов (экземпляров классов) CIM используется командлет Get-CimInstance. В отличие от WMI, результирующие CIM-объекты (resultant object или экземпляры класса) не содержат методов класса. Поскольку извлечь метод непосредственно невозможно, придется вызывать командлет Invoke-CimMethod. Рассмотрим класс Win32_Service — запущенные в системе службы) и его экземпляр для службы spooler на локальной машине:
Get-CimInstance Win32_service -filter "Name='spooler'"
Посмотрим на структуру результирующего объекта:
Get-CimInstance Win32_service -filter "Name='spooler'" | Get-Member
На этом этапе преимущества командлетов для работы с объектами CIM неочевидны. Они в первую очередь касаются удаленной работы в распределенной среде и будут подробно рассмотрены в последней статье цикла, посвященной решению практических задач администрирования.
Есть и специфичный для WMI инструментарий: язык запросов WMI Query Language (WQL), напоминающий SQL. WQL-запрос для поиска всех стартующих при запуске системы служб выглядит так:
select * from win32_service where startmode="Auto"
Из PowerShell они выполняется следующим образом:
Get-WmiObject -Query 'select * from win32_service where startmode="Auto"'
Работа с COM-объектами
Для обеспечения взаимодействия между приложениями в Windows была разработана технология связывания и внедрения объектов (Object Linking and Embedding или OLE). Позже появилась технология OLE Automation, с помощью которой приложения клиенты автоматизации могли вызывать функции других приложений — серверов автоматизации. OLE и OLE Automation были основаны на базовой технологии Component Object Model (COM), которая предлагает единый двоичный стандарт для программных компонентов. Созданные по нему и зарегистрированные в операционной системе объекты могут использоваться в других приложениях с помощью исполняемых файлов или динамических библиотек.
Примерно с середины девяностых годов вместо OLE стал использоваться другой термин — ActiveX. До появления платформы .NET технология ActiveX считалась ключевой, а объекты COM до сих пор активно используются для интеграции приложений в Windows — многие продукты Microsoft и сторонних разработчиков являются серверами автоматизации и предоставляют через них доступ к своим сервисам. Для обращения к объектам используется ProgID — символьный идентификатор, который присваивается им при регистрации в реестре Windows. Он имеет следующий вид:
Библиотека_типов.Класс.Версия
Версия обычно не указывается:
Библиотека_типов.Класс
Несколько примеров доступных ProgID: InternetExplorer.Application (приложение Internet Explorer), Word.Application (приложение Microsoft Word), WScript.Shell (класс Shell из объектной модели сервера сценариев Windows Script Host или WSH).
Создать экземпляр объекта можно с помощью рассмотренного в предыдущей статье командлета New-Object, а посмотреть его структуру — с помощью Get-Member:
$myshell = New-Object -ComObject WScript.Shell
$myshell | Get-Member
Для работы с объектами используются свойства и методы. Скажем, чтобы создать на рабочем столе пользователя ярлык, нужно вызвать метод CreateShortcut():
$link = $myshell.CreateShortcut("$Home\Desktop\Home.lnk")
Обратите внимание, что ярлык — это тоже объект COM:
$link | Get-Member
Нам остается заполнить его свойства и сохранить:
$link.TargetPath = $Home
$link.Save()
Таким способом мы создали ярлык на рабочем столе активного пользователя, а теперь разберем работу с внешними сервисами автоматизации на примере COM-объекта Shell.Application. С его помощью можно автоматизировать некоторые действия в проводнике Windows:
$myshell=New-Object -ComObject Shell.Application
или для краткости:
$myshell=New-Object -com Shell.Application
$myshell | Get-Member
У объекта Shell.Application есть довольно много различных методов управления окнами. К примеру, для отображения содержимого заданного каталога используется Explore():
$myshell.Explore("c:\")
Справочная система вызывается с помощью метода Help():
$myshell.Help()
Есть также три метода для вызова диалоговых окон поиска: FindFiles(), FindComputer() и FindPrinter().
$myshell.FindFiles()
$myshell.FindComputer()
$myshell.FindPrinter()
Открыть диалоговое окно запуска программ можно с помощью метода FileRun(), а для вызова окна установки даты/времени нужен метод SetTime(). Есть, к примеру, методы для вызова окна настройки панели задач, элементов панели управления с указанием одного из доступных файлов cpl, для управления открытыми окнами:
$myshell.MinimizeAll()
$myshell.UndoMinimizeAll()
$myshell.TileHorizontally()
$myshell.TileVertically()
Метод Windows() позволяет получить доступ к коллекции открытых в проводнике или в браузере Internet Explorer окон. Посмотрим доступные для этой коллекции свойства и методы:
$myshell.Windows() | Get-Member
Существуют и другие полезные COM-объекты, количество которых зависит от установленного в системе ПО. Когда-то основным средством автоматизации в Windows считался сервер сценариев WSH, объектная модель которого включает и COM-объекты: предназначенный для работы с сетевыми функциями WScript.Network и уже упомянутый нами WScript.Shell. Последний не только создает ярлыки на рабочем столе, с его помощью можно, например, выводить информационные окна с сообщениями и кнопками, переключаться между приложениями, запускать программы или имитировать нажатия клавиш.
Работа со службой каталогов ADSI
Под каталогом в общем случае подразумевается источник информации, в котором хранятся данные о некоторых объектах. Под службой каталога мы понимаем часть распределенной компьютерной системы, позволяющий обращаться к хранящимся объектам и манипулировать ими. Служба каталога может объединять данные об объектах сети и осуществляющих манипуляцию ими сервисов — она представляет собой единую точку входа для взаимодействия с сетевыми ресурсами. В гетерогенной компьютерной сети таких служб может быть множество: локальный диспетчер SAM (Security Account Manager) для не входящих в домен компьютеров, Active Directory и т.д.
Для взаимодействия с разными службами каталогов требуются различные инструменты, что создает определенные неудобства. Начиная с Windows 2000 корпорация Microsoft внедрила в операционные системы унифицированную технологию ADSI (Active Directory Service Interface) для не зависящего от конкретного сетевого протокола доступа. Чтобы находить объекты, для каталога определяется пространство имен. Поскольку разные службы каталогов используют различные способы именования, ADSI определяет позволяющее однозначно идентифицировать любой объект соглашение. Вводится понятие состоящих из двух частей строк связывания (binding string) или ADsPath. Первая часть имени определяет службу каталогов (провайдера ADSI), а вторая — расположение объекта в каталоге. Приведем примеры обозначения разных провайдеров ADSI:
LDAP:// используется для основанной на LDAP службы каталогов, в т.ч. для Active Directory;
WinNT:// используется для локальных компьютеров.
Специальных командлетов для работы с ADSI в PowerShell нет. Вместо них применяется оператор приведения типов [ADSI] после которого указывается строка связывания. Например, для подключения к пользователю Ivanov из домена test.ru нужна следующая конструкция:
$user = [ADSI]"LDAP://CN=Ivanov,DC=TEST,DC=RU"
Чтобы работать с локальными учетными записями, придется подключиться к компьютеру с соответствующим именем (для подключения к локальному компьютеру вместо имени достаточно использовать точку):
$computer = [ADSI]"WinNT://."
Для примера создадим на локальной машине нового пользователя Ivanov:
$user = $computer.Create("user","Ivanov")
$user.Put("Description","Создан из PowerShell")
$user.SetInfo()
Теперь подключимся к нему:
$user1 = [ADSI]"WinNT://./Ivanov,user"
$user1.Description
Форматирование вывода
Интерактивная работа часто требует выводить данные на экран. В других оболочках команды и утилиты сами занимаются форматированием вывода, но возвращаемые функциями и командлетами бинарные объекты обычно не умеют этого делать. В PowerShell вывод форматируют четыре специальных командлета, которым объекты «скармливаются» через конвейер. Более подробные сведения них можно получить с помощью Get-Help:
Format-Table форматирует вывод в виде таблицы, столбцы которой содержат значения свойств объекта или вычисляемые значения. Поддерживается возможность группировки данных;
Format-List выводит объект как список свойств, каждое из которых отображается на новой строке. Поддерживается возможность группировки данных;
Format-Custom форматирует вывод с использованием пользовательского представления;
Format-Wide форматирует объекты в виде широкой таблицы, в которой отображается только одно свойство каждого объекта.
Если ни один из перечисленных командлетов не вызван, применяется соответствующий типу отображаемых данных модуль форматирования. Правила отображения хранятся в конфигурационных файлах в формате XML с расширением .ps1xml, которые находятся в каталоге $PSHome. Их список можно получить с помощью следующей команды:
dir $pshome\*format*.ps1xm
Редактировать конфигурационные файлы вручную не рекомендуется, лучше создать собственные и включить их в список загружаемых с помощью командлета Update-FormatData. Если модуль форматирования по умолчанию для нужного типа не определен, PowerShell отображает на экране свойства объекта в виде списка.
На этом мы завершим описание работы с объектами в PowerShell, а заключительная статья цикла будет посвящена решению практических задач управления распределенной информационной средой предприятия. В ней нам пригодится весь описанный инструментарий. Основной упор будет сделан на объекты CIM и сравнение их с WMI. Прошлые части можно найти по ссылкам ниже.
Часть 1: Основные возможности Windows PowerShell
Часть 2: Введение в язык программирования Windows PowerShell
Часть 3: Передача параметров в скрипты и функции, создание командлетов
Часть 4: Работа с объектами, собственные классы
Tek-Tips is the largest IT community on the Internet today!
Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!
-
Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!
-
Home
-
Forums
-
Software
-
MIS/IT
-
Operating Systems — Hardware Independent
-
Microsoft: Windows servers
You should upgrade or use an alternative browser.
any idea what is in Windows\system32\wbem\Repository\FS ?
-
Thread startersrenshaw
-
Start date
- Status
- Not open for further replies.
-
#1
Couls someone tell me what are those files ?
I run a nightly backup and it tell me that those files are always in use.
Should I remove those from the backup or ar they important files ?
The following is from the backup log:
C:\WINDOWS\system32\wbem\Repository\FS
INDEX.BTR : Bkp : 209 — Object is busy
MAPPING.VER : Bkp : 209 — Object is busy
MAPPING1.MAP : Bkp : 209 — Object is busy
MAPPING2.MAP : Bkp : 209 — Object is busy
OBJECTS.DATA : Bkp : 209 — Object is busy
And
C:\WINDOWS\system32\wbem\Repository\FS
INDEX.BTR : Bkp : 209 — Object is busy
INDEX.MAP : Bkp : 209 — Object is busy
MAPPING.VER : Bkp : 209 — Object is busy
MAPPING1.MAP : Bkp : 209 — Object is busy
MAPPING2.MAP : Bkp : 209 — Object is busy
OBJECTS.DATA : Bkp : 209 — Object is busy
OBJECTS.MAP : Bkp : 209 — Object is busy
Thanks
Simon
-
#2
does your backup include system state, or is it just data backup?
Aftertaf
«Solutions are not the answer.» — Richard Nixon
- Thread starter
-
#3
Shadow Copy are basically like a Ghost right ?
Still, that don’t tell me what are those files ans if they are important.
-
#4
but no, I dont know what those files are for
- Status
- Not open for further replies.
Similar threads
-
Home
-
Forums
-
Software
-
MIS/IT
-
Operating Systems — Hardware Independent
-
Microsoft: Windows servers
-
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.
- What is WMI?
- Understanding WMI Persistence
- How does a WMI persistent object look like?
- WMI Persistence Template by Matt G.
- WMI Persistence via PowerLurk by Sw4mpf0x
- WMI Persistence Detection
- What about DFIR?
- Detection Logics & Lessons Learned
- So, to summarize
- Changes to your Sysmon Config
- Some references
- EventCode 400 sample contents
- EventCode 403 sample contents
What is WMI?
WMI is Microsoft’s implementation of WBEM (Web Based Enterprise Management) which is based on CIM and allows for the remote management of multiple system components in Windows environments. WMI is used on a daily basis by sysadmins across large domains due to its flexibility and scalability. Easy to deploy, scripts that leverage WMI can be seen everywhere. Unfortunately, as with everything that is widely deployed, has “remote” capabilities and runs on “windows”: the dark force is strong around it (just for fun: MS17-010).
It is known that WMI can be abused in many ways to either gather information, make changes and create persistence mechanisms. An excellent article by Matt Graeber (@mattifestation) called Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asyncronous, and Fileless Backdoor was an eye opener for many of us in the cybersec world. We knew this was possible, but forgot how flexible it was. The main strength of WMI persistence is its stealthiness and effectiveness. When a command is executed by WMI as a result of “evil” the only thing you will see is WmiPrvse.exe as the process. Distinguishing a valid system action from an invalid one is very hard under these circumstances. In other words, WMI persistence defeats non-repudiation!
What I will cover here are different methods for detecting WMI persistence that you could leverage within your network to hunt for this treat.
Understanding WMI Persistence
First, rather than re-inventing the wheel, I will link here below the sources that I consulted to learn more about WMI:
- Matt Graeber’s article (mentioned above)
- Pentestarmoury article “Creeping on Users with WMI Events” by Sw4mp_f0x. He also developed PowerLurk (see below)
- Permanent WMI Subscriptions
- Derbycon 2015 presentation by Matt
How does a WMI persistent object look like?
Let’s use two scripts that allow us to easily create a malicious persistence without having to do it step by step (have a look at the PS files to understand all the bits and pieces involved), namely:
- PowerLurk by Sw4mp_f0x
- WMI Persistence Template Gist by Matt G.
- Alternatively, you can also use an adaptation of Matt’s work by n0pe-sled WMI-Persistence.ps1
WMI Persistence Template by Matt G.
We tweaked some of the parameters in the script to make sure the timer event launches every minute and that no cleanup is performed at the end. After launching it, we can inspect the newly created Event Consumers/Filters/Bindings as follows:
EventFilter
Get-WmiObject -Namespace root\subscription -Class __EventFilter
Result:
__GENUS : 2
__CLASS : __EventFilter
__SUPERCLASS : __IndicationRelated
__DYNASTY : __SystemClass
__RELPATH : __EventFilter.Name="TimerTrigger"
__PROPERTY_COUNT : 6
__DERIVATION : {__IndicationRelated, __SystemClass}
__SERVER : W10B1
__NAMESPACE : ROOT\subscription
__PATH : \\W10B1\ROOT\subscription:__EventFilter.Name="TimerTrigger"
CreatorSID : {1, 5, 0, 0...}
EventAccess :
EventNamespace : root/cimv2
Name : TimerTrigger
**Query : SELECT * FROM __TimerEvent WHERE TimerID = 'PayloadTrigger'**
QueryLanguage : WQL
PSComputerName : W10B1
EventConsumer
Get-WmiObject -Namespace root\subscription -Class __EventConsumer
Result:
[snip]
__GENUS : 2
__CLASS : CommandLineEventConsumer
__SUPERCLASS : __EventConsumer
__DYNASTY : __SystemClass
__RELPATH : CommandLineEventConsumer.Name="ExecuteEvilPowerShell"
__PROPERTY_COUNT : 27
__DERIVATION : {__EventConsumer, __IndicationRelated, __SystemClass}
__SERVER : W10B1
__NAMESPACE : ROOT\subscription
__PATH : \\W10B1\ROOT\subscription:CommandLineEventConsumer.Name="ExecuteEvilPowerShell"
**CommandLineTemplate : powershell.exe -NoP -C "iex ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((Get-ItemProperty -Path HKLM:\SOFTWARE\PayloadKey -Name PayloadValue).PayloadValue)))"**
FilterToConsumerBinding
Get-WmiObject -Namespace root\subscription -Class __FilterToConsumerBinding
Result:
[snip]
__NAMESPACE : ROOT\subscription
**__PATH : \\W10B1\ROOT\subscription:__FilterToConsumerBinding.Consumer="CommandLineEventConsumer.Name=\"ExecuteEvilPowerShell\"",Filter="__EventFilter.Name=\"TimerTrigger\""**
**Consumer : CommandLineEventConsumer.Name="ExecuteEvilPowerShell"**
CreatorSID : {1, 5, 0, 0...}
DeliverSynchronously : False
DeliveryQoS :
**Filter : __EventFilter.Name="TimerTrigger"**
As we can observe, this persistence is based off a Timer intrinsic Event type. If you launched it and head to C:\ you will see the payload_result.txt file as per the script:
$TimerArgs = @{
IntervalBetweenEvents = ([UInt32] 6000) # 6000 ms == 1 min
SkipIfPassed = $False
TimerId = $TimerName
}
$Payload = {
# Prep your raw beacon stager along with Invoke-Shellcode here
"Owned at $(Get-Date)" | Out-File C:\payload_result.txt
}
Let’s look at the persistent registry key generated by the script via Invoke-WmiMethod -Namespace root/default -Class StdRegProv -Name CreateKey -ArgumentList @($HiveVal, $PayloadKey)
(creating the Registry Key) & Invoke-WmiMethod -Namespace root/default -Class StdRegProv -Name SetStringValue -ArgumentList @($HiveVal, $PayloadKey, $EncodedPayload, $PayloadValue)
(storing the payload value inside the key)
PS C:\Windows\system32> Get-ItemProperty 'HKLM:\SOFTWARE\PayloadKey'
PayloadValue : DQAKACAAIAAgACAAIwAgAFAAcgBlAHAAIAB5AG8AdQByACAAcgBhAHcAIABiAGUAYQBjAG8AbgAgAHMAdABhAGcAZQByACAAYQBsAG8AbgBnACAAdwBpAHQAaAAgAEkAbgB2AG8AawBlAC0AUwBoAGUAbABsAGMAbwBkAGUAIABoAGUAcgBlAA0ACgANAAoAIAAgACAAIAAiAE8AdwBuAGUAZAAgAGEAdAAgACQAKABHAGUAdAAtAEQAYQB0AGUAKQAiACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAEMAOgBcAHAAYQB5AGwAbwBhAGQAXwByAGUAcwB1AGwAdAAuAHQAeAB0AA0ACgA=
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\PayloadKey
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName : PayloadKey
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
Alternatively:
We can observe the BASE64 ciphered payload (hold on to this, as it will become one of our detection artifacts later).
Now let’s throw in that juicy iex keyword to the Splunk mix and see what it comes up with:
Query: WmiPrvse OR powershell AND "iex" (NOT *google* NOT splunk NOT TargetImage=*powershell* NOT TargetImage=*wmiprvse* NOT TargetImage=*chrome* NOT TargetImage=*vmware* NOT EventCode=600) | reverse | table _time, EventCode, Message
We start observing some other interesting events popping up here. Disregarding Sysmon EventCode 20 (belongs to the new 6.10 version) which will be dissected later, we can see 5861 (Source: Microsoft-Windows-WMI-Activity/Operational), 400 (Source: Windows Powershell / Message: Engine state is changed from None to Available)1 and 403 (Source: Windows Powershell / Message: Engine state is changed from Available to Stopped)2. All of them are standard Windows Events, I haven’t “enabled” anything in particular here. I’m just farming what the OS already gives you by default.
The interesting thing about all these events is that they all reveal the powershell code used as payload: powershell.exe -NoP -C iex ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((Get-ItemProperty -Path HKLM:\SOFTWARE\PayloadKey -Name PayloadValue).PayloadValue)))
― ―
Most interesting of them all is Event 5861, which is giving us a lot of information about the persistence, namely the Binding itself.
WMI Persistence via PowerLurk by Sw4mpf0x
We can reproduce the same Timer Triggered Event as above with more ease with this great script which allows for a lot of flexibility.
Register-MaliciousWMIEvent -EventName MaliciousWMIEvent -LocalScriptBlock {Invoke-Expression -Command "cmd /c calc.exe"} -Trigger Interval -IntervalPeriod 60 -TimerId MaliciousTimer
this will simply start calc every 60 seconds and we can see the timer event
__GENUS : 2
__CLASS : __IntervalTimerInstruction
__SUPERCLASS : __TimerInstruction
__DYNASTY : __SystemClass
__RELPATH : __IntervalTimerInstruction.TimerId="MaliciousTimer"
__PROPERTY_COUNT : 3
__DERIVATION : {__TimerInstruction, __EventGenerator, __IndicationRelated, __SystemClass}
__SERVER : W10B1
__NAMESPACE : ROOT\cimv2
__PATH : **\\W10B1\ROOT\cimv2:__IntervalTimerInstruction.TimerId="MaliciousTimer"**
IntervalBetweenEvents : 60000
SkipIfPassed : False
TimerId : MaliciousTimer
PSComputerName : W10B1
Let’s go ahead and remove it though:
Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding | Remove-WmiObject -Verbose
Get-WMIObject -Namespace root\Subscription -Class __EventFilter | Remove-WmiObject -Verbose
Get-WMIObject -Namespace root\Subscription -Class __EventConsumer | Remove-WmiObject -Verbose
Get-WmiObject -Class __IntervalTimerInstruction | Remove-WmiObject -Verbose
We can do many more things, but this post is mainly about how to detect such sneaky persistence mechanisms, so let’s go ahead and grab our majestic free install of Splunk Enterprise with a 60 day trial and let’s make use of our best friend Sysmon the Great.
WMI Persistence Detection
For the purposes of this test, I’ve used a “log all” approach with Sysmon, you can find a sample config file here (Threat Hunting Ecosystem as a Code is my next project, don’t look at it yet, it’s ugly!)
So let’s go ahead and create a new TimerEvent and see what our logs come up with. We shall use the following search:
LogName=Microsoft-Windows-WMI-Activity/Operational AND NOT EventCode=5858 AND NOT "sysmon"
-
First thing we notice is that Windows already comes with a default “WMI-Event Detector” which is Event Id 5860 in the Microsoft-Windows-WMI-Activity/Operational Log
-
Second, becase I am running Powershell v5, Script Block Auditing is enabled by default, hence, the malicious script was also captured:
-
We also notice via another Event Id 5860 that some application with the Process Id 2024 issued a query to the WMI provider:
Who is this guy?
PS C:\WINDOWS\system32> Get-Process -Id 2024
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
425 20 22676 21804 174.56 2024 0 Sysmon64
The only problem we noticed here is that, for Timer-based WMI Events, sysmon wasn’t generating any logs. So you need to monitor Windows Event Id 5859/5861 if you want to catch those. ― ―
What would happen if we create a script event consumer?
$script = @’
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile="c:\test\log.txt"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "%TargetInstance.ProcessName% started at PID %TargetInstance.ProcessId%" & vbCrLf
objFile.Close
‘@
Register-MaliciousWmiEvent -EventName CalcMalicious -PermanentScript $script -Trigger ProcessStart -ProcessName notepad.exe -ScriptingEngine VBScript
As we can observe, this pretty handy Windows Event Id 5861 provides all the information pertaining to the FilterToConsumerBinding, the EventConsumer and EventFilter
We also observe Windows Event Id 5859 showing the EventFilter which is effectively registered in the NotificationQueue:
LogName=Microsoft-Windows-WMI-Activity/Operational
SourceName=Microsoft-Windows-WMI-Activity
EventCode=5859
EventType=0
Type=Information
ComputerName=W10B1
User=NOT_TRANSLATED
Sid=S-1-5-18
SidType=0
TaskCategory=The operation completed successfully.
OpCode=Info
RecordNumber=321
Keywords=None
Message=Namespace = //./root/CIMV2; NotificationQuery = SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='notepad.exe'; OwnerName = S-1-5-21-2876542525-3899777576-1000537697-1001; HostProcessID = 972; Provider= WMI Kernel Trace Event Provider, queryID = 0; PossibleCause = Permanent
And one other small but important piece of information is the presence of Event Id 5857 which is telling us who the provider is (an executable) whose task is to carry out the actions determined in the EventConsumer class:
LogName=Microsoft-Windows-WMI-Activity/Operational
SourceName=Microsoft-Windows-WMI-Activity
EventCode=5857
EventType=0
Type=Information
ComputerName=W10B1
User=NOT_TRANSLATED
Sid=S-1-5-18
SidType=0
TaskCategory=The operation completed successfully.
OpCode=Info
RecordNumber=322
Keywords=None
Message=ActiveScriptEventConsumer provider started with result code 0x0. HostProcess = wmiprvse.exe; ProcessID = 972; ProviderPath = %SystemRoot%\system32\wbem\scrcons.exe
Let’s commit that to memory for a second: %SystemRoot%\system32\wbem\scrcons.exe. What the event is telling us is the executable in charge of running our script. Riding the Google brave horses I was able to obtain good answers from the Internet Elders: https://msdn.microsoft.com/en-us/library/aa940177(v=winembedded.5).aspx Here it says that these are the handlers for common event consumers:
Scrcons.exe. ActiveScriptEventConsumer
Smtpcons.dll. SMTPEventConsumer
Wbemcons.dll. CommandLineEventConsumer, NTEventLogEventConsumer, LogFileEventConsumer
So essentially, even if you are NOT monitoring for either Sysmon Events 19, 20 & 21 or Windows native Events in the WMI/Operational space Ids 5857, 5859, 5860 & 5861, you can still detect the presence of potentially malicious WMI persistence by leveraging the event consumer handlers listed above. Let’s ask Sysmon for Scrcons.exe
Now what a surprise! you would be expeting that WmiPrvse.exe would start scrcons.exe, instead it’s this regular non-profit bloke svchost.exe. Sysmon is even providing us with the name Description: WMI Standard Event Consumer - scripting
Looking for further clues of scrcons.exe returns a Sysmon Event Id 11 (File Created) event where our little friend created a file.
If we were expecting to see this file, written to disk by wscript.exe we will be disappointed ― ―
This time though, Sysmon seems to have noticed that a malicious event subscription was created and here we have it:
Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Sysmon/Operational";id=20} | Select-Object -ExpandProperty Message
WmiEventConsumer activity detected:
EventType: WmiConsumerEvent
UtcTime: 2018-03-02 14:17:53.442
Operation: Created
User: W10B1\Artanis
Name: "CalcMalicious"
Type: Script
Destination: "Set objFSO=CreateObject(\"Scripting.FileSystemObject\")\noutFile=\"c:\\test\\log.txt\"\nSet objFile = objFSO.Cre
ateTextFile(outFile,True)\nobjFile.Write \"%TargetInstance.ProcessName% started at PID %TargetInstance.ProcessId%\" & vbCrLf\no
bjFile.Close"
If you are using Sysmon events to monitor for WMI event subscriptions, you only need to capture the results of Event Id 19 as it will display the event consumer which is were the juicy information is that allows us to discriminate benign from malicious.
What happens if we instead create a CommandLine Event Subscription instead of a Script based one? The command would look like this with PowerLurk:
Register-MaliciousWmiEvent -EventName LogCalc1 -PermanentCommand “cmd.exe /c msg Artanis This is Persistence!” -Trigger ProcessStart -ProcessName calculator.exe
This time, instead of scrcons.exe we shall see wbemcons.dll as the event handler, and instead of a process being a child of another process we shall see WmiPrvse.exe loading wbemcons.dll. In all my experimental hunts I can assure you that the presence of wbemcons.dll being loaded as a module by WmiPrvse.exe is extremely rare, so do pay attention to those if you are not monitoring WMI/Operational native Windows events.
I will leave it as an exercise to the reader to investigate which events are generated by creating a CommandLine Event Consumer.
What about DFIR?
It happens to be the case that any permanent event subscription gets written to a WMI database file called OBJECTS.DATA that can be located here:
- C:\Windows\System32\wbem\Repository\OBJECTS.DATA
- C:\Windows\System32\wbem\Repository\FS\OBJECTS.DATA
It turns out that the information pertaining WMI event subscriptions can be located there in plain text. The file has a binary format and its structure, AFAIK, is undocumented. However, there are a few out there that were brave enough to come up with some cool python scripts that make use of The Sword of RegEx The Great and Meticulous
that allow for parsing of these files, namely:
- https://github.com/darkquasar/WMI_Persistence (developed by me)
- https://github.com/davidpany/WMI_Forensics (David Pany script)
- https://github.com/fireeye/flare-wmi (a few scripts by FireEye analysts)
So even if you are (well… luckily after reading this post “were”) not collecting any WMI telemetry data in your environment, you can still go out there and hunt for these threats by collecting all the OBJECTS.DATA files in your hosts. The scripts listed above allow for easy parsing of a folder full of these files so the heavy lifting will be on the collecting side of things
Detection Logics & Lessons Learned
You may think that WMI fileless persistence and malware execution mechanisms are a very low risk threat thus spending business cycles into creating a detection for this drops way down the list of priorities. It is, however, an extremely easy to detect tactic and if your priority list is not packed with threat scenarios like this one then you are not putting together a proper list!
We all know looking at detailed TTPs is a tedious process, but only by adopting a systemic approach you will be able to extend your detection & prevention surface. It’s an ants work, mixed with that of a dragon ― ―
So, to summarize
Monitor | Detect | Suited for |
---|---|---|
Sysmon Event Id 11 (File Write) where “Image” is “C:\WINDOWS\system32\wbem\scrcons.exe”. | Suspicious files written by the script event consumer handler | Environments with Sysmon monitoring |
Sysmon Event Id 1 where “ParentImage” is C:\Windows\System32\svchost.exe AND Image is “C:\WINDOWS\system32\wbem\scrcons.exe”. Alternatively Windows Security Log Event ID 4688 (Process Created) can also be monitored. | Instances of an Active Script Event Consumer WMI Persistence | When you are not monitoring Windows native WMI/Operational events OR,when a malicious actor disabled native windows event logging and you have another technology in place (for example EDR) |
Sysmon Event Id 7 where “Image” is C:\Windows\System32\wbem\WmiPrvSE.exe AND “ImageLoaded” contains “wbemcons.dll”. | Instances of an Active CommandLine Event Consumer Persistence | When you are not monitoring Windows native WMI/Operational events,OR,when a malicious actor disabled native windows event logging and you,have another technology in place (for example EDR) |
Windows Event Id 5859 in WMI-Activity/Operational | Suspicious Event Consumers | Environments with no Sysmon monitoring using solely native Windows Events OR for Intrinsic Timer Events (Sysmon doesn’t catch those!) |
Windows Event Id 5861 in WMI-Activity/Operational | Suspicious Event Filters | Environments with no Sysmon monitoring using solely native Windows Events OR for Intrinsic Timer Events (Sysmon doesn’t catch those!) |
Hopefully in my next post I will resume the Mimikatz one and then I will jump into Meterpreter detections
Changes to your Sysmon Config
We will add a tag for the new event that has a pretty tight condition: it will only collect WMI events when they are created. This way, the FP ratio is reduced to a minimum, but as a trade off you need to be really paying attention and treat Alarms pertaining to these events as critical always.
<!--SYSMON EVENT ID 19,20,21 : WMIEvent-->
<WmiEvent onmatch="include">
<Operation condition="is">Created</Operation>
</WmiEvent>
Some references
- Malware using WMI Persistence: WMIGhost / Actors: APT29POSHSPY
- Yeap, cryptominers WMI’ing the sh!@# out of Browsers
- This dude man! mattifestation
- List of modules involved in each WMI event https://msdn.microsoft.com/en-us/library/aa940177(v=winembedded.5).aspx
- https://msdn.microsoft.com/en-us/library/aa392282(v=vs.85).aspx This explains how to create an NTEventLogEventConsumer class and how to setup one of its properties (insertionstrings) to a string. It also does this via MOF and compiling the MOF. The MOF then is embedded in OBJECTS.DATA. WMIPers is not parsing the “_EventConsumer” for these events very well, must look into that. The interesting thing though is that you could store anything in those “strings”, why not a payload?
- https://msdn.microsoft.com/en-us/library/aa393016(v=vs.85).aspx Ability to register EventConsumers and EventFilters can be restricted by setting the EventAccess attribute of the EventFilter instance.
arrivederci my friends, wine and fettuccine awaits!
EventCode 400 sample contents
09/19/2017 11:44:22 PM
LogName=Windows PowerShell
SourceName=PowerShell
EventCode=400
EventType=4
Type=Information
ComputerName=W10B1
TaskCategory=Engine Lifecycle
OpCode=Info
RecordNumber=56
Keywords=Classic
Message=Engine state is changed from None to Available.
Details:
NewEngineState=Available
PreviousEngineState=None
SequenceNumber=13
HostName=ConsoleHost
HostVersion=5.1.14393.206
HostId=9ebd19fb-d695-44ec-a9b1-51d48db8b1ef
HostApplication=powershell.exe -NoP -C iex ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((Get-ItemProperty -Path HKLM:\SOFTWARE\PayloadKey -Name PayloadValue).PayloadValue)))
EngineVersion=5.1.14393.206
RunspaceId=0a4191f5-9ee9-417b-9ebe-fbb73aa20b37
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=
EventCode 403 sample contents
09/19/2017 11:44:23 PM
LogName=Windows PowerShell
SourceName=PowerShell
EventCode=403
EventType=4
Type=Information
ComputerName=W10B1
TaskCategory=Engine Lifecycle
OpCode=Info
RecordNumber=57
Keywords=Classic
Message=Engine state is changed from Available to Stopped.
Details:
NewEngineState=Stopped
PreviousEngineState=Available
SequenceNumber=15
HostName=ConsoleHost
HostVersion=5.1.14393.206
HostId=9ebd19fb-d695-44ec-a9b1-51d48db8b1ef
HostApplication=powershell.exe -NoP -C iex ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String((Get-ItemProperty -Path HKLM:\SOFTWARE\PayloadKey -Name PayloadValue).PayloadValue)))
EngineVersion=5.1.14393.206
RunspaceId=0a4191f5-9ee9-417b-9ebe-fbb73aa20b37
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=
threat hunting, hunting, wmi, windows management instrumentation, backdoor, persistene, siem, ioc, splunk, elk, darkquasar, volatility