Let’s check WinRM Security Event ID Details using SCCM CMPivot. You can use this method to collect the details of the Windows devices based on Event IDs. Windows added additional details to WinRM event logs. More details are below.
After July Cumulative Updates (KB5015807 and KB5015814), it adds IP address auditing for incoming Windows Remote Management (WinRM) connections in security event 4262 and WinRM event 91.
You can also use CMPivot to query the registry entries on Windows servers and client operating systems. The CMPivot gives you almost live data of the online SCCM clients. So there is no delay, unlike other reporting methods.
CMPivot is the subset of the KQL query language that is used in Azure log analytics. You can also use the Intune portal to check the registry checks using the CMPivot query if you have already enabled the SCCM Cloud (tenant) attach feature.
- CMPivot Query For SCCM BitLocker Management Event Logs
- Publish CMPivot Query to the SCCM Community Hub Contributions
You can get the WinRM Event ID Details from the Event Viewer. You can use the following path to get the Event ID details using CMPivot. But there is a catch! More details are available in the below section.
- WinRM Event Logs: Microsoft – Windows – Windows Remote Management
Security Event ID Details
Let’s check how to collect the Security Event ID details using SCCM CMPivot and list down or get the count of devices having a particular security event log. Again, you need to make some adjustments in the CMPivot query to get this working. More details are below.
- Security Event Logs: Windows Logs -> Security
Prerequisite for SCCM CMPivot
Ensure you are running the latest version of the SCCM client and CMPivot (SCCM console). Appropriate SCCM security permissions are required to run CMPivot.
Also, SCCM client devices should require PowerShell version 4.0. The Start CMPivot action doesn’t appear in the console when connected to an SCCM CAS site.
Launch CMPivot to Check WinRM Event ID Details
There are different methods to launch CMPivot. The in-console CMPivot method is explained in this post. However, there are other methods as well, such as:
- Use standalone CMPivot Tool
- Use MEM Admin Center (aka Intune) portal
Let’s check WinRM Event ID Details using SCCM CMPivot. Always use the smallest device collection as the first step for initial testing. This will help to understand whether the CMPivot query is working as expected or not.
- Navigate to the Device Collections against which you want to run the CMPivot query to review the BitLocker Management event logs.
- Select any one of the device collections as per your requirement.
- Right-Click on Device collection.
- Select Start CMPivot.
WinEvent Vs. EventLog
Let’s understand which CMPivot entity should be used to get the event log details. I see there are some differences, as listed down in the below table, between both entities.
I use WinEvent for checking the Microsoft Windows related events. The Winevent is specifically for windows events, and EventLog is more generic and even can be used for 3rd party app event logs.
CMPivot Entity Name | Description | Properties |
---|---|---|
WinEvent | Events from a Windows event log | Device LevelDisplayName DateTime Message ProviderName ID |
EventLog | Events from an Event log | Device Entry Type DateTime Message Source EventID |
Check WinRM Event ID Details using SCCM CMPivot
Let’s try to use Windows Remote Management (WinRM) events to track the devices with some errors or with specific event IDs etc. But you must be careful with the CMPivot query, as explained below.
The following is the WinRM Event Logs path: Microsoft – Windows – Windows Remote Management. The question is how to convert this event log path into the CMPivot query event log path.
Wait, Microsoft-Windows-Windows Remote Management/Operational -> this is not going to work! Because Windows Remote Management is not the actual name of the event log path. You must use WinRM instead, as shown below.
- Click on the Query Tab from the CMPivot application/tool.
- Paste the WinRM CMPivot Query to the “query” window.
- The following query gives the list of all WinRM events for the last 2 hours.
- Click on the Run Query button and wait for it to complete the execution of the query.
WinEvent('Microsoft-Windows-WinRM/Operational', 2h)
CMPivot query takes a long time to complete if you are running against a larger collection. So hold your horses and test your CMPivot queries with smaller collections first or run against a particular device.
As explained below, you can expand or filter down the query to get the exact details or count of devices with a particular error. With the below query, let’s check the WinRM error code 2150858770. This CMPivot query will return the device details with the error code within the last hour (1h).
WinEvent('Microsoft-Windows-WinRM/Operational', 1h) | where Message contains 'error code 2150858770'
You can also fetch the high-level count of errors per device with any particular WinRM error or message using the SCCM CMPivot query shared below.
WinEvent('Microsoft-Windows-WinRM/Operational') |
summarize countif( (Message contains 'error code 2150858770') ) by Device |
where (countif_ > 0)
Check Security Event ID Details
Let’s try to use Windows Security events to track the devices with some errors or with specific event IDs etc. But you need to be careful with the CMPivot query here, as explained below.
Security Event Logs path is Windows Logs -> Security, and However, when you convert that into CMPivot, you need to be a bit more careful. You need to use “Security” as the path mentioned in the CMPivot query below to fetch the Windows security events.
NOTE! – The following CMPivot query gets Windows security event log details from all the devices in a particular collection for the last 2 hours. This information can be overwhelming. So try to reduce the number of devices in the collection before running this query.
WinEvent('Security', 2h)
You can get the IP address auditing for incoming Windows Remote Management (WinRM) connections in security event 4262 and WinRM event 91 using the following CMPivot query.
The following CMPivot query helps to get new security events from the devices for the last 2 hours based on the specific event IDs.
WinEvent('Security', 2h) | where ID == 4262 or ID == 91
Some other sample CMPivot queries to check IP address auditing for WinRM connections.
WinEvent('Security') |
summarize countif( (Message contains 'IP Address') ) by Device |
where (countif_ > 0)
Resources
CMPivot overview – Configuration Manager | Microsoft Docs
Author
Anoop C Nair is Microsoft MVP! He is a Device Management Admin with more than 20 years of experience (calculation done in 2021) in IT. He is Blogger, Speaker, and Local User Group HTMD Community leader. His main focus is on Device Management technologies like SCCM 2012, Current Branch, and Intune. He writes about ConfigMgr, Windows 11, Windows 10, Azure AD, Microsoft Intune, Windows 365, AVD, etc.
From Wikipedia, the free encyclopedia
Developer(s) | Microsoft |
---|---|
Operating system | Microsoft Windows |
Type | Application programming interface |
License | Proprietary commercial software |
Website | docs |
Windows Remote Management (WinRM) is the Microsoft implementation of the DMTF-standard WS-Management. It allows accessing or exchanging management information across a common network. Utilizing scripting objects or the built-in command-line tool, WinRM can be used with any remote computers that may have baseboard management controllers (BMCs) to acquire data. On Windows-based computers including WinRM, certain data supplied by Windows Management Instrumentation (WMI) can also be obtained.[1]
winrs
Developer(s) | Microsoft |
---|---|
Operating system | Microsoft Windows |
Type | Command |
License | Proprietary commercial software |
Website | docs |
- WinRM Scripting API: Provides an Application programming interface enabling scripts to remotely acquire data from computers that perform WS-Management operations.
- winrm.cmd: Built-in systems management command line tool allowing a machine operator to configure WinRM. Implementation consists of a Visual Basic Scripting (VBS) Edition file (Winrm.vbs) which is written using the aforementioned WinRM scripting API.
- winrs.exe: Another command line tool allowing the remote execution of most Cmd.exe commands. This tool utilizes the WS-Management protocol.
- Intelligent Platform Management Interface (IPMI) driver: Provides hardware management and facilitates control of remote server hardware through BMCs. IPMI is most useful when the operating system is not running or deployed as it allows for continued remote operations of the bare metal hardware/software.
- WMI plug-in: Allows WMI data to be made available to WinRM clients.[2]
- WMI service: Leverages the WMI plug-in to provide requested data or control and can also be used to acquire data from most WMI classes. Examples include the Win32_Process, in addition to any IPMI-supplied data.
- WS-Management protocol: Web Services Management is a DMTF open standard defining a SOAP-based protocol for the management of servers, devices, applications and various Web services. WS-Management provides a common way for systems to access and exchange management information across the IT infrastructure.[3]
- Ports: By default WinRM HTTPS used 5986 port, and HTTP uses 5985 port. By default, port 5985 is in listening mode, but port 5986 has to be enabled.
Ansible communicates with Windows servers over WinRM using the Python pywinrm package and can remotely run PowerShell scripts and commands.[4]
Thycotic’s Secret Server also leverages WinRM to enable PowerShell remoting.[5]
SolarWinds Server and Application Monitoring software (SAM) utilizes a WinRM server on monitored servers for its PowerShell integration.[6]
CloudBolt leverages WinRM as part of Blueprints, Server Actions, and CB Plugins to execute remote scripts on Windows servers using the python pywinrm module.[7]
WinRM uses Kerberos for initial authentication by default. This ensures that actual credentials are never sent in client-server communications, instead relying on features such as hashing and tickets to connect.[8] Although WinRM listeners can be configured to encrypt all communications using HTTPS, with the use of Kerberos, even if unencrypted HTTP is used, all communication is still encrypted using a symmetric 256-bit key after the authentication phase completes. Using HTTPS with WinRM allows for additional security by ensuring server identity via SSL/TLS certificates thereby preventing an attacker from impersonating it.[9]
- ^ windows-sdk-content. «Windows Remote Management — Windows applications». docs.microsoft.com. Retrieved 2019-02-21.
- ^ windows-sdk-content. «Windows Remote Management Glossary — Windows applications». docs.microsoft.com. Retrieved 2019-02-21.
- ^ windows-sdk-content. «About Windows Remote Management — Windows applications». docs.microsoft.com. Retrieved 2019-02-21.
- ^ «Windows Remote Management — Ansible Documentation». docs.ansible.com. Retrieved 2019-02-21.
- ^ «Thycotic Support». thycotic.force.com. Retrieved 2019-02-21.
- ^ «Create a WinRM HTTPS listener». SolarWinds Worldwide, LLC. Help and Support. 2016-03-24. Retrieved 2019-02-24.
- ^ «Remote Scripts — CloudBolt 8.7 Documentation». docs.cloudbolt.io. Retrieved 2019-06-04.
- ^ «How To: Configure WINRM for HTTPS». support.microsoft.com. Retrieved 2019-02-24.
- ^ FoxDeploy (2017-02-08). «Is WinRM Secure or do I need HTTPs?». FoxDeploy.com. Retrieved 2019-02-24.
- Windows Remote Management — Windows applications | Microsoft Docs
Время на прочтение9 мин
Количество просмотров9.8K
Идея написать блог о том, как злоумышленники используют для перемещения в инфраструктуре жертвы возможности службы Windows Remote Management (WinRM) (Т1021.006), возникла у Антона Величко, руководителя Лаборатории компьютерной криминалистики компании F.A.C.C.T., еще в январе 2022 года. И виной тому стали не затянувшиеся новогодние праздники и наличие свободного времени, как может показаться, а как раз наоборот. В тот момент криминалисты F.A.C.C.T. столкнулись с очередным «праздничным» всплеском кибератак на российские компании, и в процессе реагирования на инцидент у одного из наших клиентов обнаружили интересный кейс, о котором Антон Величко и его соавтор — Кирилл Полищук захотели подробно рассказать.
Незваные гости
Итак, как все происходило: атакующие получили первоначальный доступ к периметру компании, проэксплуатировав уязвимость одного из публично доступных сервисов, и захватили полный контроль над инфраструктурой жертвы, развив атаку. Используя различные техники закрепления, злоумышленники обеспечили себе возможность доступа к внутреннему периметру на протяжении года! За это время они успешно провели не менее четырех атак, в ходе которых им удалось провести эксфильтрацию данных, неоднократно вмешиваться в работу различных систем, удалить критически важную информацию или зашифровать данные.
После очередной атаки IT-специалисты восстанавливали и перестраивали инфраструктуру, а спустя какое-то время злоумышленники возвращались, и атака повторялась снова. Таким образом, злоумышленники не только планомерно разрушали бизнес-процессы компании, но и превратили в ад жизнь IT-персонала, который любой малейший сбой в том или ином отделе воспринимал как очередной инцидент информационной безопасности и «невидимую руку хакеров».
Безусловно, провернуть такую кампанию злоумышленникам удалось не только благодаря недостатку у жертвы соответствующих компетенций и инструментов для обеспечения информационной безопасности, но и благодаря своим профессиональных навыкам.
На протяжении года злоумышленники закреплялись на множестве устройств, используя различные утилиты двойного назначения и бэкдоры, которые они разместили в том числе на различных сетевых устройствах, и после проведения клиентом восстановительных работ снова возвращались в сеть.
Для перемещений по сети злоумышленники преимущественно использовали протокол удаленного рабочего стола (Remote Desktop Protocol), а после того как он был запрещен администраторами, переключились на WinRM. Использование злоумышленниками данной службы и наличие недокументированного и ранее не описанного артефакта, который был впервые обнаружен в ходе нашего реагирования, позволили выявить и дополнить список скомпрометированных узлов и лишить злоумышленников возможности взаимодействовать с сетью клиента.
В этом блоге мы хотим поделиться с профессиональным сообществом и читателями информацией о том, на какие артефакты можно опираться в процессе реагирования на инцидент, а также как оперативно выявить эксплуатируемые атакующими хосты инфраструктуры в случаях, когда они перемещаются при помощи WinRM.
Краткая справка о WinRM
WinRM — это название как службы, так и протокола Windows, разработанного прежде всего для IT-специалистов. Она используется для удаленного управления, администрирования и мониторинга систем. WinRM была впервые представлена в операционной системе Windows Vista в 2006 году и с тех пор интегрирована во все последующие версии Windows.
WinRM является реализацией протокола WS-Management, предназначенного для управления различными устройствами при помощи SOAP-запросов.
-
Служба WinRM запускается и работает в контексте процесса svchost.exe -k NetworkServices -p -s WinRM.
-
Начиная с версии 2.0 WinRM, слушатель службы %systemroot%\system32\WsmSvc.dll по умолчанию прослушивает порты 5985/TCP для HTTP-соединений и 5986/TCP для HTTPS-соединений. В Windows Server 2008 / Windows 7 использовались 80/TCP и 443/TCP соответственно.
-
WinRM поддерживает следующие механизмы аутентификации:
-
Basic — для аутентификации клиента и авторизации его запросов к серверу с помощью базовых HTTP-заголовков. Этот механизм аутентификации небезопасный и не рекомендуется к использованию, так как передача учетных данных происходит в явном виде.
-
Digest — это механизм аутентификации, который использует HTTP-заголовки для передачи аутентификационных данных между клиентом и сервером с помощью хеш-функции.
-
NTLM — для аутентификации клиента по имени пользователя и паролю, если клиент и сервер не являются членами одного домена или если применяется схожий механизм аутентификации.
-
Kerberos — для взаимной аутентификации между клиентом и сервером в домене Windows. Клиент и сервер должны быть членами одного домена.
-
SSL-сертификаты — для проверки легитимности сервера и клиента при использовании протокола HTTPS. Этот механизм аутентификации обеспечивает безопасность передаваемых данных посредством шифрования.
-
CredSSP — для делегирования учетных данных на сервер, который может их использовать для выполнения задач на удаленных компьютерах.
-
-
WinRM позволяет создать список доверенных узлов.
-
WinRM позволяет устанавливать продолжительные интерактивные сеансы с удаленным хостом, выполнять отдельные команды, скрипты, а также запросы WMI (CIM).
Выполнение PSRP, WinRS, CIM over WinRM
Перед тем как мы поговорим о том, какие артефакты могут нам помочь в расследовании инцидентов, хотелось бы рассказать об основных способах выполнения команд на хостах при помощи WinRM.
Как уже ранее говорилось, WinRM позволяет устанавливать интерактивные сессии и выполнять различные команды. При помощи штатных средств Windows это можно сделать несколькими способами:
-
PowerShell Remoting (PSRP)Например:Invoke-Command -ComputerName <RemoteComputer> -Scriptblock {EVIL.exe}Enter-PSSession -ComputerName <RemoteComputer> и др.
-
Windows Remote Shell (WinRS)Например:winrs -r: <RemoteComputer> EVIL.exe
-
WMI (CIM) over WinRM (начиная с PowerShell версии 3.0 добавлены командлеты CIM, работа которых осуществляется через WinRM).Например:Invoke-CimMethod -ClassName Win32_Process -MethodName “Create” -ComputerName <RemoteComputer> -Arguments @{CommandLine=’EVIL.exe’} и др.
Процессы, порождаемые PSRP, WinRS, CIM over WinRM
В зависимости от выбранного способа выполнения WinRM передаст управление DCOM-серверу (Distributed Component Object Model), который проведет запуск одного из трех провайдеров:
-
%systemroot%\system32<b style=»box-sizing: border-box; outline: none; -webkit-tap-highlight-color: transparent; font-weight: bolder;»>wsmprovhost.exe (Microsoft Web Services Management Provider Host);
-
%systemroot%\system32<b style=»box-sizing: border-box; outline: none; -webkit-tap-highlight-color: transparent; font-weight: bolder;»>winrshost.exe (Microsoft Windows Remote Shell Host);
-
%systemroot%\system32<b style=»box-sizing: border-box; outline: none; -webkit-tap-highlight-color: transparent; font-weight: bolder;»>wmiprvse.exe (Windows Management Instrumentation Provider Host).
Таким образом, процесс того или иного провайдера будет запущен в контексте процесса svchost.exe -k -DcomLaunch -p, который, в свою очередь, станет родительским для порождаемой полезной нагрузки.
На рис. 1, 2 и 3 представлены цепочки процессов, возникающие при использовании PowerShell Remoting, Windows Remote Shell, а также при выполнении CIM-запросов.
Инструменты Red Team
При WinRM-перемещениях по хостам атакуемой инфраструктуры злоумышленники используют не только легитимные средства, но и различные инструменты или фреймворки, в которых реализована возможность взаимодействия с WinRM. Список некоторых инструментов и фреймворков представлен ниже.
При использовании данных инструментов на атакуемых хостах генерируется большое количество различных релевантных событий, позволяющих обнаружить использование WinRM как средство для продвижения по инфраструктуре.
Теперь рассмотрим небольшую эмуляцию, проделанную при помощи Evil-WinRM, и проведем реконструкцию активности на хосте по записям журналов событий.
В рамках данной эмуляции мы подключились к контроллеру домена, выполнили команды whoami, hostname, загрузили в него файл evil.exe и запустили его (рис. 4).
В данном случае, при реконструкции действий атакующего, в журналах атакуемой ОС мы обнаружим список характерных событий, указывающих на использование PowerShell Remoting. Наиболее информативные из них, по моему мнению, представлены ниже.
Описание |
ID события |
1. События с назначенными привилегиями и нового входа с Logon ID, именем пользователя и адресом удаленного хоста |
4672, 4624 (Security.evtx) |
2. Событие запуска провайдера wsmprovhost.exe и оболочки WS-Man |
4688 (Security.evtx) |
3. События запуска процессов whoami.exe, hostname.exe, порождаемых от провайдера (оболочки) wsmprovhost.exe |
4688 (Security.evtx) |
4. Вызовы командлетов и создание блоков скрипта при доставке полезной нагрузки evil.exe |
4103, 4104 (Microsoft-Windows-PowerShell%4Operational.evtx) |
5. События запуска процесса evil.exe, порождаемого от провайдера (оболочки) wsmprovhost.exe |
4688 (Security.evtx) |
При проведении реагирования на инцидент журналы событий значительно упрощают и сокращают время реагирования, а также позволяют быстрее добраться до точки входа и выявить большое количество индикаторов компрометации и используемых техник продвижения.
Ни для кого не секрет, что атакующие для противодействия обнаружению и усложнения задач реагирующему специалисту довольно часто очищают журналы событий. Очистку журналов они могут осуществлять как штатными средствами ОС, так и с помощью функциональных возможностей, реализованных в используемых ими инструментах. И в этих условиях специалист будет вынужден погрузиться в более глубокий анализ различных источников криминалистических данных, таких как AmCache, ShimCache, SRUDB, $MFT и многих других. Но среди них не так много источников, которые позволят нам оттолкнуться и «пойти» в сторону точки входа.
Так, однажды погрузившись в исследование, нами был обнаружен параметр реестра WSManSafeClientList, который позволяет не только выявить технику продвижения, но и ряд потенциально эксплуатируемых атакующими узлов (рис. 5).
Список «безопасных» клиентов
Параметр реестра WSManSafeClientList появился в системах с момента появления Windows 8 и располагается по пути HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\SafeClientList. В него сохраняются IP-адреса успешно подключавшихся с помощью WinRM клиентов. А запись в него осуществляется слушателем службы WsmSvc.dll.
Проведенными исследованиями установлено, что:
-
параметр WSManSafeClientList отсутствует на хостах, к которым подключения не осуществлялись (в том числе когда служба WinRM сконфигурирована и запущена);
-
в параметр WSManSafeClientList записываются HEX-значения адресов IPv4 и IPv6, ранее подключавшихся при помощи WinRM;
-
максимальный размер параметра составляет 160 байт и может содержать до 10 уникальных IP-адресов;
-
размер каждой записи составляет 16 байт (рис. 6).
Запись адресов в параметр WSManSafeClientList осуществляется спустя 15 минут после успешного подключения с адреса, которого нет среди ранее записанных адресов, или в момент остановки службы.
В случае если адрес последнего подключившегося хоста уже имеется в списке, то порядок адресов в параметре не меняется и запись в него не производится.
При превышении количества записей в параметре первый адрес в списке будет удален, а новый — добавлен в конец списка (рис. 7).
Выводы и рекомендации
Несмотря на то, что WinRM — не самый часто используемый инструмент, возможности, предоставляемые атакующим службой WinRM и тривиальность детектирования традиционных методов продвижения по сети, обусловят все большее распространение данной техники.
Для защиты от подобных атак мы в очередной раз рекомендуем следующее:
-
Регулярно осуществляйте установку критических обновлений операционной системы и используемых программных продуктов.
-
Обеспечьте надежную защиту средств удаленного доступа в ИТ-инфраструктуру, в том числе с помощью мультифакторной аутентификации.
-
Глубина хранения журналов событий операционной системы и средств защиты информации должна быть не менее 3 месяцев.
-
Настройте сбор Windows событий:
-
успешных и неуспешных попыток входа;
-
включение/отключение учетных записей, их блокировка;
-
создание локальных и доменных учетных записей;
-
добавление пользователей в группы, особенно предоставляющие повышенные привилегии;
-
создание служб, процессов и задач в планировщике;
-
изменение доменных и локальных политик безопасности;
-
выполнение команд, при помощи различных командных интерпретаторов;
-
критические срабатывания встроенного защитника Windows (Windows Defender);
-
доступа к объектам общей сетевой папки;
-
очистки журналов событий.
-
-
Обеспечить защиту конечных устройств поможет решение F.A.C.C.T. Managed XDR, а Attack Surface Management — позволит контролировать уровень информационной безопасности инфраструктуры организации.
-
Чтобы сформировать надежную, эффективную на практике защиту потребуются не только временные и материальные затраты, но и четкий список того, что необходимо улучшать или строить заново для успешного противостояния современным угрозам. Составить такой перечень поможет комплекс услуг Лаборатории компьютерной криминалистики компании F.A.C.C.T. по оценке готовности компании к реагированию на инциденты, а также проведение киберучений в формате Purple Teaming.
Discover what WinRM protocol is all about and gain insight on how you can use it to manage your network
Technology Advisor | Cybersecurity Evangelist
Updated: November 19, 2024
Windows Remote Management (WinRM) is Microsoft’s implementation of the Web Services-Management (WS-Management) protocol, which provides a standardized method for systems, both hardware and software, from various vendors to communicate
This protocol facilitates the exchange of management data across an organization’s IT infrastructure, enabling seamless interoperability between diverse systems. By providing a unified framework, WinRM is especially beneficial for IT administrators who need to oversee extensive Windows-based network environments.
WinRM plays a crucial role in simplifying remote management tasks, such as system configuration, monitoring, and troubleshooting, making it an indispensable tool for network administrators. Microsoft first introduced this protocol with WinRM 1.1, which was compatible with Windows XP, Windows Server 2003, Windows Vista, and Windows Server 2008. This initial version laid the groundwork for the more advanced functionalities that followed.
The release of WinRM 2.0 brought significant enhancements, including the ability to execute PowerShell 2.0 scripts and cmdlets on remote systems. This version was included with Windows 7 and Windows Server 2008 R2, further streamlining administrative tasks across multiple machines. In 2012, Microsoft introduced WinRM 3.0, which came pre-installed with Windows 8 and Windows Server 2012. This version featured improved performance and deeper integration, cementing WinRM as a vital component of modern Windows infrastructure management.
Why is the WinRM protocol important?
Why is the WinRM protocol important and why do we need it? With WinRM protocol, the connection between computers or servers can be easily established, so that remote operations can be performed. You can obtain data or manage resources on remote computers as well as the local computer. Connecting to a remote computer in a Windows Remote Management script is very similar to making a local connection. The WinRM protocol is intended to improve hardware management in a network environment with various devices running a variety of operating systems.
As a command-line tool, WinRM is built into Windows operating systems and based on .NET and PowerShell, which allows scripts and remote PowerShell commands to be invoked on Windows-based machines or a large set of remote machines without RDP or log into the remote machine. This method makes it easier for Windows Administrators to manage multiple machines using scripts and cmdlet, and perform tasks such as:
- Monitor, manage and configure servers, operating systems, and client machines from a remote location.
- Remotely communicate and interface with hosts through readily available channels/ports within your network, including workstations, servers, and any operating system that supports it.
- Execute commands remotely on systems that you are not local to you but are network accessible
The Windows Remote Shell (WinRS) command-line tool relies on WinRM to execute remote commands. It leverages WinRM to let you launch processes on remote machines. WinRM is the server component of this remote management application and WinRS is the client component for WinRM, which runs on the remote computer attempting to remotely manage the WinRM server. However, both computers must have WinRM installed and enabled on them for WinRS to work and retrieve information from the remote system.
WinRM architecture and components
The WinRM architecture consists of components on the client and server computers. The diagram in Figure 1.0 below shows the components on both the requesting client and responding server computers, and how they interact with each other, including the protocol that is used to communicate between them.
Table 1.0 below is a breakdown of the various WinRM components and where they reside.
Component | Description | Residence |
---|---|---|
WinRM application | WinRM command-line tool that uses the WinRM scripting API to make calls to request data or to execute methods | Client-side |
WSMAuto.dll | The Automation layer that provides scripting support | Client and server-side |
WsmCL.dl | API layer within the OS | Client and server-side |
HTTP API | Provides support for HTTP and HTTPS transport | Client and server-side |
WsmSvc.dll | WinRM listener service | Server-side |
WsmProv.dll | Provider subsystem | Server-side |
WsmRes.dll | Resource file | Server-side |
WsmWmiPl.dll | WMI plug-in that allows you to obtain WMI data through WinRM | Server-side |
IPMI driver and WMI IPMI provider | Supply any hardware data that is requested using the IPMI (Intelligent Platform Management Interface) classes | Server-side |
Table 1.0 | WinRM components and description
WinRM configuration and commands
For the WinRM command-line tool and scripts to run, and perform data operations effectively, Windows Remote Management (WinRM) must be installed and configured. However, the good news is that WinRM is automatically installed with all currently-supported versions of the Windows operating system, including IPMI (Intelligent Platform Management Interface) WMI (Windows Management Instrumentation) provider components.
By default, WinRM is enabled on Windows Server OS since Windows Server 2012, but not on Windows 10 operating system. This means that you need to enable it on Windows 10 machines. To enable WinRM on a Windows 10 machine, open PowerShell and run the following cmdlet:
Enable-PSRemoting -force
If you have a single Windows 10 machine that is not part of an Active Directory domain network, you may need to add the machine you are going to connect from to the trusted host of the Windows 10 machine. The reason we need to add trusted hosts is to be able to connect to a Windows machine using WinRM.
However, in situations where you have 100+ Windows 10 machines in an Active Directory domain network, you may need to use a Group Policy (GPO) to get it working with minimal effort. To use a GPO, create a new one or edit an existing one and modify the following settings and set WinRM to “Enabled”:
- Computer Configuration > Policies > Administrative Templates > Windows Components > Windows Remote Management (WinRM) > WinRM Service > Allow remote server management through WinRM
Remember to apply the GPO to the Organizational Units (OU) that have all your Windows 10 machines. Within a few minutes after applying the GPO to the OU, all your hosts will get the policy update. In this case, there is no need to modify the trusted hosts’ list.
The table below is a collection of some WinRM commands you can use to execute remote operations. Please note that these commands work best when you are on an Active Directory domain network. For workgroup machines, the WinRM service may require additional configuration such as modifying the trusted hosts’ list.
Description | Command | Remark |
---|---|---|
Locate listeners and the addresses | winrm e winrm/config/listener | |
Check the state of configuration settings | winrm get winrm/config | |
Quickly configure the WS-Man service | winrm QuickConfig | Run from an Elevated Command prompt |
Quickly delete the WS-Man listener | winrm invoke Restore winrm/Config @{} | Run from an Elevated Command prompt |
Display your machine’s basic hardware info | winrm enumerate wmicimv2/Win32_ComputerSystem | Run from an Elevated Command prompt |
Display your operating system properties | winrm get wmicimv2/Win32_OperatingSystem | Run from an Elevated Command prompt |
Output your OS info in XML | winrm get wmicimv2/Win32_OperatingSystem -format:pretty | Run from an Elevated Command prompt |
Test WS-Man access to a remote machine | winrm id -remote: | Run from an Elevated Command prompt |
Grab a remote machine’s WS-Man config | winrm get winrm/Config -r: | Run from an Elevated Command prompt |
Grab a remote machine’s CPU load | winrm g wmicimv2/Win32_Processor?DeviceID=CPU0 -fragment:LoadPercentage -r: | Run from an Elevated Command prompt |
Grab a remote machine’s free memory | winrm g wmicimv2/Win32_OperatingSystem -fragment:FreePhysicalMemory -r: | Run from an Elevated Command prompt |
Stop a service on a remote machine | winrm invoke stopservice wmicimv2/Win32_Service?name=w32time -r: | Run from an Elevated Command prompt |
Start a service on a remote machine | winrm invoke startservice wmicimv2/Win32_Service?name=w32time -r: | Run from an Elevated Command prompt |
Reboot a remote machine | winrm invoke reboot wmicimv2/Win32_OperatingSystem -r: | Run from an Elevated Command prompt |
Run a command on a remote machine (this uses winrS, not winrM) | winrs -r: ipconfig /all | Run from an Elevated Command prompt |
Use PowerShell to grab the WS-Man Win32_OperatingSystem XML output | [xml]$osInfo = winrm get wmicimv2/Win32_OperatingSystem /format:pretty | Run from PowerShell |
Display the OS version property | $osInfo.Win32_OperatingSystem.Version | Run from PowerShell |
Display the last boot time | $osInfo.Win32_OperatingSystem.LastBootupTime.DateTime | Run from PowerShell |
Put free memory metric into an XML variable | [xml]$freemem = cmd /c “winrm get wmicimv2/Win32_OperatingSystem -fragment:FreePhysicalMemory -f:pretty -r:” | Run from PowerShell |
Display the free memory value | $freemem.XMLFragment.FreePhysicalMemory | Run from PowerShell |
Table 2.0 | Common WinRM commands and description
WinRM security
By default, WinRM uses Kerberos for authentication. This means that Windows never sends the actual credentials to the system requesting validation instead of relying on features such as hashing and tickets to connect.
WinRM listens on TCP port 80 (HTTP) by default, it doesn’t mean traffic is unencrypted. Traffic by default is only accepted by WinRM when it is encrypted using the Negotiate or Kerberos SSP. WinRM also includes helper code that lets the WinRM listener share port 80 with the Microsoft IIS web server or any other application that may need to use that port. Although WinRM listeners can be configured to encrypt all communications using HTTPS, with the use of Kerberos, even if unencrypted HTTP is used, all communication is still encrypted using a symmetric 256-bit key after the authentication phase completes.
You can manually configure WinRM to use HTTPS. The purpose of configuring WinRM for HTTPS is to encrypt the data being sent across the network. This allows for additional security by ensuring server identity via SSL/TLS certificates thereby preventing an attacker from impersonating it. To configure WinRM to use HTTPS, a local computer Server Authentication certificate with a CNAME matching the hostname is required to be installed. To install certificates for the local computer, follow the steps below:
- Select Start and then select Run (or using keyboard combination press Windows key+R)
- Type MMC and then press Enter
- Select File from menu options and then select Add or Remove Snap-ins
- Select Certificates and select Add
- Go through the wizard selecting the Computer account
- Install or view the certificates under Certificates (Local computer) >> Personal >> Certificates.
Once the certificate is successfully installed, use the following command to configure WRM to listen on HTTPS: winrm quickconfig -transport:https
Notable applications of WinRM
- SolarWinds Server & Application Monitor software (SAM) enables remote access for PowerShell with WinRM. It utilizes a WinRM server on monitored servers for its PowerShell integration.
- Thycotic Secret Server—privileged access management (PAM) solution, relies on WinRM components to run PowerShell scripts.
- Ansible—an agentless open-source software provisioning and deployment tool, leverages WinRM to communicate with Windows servers and run PowerShell scripts and commands. Ansible is agentless because of its ability to remotely connect via WinRM, thereby allowing remote PowerShell execution to do its tasks.
- CloudBolt—a hybrid cloud management platform, leverages WinRM as part of Blueprints, Server Actions, and CB Plugins to execute remote scripts on Windows servers using the python pywinrm module.
Windows Remote Management FAQs
Is WinRM the same as RDP?
WinRM and RDP are two different systems, although both were developed by Microsoft. WinRM is designed for the remote management of Windows computers. RDP stands for Remote Desktop Protocol and it provides a view of the Desktop of a remote Windows computer. There are also RDP clients available for Linux, Unix, macOS, Android, and iOS.
What is the difference between WinRM and WMI?
WinRM is the Windows Remote Management system. WMI is the Windows Management Instrumentation system. WMI collects status reports on the services that are integrated into the Windows system. WinRM is a remote protocol. In truth, WinRM extracts WMI data from remote computers, so it uses WMI as a local agent.
Is WinRM enabled by default?
WinRM isn’t enabled by default in Windows Server versions up to 2012. From Windows Server 2012 R2, WinRM is enabled by default.
Windows Remote Management, or WinRM, is a Windows-native built-in remote management protocol in its simplest form that uses Simple Object Access Protocol to interface with remote computers and servers, as well as Operating Systems and applications.
WinRM is a command-line tool that is used for the following tasks:
- Remotely communicate and interface with hosts through readily available channels/ports within your network, including workstations, servers and any operating system that supports it.
- Execute commands remotely on systems that you are not local to you but are network accessible
- Monitor, manage and configure servers, operating systems and client machines from a remote location.
History of WinRM
The earlier release, versions 1.1, was found in Windows Vista and Windows Server 2008, though could later be installed manually for Windows XP and Windows 2003.
A newer version, 2.0, can be found in Windows 7 and Windows Server 2008 R2, and the latest version of the software, 3.0, comes pre-installed out of the box in Windows 8 and Windows 2012 Server.
As for the latest windows installment, Windows 10, you’ll need to enable it as it does not come enabled by default.
It does require a little bit of setup and configuration, as it is not usually enabled and configured by default, but as it comes pre-installed and ready to go it’s a pretty simple process – do note that simple doesn’t always mean easy, unfortunately.
Configuring WinRM can sometimes be a breeze though it can sometimes be a bit of a hassle to get all the errors out of the way and get it sorted out just right.
Thankfully a great number of resources exist to aid in this part of the process and even several tools to help automate it!
Check out this great Tool below from Solarwinds that allows your to Remotely Enable WinRM on any PC or Server within your Network from your workstation.
A sort of sister process, Windows Remote Shell or WinRS, is the counterpart to WinRM. WinRS acts as the clients to WinRMs server component, providing the actual functionality and method of enacting commands and processes.
Most actual remote commands will be run via WinRS to a remote system with WinRM configured on it.
WinRM has several noteworthy benefits and strengths. As mentioned above, it’s built into the operating system, making installation and compatibility less of an issue.
It utilizes SOAP (Simple Object Access Protocol) requests in XML format, making it quite simple to work with.
Ports and Compatibility
WinRM Port is 5985 and 5986 (HTTPS)
In previous versions of WinRM, though, communications used to be done over port 80/443.
But since many server administrators take extra pre-cautions when locking down servers and desktop machines, blocking incoming traffic on Ports 80 and 443 was a given.
This was a problem for Powershell and WS-Management users as to why their connections where getting blocked and/or dropped while trying to manage systems remotely – thus leading Microsoft to change the default ports to the ones specified above, HTTP Port 5985 and HTTPS Port 5986 for WinRM connectivity.
If for some reason using the new port assignments are going to be a problem for your environment, and you would like configure systems to accept traffic on HTTP Port 80 and HTTPS Port 443, then this is where “Compatibility Listeners” come into play.
Compatibility Listeners cant be directly addressed, as other listeners are, but you can however allow traffic on these ports by either running a special command that configures the WinRM service to enable traffic on either port 80 or 443 like this:
winrm set winrm/config/service @{EnableCompatibilityHttpListener=”true”}
winrm set winrm/config/service @{EnableCompatibilityHttpsListener=”true”}
or applying a New Group Policy settings within this string:
Computer Configuration > Administrative Templates > Windows Components > Windows Remote Management (WinRM) > WinRM Service
and then set either of these keys to “YES”
“Turn On Compatibility HTTP Listener” (if you would like to allow WinRM over HTTP port 80)
“Turn On Compatibility HTTPS Listener” (if you would like to allow WinRM over HTTPS port 443)
You can find more info about compatilibity settings on the MSDN Blog post here
It is worth pointing out that WinRM/WinRS can be a little finnicky when it comes to user accounts and permissions – any long time Windows environment tech won’t be too surprised by this.
When dealing with remote management in a situation like this you have to be pretty sure your accounts and permissions are properly configured, and there’s several ways that you can set things up so that it works perfectly with WinRM.
It does introduce on potential flaw, but only in the case of particularly bad password and user account etiquette.
Generally speaking, though, the usual nuances apply here like with most Windows workgroup accounts and permissions.
If I am logged into an ‘Administrator’ account with a certain password and hit up WinRM on another system which has the exact same username and password combination, then I’m in with full permissions.
But with the basics of what WinRM is out of the way, it begs the obvious next question – what can it do? As the name intuitively implies it’s all about remote management.
Part of it’s strength lies in its ability to do far more than just manage workstations, though – WinRM can provide remote management to a range of devices, physical and soft, including applications, a wide range of different vendors’ hardware, operating systems (not just Windows!), and more.
Almost any range of commands can be performed remotely once setup and configured properly, which does become especially useful in the realm of managing workstations and servers on any Windows-based environment, as you can effortlessly start and stop processes, check configurations and system status, perform maintenance, install or remove services.. just about anything!
If there’s a command line process that you can run on a Windows system then it’s a sure bet you can use it via WinRM for remote management. There’s a lot of options for remote system management, but sometimes it’s best to just go with what’s built in and already more or less ready to go.
A little configuration and setup is all it takes and you’ll be well on your way to easy native remote management, as long as the initial configuration woes don’t get in the way.
Importance of WinRM
The Microsoft Windows ecosystem relies heavily on Windows Remote Management (WinRM), which enables remote management and administration of Windows-based devices or computers. Several crucial elements help us understand its significance:
WinRM has the ability to operate a variety of devices within its range, whether they are local or remote. The ability to manage workstations and the hardware connected to physical systems makes it a unique option.
Users can manage, monitor, configure servers, operating systems as well as client computers remotely without any hassle with WinRM.
Another crucial element to keep in mind is that the system’s configuration must be correctly set up with clearly defined ports. Due to this, the system is able to initiate and terminate any operations, determine its current state, and perform maintenance as and when the user requires it. WinRM’s utility can be used to install software as well as remove it. With the help of the ‘winRMquickconfig’ tool running in cmd, configuration is simple.
Running commands with WinRM becomes much easier if all the configurations and ports are managed properly. There are many different processes that can be used with WinRM, but it is usually preferable to utilize the built-in processes because they are generally simpler. Although initial configuration takes some time, it is beneficial to have it in order to speed up later laborious tasks. Also, installing WinRM does not require knowledge of WQL query, it is utilized for setup within the system.
Additionally, the system’s security is a default process because it never sends real credentials during network communications.
As long as the initial configuration issues don’t get in the way, a little configuration and setup will be enough to get you started on the path to simple native remote management.
Another key point to keep in mind is you can also utilize HTTPS along with WinRM to securely authenticate the servers. If SSL/TLS certificates are used to ensure the same, an additional layer of security is provided, preventing attackers from using or copying the system credentials.
WinRM makes use of a number of components, including scripting, cmd, plugins, services, and management protocol. As said before, WinRS serves as the system’s power source to guarantee the appropriate operation of all the servers and tools connected to the device. It uses an intelligent platform interface to manage the hardware with the aid of remote servers. IP interface is useful if the operating system is broken or if it must operate continuously in a remote location.
What are the Advantages of using WinRM?
WinRM is often used for administrative task automation, remote script execution, and administering numerous Windows machines remotely. There are several other benefits to using WinRM (Windows Remote Management), including:
- Port WinRM’s port is primarily advantageous. The port used by WinRM is crucial since the same port is also used for communication network security. As a result, WinRM’s security is not in any way affected. WinRM makes use of the port that firewalls leave open. Both remote connection and secure connection can use the same port. The complete operation of WinRM and network administration can be accomplished with a single port.
- Security To protect the communication between the administrator’s computer and the remote systems, WinRM offers encryption and authentication procedures as a top priority. This guarantees the privacy and accuracy of sensitive information and administrative directives.
- Remote Accessibility When managing geographically scattered systems, WinRM’s remote access and management capabilities are very helpful. As a result, less physical access to each machine is required, saving both time and money. Additionally, it enables the database to perform all system-related operations and administer all servers.
- Scripting and Automation Instead of exploring the shell, the WinRM solution immediately provides the shell scripts. This script aids in managing the system and, if necessary, additional hardware or software. It works well with PowerShell and other scripting languages. As a result, it is easier to automate repetitive tasks, enforce configuration requirements, and guarantee consistent system management.
- Cross-Platform Management WinRM is primarily built for Windows systems, but it may be expanded to handle non-Windows systems through configuration and scripting, fostering a more unified approach to system management.
WinRM FAQs
How does WinRM work?
WinRM allows for remote management of a Windows computer by sending management commands over HTTP or HTTPS. The commands are executed on the remote computer, and the results are returned to the client.
What are the benefits of using WinRM?
The benefits of using WinRM include the ability to remotely manage Windows computers, automate administrative tasks, and remotely execute scripts on remote computers.
Is WinRM secure?
WinRM can be secured using HTTPS, which encrypts the data being transmitted. However, it is important to properly secure the WinRM service, including setting strong authentication methods and using a trusted certificate for HTTPS.
How is WinRM different from Remote Desktop (RDP)?
WinRM is a protocol for remote management, while Remote Desktop (RDP) is a protocol for remote desktop access. WinRM allows for remote execution of management commands, while RDP provides a graphical interface for remote desktop access.
What are some common use cases for WinRM?
Common use cases for WinRM include remotely managing multiple Windows computers, automating administrative tasks, and executing scripts on remote computers.
How do I enable WinRM on a Windows computer?
To enable WinRM on a Windows computer, you can use the «winrm quickconfig» command in the Command Prompt or enable the WinRM service in the Services Manager.
How do I connect to a remote computer using WinRM?
To connect to a remote computer using WinRM, you can use a management tool such as Windows PowerShell or a third-party tool that supports WinRM. You will need to provide the remote computer’s hostname or IP address, and have the proper authentication credentials to connect.