In my lab setup, I had carefully configured a network of Windows servers, each armed with PowerShell 7. My intention was to seamlessly manage these servers from a Windows 11 client, also equipped with PowerShell 7. The logical choice was to employ the well-known Enter-PSSession
cmdlet to establish a remote connection. However, this seemingly straightforward process took an unexpected turn. Instead of connecting to the PowerShell 7 instance on the remote machines, I found myself interacting with PowerShell 5.1.
This encounter with version mismatch ignited a curiosity to dive deeper into the intricacies of PowerShell remoting and uncover the methods to explicitly connect to PowerShell 7’s WSMan interface. Join me as I unravel the journey of understanding and overcoming this challenge, shedding light on the nuances of PowerShell remoting with a focus on PowerShell 7.
- WSMAN protocols
- Using WMI through WSMAN
- Using CredSSP
- Comparing WSMAN and other remoting techniques
In the previous chapters, we’ve looked at using the capabilities built into the WMI cmdlets to provide access to remote systems. Using the -ComputerName parameter is a simple method of creating a connection to a remote machine, and this is the approach we’ve used in the majority of the techniques explored in previous chapters. But there are a number of scenarios where this approach isn’t enough:
- WMI uses Distributed COM (DCOM) to connect to a remote machine. This may not be available or may be blocked by a firewall.
- You may want to run multiple WMI commands against the same machine— this involves creating and destroying multiple connections. It would be more efficient to create one session and run multiple commands. Some information about the connection is cached, but it’s still quicker to create one session and run multiple commands.
- You may need to perform out-of-band hardware management (accessing the hardware by dedicated management links that aren’t used by general users) or access non-Windows machines.
17.1. Remoting protocols
17.2. Using WSMAN
17.3. Using CredSSP to access remote machines
17.4. How to choose between WMI, remoting, and WSMAN
17.5. Summary
Вступление
Идея написать блог о том, как злоумышленники используют для перемещения в инфраструктуре жертвы возможности службы Windows Remote Management (WinRM) (Т1021.006), возникла у меня еще в январе 2022 года. И виной тому стали не затянувшиеся новогодние праздники и наличие свободного времени, как может показаться, а как раз наоборот. В тот момент криминалисты F.A.C.C.T. столкнулись с очередным «праздничным» всплеском кибератак на российские компании, и в процессе реагирования на инцидент у одного из наших клиентов обнаружили интересный кейс, о котором хочу подробно рассказать.
Итак, как все происходило: атакующие получили первоначальный доступ к периметру компании, проэксплуатировав уязвимость одного из публично доступных сервисов, и захватили полный контроль над инфраструктурой жертвы, развив атаку. Используя различные техники закрепления, злоумышленники обеспечили себе возможность доступа к внутреннему периметру на протяжении года! За это время они успешно провели не менее четырех атак, в ходе которых им удалось провести эксфильтрацию данных, неоднократно вмешиваться в работу различных систем, удалить критически важную информацию или зашифровать данные.
После очередной атаки IT-специалисты восстанавливали и перестраивали инфраструктуру, а спустя какое-то время злоумышленники возвращались, и атака повторялась снова. Таким образом, злоумышленники не только планомерно разрушали бизнес-процессы компании, но и превратили в ад жизнь IT-персонала, который любой малейший сбой в том или ином отделе воспринимал как очередной инцидент информационной безопасности и «невидимую руку хакеров».
Безусловно, провернуть такую кампанию злоумышленникам удалось не только благодаря недостатку у жертвы соответствующих компетенций и инструментов для обеспечения информационной безопасности, но и благодаря своим профессиональных навыкам.
На протяжении года злоумышленники закреплялись на множестве устройств, используя различные утилиты двойного назначения и бэкдоры, которые они разместили в том числе на различных сетевых устройствах, и после проведения клиентом восстановительных работ снова возвращались в сеть.
Для перемещений по сети злоумышленники преимущественно использовали протокол удаленного рабочего стола (Remote Desktop Protocol), а после того как он был запрещен администраторами, переключились на 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).
29-08-2023
Just found another bug. After delegating remote access using:
And trying to logon remotely with the delegated account using this command:
I got a weird error message, that showed me this:
Enter-PSSession: Connecting to remote server lab-dc01.water.lan failed with the following error message : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2689860592" Machine="lab-dc01.water.lan"><f:Message><f:ProviderFault provider="PowerShell.7" path="C:\Windows\system32\PowerShell\7.3.6\pwrshplugin.dll"></f:ProviderFault></f:Message></f:WSManFault> For more information, see the about_Remote_Troubleshooting Help topic.

Obviously this is not the behavior I would like to see, and I’m assuming there’s a programming error. I filed another bug report on GitHub:
I’ve began by understanding the role of PowerShell remoting in connecting and managing remote systems. Despite encountering version discrepancies during remote sessions, I learned that using the -ConfigurationName
parameter with the Enter-PSSession
cmdlet provides a direct path to desired endpoints, ensuring specific PowerShell versions and tailored settings.
Moreover, I realized that the flexibility of PowerShell remoting extends to cross-version compatibility. A PowerShell 7 terminal effortlessly connects to PowerShell 5.1 endpoints, simplifying management in mixed-environment scenarios.
In conclusion, PowerShell remoting empowers us to manage remote systems with precision and flexibility. By embracing its tools, we’re equipped to streamline tasks, troubleshoot issues, and automate processes across diverse environments.
I hope this information is useful and don’t hesitate to ask questions or comment on the blog post.
Процессы, порождаемые PSRP, WinRS, CIM over WinRM
В зависимости от выбранного способа выполнения WinRM передаст управление DCOM-серверу (Distributed Component Object Model), который проведет запуск одного из трех провайдеров:
- %systemroot%\system32\wsmprovhost.exe (Microsoft Web Services Management Provider Host);
- %systemroot%\system32\winrshost.exe (Microsoft Windows Remote Shell Host);
- %systemroot%\system32\wbem\wmiprvse.exe (Windows Management Instrumentation Provider Host).
Таким образом, процесс того или иного провайдера будет запущен в контексте процесса svchost.exe -k -DcomLaunch -p, который, в свою очередь, станет родительским для порождаемой полезной нагрузки.
На рис. 1, 2 и 3 представлены цепочки процессов, возникающие при использовании PowerShell Remoting, Windows Remote Shell, а также при выполнении CIM-запросов.
Рис. 1. Цепочка процессов при использовании PowerShell Remoting
Рис. 2. Цепочка процессов при использовании WinRS
Рис. 3. Цепочка процессов при выполнении CIM-запросов
PowerShell Remoting
- Session: A PowerShell remoting session is a connection established between a local and a remote computer. This session allows you to send commands and receive output as if you were working directly on the remote machine.
- Remote Session Configuration: On the remote machine, a session configuration (also known as an endpoint) defines which PowerShell commands and features can be used in the remote session. This configuration ensures security and control over what operations can be performed remotely.
- Enter-PSSession: This cmdlet is used to initiate an interactive remote session with a remote computer. It allows you to interact with the remote machine’s PowerShell environment as if you were using it directly. You can run commands, navigate the file system, and more.
- New-PSSession: This cmdlet creates a persistent remote session (or session state) that can be reused for multiple commands. This is particularly useful for reducing the overhead of establishing a new session for each command.
- Invoke-Command: This cmdlet lets you execute scripts or commands on a remote computer. You can pass in script blocks or script files, and the results are returned to the local machine.
- Exit-PSSession: This cmdlet is used to end an interactive remote session that was initiated using
Enter-PSSession
. It returns you to the local machine’s session.
Setting Up PowerShell Remoting:
- Enable Remoting: PowerShell remoting must be enabled on both the local and remote machines. On Windows, you can use the
Enable-PSRemoting
cmdlet to configure the necessary settings. - Firewall Considerations: Remoting requires specific ports to be open in the firewall. The necessary ports can be configured using Group Policy or by running the
Enable-PSRemoting
cmdlet with appropriate parameters.
- Authentication: Remoting supports various authentication methods, including Kerberos and NTLM for Windows machines, and SSH for cross-platform remoting.
- Encryption: By default, remoting sessions are encrypted to protect data transferred between the local and remote machines. Specially in domains it’s not necessary to enable TLS encryption on top of encryption by Kerberos.
Use Cases: PowerShell remoting is incredibly versatile and can be used for a variety of tasks, including:
- Configuration Management: Remotely configure software, services, and settings on multiple machines simultaneously.
- Software Deployment: Install or update software across a network of machines.
- Troubleshooting: Remotely investigate and resolve issues on remote computers.
- Data Collection: Retrieve information, logs, and system data from remote systems.
- Automation: Create and deploy scripts to automate repetitive tasks across multiple machines.
Installing PowerShell 7
Before you can start using PowerShell 7, you’ll need to download and install it. You can obtain the latest version of PowerShell 7 from the official GitHub repository or the PowerShell website. Visit https://github.com/PowerShell/PowerShell or https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows to access the downloads.
Installing PowerShell 7 with the GUI:
- Download: Navigate to the official PowerShell website or the GitHub repository to download the latest installer for PowerShell 7.
- Run the Installer: Once the installer executable (e.g., PowerShell-7.x.x-win-x64.msi) is downloaded, run it.
- Setup Wizard: The installer will launch a setup wizard. Follow the on-screen instructions to proceed through the installation process.
- Choose Installation Location: You can either accept the default installation location or choose a different one. Remember the installation path for future reference.
- Installation Options: The wizard may provides options for interacting with PowerShell 7. In our case we should at a minimum select the option “Enable PowerShell remoting”.

- Completing the Installation: Once you’ve made your selections, click “Install” to begin the installation process.
- Finish: Once the installation is complete, you’ll see a confirmation message. You can now launch PowerShell 7 from the Start Menu or by typing
pwsh
in a command prompt.
Note! At the time of writing there seems to be a bug in the GUI installation. Selecting the “Enable PowerShell remoting” option doesn’t enable PowerShell remoting. The MSI installation however works as expected. I’ve reported the bug here: https://github.com/PowerShell/PowerShell/issues/20173
Installing PowerShell 7 Using the MSI File:
- Download: As before, download the latest MSI installer for PowerShell 7 from the official PowerShell website or the GitHub repository.
- Command Prompt: Open a Command Prompt window with administrative privileges.
- Navigate to the Download Location: Use the
cd
command to navigate to the directory where the downloaded MSI installer is located. - Install: Run the following command to install PowerShell 7 using the MSI file:
msiexec.exe /package PowerShell-7.3.6-win-x64.msi /quiet ENABLE_PSREMOTING=
Replace PowerShell-7.3.6-win-x64.msi
with the actual filename of the MSI installer. Just in case I’ve listed all the options here for reference.
ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL
– This property controls the option for adding theOpen PowerShell
item to the context menu in Windows Explorer.ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL
– This property controls the option for adding theRun with PowerShell
item to the context menu in Windows Explorer.ENABLE_PSREMOTING
– This property controls the option for enabling PowerShell remoting during installation.REGISTER_MANIFEST
– This property controls the option for registering the Windows Event Logging manifest.ADD_PATH
– This property controls the option for adding PowerShell to the Windows PATH environment variable.USE_MU
– Use Microsoft Update to update the version of PowerShell.ENABLE_MU
– Enable the use of Microsoft Update.DISABLE_TELEMETRY
– This property controls the option for disabling PowerShell’s telemetry by setting thePOWERSHELL_TELEMETRY_OPTOUT
environment variable.
- Open a Powershell 7 terminal as administrator.
- cd to
$PSHOME
, in my case that’s “C:\Program Files\PowerShell\7”. - Execute the script, “
Install-PowerShellRemoting.ps1
“. - Restart the WinRM (Windows Remote Management) service, “
Restart-Service winrm
“.
Инструменты Red Team
При WinRM-перемещениях по хостам атакуемой инфраструктуры злоумышленники используют не только легитимные средства, но и различные инструменты или фреймворки, в которых реализована возможность взаимодействия с WinRM. Список некоторых инструментов и фреймворков представлен ниже.
При использовании данных инструментов на атакуемых хостах генерируется большое количество различных релевантных событий, позволяющих обнаружить использование WinRM как средство для продвижения по инфраструктуре.
Теперь рассмотрим небольшую эмуляцию, проделанную при помощи Evil-WinRM, и проведем реконструкцию активности на хосте по записям журналов событий.
В рамках данной эмуляции мы подключились к контроллеру домена, выполнили команды whoami, hostname, загрузили в него файл evil.exe и запустили его (рис. 4).
Рис. 4. Действия с хоста атакующего
В данном случае, при реконструкции действий атакующего, в журналах атакуемой ОС мы обнаружим список характерных событий, указывающих на использование PowerShell Remoting. Наиболее информативные из них, по моему мнению, представлены ниже.
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) 400, 800 (Windows PowerShell.evtx) 4103, 4104 (Microsoft-Windows-PowerShell%4Operational.evtx) |
4. Вызовы командлетов и создание блоков скрипта при доставке полезной нагрузки evil.exe | 4103, 4104 (Microsoft-Windows-PowerShell%4Operational.evtx) |
5. События запуска процесса evil.exe, порождаемого от провайдера (оболочки) wsmprovhost.exe | 4688 (Security.evtx) 800 (Windows PowerShell.evtx) 4103, 4104 (Microsoft-Windows-PowerShell%4Operational.evtx) |
6. Событие остановки оболочки wsmprovhost.exe | 403 (Windows PowerShell.evtx) |
7. Событие выхода | 4634 (Security.evtx) |
При проведении реагирования на инцидент журналы событий значительно упрощают и сокращают время реагирования, а также позволяют быстрее добраться до точки входа и выявить большое количество индикаторов компрометации и используемых техник продвижения.
Ни для кого не секрет, что атакующие для противодействия обнаружению и усложнения задач реагирующему специалисту довольно часто очищают журналы событий. Очистку журналов они могут осуществлять как штатными средствами ОС, так и с помощью функциональных возможностей, реализованных в используемых ими инструментах. И в этих условиях специалист будет вынужден погрузиться в более глубокий анализ различных источников криминалистических данных, таких как AmCache, ShimCache, SRUDB, $MFT и многих других. Но среди них не так много источников, которые позволят нам оттолкнуться и «пойти» в сторону точки входа.
Так, однажды погрузившись в исследование, нами был обнаружен параметр реестра WSManSafeClientList, который позволяет не только выявить технику продвижения, но и ряд потенциально эксплуатируемых атакующими узлов (рис. 5).
Рис. 5. Список «безопасных» клиентов
Problem statement
Armed with a lab comprising Windows servers and a Windows 11 client, all equipped with PowerShell 7, my intention was to streamline remote management using the trusty Enter-PSSession
cmdlet. Little did I know that this endeavor would lead me to uncover an intriguing version discrepancy.
The initial signs of this enigma appeared innocuously. After executing Enter-PSSession
to connect to one of the Windows servers, I promptly fired the $PSVersionTable
cmdlet to examine the PowerShell version of the remote system. Much to my surprise, the version reported was 5.1, not the expected 7 that I had anticipated.
My Windows 11 client and the Windows servers were all equipped with PowerShell 7, and my assumption was that the remote sessions would automatically align with the PowerShell 7 environment. However, reality had other plans, as the remote session seemed to default to PowerShell 5.1.

Let’s find out how this can be fixed!
Выполнение 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’} и др.
Understanding PowerShell Remoting Endpoints
In the realm of PowerShell remoting, an “endpoint” refers to a pre-defined configuration that determines how remote sessions are established and what commands can be executed on a remote computer. Endpoints serve as gateways to the remote machine’s PowerShell environment, controlling the scope and capabilities of the remote session.
- Configuration Control: Endpoints allow administrators to define specific settings for remote sessions. These settings can include which PowerShell version to use, which modules are available, and what security protocols are required.
- Security: Endpoints play a crucial role in ensuring security during remoting. They help enforce security policies by allowing administrators to control which commands and scripts can be executed remotely.
- Scalability: By defining endpoints, you can create consistent and tailored remote session experiences for various users and use cases. This scalability enhances the efficiency and manageability of remote administration.
Viewing Endpoint Configuration:
To view the configuration of a remote session endpoint, you can use the Get-PSSessionConfiguration
cmdlet. This cmdlet provides insights into the available endpoint configurations on a remote computer.

As you can see in the picture above, the endpoints have a reference name, stay tuned as this is part of the solution we’re looking for.
Connecting to a Specific PowerShell Endpoint
One powerful aspect of PowerShell remoting is the ability to connect to specific endpoints, each tailored to different scenarios and environments. This capability allows us to not only manage version consistency but also customize the remote session experience to match our needs.
Using the -ConfigurationName
Parameter:
The key to connecting to a particular endpoint lies in the -ConfigurationName
parameter of the Enter-PSSession
cmdlet. By specifying the desired endpoint’s configuration name, we can establish a remote session that aligns with the version and settings associated with that endpoint.
For instance, let’s consider a scenario where we have a Windows server named “lab-srv01.water.lan“, and we want to connect to a PowerShell 7-specific endpoint configuration named "
powershell.7"
. This configuration is tailored to PowerShell 7, ensuring that our remote session operates with PowerShell 7’s capabilities and features.
Connecting to PowerShell 7 Endpoint:
In this example, we use the -ComputerName
parameter to specify the target remote machine (lab-srv01.water.lan
) and the -ConfigurationName
parameter to specify the endpoint configuration ("powershell.7"
). By doing so, we’re guaranteed to establish a remote session that operates under the PowerShell 7 environment, regardless of any other available endpoints.

Список «безопасных» клиентов
Проведенными исследованиями установлено, что:
- параметр WSManSafeClientList отсутствует на хостах, к которым подключения не осуществлялись (в том числе когда служба WinRM сконфигурирована и запущена);
- в параметр WSManSafeClientList записываются HEX-значения адресов IPv4 и IPv6, ранее подключавшихся при помощи WinRM;
- максимальный размер параметра составляет 160 байт и может содержать до 10 уникальных IP-адресов;
- размер каждой записи составляет 16 байт (рис. 6).
Рис. 6. Пример 10 записей параметра WSManSafeClientList и их интерпретация
Запись адресов в параметр WSManSafeClientList осуществляется спустя 15 минут после успешного подключения с адреса, которого нет среди ранее записанных адресов, или в момент остановки службы.
В случае если адрес последнего подключившегося хоста уже имеется в списке, то порядок адресов в параметре не меняется и запись в него не производится.
При превышении количества записей в параметре первый адрес в списке будет удален, а новый — добавлен в конец списка (рис. 7).
Рис. 7. Пример 10 записей параметра WSManSafeClientList после превышения лимита записей
Connecting a PowerShell 7 Terminal to a PowerShell 5.1 Endpoint
One of the remarkable features of PowerShell remoting is its ability to bridge the gap between different PowerShell versions. While we’ve explored the importance of version consistency, it’s worth noting that a PowerShell 7 terminal can establish a remote connection to a PowerShell 5.1 endpoint.
PowerShell remoting is designed with a compatibility layer that allows newer versions of PowerShell to communicate with older endpoints. This means that even if you’re using a PowerShell 7 terminal, you can still connect to and interact with systems running PowerShell 5.1 through remoting.
Why It Matters:
Obtaining the PowerShell 5.1 Endpoints:

So, for example we have an open PowerShell 7 terminal and we would like to connect specifically to a certain endpoint, we could use something like this:

Выводы и рекомендации
Несмотря на то, что WinRM — не самый часто используемый инструмент, возможности, предоставляемые атакующим службой WinRM и тривиальность детектирования традиционных методов продвижения по сети, обусловят все большее распространение данной техники.
Для защиты от подобных атак мы в очередной раз рекомендуем следующее: