What is this?

This knowledgebase contains questions and answers about PRTG Network Monitor and network monitoring in general.

Learn more

PRTG Network Monitor

Intuitive to Use. Easy to manage.
More than 500,000 users rely on Paessler PRTG every day. Find out how you can reduce cost, increase QoS and ease planning, as well.

Free Download

Top Tags


View all Tags

How can I monitor WMI sensors if the target machine is not part of a domain?

Votes:

0

Is it possible to monitor WMI sensors if the target machine is not part of the actual domain?

active-directory domain prtg registry troubleshooting wmi

Created on Feb 2, 2010 1:19:10 PM by  Dirk Paessler [Founder Paessler AG] (11,025) 3 6

Last change on Jul 21, 2010 1:55:04 PM by  Daniel Zobel [Product Manager]



20 Replies

Accepted Answer

Votes:

3

This article applies to PRTG Network Monitor 16 or later

Monitoring WMI Sensors Outside a Domain

If the server on which PRTG is installed is part of a domain, whereas a few target machines are not, WMI monitoring often fails with the following error:

Connection could not be established (80070005: Access Denied …)

This article lists a few possible steps to resolve this issue to successfully monitor target machines outside your Windows domain.

Basic Steps

  • First of all, please check if the correct credentials are used, especially if the hostname is entered in the field Domain or Computer Name in PRTG. You can try to use localhost here, especially in the settings of the parent group (if all devices in this group are outside of the domain, of course). Please do not leave this field empty!
  • Verify if any firewalls in between PRTG and the target machine(s) may be interfering with connections on port 135.
  • Check the access rights to the target machine. You can either try accessing as a local user with corresponding rights or as a domain admin:
    • If you want to use a local user to monitor the target machine (no matter if workgroup or domain machine), set up this user account as following.
      Note: This approach does not work with a domain user!
      • Open the Computer/Server Management tool on the target machine.
      • Navigate to System | Local Users and Groups | Groups.
      • Add the local user to Distributed COM Users and to Performance Monitor Users.
      • Navigate to Services and Applications below in the management panel.
      • Right-click WMI Control and choose Properties.
      • Select the Security tab.
      • Navigate to the namespace you are interested in (for example, Root\CIMV2).
      • Click the Security button.
      • Add the local user and give these permissions: Execute Methods, Enable Account, and Remote Enable.
      • Start DCOMCNFG.exe
      • Navigate to Component Services | Computers | My Computer.
      • Right-click My Computer and choose Properties.
      • Select the COM Security tab.
      • In section Launch and Activation Permissions click Edit Limits...
      • Add the local user and allow these permissions: Local Launch, Remote Launch and Remote Activation.
      • Monitoring with a local user user account should now work. Otherwise, try using a domain admin as described below.
    • Check the access permissions on all computers running a PRTG probe with WMI sensors (can be local probe system, systems with remote probes, on every node in a cluster setup):
      • Start DCOMCNFG.exe on each system running a PRTG probe.
      • Navigate to Component Services | Computers | My Computer.
      • Right-click My Computer and choose Properties.
      • Select the COM Security tab.
      • In section Access Permissions click Edit Limits...
      • Add the group Everyone and allow the permission Remote Access.
      • Confirm and restart the computer.
    • The next thing you should try is to configure the PRTG Probe service to run under a domain administrator account. Sometimes the access rights of the System Account under which the PRTG Probe runs by default are not sufficient. Even though it may sound awkward to use a domain administrator account to query a machine outside of a domain, do try this, as we have actually seen cases where this option got the WMI sensors (for this particular target) to work.
  • Ensure that Remote Management is enabled on on the target server. See Microsoft TechNet: Configure Remote Management in Server Manager (Windows Server 2012)
  • If the target host(s) are accessible with our WMI Tester tool, but PRTG still insists on showing the 80070005 error, try using "localhost" as "domain or computer name" in the Windows credentials section of the device's settings.

The next options have to be differentiated by the Windows version running on the target machine:

Windows 7

  • Open the control panel, head to “System and Security”, and then click on “Windows Firewall”
  • Click on “Advanced Settings” and then, for both Inbound and Outbound Rules, do the following:
  • To enable WMI traffic passing the firewall, select all checkboxes for “Windows Management Instrumentation”. Confirm this by closing the windows.
  • Open a command prompt (as administrator) and enter the following line to set another firewall group rule: netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
  • Eventually reboot the target machine. It should now be possible to monitor with WMI.
  • Add the monitoring user to the Performance Monitor Users group
  • UAC blocks some (not all) WMI counters, resulting in error 80041003: The current user does not have permission to perform the action. . You can add the following registry key to disable this feature of UAC.
    Path: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System Add a new DWORD value:
    Name: LocalAccountTokenFilterPolicy
    Value: 1
    • Note: This disables some of the protection provided by UAC. Specifically, any remote access to the server using an administrator security token is automatically elevated with full administrator rights, including access to the root folder. More information can be found here: http://support.microsoft.com/kb/951016
      We have also seen cases where it was necessary to disable the UAC completely to get WMI Monitoring running.

Windows XP/2003

  • Head to “Start”->”Run…” and start the registry editor (regedit)
  • Navigate to the following key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\
  • Make sure that “ForceGuest” is set to “0”
  • Eventually reboot the target machine. It should now be possible to monitor with WMI.
  • For further reference please see http://support.microsoft.com/default.aspx?scid=kb;en-us;290403

Windows Vista/2008 (R2)

  • Open the control panel, head to the Windows firewall
  • Click on “Change Settings” and then please select the “Exceptions” tab
  • To enable WMI traffic passing the firewall, select the check box for “Windows Management Instrumentation (WMI)”. Confirm this with Ok.
  • Open a command prompt (as administrator) and enter the following line to set another firewall group rule: netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yesNote: The name of the group is language dependent and must be translated for non-English Windows versions! So, if you run this command on a German Windows version, you have to replace windows management instrumentation (wmi) by Windows-Verwaltungsinstrumentation (WMI).
  • Eventually reboot the target machine. It should now be possible to monitor with WMI.
  • For further reference please see: http://msdn.microsoft.com/en-us/library/aa822854(VS.85).aspx
  • Add the monitoring user to the Performance Monitor Users group

Created on Feb 2, 2010 1:21:44 PM by  Dirk Paessler [Founder Paessler AG] (11,025) 3 6

Last change on Jul 29, 2016 11:52:26 AM by  Gerald Schoch [Paessler Support]



Votes:

0

the given solution doesn't work in my network

PRTG Server ist installed on WinXP Pro SP3 (in a domain) and should monitor a Win2k8 (not in a domain)

is there another solution ?

Michael

Created on May 4, 2010 10:39:04 AM



Votes:

0

run the WMI Tester on your XP PC and check if you can get information from the 2008 Server

https://www.paessler.com/tools/wmitester

Created on May 4, 2010 12:58:07 PM by  Aurelio Lombardi [Paessler Support]



Votes:

0

finally I got it! I had to do all the settings listet in http://msdn.microsoft.com/en-us/library/aa822854(VS.85).aspx especially the CIMOM thing. A reboot was necessary, too.

After reboot all works fine!

Thanx Michael

Created on May 7, 2010 6:03:06 AM



Votes:

0

I'm trying to set it up for win 7 Professional

After adding the WMI rules to the firewall I open a command prompt (as administrator) and enter the following line to set another firewall group rule:

netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes

I get an error :

"Aucune règle ne correspond aux critères spécifiés"

No rule matches the criteria specified

????

Created on Nov 10, 2010 9:04:58 AM

Last change on Nov 10, 2010 10:52:40 AM by  Daniel Zobel [Product Manager]



Votes:

0

Please check if WMI connection works if you turn off the firewall, to make sure that the firewall settings are the cause.

Created on Nov 10, 2010 9:17:04 AM by  Aurelio Lombardi [Paessler Support]

Last change on Nov 10, 2010 10:52:56 AM by  Daniel Zobel [Product Manager]



Votes:

0

I have just turn off the firewall but the result is the same.

It's strange because I was able to get all the list of WMI sensor. It means that my account and password for accessing my windows machine is correct.

Created on Nov 10, 2010 9:24:32 AM



Votes:

0

Dear Maurice,

as for the firewall rule, it seems you are using a French Windows, therefore the correct French Term for "windows management instrumentation (wmi)" has to be used. Furthermore, please check if the user you are using is correctly entered in the user group of DCOM-Users.

Best Regards.

Created on Nov 10, 2010 2:53:24 PM by  Torsten Lindner [Paessler Support]



Votes:

0

Where I need to check if the user is correctly entered in the user group DCOM-Users ?

Created on Nov 10, 2010 3:37:29 PM



Votes:

0

In the Computer Management (Windows: Start->Settings->Control Panel->Administrative Tools->Computer Management), please add the user to the "Distributed COM Users"-Group.

Created on Nov 10, 2010 5:29:52 PM by  Torsten Lindner [Paessler Support]



Votes:

0

Thanks. I was able to add my user to this DCOM group.

But I get always this error message :

"Connection could not be established (80041003: The current user does not have permission to perform the action. - Host: 195.49.12.XXX, User: YYY, Password: ***, Domain: ntlmdomain:srv-forum) (code: PE015)"

About the firewall, I have setup this Input rules :

Windows Management Instrumentation (WMI-In)
Windows Management Instrumentation (DCOM-In)
Windows Management Instrumentation (ASync-In)

and this output rule :

Infrastructure de gestion Windows (WMI-Out)

What I am missing ??

Created on Nov 11, 2010 10:16:08 AM

Last change on Nov 11, 2010 12:54:08 PM by  Torsten Lindner [Paessler Support]



Votes:

0

Please also read this KB article for general WMI configuration if you haven't yet:

https://www.paessler.com/knowledgebase/en/topic/1043-my-wmi-sensors-don-t-work-what-can-i-do

If nothing else helps there is the possibility to install a remote probe on the target system. Then there should be no problems with WMI access rights.

Created on Nov 15, 2010 12:44:20 PM by  Tobias Lange [Paessler Support]



Votes:

0

Finally I was able to make it working.

This link is the way to go :

http://bit.ly/dhjcSz

Now my problem of remote access from PRTG 8 is solved.

Created on Nov 15, 2010 3:48:21 PM



Votes:

0

Here is one thing we've added to our article above:

  • If the target host(s) are accessible with our WMI Tester tool, but PRTG still insists on showing the 80070005 error, try using "localhost" as "domain or computer name" in the Windows credentials section of the device's settings.

Kind regards,

- Volker

Created on Nov 2, 2011 12:40:52 PM by  Volker Uffelmann [Paessler Support]



Votes:

1

I followed most of the instructions above and still couldn't get it to work. I kept getting the 80041003 error. I finally found a solution, that didn't involve using an administrator account for the Probe machine or for the target DMZ account, and I didn't have to turn off UAC, and I didn't have to edit the registry.

The remote machine in this case is a Server 2008 R2 machine. I'm using a normal user account. I added this account to "Distributed COM Users" and "Performance Monitor Users". Doesn't seem to work without these two groups.

Here's what I did. Brought up the management panel (right click on the computer icon, and select manage). I then found the "WMI Control" (right below Services), right-clicked on Properties, then went to the Security tab. I clicked on the namespace I was interested in (in my case, root/CIMV2) and then hit the Security button. I added the user I was trying to access with and gave it the following Permissions: Execute Methods, Provider Write, Enable Account, and most importantly, Remote Enable. This last permission is key.

Once I did that, I had no problem adding WMI/counter sensors.

Created on Apr 1, 2014 7:37:26 AM



Votes:

0

Fixed it! This great little free VBS script from LanSweeper did the trick! I was going nuts with firewall settings, registry setting, services, etc.

See http://www.lansweeper.com/kb/3/WMI-Access-is-denied.html -> http://www.lansweeper.com/files/lansweeper.vbs

Run it once from an elevated command prompt, problem fixed!

-- Ken

Created on Jul 9, 2015 4:19:32 PM



Votes:

0

Which settings are mandatory when I use Windows 10?

Created on Apr 3, 2017 7:23:16 AM



Votes:

0

Christian, I'm afraid we do not have an extensive list for a work group Windows 10, and how to monitor it with PRTG via WMI. Please try the tips in this very article here. Otherwise there is always the alternative of installing a Remote Probe on the target host, because local WMI monitoring does not need authentication (as per Microsofts design) and thus is much less troublesome in this scenario with work group machines.

Created on Apr 4, 2017 9:06:31 AM by  Torsten Lindner [Paessler Support]



Votes:

0

Putting localhost in as the domain name for the credentials fixed my issue (PE015). I had changed the monitoring user for a few hosts that were off domain and started getting heaps of PE015 errors. Apparently "." or blank is no good as the domainame - but "localhost" works fine which is heaps better that putting a different local hostname into the domain feild for each set of credentials.

Created on Aug 3, 2018 1:50:13 AM



Votes:

5

To accomplish this I have created an PowerShell Script.

Especially the Firewall part was tricky to set up. Use it on your own Risk.

Initial Release: Version: 1.0.0.0 10.September.2019 Current Release: Version: 1.0.1.0 11.September.2019

Changelog: 1.0.1.0 Fixed Parameter "-WmiNamespaceInheritPermissions" was not in use. Added Comment to UAC section

#Requires -RunAsAdministrator
<#
.Synopsis
    This script is to create an local user account
    which is used to query this local computer over PRTG and WMI and
    open the Windows Firewall to allow WMI Remoting

.DESCRIPTION
    
    1. Create an Local user with the iads WinNT:// system provider

    2. Put Local user into the local groups (international found by SID not by name, with the help of WMI Win32_Group class)
            "Distributed COM Users"
            SID: S-1-5-32-562
               and
            "Performance Monitor Users"
            SID: S-1-5-32-558 
    
    3. Grant User permissions to the target WMI Namespace 
    
    4. Enable Windows-Firewall rule to allow WMI Access
        
        using the CMD command "netsh advfirewall firewall ..." because PowerShell commands do not support Rule-Groups.

        (!!! Atention !!! this command is international translated and language dependent !!!!!)
        
        eg. for german: netsh advfirewall firewall set rule group="Windows-Verwaltungsinstrumentation (WMI)" new enable=yes
        eg. for english: netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes

    5. This Script do not touch the UAC (registry key)!

        UAC can in some cases filter information through WMI so that the information is not as complete as it could be.
        Some are recommend turning off UAC filtering on the target machine. It can be done by setting a registry key.
        Change it on your own Risk!

        HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy = 1

        See: Microsoft documentation "User Account Control and WMI" https://docs.microsoft.com/de-de/windows/win32/wmisdk/user-account-control-and-wmi?redirectedfrom=MSDN


    This Script is designed to run local on the target computer who is accessed by PRTG and Windows Management Instrumentation (WMI). 
    If you like to run this script remote on the target Computer, run this script with Invoke-Command.

    
    
    For documentation of the user account flags,
    search kewords are: "win32 api iads ADS_USER_FLAG_ENUM"

    The ADS_USER_FLAG_ENUM enumeration defines the flags used for setting user properties in the directory.
    These flags correspond to values of the userAccountControl attribute in Active Directory when using the LDAP provider,
    and the userFlags attribute when using the WinNT system provider.
    See: https://docs.microsoft.com/en-us/windows/win32/api/iads/ne-iads-ads_user_flag_enum

    
    
    Copyright 2019 Peter Kriegel (modified MIT License)

    Permission is hereby granted, free of charge,
    to any person obtaining a copy of this script and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
    and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    THIS SCRIPT IS NOT SUPPORTED UNDER ANY SUPPORT PROGRAM OR SERVICE. 
    THE AUTHOR FURTHER DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING, WITHOUT LIMITATION,
    ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR OF FITNESS FOR A PARTICULAR PURPOSE.
    THE ENTIRE RISK ARISING OUT OF THE USE OR PERFORMANCE 
    OF THIS SCRIPT AND DOCUMENTATION REMAINS WITH YOU. IN NO EVENT THE AUTHOR OR
    ANYONE ELSE INVOLVED IN THE CREATION, PRODUCTION, OR DELIVERY OF THIS SOFTWARE BE 
    LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS 
    PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING 
    OUT OF THE USE OF OR INABILITY TO USE THIS SCRIPT OR DOCUMENTATION, EVEN IF THE AUTHOR 
    HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

    IT IS UP TO YOU, THAT YOU HAVE READ AND UNDERSTOOD WHAT THIS SCRIPT IS GOING TO PROCESS BEFORE YOU RUN IT.

    IF YOU REPUBLISH THIS SCRIPT, CREDIT THE AUTHOR AND PROVIDE A LINK TO THE ORIGIN!

    End of Copyright

.NOTES
    Author: Peter Kriegel
    Initial Release: Version: 1.0.0.0 10.September.2019
    Current Release: Version: 1.0.1.0 11.September.2019
         
         Changelog:
         1.0.1.0 Fixed Parameter "-WmiNamespaceInheritPermissions" was not in use.
                 Added Comment to UAC section   
#>

# Start variables to set
param (
    # ComputerName to add the User and to modify the Firewall
    [String]$ComputerName = $Env:COMPUTERNAME,
    # Username to add
    [String]$UserName = 'PRTGquery',
    # Password for the User; If it is leaved blank, the password is requested in interactive mode!!!
    [String]$UserPassword,
    # Fullname of the User (only for description)
    [String]$UserFullname = 'PRTG user',
    # Userflags of the new created User account; see Microsoft documentation of the "ADS_USER_FLAG_ENUM" enumeration
    [Int]$UserFlags = 64 + 65536, # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
    # Description for the new created User account
    [String]$UserDescription = 'Query this Computer with PRTG',
    # WMI Namespace who the user is granted permissions.
    [String]$WmiNamespace = 'root/cimv2',
    # the User permissions to grant to the WMI-Namespace. (default here is least privilege as read only)
    [ValidateSet('Enable','MethodExecute','FullWrite','PartialWrite','ProviderWrite','RemoteAccess','ReadSecurity','WriteSecurity')]
    [String[]]$WmiNamespacePermissions = @('Enable','MethodExecute','ReadSecurity','RemoteAccess'),
    # If true the user permissions is inherited even to sub namespaces of the given namespace, if false only the Namespace is granted for the user
    [Bool]$WmiNamespaceInheritPermissions = $True,
    # add / modify firewall groupname to your language! (we have MUI environment and try to use the englisch version too, so a message like "No rules match the specified criteria." is normal)
    [String[]]$WindowsFirewallRuleGroupNames = @('Windows-Verwaltungsinstrumentation (WMI)','windows management instrumentation (wmi)') 
)




# Query / convert Password for the User
$PwEqualOrQuit = $False
$Pwd1 = $Null
$Pwd2 = $Null

If(-Not ([String]::IsNullOrEmpty(($UserPassword.Trim())))) {
    $Pwd1 = ConvertTo-SecureString -String $UserPassword -AsPlainText -Force
    $UserPassword = $Null
} Else {

    Do {

        $Pwd1 = Read-Host "Enter password for the user $UserName (Q or q to quit)" -AsSecureString

        If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1)) -ieq 'q') {
            $Pwd1 = $Null
            $PwEqualOrQuit = $True
        } Else {
            $Pwd2 = Read-Host "Reenter password for the user $UserName (Q or q to quit)" -AsSecureString
            If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd2)) -ieq 'q') {
                $Pwd1 = $Null
                $PwEqualOrQuit = $True
            }
        }

        If(-Not $PwEqualOrQuit) {
            If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1)) -ceq [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd2))) {
                $PwEqualOrQuit = $True
            } Else {
                Write-Host "`nPasswords dont match!`nTry again`n"
            }
        }

    } while (-Not $PwEqualOrQuit)

    If ($Null -eq $Pwd1) {
        Write-Host 'User has quitted!'
        Return
    } Else {
        # Write-Host "Passwords matched!"
    }
}


# Create new local user
Try {
  
    $Computer = [ADSI]"WinNT://$ComputerName,Computer"

    $LocalUser = $Computer.Create("User", $UserName)
    $LocalUser.SetPassword(([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1))))
    $LocalUser.UserFlags = $UserFlags
    $LocalUser.SetInfo()
    $LocalUser.Put('Fullname', $UserFullname)
    $LocalUser.SetInfo()
    $LocalUser.Put('Description', $UserDescription)
    $LocalUser.SetInfo()
} Catch {
    Write-Error $Error[0]
    Return
}

# Add User to groups

<#

    To access WMI and performance data remotely and
    If a target computer is outside of a domain or the user is an local account,
    the user has to be a member of the local "Distributed COM Users" group and
    of the "Performance Monitor Users" group on the local machine.

    Additionally you have to grant permissions (read) to a WIM / CIM namespace (and subtree).
    For an example Namespace Root/CIMV2
    If the user needs access to all the namespaces, you can set the settings at the Root level (Root).
    You have to recurse the permissions to the sub-namespaces with the security setting of "This namespace and subnamespaces"!

    "Distributed COM Users"
    SID: S-1-5-32-562
    Name: BUILTIN\Distributed COM Users
    Description: An alias. A group for COM to
    provide computerwide access controls that
    govern access to all call, activation, or launch
    requests on the computer.

    "Performance Monitor Users"
    SID: S-1-5-32-558
    Name: BUILTIN\Performance Monitor Users
    Description: An alias. Members of this group
    have remote access to monitor this computer.

    To set a non Domain User into the local "Administrators" group to access WMI / CIM does not worked.

#>


# Get Groups by SID
Get-WMIObject -Class 'Win32_Group' -Filter "LocalAccount='True' AND (SID='S-1-5-32-562' OR SID='S-1-5-32-558')" -ComputerName $ComputerName | ForEach-Object {
        
    # add User to Groups
    $AdsiGroup = [ADSI]"WinNT://$ComputerName/$($_.Name),group"
    $AdsiGroup.psbase.Invoke('Add',([ADSI]"WinNT://$ComputerName/$UserName").path)
}

Function Set-WMINamespacePermissions {
<#
.Synopsis
   A Script for modifying the current security descriptor of a WMI namespace. 
.DESCRIPTION
   A Script for modifying the current security descriptor of a WMI namespace. 
.EXAMPLE
   Set-WMINamespacePermissions.ps1 -namespace root/cimv2 -account "contoso\AD - Remote WMI Access" -operation Add -permissions Enable
.EXAMPLE
   Set-WMINamespacePermissions.ps1 root/cimv2 add steve Enable,RemoteAccess
.NOTES
   
   Original Content by Steve Lee
   
   Blog links:

   https://blogs.msdn.microsoft.com/wmi/2009/07/20/scripting-wmi-namespace-security-part-1-of-3/
   https://blogs.msdn.microsoft.com/wmi/2009/07/23/scripting-wmi-namespace-security-part-2-of-3/
   https://blogs.msdn.microsoft.com/wmi/2009/07/27/scripting-wmi-namespace-security-part-3-of-3/
    
   
   Modified by Graeme Bray and
    Peter Kriegel (converted into a Function and fixed a Bug with inheritance)
   

   Original "Set-WMINameSpaceSecurity.ps1", taken from:
   https://gallery.technet.microsoft.com/Set-WMI-NameSpace-Security-5081ad6d

   Disclaimer
    The sample scripts are not supported under any Microsoft standard support program or service. 
    The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims 
    all implied warranties including, without limitation, any implied warranties of merchantability 
    or of fitness for a particular purpose. The entire risk arising out of the use or performance 
    of the sample scripts and documentation remains with you. In no event shall Microsoft, its 
    authors, or anyone else involved in the creation, production, or delivery of the scripts be 
    liable for any damages whatsoever (including, without limitation, damages for loss of business 
    profits, business interruption, loss of business information, or other pecuniary loss) arising 
    out of the use of or inability to use the sample scripts or documentation, even if Microsoft 
    has been advised of the possibility of such damages.
#>
    Param ( [parameter(Mandatory=$true,Position=0)][string] $namespace,
        [parameter(Mandatory=$true,Position=1)][string] $operation,
        [parameter(Mandatory=$true,Position=2)][string] $account,
        [parameter(Position=3)][string[]] $permissions = $null,
        [bool] $allowInherit = $false,
        [bool] $deny = $false,
        [string] $computerName = ".",
        [System.Management.Automation.PSCredential] $credential = $null)
   
    Process {
        $ErrorActionPreference = "Stop"
 
        Function Get-AccessMaskFromPermission($permissions) {
            $WBEM_ENABLE            = 1
                    $WBEM_METHOD_EXECUTE = 2
                    $WBEM_FULL_WRITE_REP   = 4
                    $WBEM_PARTIAL_WRITE_REP              = 8
                    $WBEM_WRITE_PROVIDER   = 0x10
                    $WBEM_REMOTE_ACCESS    = 0x20
                    $WBEM_RIGHT_SUBSCRIBE = 0x40
                    $WBEM_RIGHT_PUBLISH      = 0x80
            $READ_CONTROL = 0x20000
            $WRITE_DAC = 0x40000
       
            $WBEM_RIGHTS_FLAGS = $WBEM_ENABLE,$WBEM_METHOD_EXECUTE,$WBEM_FULL_WRITE_REP,`
                $WBEM_PARTIAL_WRITE_REP,$WBEM_WRITE_PROVIDER,$WBEM_REMOTE_ACCESS,`
                $READ_CONTROL,$WRITE_DAC
            $WBEM_RIGHTS_STRINGS = "Enable","MethodExecute","FullWrite","PartialWrite",`
                "ProviderWrite","RemoteAccess","ReadSecurity","WriteSecurity"
 
            $permissionTable = @{}
 
            for ($i = 0; $i -lt $WBEM_RIGHTS_FLAGS.Length; $i++) {
                $permissionTable.Add($WBEM_RIGHTS_STRINGS[$i].ToLower(), $WBEM_RIGHTS_FLAGS[$i])
            }
       
            $accessMask = 0
 
            foreach ($permission in $permissions) {
                if (-not $permissionTable.ContainsKey($permission.ToLower())) {
                    throw "Unknown permission: $permission`nValid permissions: $($permissionTable.Keys)"
                }
                $accessMask += $permissionTable[$permission.ToLower()]
            }
       
            $accessMask
        }
 
        if ($PSBoundParameters.ContainsKey("Credential")) {
            $remoteparams = @{ComputerName=$computer;Credential=$credential}
        } else {
            $remoteparams = @{ComputerName=$computerName}
        }
       
        $invokeparams = @{Namespace=$namespace;Path="__systemsecurity=@"} + $remoteParams
 
        $output = Invoke-WmiMethod @invokeparams -Name GetSecurityDescriptor
        if ($output.ReturnValue -ne 0) {
            throw "GetSecurityDescriptor failed: $($output.ReturnValue)"
        }
 
        $acl = $output.Descriptor
        $OBJECT_INHERIT_ACE_FLAG = 0x1
        $CONTAINER_INHERIT_ACE_FLAG = 0x2
 
        $computerName = (Get-WmiObject @remoteparams Win32_ComputerSystem).Name
   
        if ($account.Contains('\')) {
            $domainaccount = $account.Split('\')
            $domain = $domainaccount[0]
            if (($domain -eq ".") -or ($domain -eq "BUILTIN")) {
                $domain = $computerName
            }
            $accountname = $domainaccount[1]
        } elseif ($account.Contains('@')) {
            $domainaccount = $account.Split('@')
            $domain = $domainaccount[1].Split('.')[0]
            $accountname = $domainaccount[0]
        } else {
            $domain = $computerName
            $accountname = $account
        }
 
        $getparams = @{Class="Win32_Account";Filter="Domain='$domain' and Name='$accountname'"}
 
        $win32account = Get-WmiObject @getparams
 
        if ($win32account -eq $null) {
            throw "Account was not found: $account"
        }
 
        switch ($operation) {
            "add" {
                if ($permissions -eq $null) {
                    throw "-Permissions must be specified for an add operation"
                }
                $accessMask = Get-AccessMaskFromPermission($permissions)
   
                $ace = (New-Object System.Management.ManagementClass("win32_Ace")).CreateInstance()
                $ace.AccessMask = $accessMask
                if ($allowInherit) {
                     # $ace.AceFlags = $OBJECT_INHERIT_ACE_FLAG + $CONTAINER_INHERIT_ACE_FLAG <- Bug !!!!
                     $ace.AceFlags = $CONTAINER_INHERIT_ACE_FLAG
                } else {
                    $ace.AceFlags = 0
                }
                       
                $trustee = (New-Object System.Management.ManagementClass("win32_Trustee")).CreateInstance()
                $trustee.SidString = $win32account.Sid
                $ace.Trustee = $trustee
           
                $ACCESS_ALLOWED_ACE_TYPE = 0x0
                $ACCESS_DENIED_ACE_TYPE = 0x1
 
                if ($deny) {
                    $ace.AceType = $ACCESS_DENIED_ACE_TYPE
                } else {
                    $ace.AceType = $ACCESS_ALLOWED_ACE_TYPE
                }
 
                $acl.DACL += $ace.psobject.immediateBaseObject
            }
       
            "delete" {
                if ($permissions -ne $null) {
                    throw "Permissions cannot be specified for a delete operation"
                }
       
                [System.Management.ManagementBaseObject[]]$newDACL = @()
                foreach ($ace in $acl.DACL) {
                    if ($ace.Trustee.SidString -ne $win32account.Sid) {
                        $newDACL += $ace.psobject.immediateBaseObject
                    }
                }
 
                $acl.DACL = $newDACL.psobject.immediateBaseObject
            }
       
            default {
                throw "Unknown operation: $operation`nAllowed operations: add delete"
            }
        }
 
        $setparams = @{Name="SetSecurityDescriptor";ArgumentList=$acl.psobject.immediateBaseObject} + $invokeParams
 
        $output = Invoke-WmiMethod @setparams
        if ($output.ReturnValue -ne 0) {
            throw "SetSecurityDescriptor failed: $($output.ReturnValue)"
        }
    }
}


# Set User permissions to WMI-Namespace
Set-WMINamespacePermissions -namespace $WmiNamespace -operation 'add' -account "$ComputerName\$UserName" -permissions $WmiNamespacePermissions -allowInherit $WmiNamespaceInheritPermissions -ComputerName $ComputerName


# Set firewall rules
ForEach ($FwGroupName in $WindowsFirewallRuleGroupNames) {
    & 'netsh' @('advfirewall','firewall','set','rule','group=' + $FwGroupName ,'new','enable=yes')
}

Created on Sep 11, 2019 10:24:05 AM

Last change on Sep 11, 2019 11:21:42 AM by  Dariusz Gorka [Paessler Support]




Disclaimer: The information in the Paessler Knowledge Base comes without warranty of any kind. Use at your own risk. Before applying any instructions please exercise proper system administrator housekeeping. You must make sure that a proper backup of all your data is available.