In this articole we describe how to enable WMI on Windows Server.
Step 1. Create an user on Windows Server.
To configure WMI on your device so that NMIS can discover and monitor it, you must create a user who has access to WMI objects on the device.
1.- Go to Start > Control Panel > Administrative Tools > Computer Management > Local Users and Groups.
2.- Right-click Users and select New User.
3.- Create a user. Example: nmiswmi
Note: Windows allows certain WMI classes to be pulled only via Administrator account.
4.- Select this user (nmiswmi) and right-click to select Properties > Member of tab.
5.- Select Distributed COM Users and click Add.
6.- Click OK to save.
Step 2. Check required DCOM and WMI services for Windows.
The following services must be started and configure for automatic startup:
- Server
- Remote Registry
- Windows Management Instrumentation
1.- Open the Run menu, press the following logo key + R.
2.- Type the following: services.msc
3.- Click OK.
4.- In the details pane, verify these services are started and set to automatic startup:
- Server
- Remote Registry
- Windows Management Instrumentation
5.- To change a service property, right-click on the service name, and then click Properties.
6.- From the Startup type list box, select Automatic.
7.- If the Service status is not started, click Start.
8.- Click OK.
9.- Close the Services window.
Step 3. Enabling DCOM for Windows Server.
1.- Open the Run menu, press the Windows logo key + R.
2.-Type the following: dcomcnfg
3.-Click OK.
4.- The Component Services window is displayed.
5.- Under Component Services, expand Computers, and then click My Computer.
6.- On the Action menu, click Properties.
7.- Select the Default Properties tab.
8.- Configure the following Default Properties:
Select the Enable Distributed COM on this computer check box.
Using the Default Authentication Level list box, select Connect.
Using the Default Impersonation Level list box, select Identify.
9.- Click OK.
Note: The system displays a message about changing the DCOM Machine wide settings. Click Yes to continue.
Step 4. Configuring DCOM communication for Windows Server.
1.- From the DCOM Configuration (dcomcnfg) window, expand Component Services, expand Computers, and select My Computer.
2.- On the Action menu, click Properties.
3.- Select the Default Protocols tab.
4.- Configure the following options:
- If Connection-oriented TCP/IP is listed in the DCOM Protocols window, go to Step 5.
- If Connection-oriented TCP/IP is not listed in the DCOM Protocol window, select Add.
- From the Protocol Sequence list box, select Connection-oriented TCP/IP.
5.- Click OK.
Step 5. Configuring Windows Server user accounts for DCOM.
You must select an existing account with administrative access or create a normal user account that is a member of an administrative group to access the host.
1.- From the DCOM Configuration (dcomcnfg) window, expand Component Services, expand Computers, and select My Computer.
2.- On the Action menu, click Properties.
3.- Select the COM Security tab.
4.- In Access Permissions, click Edit Default.
5.- Select the user (nmiswmi) or group requiring DCOM access.
Note: If the user or group requiring DCOM access is not listed in the permissions list, you must add the user to the configuration.
6.- Configure the following user permissions:
- Local Access — Select the Allow check box.
- Remote Access — Select the Allow check box.
7.- Click OK.
8.- In Launch and Activation Permissions, click Edit Default.
9.- Select the user or group requiring DCOM access.
Note: If the user or group requiring DCOM access is not in the permissions list, you must add the user to the configuration.
10.- Configure the following user permissions:
- Local Launch — Select the Allow check box.
- Remote Launch — Select the Allow check box.
- Local Activation — Select the Allow check box.
- Remote Activation — Select the Allow check box.
11.- Click OK.
12.- Click OK to close the Component Services window.
Step 6. Configuring Windows Server Firewall.
1.- Open the Run menu, press the Windows logo key + R.
2.- Type the following: wf.msc.
3.- Click OK.
4.- Select Inbound Rules.
5.- On the Action menu, click New Rule.
6.- Select Custom and click Next. The Program window is displayed.
7.- Select All programs, and click Next. The Protocol and Ports window is displayed.
8.- From the Protocol type list box, select TCP and click Next.
9.- Under Which remote IP addresses does this rule apply to field, select the radio button These IP addresses.
10.- Click Add.
11.- In the IP address or subnet text box, type the IP address of NMIS server.
12.- Click OK.
13.- Click Next.
14.- Select Allow the connection, and click Next.
15.- Select one or more network profiles to which the rule applies and click Next.
16.- Type a name and description for the firewall rule.
17.- Click Finish. You can now exit the Windows Firewall with Advanced Security panel.
Step 7. Configuring WMI user access for Windows Server.
The user or group you configured for DCOM access must also have Windows Management Instrumentation (WMI) permission.
1.- Open the Run menu, press the Windows logo key + R.
2.- Type the following: wmimgmt.msc
3.- Click OK.
4.- Right-click on WMI Control (Local), select Properties. The WMI Control (Local) Properties window is displayed.
5.- Click the Security tab. The Namespace navigation is displayed.
6.- From the Namespace menu tree, expand Root, click CIMV2.
7.- Click the Security button the menu tree. The Security for ROOT\CIMV2 window is displayed.
8.- Select the user or group requiring WMI access.
Note: If the user or group requiring WMI access is not listed in the permissions list, you must add the user to the configuration.
9.- Select the check boxes to add the following permissions:
- Execute Methods — Select the Allow check box.
- Provider Write — Select the Allow check box.
- Enable Account — Select the Allow check box.
- Remote Enable — Select the Allow check box.
Note: If the user or group you are configuring is a system administrator, the allow permission check boxes might be selected as the permissions are inherited.
10.- Click OK.
11.- Close the WMIMGMT — WMI Control (Local) window.
Step 8. Configuring DCOM access for Windows Server.
1.- Open the Run menu, press the Windows logo key + R.
2.- Type the following command to open the registry editor: regedit
3.- Click OK.
Note: You must be a system administrator to edit registry settings.
4.- Locate the following registry location: HKEY_CLASSES_ROOT\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}
5.- Right-click the entry {76A64158-CB41-11D1-8B02-00600806D9B6}, then click Permissions.
6.- Click the Advanced button. The Advanced Security Settings are displayed.
7.- In the Owner field, click Change.
8.- In the Enter the object name field, set the owner as Administrators.
9.- Click OK.
10.- In the Permissions entries field, select your user and click Edit.
11.- Configure the following parameters for your user:
In the Type field, select Allow.
In the Applies to field, select This key and subkeys.
In the Basic permissions field, select Full Control. By default, selecting Full Control adds Read as a permission type.
12.- Click OK to return to the Advanced Security Settings window.
13.- In the Owner field, click Change.
14.- In the Enter the object name field, set the owner as your nmiswmi user.
15.- Click OK until you return to the Registry Editor.
16.- Repeat this process for the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Wow6432Node\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}
17.- Close the Registry Editor.
Step 9. Testing the WMI connection from NMIS.
1.- Create a credential file like this:
# vi /tmp/credential.txt username=nmiswmi # Username configured on Windows Server in this case nmiswmi password=Password2022 # password for nmiswmi user domain=WIN-SJLNF25QVLF # Domain Name
2.- Use this command to test WMI connection.
# /usr/local/nmis9/bin/wmic -A /tmp/credential2.txt //X.X.X.X "select Caption,Manufacturer,Model,Name from Win32_ComputerSystem"
Where: X.X.X.X is the IP Address of Windows Server
Command output:
# /usr/local/nmis9/bin/wmic -A /tmp/credential.txt //192.168.0.105 "select Caption,Manufacturer,Model,Name from Win32_ComputerSystem" CLASS: Win32_ComputerSystem Caption|Manufacturer|Model|Name WIN-SJLNF25QVLF|VMware, Inc.|VMware Virtual Platform|WIN-SJLNF25QVLF
All PowerShell cmdlets dealing with WMI (Windows Management Instrumentation) support remote access. In this article, you’ll learn about the prerequisites to connect to remote computers and run any WMI operation remotely.
WMI supports two protocols to connect to remote computers: DCOM (Distributed COM) and WinRM (Windows Remote Management).
DCOM is the older technology and was introduced with Windows NT. While it is enabled by default on many servers for historic reasons, it is considered out-dated.
WinRM is a webservice-based modern protocol and was introduced in PowerShell 2. It is more reliable, safer, and faster. Unlike DCOM, it uses only one dedicated firewall port.
Connecting via DCOM
Since DCOM is considered obsolete, it is not recommended to use this protocol. If you still use the old cmdlet Get-WmiObject
, it is your only choice, though. Use the code below to try and connect to a remote machine:
# the computer name or IP address you want to connect to:
$computer = '192.168.2.109'
# use a user account that has Administrator permissions on
# the target computer:
$credential = Get-Credential
# try and retrieve BIOS information:
Get-WmiObject -Class Win32_BIOS -ComputerName $computer -Credential $credential
When the code succeeds, you receive BIOS information from the remote machine:
SMBIOSBIOSVersion : 4KCN45WW
Manufacturer : LENOVO
Name : 4KCN45WW
SerialNumber : PF0LTV33
Version : LENOVO - 1
If you get an error, it indicates that some of the prerequisites are missing:
- Access Denied: the user account that you used has no Administrator privileges on the target machine.
- RPC Server Unavailable: the target computer could not be reached. It is turned off, you misspelled its name, or the firewall blocked access.
Adding Firewall Exception
For DCOM, the Remote Administration Exception must be enabled in the target computer firewall. The easiest manual way is to use an old and obsolete command. Run it on the target computer with Administrator privileges:
netsh firewall set service remoteadmin enable
Once the command executed, try again the code above.
Using CimCmdlets
Get-WmiObject
is considered obsolete and was replaced by the CIM cmdlets in PowerShell 3. It is recommended to use Get-CimInstance
instead of Get-WmiObject
.
One of the most fundamental differences between these two is the default network protocol they use: Get-WmiObject
always uses DCOM whereas Get-CimInstance
uses the modern WinRM protocol by default but can also be configured to fall back to DCOM.
To repeat above example with Get-CimInstance
, try this code:
# the computer name or IP address you want to connect to:
$computer = '192.168.2.109'
# use a user account that has Administrator permissions on
# the target computer:
$credential = Get-Credential
# create a CIM session that uses DCOM:
$options = New-CimSessionOption -Protocol Dcom
$session = New-CimSession -ComputerName $computer -SessionOption $options -Credential $credential
# try and retrieve BIOS information:
Get-CimInstance -ClassName Win32_BIOS -CimSession $session
# remove session after use
Remove-CimSession -CimSession $session
The result looks almost the same. CIM Cmdlets always automatically add the property PSComputerName, though.
Connecting via WinRM
Whenever possible, you should avoid using the obsolete protocol DCOM, and use the modern protocol WinRM instead. This is why the CIM cmdlets use this protocol by default.
Testing WinRM Connectivity
The first test should be whether the target machine is already set up for WinRM. Test-WsMan
does exactly that and tests the connection much like the old-fashioned ping command: it checks whether WinRM echoes your request. For this, no permissions are required, so it is just checking the physical connectivity from you to the target computer.
Run this code:
# the computer name or IP address you want to connect to:
$computer = '192.168.2.109'
# test whether the physical connection to the target is
# possible (no permissions required):
Test-WSMan -ComputerName $computer
You should receive a result similar to this:
wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor : Microsoft Corporation
ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 3.0
If you receive an error message instead, then most likely the target machine is not yet set up to receive WinRM remoting requests. The next section explains how you enable WinRM on the target machine.
Enabling PowerShell Remoting
On servers, WinRM remoting is enabled by default. On clients, it is not. To manually enable WinRM remoting, run this command with Administrator privileges:
Enable-PSRemoting -SkipNetworkProfileCheck -Force
Note: Do this on the target machine (the one you want to connect to). The client machine (the one where you are running PowerShell code) does not need to have remoting turned on.
When you do this for the first time, the command reports in detail the settings it configured. If it ran before, you see no return values.
Run
Disable-PSRemoting
to disable PowerShell remoting. This cmdlet will not revert all the settings done byEnable-PSRemoting
because part of these settings may be required by other services. Instead,Disable-PSRemoting
disables connections and effectively prevent connections.
Once PowerShell remoting is enabled, use Test-WsMan
(see above) to test connectivity.
Test-WsMan
is an anonymous test. When it succeeds, you know that PowerShell remoting is enabled and all firewall exceptions are in place. Permissions are not subject to this test, so let’s test these next (see below)
Testing Authentication
Once WinRM remoting is enabled, anyone with Administrator privileges on that machine can run code remotely. There are two ways to authenticate: via Kerberos (default) and via Negotiate.
If all permissions are in place, you might get away with running this minimal code to access WMI information remotely:
# the computer name or IP address you want to connect to:
$computer = '192.168.2.109'
# try and retrieve BIOS information:
Get-CimInstance -ClassName Win32_BIOS -ComputerName $computer
It requires:
- that WinRM was enabled on the target computer
- that Negotiate authentication is enabled
- that your current user account has Administrator privileges on the target machine
In most cases, this code will fail because it is using a IP address. The default WinRM authentication uses Kerberos which requires a domain controller and works only with computer names, not IP addresses.
Either replace the IP address with a computer name that can be resolved by your domain DNS, or enable Negotiate authentication (see below).
Enabling Negotiate Authentication
Here are some good reasons why you might want to enable Negotiate authentication:
- Peer-to-Peer Network: maybe you are not working in a network domain and want to test-drive remote access in a lab, or at home in your private network. Kerberos requires a network domain.
- Cross-Domain: maybe the target computer belongs to a different domain, and there are no trust relationships. Kerberos requires trust relationships.
- IP Address: or maybe you must use IP addresses. Kerberos requires computer names.
Why is Negotiate disabled by default at all? Because unlike Kerberos or certificates, it cannot guarantee that a target computer really is who it pretends to be. Any attacker with physical access to your servers could unplug a server, plug in a compromised system, and take over its IP address. So use a bit of common sense.
To enable Negotiate authentication, on the computer that initiates the connection, run the code below with Administrator privileges.
Note: do this on the client machine (the one where your PowerShell code runs). This is a client setting.
# WinRM service must run at least temporarily to
# make the change
Start-Service -Name WinRM
# define the IP addresses you trust
# this can be "*" for all, or just a subset
# in the example, all addresses starting with "192.168." are trusted:
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '192.168.*' -Force
# to add more addresses or ranges, use -Concatenate
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '10.12.100.*' -Force -Concatenate
# double-check the setting:
Get-Item -Path WSMan:\localhost\Client\TrustedHosts
# you may stop the WinRM service after the change but should do so
# only if it did not run before (may be used by other parties)
Stop-Service -Name WinRM
To revert the default settings and disable Negotiate authentication, run this command:
Clear-Item -Path WSMan:\localhost\Client\TrustedHosts
.
Testing Permissions And Using CimSessions
While you can use Get-CimInstance
with the parameter -ComputerName to directly connect to remote machines, it is not the smartest way.
A more professional way separates the network connection from subsequent calls. When you create a dedicated CimSession, you can specify any user account, and reuse the session for as many subsequent commands as you like.
So let’s just do this: first, create a Cim Session network connection with all the bells and whistles you require. Then, re-use this connection with as many Cim Cmdlets as you want. Finally: remove the session when it is no longer needed.
Use the code below to test whether your user account has the appropriate permissions to contact and retrieve information from the target system:
# the computer name or IP address you want to connect to
# if you are in a domain and want to use the default safe Kerberos
# authentication, use a computer name instead of an IP address:
$computer = '192.168.2.109'
# use a user account that has Administrator permissions on
# the target computer:
$credential = Get-Credential
# create a CIM session:
$session = New-CimSession -ComputerName $computer -Credential $credential
# try and retrieve BIOS information. This makes use of
# the session you created before:
Get-CimInstance -ClassName Win32_BIOS -CimSession $session
# remove session after use
Remove-CimSession -CimSession $session
This blog post is the first of a many part series on WMI and is intended for fairly new audiences. A basic understanding of Powershell will definitely help the reader while going through the blog, however, it is not a requirement. That’s it, let us jump into the real stuff.
Introduction
Why WMI?
WMI is a set of specifications from Microsoft that was designed for fast and efficient administration when it comes to Windows systems. And as you might know, a rule of security says “that anything useful for administration is also great at being abused by evil-doers”. WMI can really do a lot of things – from gathering statuses of computers and configuring settings to running applications and executing code. Moreover, WMI is present on all available Windows OS versions, so targeted surface is quite broad here.
What is WMI?
Let’s quickly go over a few important terms. WMI stands for Windows Management Instrumentation, which is Microsoft’s implementation of the CIM (Common Information Model) & WBEM (Web-Based Enterprise Management) – both of which are DMTF (Distributed Management Task Force) standards in general. WMI gives us a neat and uniform interface for applications/scripts to manage a computer (maybe remote and local) – incl. processes, services, etc.
The WMI Architecture
Understanding the architecture is very essential to understanding how the entire WMI ecosystem works. A broad overview of the architecture of WMI is depicted below (sourced from Graeber’s talk from BHUSA 15):
Let’s break down the major components one by one:
-
Clients/Consumers: These are essentially the end consumers which interact with WMI classes for querying data, running methods, etc. Few prominent clients include
wmic.exe
,wbemtest.exe
,winrm.exe
, VBScript/JScript and ofc Powershell cmdlets. -
Query Languages: Just like SQL provides you with a way to query a database, WMI too has WQL (WMI Query Language) / CQL for querying the WMI service. When it comes to managing remote boxes, the WBEM standard kicks in – which include DCOM and WS-Man (don’t worry if you don’t understand these terms, read on). WQL is basically SQL syntax for WMI, so is not case-sensitive.
A simple query may look like this:
which gives us information about our BIOS.
-
Repositories: These are the databases that we talked about previously that stores all static data (definitions) of classes. The repositories are defined by MOF (managed object format) files which define the structure, classes, namespaces, etc. The database files can be found under the
%WINDIR%\System32\Wbem\Repository
directory. -
MOF Files: MOF files are basically used to define WMI namespaces, classes, providers, etc. You’ll usually find them under the
%WINDIR%\System32\Wbem
directory with the extension.mof
. In a later part of the series, we’ll take a look at how we can write our own MOF files to extend the feature-set of WMI. -
Providers: Whatever is defined in the repositories can be accessed with the help of WMI providers. They are usually DLL files and associated with a MOF file –
cimwin32.dll
,stdprov.dll
, etc to name a few, however, they can take the form of other types as well (Class, Event, Event Consumer, Method, etc). The providers are essential to the ecosystem because they monitor events and data from specific defined objects. Think of providers like drivers which provide a bridge between managed objects and WMI.In the screenshot below, the DLL files are the providers of the associated MOF files:
-
Managed Objects: These are aliases of the resources in context, i.e. a managed object can be the service, process or OS being managed by WMI.
-
Namespaces: Put simply, namespaces are logical divisions of classes meant for easy discovery and usage. They are divided into 3 groups:
- system
- core
- extension
and 3 types:
- abstract
- static
- dynamic
Few prominent namespaces that come by default are:
root\cimv2
,root\default
,root\security
,root\subscription
, etc.
That’s it with the architecture. Now let’s learn a bit about using WMI with Powershell.
Using WMI with Powershell
Now that we’re done with the theory part, let’s quickly spawn a PS terminal. It is important to remember that up to v2 of Powershell, there are only a few cmdlets to interact with WMI. We’ll quickly check our Powershell version and change the version to 2:
Now, lets run Get-Command -CommandType Cmdlet *wmi*
in a Powershell prompt. This leads us to:
TIP: The names of the commands are pretty self-explanatory (and we’ll dig into more later as well). At any point in time, you can use Powershell’s standard syntax:
help <command>
to get more info on what the specific command does. e.g. you might want to tryhelp Invoke-WmiMethod
to view what the command does – very similar to Linux manpages.
From Powershell v3 onwards, MS introduced CIM cmdlets which make use of WS-MAN and CIM standards to manage objects. Having access to CIM cmdlets has advantages in 2 contexts:
- In machines where WMI/DCOM itself is blocked from running (maybe due to a host-based firewall rule?) but WinRM/WS-MAN (Windows Remote Management) is enabled, we can still use CIM to do exactly what we can do with WMI.
- CIM itself is an industry-standard and is implemented cross-platform, which means it can be used to work with non-Windows boxes as well.
Phew! That’s a mouthful of words. Let’s understand what the new terms here mean:
DCOM: An alias for Distributed Component Object Model, DCOM is a proprietary Microsoft protocol for communication between software components on networked computers. WMI uses Distributed COM (DCOM) to connect to a remote machine. However, DCOM isn’t that firewall-friendly.
WS-MAN: WS-MAN or WS-Management is a DMTF standard that provides a common way for systems to access management information across the IT infrastructure. WS-MAN on the other hand uses HTTP, so is definitely firewall-friendly.
We’ll redo what we did above, but after changing the Powershell version back to default (in my case I’ve Powershell v5):
Repeating what we said above, CIM cmdlets can do everything that WMI cmdlets can. If we want to map the functionalities between both WMI cmdlets and CIM cmdlets, here’s a tabular representation of the functionality comparison between both types:
Use \ Types | WMI Cmdlets | CIM Cmdlets |
---|---|---|
Get information about classes | Get-WmiObject |
Get-CimInstance |
Invoking a method | Invoke-WmiMethod |
Invoke-CimMethod |
Subscribing to an event | Register-WmiEvent |
Register-CimIndicationEvent |
Creating/updating instances of a class | Set-WmiInstance |
Set-CimInstance |
Deleting instances of a class | Remove-WmiObject |
Remove-CimInstance |
Running WMI queries with Powershell
Now that we know about the different cmdlets available for us to use, we can try running the sample WQL query above. We already know that Get-WmiObject
can be used to get info about classes. So let’s run the cmdlet with the -Query
parameter:
Get-WmiObject -Query 'select * from win32_bios'
Conclusion
This blog post was meant for giving an overview of what we’ll be dealing with in the next parts of the series. There are a lot of technical buzzwords here but understanding them is necessary. I hope you enjoyed reading through so far, and I’m looking forward to our journey together into exploring WMI.
Adios amigo!
WMI comes installed on all of Microsoft’s modern operating systems. What this page will describe is how to enable remote access to WMI.
The following steps should only take a minute or two of your time.
1. Enable remote WMI requests
This setting is usually all that needs to be changed to get WMI working. (Steps 2 and 3 are typically not needed, but they might be in some circumstances)
1. On the target server, go to Administrative Tools -> Computer Management.
2. Expand ‘Services and Applications’
3. Right click for Properties on ‘WMI Control’.
4. Select the Security tab
5. Press the Security button
6. Add the monitoring user (if needed), and then be sure to check Remote Enable for the user/group that will be requesting WMI data.
At this point go back and see if this fixes the problem. It might take a couple of minutes for the reports to re-generate.
2. Allow WMI through Windows firewall
All users (including non-administrators) are able to query/read WMI data on the local computer.
For reading WMI data on a remote server, a connection needs to be made from your management computer (where our monitoring software is installed) to the
server that you’re monitoring (the target server). If the target server is running Windows Firewall (aka Internet
Connection Firewall) like what is shipped with Windows XP and Windows 2003, then you need to tell it to let remote WMI
requests through1. This can only be done at the command prompt. Run the following on the target computer if it is running a Windows firewall:
netsh firewall set service RemoteAdmin enable
3. Enable DCOM calls on the remote machine
If the account you are using to monitor the target server is NOT an administrator on the target server,
you need to enable the non-administrator to interact with DCOM by following the simple steps listed
here.
Follow the steps for:
- To grant DCOM remote launch and activation permissions for a user or group
- To grant DCOM remote access permissions
Further Investigation
If the above steps didn’t help, we recommend installing the WMI Administrative Tools from Microsoft. This includes a WMI browser that will let you connect to a remote machine and
browse through the WMI information. That will help to isolate any connectivity/rights issues in a more direct and simple environment. Once the WMI browser can access a remote machine,
our products should be able to as well.
WMI Administrative Tools:
http://www.microsoft.com/downloads/details.aspx?FamilyId=6430F853-1120-48DB-8CC5-F2ABDC3ED314&displaylang=en
Finally, UAC
From reports we’re receiving from the field, it appears UAC needs to be disabled for remote WMI queries to work. With UAC running, an administrator account actually
has two security tokens, a normal user token, and an administrator token (which is only activated when you pass the UAC prompt). Unfortunately, remote requests that
come in over the network get the normal user token for the administrator, and since there is no way to handle a UAC prompt remotely, the token can’t be elevated to
the true-administrator security token.
References
1. https://learn.microsoft.com/en-us/windows/win32/wmisdk/connecting-to-wmi-remotely-with-vbscript?redirectedfrom=MSDN
See «To Configure Connection 1». Our software doesn’t use or need Connection 2.
Other helpful pages
Connecting to WMI Remotely Starting with Windows Vista
Connecting to WMI on a Remote Computer
Время на прочтение9 мин
Количество просмотров8.8K
Давным-давно, когда трава была зеленее, а интернет безопаснее, в ИТ родилась инициатива Web Based Enterprise Management (WBEM). Первоначально спонсируемая в 1996 году такими компаниями как Cisco Systems, Intel и Microsoft, она получила широкое распространение и реализацию на различных платформах: от MAC OS до Redhat. WBEM четко документирован, основан на стандартах Интернета и представляет собой иной подход к управлению системами, отличный, например, от SNMP протокола.
Адаптация WBEM для Windows получила название WMI (Windows management interface) и впервые была представлена в Windows XP. Нам известно, что системы обновляются быстрее, чем их компоненты и многие уязвимости, бывшие ранее удобным инструментом управления, кочуют из версии в версию. В этой статье я хочу описать как выполняются задачи WMI и как избежать потенциальных рисков.
В силу своей мощности, WMI позволяет с помощью специальных утилит или сценариев производить различные потенциально опасные действия на ПК, в том числе, остановку критичных для работы служб и даже выключение компьютера. Например, так:
(Get-WmiObject Win32_OperatingSystem -EnableAllPrivileges).Win32Shutdown(5)
(GWMI -Class Win32_Service -Filter «name=’WinRM’» -ComputerName Server).StopService()
Кроме того, на удаленной машине эти действия выполнить так же просто, как на локальной — достаточно написать имя нужной машины в пути к WMI-объекту.
Пространство имен WMI – это раздел репозитория WMI, который призван группировать классы и объекты WMI по назначению, плюс, определять атрибуты безопасности при доступе к классам и объектам в каждом таком контейнере. Все пространства имен начинаются с корня, который в WMI обозначается ключевым словом root. После имени корня через косую черту указывается пространство имен. Пространства имен могут быть вложенными. Большинство интересных классов и объектов размещается в пространстве имен root/CIMv2.
Одно из существующих в Windows пространств имен WMI может быть выбрано по умолчанию. Это означает, что если вы попытаетесь подключиться к этому хосту, не указав пространство имен, то вы автоматически будете подключены к выбранному по умолчанию. В стандартной инсталляции Windows по умолчанию выбрано пространство root\cimv2.
Технология WMI предназначена для администраторов Windows, и вся система безопасности в WMI устроена так, чтобы с помощью сценариев WMI пользователь мог на заданном ПК выполнить лишь те действия, на которые ему даны разрешения/привилегии. Это так называемые привилегии по умолчанию. Так реализуется безопасность WMI на уровне операционной системы: если пользователю на уровне операционной системы не дана привилегия перезагружать компьютер, то и с помощью WMI он и не сможет этого сделать.
Дополнительные политики безопасности в WMI реализованы на уровне пространств имен протокола Distributed СОМ (DCOM) – распределенной объектной модели компонентов. Чтобы более подробно рассмотреть эти типы безопасности WMI, кратко напомню основные общие понятия, связанные с безопасностью в Windows. А основана эта безопасность на именах пользователей и их паролях.
О разрешениях WMI
Когда в Windows создается пользователь, его системной учетной записи присваивается уникальный идентификатор безопасности (Security IDentifier или SID). На основе SID для пользователя формируется маркер доступа (Access Token), в который также добавляется список групп, членом которых является пользователь и список привилегий, которыми он обладает (например, остановка служб или выключение компьютера). Этот маркер доступа присваивается также всем процессам, которые запускает пользователь. В это время каждый объект операционной системы, доступ к которому определяет система безопасности – файл, либо процесс, либо служба или что-то ещё, имеет дескриптор безопасности (Security Descriptor, SD). В этом дескрипторе, в свою очередь, хранится список контроля доступа (Access Control List, ACL) для этого объекта.
Итак, при обращении пользователя или запущенного им процесса к объекту происходит сравнение маркера доступа данного пользователя со списком контроля доступа. В зависимости от результатов выдается или отклоняется разрешение/привилегия на выполнение запрашиваемых действий над объектом.
На уровне пространств имен механизм безопасности WMI соответствует общей модели безопасности Windows. Каждое пространство имен может иметь собственный дескриптор безопасности, на котором хранится список контроля доступа (ACL).
Каждая запись списка контроля доступа (Access Control Entry, АСE) содержит информацию о том, какие разрешения имеет определенный пользователь при выполнении различных операций в этом пространстве имен.
А вот и список разрешений при работе с пространством имен:
Выполнение методов (Execute Methods). Позволяет вызывать методы классов из определенного пространства имен. Будет ли метод выполнен или произойдет отказ, зависит от того, имеет ли пользователь разрешение на выполнение этой операции в системе.
Полная запись (Full Write). Разрешает создавать и модифицировать подпространства имен, системные классы и экземпляры классов.
Частичная запись (Partial Write). Открывает возможность создавать и модифицировать любые статические классы и экземпляры несистемных классов.
Запись поставщика (Provider Write). Позволяет записывать в репозиторий CIM классы провайдеров WMI и экземпляры этих классов.
Включить учетную запись (Enable Account). Предоставляет право чтения пространства имен WMI. Пользователи с этим разрешением, могут запускать на локальном компьютере сценарии, которые читают данные WMI.
Включить удаленно (Remote Enable). Разрешает пользователям получить доступ к пространству имен WMI на удаленном компьютере. По умолчанию этим разрешением обладают только администраторы, обычные пользователи не могут получать данные WMI с удаленных машин.
Прочесть безопасность (Read Security). Дает право читать дескриптор безопасности для пространства имен WMI без возможности его модификации.
Изменение правил безопасности (Edit Security). Позволяет изменять дескриптор безопасности для пространства имен WMI.
Все эти записи списка контроля доступа хранятся в репозитории WMI. Разрешения WMI для конкретного пространства имен применяются ко всем подпространствам имен и классам, которые определены в этом пространстве (наследуются ими). Собственные же разрешения безопасности для отдельного класса WMI определить нельзя.
О настройке по умолчанию
В Windows группа администраторов обладает всеми разрешениями из таблицы выше, а для остальных пользователей включена учетная запись (Enable Account), разрешено вызывать методы (Execute Methods) и записывать в CIM экземпляры классов провайдеров (Provider Write).
Администратор может изменить разрешения для определенных пользователей с помощью утилиты для настройки параметров WMI (оснастка wmimgmt.msc консоли управления ММС).
Скриншот 1.
Для доступа к инфраструктуре WMI на удаленном компьютере используется вышеуказанный протокол DCOM. Пользователь запускает сценарий или подключается к WMI с помощью специальных утилит и выступает в качестве клиента, а объект WMI, к которому идет обращение, является сервером. Чтобы определить, какой маркер доступа будет применяться при работе с WMI на удаленном компьютере, используются стандартные уровни имперсонации протокола DCOM.
Об имперсонации или Impersonation Levels
По-русски звучит несколько коряво. Что такое имперсонация и зачем она нужна? Это метод, при котором для подключения к ресурсу процесс или система должны использовать не свой контекст безопасности, а учетные данные другого субъекта безопасности.
Представьте – некая служба, запущенная в контексте безопасности LocalSystem, должна выполнить действие от лица другой учетной записи (например, от лица текущего зарегистрированного на компьютере пользователя). В этом случае службе необходимо создать специальный маркер доступа (Access Token), описывающий контекст безопасности той учетной записи, под которой мы хотим выполнить указанное действие.
Для того чтобы создать такой маркер доступа, службе необходимо знать учетные данные этого пользователя, а если этот процесс происходит на локальной машине, получить копию маркера доступа ранее зарегистрированного локально пользователя.
Еще для этого контекст безопасности службы должен обладать привилегией создания маркеров доступа.
Бывает более сложный вариант имперсонации – делегирование. Этот вариант необходим тогда, когда подключение к конечному ресурсу выполняется не самим субъектом безопасности (в примере выше – службой от лица пользователя), а через посредника (например, промежуточный сервер).
Представьте: пользователь подключается не напрямую к базе данных, а через веб-приложение на третьем сервере. Для осуществления такого подключения веб-приложение должно получить от субъекта безопасности (нашей службы) маркер доступа с правом делегирования – это позволит веб-приложению использовать маркер доступа субъекта безопасности уже при подключении к базе данных.
В случае с WMI делегирование может выглядеть так: мы, работая на станции администратора, подключаемся по WMI к некому серверу и запускаем на нем процесс с помощью метода Execute класса Win32_Process. Этот процесс не что иное, как другой скрипт WMI, который подключается к ещё одному хосту в сети для того, чтобы совершить какие-то действия. Если мы не воспользуемся делегированием, то на конечной машине скрипт будет запущен в контексте безопасности учетной записи промежуточного сервера, что далеко не всегда желаемо. С другой стороны, подобная ситуация с делегированием в реальной жизни случается достаточно редко.
Об уровнях Impersonation Levels
Анонимный доступ (Anonymous). Объект-сервер не имеет права получить информацию о пользователе или процессе, который обращается к данному объекту (иными словами, объект не может олицетворить клиента). Этот уровень олицетворения в WMI не используется.
Идентификация (Identify). Объект-сервер может запросить маркер доступа, связанный с клиентом, но не может произвести олицетворение.
В сценариях WMI этот уровень олицетворения используется редко, в этом случае нельзя запускать сценарии WMI на удаленных машинах.
Олицетворение (Impersonate). Объект-сервер может пользоваться всеми правами и привилегиями, которыми обладает клиент. В сценариях WMI рекомендуется использовать именно этот уровень олицетворения, ибо в таком случае сценарий WMI на удаленной машине сможет выполнять все действия, которые разрешено осуществлять пользователю, запустившему этот сценарий.
Делегирование (Delegate). Объект на сервере, к которому обращается клиент, может обратиться от имени клиента к другому объекту на другом сервере. Делегирование позволяет сценарию использовать на удаленной машине маркер доступа запустившего его пользователя. Тот же маркер используется для доступа к объектам WMI на других рабочих станциях. Применение данного уровня олицетворения связано с потенциальным риском, делегирование в сценариях WMI следует применять только в случае особой необходимости.
Выбираемый по умолчанию уровень олицетворения зависит от версии WMI на целевом компьютере. В версиях WMI ниже 1.5 по умолчанию используется уровень Идентификация (Identify), в версии WMI 1.5 и выше —Олицетворение (Impersonate). При необходимости можно изменить уровень олицетворения по умолчанию — для этого необходимо записать наименование нужного уровня (например, impersonate или Delegate) в ключ реестра
HKEY_LOCAL_MACHINE\Software\Microsoft\Wbem\Scripting\Default Impersonation Level.
Скриншот 2.
Протокол DCOM также предоставляет возможность запросить для соединения WMI определенный уровень аутентификации (проверки подлинности) и конфиденциальности:
Отсутствует (None). Проверка подлинности отсутствует.
По умолчанию (Default). Для выбора уровня проверки подлинности используются стандартные настройки безопасности. Рекомендуется использовать именно этот уровень, так как к клиенту будет применен уровень проверки подлинности, который задается сервером.
Подключений (Connect). Клиент проходит проверку подлинности только во время подключения к серверу. После того как соединение установлено, никаких дополнительных проверок не производится.
Вызовов(Call). Клиент проходит проверку подлинности в начале каждого вызова, во время приема запросов сервером. При этом заголовки пакетов подписываются, однако сами данные (содержимое пакетов), передаваемые между клиентом и сервером, не подписываются и не шифруются.
Пакет (Pkt). Проверке подлинности подвергаются все пакеты данных, которые поступают серверу от клиентов. Как и при проверке подлинности на уровне вызовов, заголовки пакетов подписываются, но не шифруются. Сами пакеты не подписываются и не шифруются.
Целостности пакетов (Pktlntegrity). Все пакеты данных проходят проверку подлинности и целостности. Проверяется, что содержимое пакета не было изменено во время передачи от клиента серверу. При этом данные подписываются, но не шифруются.
Привилегии (PktPrivacy). Все пакеты данных проходят проверку подлинности и целостности, при этом данные подписываются и шифруются, что обеспечивает конфиденциальность передаваемых данных.
Администраторам Windows хорошо известны настройки безопасности системы, доступные в консоли безопасности системы и групповых политиках домена и раздел «User Right Assignments» (привилегии пользователей). Ряд действий с операционной системой можно проделать только при наличии у пользователя или группы, куда он входит, той или иной привилегии. К таким действиям, например, относятся: перезагрузка системы (завершение её работы), восстановление состояния системы из резервной копии или смена системного времени.
Поскольку с использованием WMI можно выполнить все эти действия, разработчики WMI заложили дополнительный механизм защиты: даже если учетная запись пользователя обладает привилегиями, необходимыми для действия с системой, он все равно не сможет выполнить это действие, пока явно не активирует привилегию перед выполнением действия. В частности, если администратор запустит скрипт WMI, запрашивающий перезагрузку системы, этого все равно не произойдет, пока в скрипте не будет явно активирована эта привилегия.
Резюме
Что предлагается сделать для обеспечения безопасности WMI-подключений:
- Изменить уровень имперсонации для критичных сервисов (Скриншот 2).
- Настроить разрешения wmimgmt.msc (Скриншот 1).
- Изменить репозиторий по умолчанию. Это может нарушить сценарий шаблонных атак.
4. Изменить группы лиц с возможностями удаленного запуска и активации WMI через утилиту DCOMCNFG
5. Чтобы запустить WMI пользователь должен быть членом группы administrators либо DCOM users. Также должна быть доступна служба remote registry.
6. Настроить файервол – входящие подключения к DCOM идут по 135 TCP-порту и (имеют?) динамический диапазон RPC.
В заключение хочу сказать следующее: WMI дает скорость, мощь и легкость запуска команд на удаленных хостах, а SQL based-семантика команд делает его легким для освоения.
В интернете очень много информации о взломах и WMI-атаках, ведь они вписываются в нынешний атакующий тренд – использование нативных инструментов взлома системы – наряду с telnet NTP и DNS. Наша задача — этот тренд уловить и найти методы противодействия уже заложенные в систему.
Автор: Галиулин Тимур GTRch