1 // Licensed to the .NET Foundation under one or more agreements. 2 // The .NET Foundation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System.ComponentModel; 6 using System.Runtime.InteropServices; 7 using System.Globalization; 8 using System.IO; 9 using System.Reflection; 10 using System.ComponentModel.Design.Serialization; 11 using System.Security; 12 using System.Security.Permissions; 13 using Microsoft.Win32; 14 15 namespace System.Management 16 { 17 internal static class CompatSwitches 18 { 19 internal const string DotNetVersion = "v4.0.30319"; 20 private const string RegKeyLocation =@"SOFTWARE\Microsoft\.NETFramework\" + DotNetVersion; 21 22 private static readonly object s_syncLock = new object(); 23 private static int s_allowManagementObjectQI; 24 25 private const string c_WMIDisableCOMSecurity = "WMIDisableCOMSecurity"; 26 27 public static bool AllowIManagementObjectQI 28 { 29 get 30 { 31 if (s_allowManagementObjectQI == 0) 32 { 33 lock (s_syncLock) 34 { 35 if (s_allowManagementObjectQI == 0) 36 { 37 s_allowManagementObjectQI = GetSwitchValueFromRegistry() == true ? 1 : -1; 38 } 39 } 40 } 41 42 return s_allowManagementObjectQI == 1 ? true : false; 43 } 44 } 45 GetSwitchValueFromRegistry()46 private static bool GetSwitchValueFromRegistry() 47 { 48 RegistryKey s_switchesRegKey = null; 49 try 50 { 51 s_switchesRegKey = Registry.LocalMachine.OpenSubKey(RegKeyLocation); 52 53 if (s_switchesRegKey == null) 54 { 55 return false; 56 } 57 58 return ((int)s_switchesRegKey.GetValue(c_WMIDisableCOMSecurity, -1 /* default */) == 1); 59 } 60 61 // ignore exceptions so that we don't crash the process if we can't read the switch value 62 catch (Exception e) 63 { 64 if (e is StackOverflowException || 65 e is OutOfMemoryException || 66 e is System.Threading.ThreadAbortException || 67 e is AccessViolationException) 68 throw; 69 } 70 finally 71 { 72 // dispose of the key 73 if (s_switchesRegKey != null) 74 { 75 s_switchesRegKey.Dispose(); 76 } 77 } 78 79 // if for any reason we cannot retrieve the value of the switch from the Registry, 80 // fallback to 'false' which is the secure behavior 81 return false; 82 } 83 } 84 85 internal static class WmiNetUtilsHelper 86 { ResetSecurity(IntPtr hToken)87 internal delegate int ResetSecurity(IntPtr hToken); SetSecurity([In][Out] ref bool pNeedtoReset, [In][Out] ref IntPtr pHandle)88 internal delegate int SetSecurity([In][Out] ref bool pNeedtoReset, [In][Out] ref IntPtr pHandle); BlessIWbemServices([MarshalAs(UnmanagedType.Interface)] IWbemServices pIUnknown, [In][MarshalAs(UnmanagedType.BStr)] string strUser, IntPtr password, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, int impersonationLevel, int authenticationLevel)89 internal delegate int BlessIWbemServices([MarshalAs(UnmanagedType.Interface)] IWbemServices pIUnknown, 90 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 91 IntPtr password, 92 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, 93 int impersonationLevel, 94 int authenticationLevel); BlessIWbemServicesObject([MarshalAs(UnmanagedType.IUnknown)] object pIUnknown, [In][MarshalAs(UnmanagedType.BStr)] string strUser, IntPtr password, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, int impersonationLevel, int authenticationLevel)95 internal delegate int BlessIWbemServicesObject([MarshalAs(UnmanagedType.IUnknown)] object pIUnknown, 96 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 97 IntPtr password, 98 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, 99 int impersonationLevel, 100 int authenticationLevel); 101 GetPropertyHandle(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out Int32 pType, [Out] out Int32 plHandle)102 internal delegate int GetPropertyHandle(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszPropertyName, [Out] out Int32 pType, [Out] out Int32 plHandle); WritePropertyValue(int vFunc, IntPtr pWbemClassObject, [In] Int32 lHandle, [In] Int32 lNumBytes, [In][MarshalAs(UnmanagedType.LPWStr)] string str)103 internal delegate int WritePropertyValue(int vFunc, IntPtr pWbemClassObject, [In] Int32 lHandle, [In] Int32 lNumBytes, [In][MarshalAs(UnmanagedType.LPWStr)] string str); GetQualifierSet(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppQualSet)104 internal delegate int GetQualifierSet(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppQualSet); Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In][Out] ref object pVal, [In][Out] ref Int32 pType, [In][Out] ref Int32 plFlavor)105 internal delegate int Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In][Out] ref object pVal, [In][Out] ref Int32 pType, [In][Out] ref Int32 plFlavor); Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In] ref object pVal, [In] Int32 Type)106 internal delegate int Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In] ref object pVal, [In] Int32 Type); Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName)107 internal delegate int Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName); GetNames(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] Int32 lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames)108 internal delegate int GetNames(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszQualifierName, [In] Int32 lFlags, [In] ref object pQualifierVal, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames); BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lEnumFlags)109 internal delegate int BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lEnumFlags); Next(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref Int32 pType, [In][Out] ref Int32 plFlavor)110 internal delegate int Next(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string strName, [In][Out] ref object pVal, [In][Out] ref Int32 pType, [In][Out] ref Int32 plFlavor); EndEnumeration(int vFunc, IntPtr pWbemClassObject)111 internal delegate int EndEnumeration(int vFunc, IntPtr pWbemClassObject); GetPropertyQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out] out IntPtr ppQualSet)112 internal delegate int GetPropertyQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszProperty, [Out] out IntPtr ppQualSet); Clone(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppCopy)113 internal delegate int Clone(int vFunc, IntPtr pWbemClassObject, [Out] out IntPtr ppCopy); GetObjectText(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText)114 internal delegate int GetObjectText(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrObjectText); SpawnDerivedClass(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out] out IntPtr ppNewClass)115 internal delegate int SpawnDerivedClass(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out] out IntPtr ppNewClass); SpawnInstance(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out] out IntPtr ppNewInstance)116 internal delegate int SpawnInstance(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out] out IntPtr ppNewInstance); CompareTo(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [In] IntPtr pCompareTo)117 internal delegate int CompareTo(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [In] IntPtr pCompareTo); GetPropertyOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName)118 internal delegate int GetPropertyOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName); InheritsFrom(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor)119 internal delegate int InheritsFrom(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string strAncestor); GetMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [Out]out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature)120 internal delegate int GetMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [Out]out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature); PutMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In] IntPtr pInSignature, [In] IntPtr pOutSignature)121 internal delegate int PutMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In] IntPtr pInSignature, [In] IntPtr pOutSignature); DeleteMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName)122 internal delegate int DeleteMethod(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName); BeginMethodEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lEnumFlags)123 internal delegate int BeginMethodEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lEnumFlags); NextMethod(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature)124 internal delegate int NextMethod(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out IntPtr ppInSignature, [Out] out IntPtr ppOutSignature); EndMethodEnumeration(int vFunc, IntPtr pWbemClassObject)125 internal delegate int EndMethodEnumeration(int vFunc, IntPtr pWbemClassObject); GetMethodQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out] out IntPtr ppQualSet)126 internal delegate int GetMethodQualifierSet(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethod, [Out] out IntPtr ppQualSet); GetMethodOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName)127 internal delegate int GetMethodOrigin(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszMethodName, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrClassName); QualifierSet_Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In][Out] ref object pVal, [In][Out] ref Int32 plFlavor)128 internal delegate int QualifierSet_Get(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] Int32 lFlags, [In][Out] ref object pVal, [In][Out] ref Int32 plFlavor); QualifierSet_Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] Int32 lFlavor)129 internal delegate int QualifierSet_Put(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName, [In] ref object pVal, [In] Int32 lFlavor); QualifierSet_Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName)130 internal delegate int QualifierSet_Delete(int vFunc, IntPtr pWbemClassObject, [In][MarshalAs(UnmanagedType.LPWStr)] string wszName); QualifierSet_GetNames(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames)131 internal delegate int QualifierSet_GetNames(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_BSTR)] out string[] pNames); QualifierSet_BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags)132 internal delegate int QualifierSet_BeginEnumeration(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags); QualifierSet_Next(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pVal, [Out] out Int32 plFlavor)133 internal delegate int QualifierSet_Next(int vFunc, IntPtr pWbemClassObject, [In] Int32 lFlags, [Out][MarshalAs(UnmanagedType.BStr)] out string pstrName, [Out] out object pVal, [Out] out Int32 plFlavor); QualifierSet_EndEnumeration(int vFunc, IntPtr pWbemClassObject)134 internal delegate int QualifierSet_EndEnumeration(int vFunc, IntPtr pWbemClassObject); GetCurrentApartmentType(int vFunc, IntPtr pComThreadingInfo, [Out] out APTTYPE aptType)135 internal delegate int GetCurrentApartmentType(int vFunc, IntPtr pComThreadingInfo, [Out] out APTTYPE aptType); VerifyClientKey()136 internal delegate void VerifyClientKey(); GetDemultiplexedStub([In,MarshalAs(UnmanagedType.IUnknown)]object pIUnknown, [In]bool isLocal, [Out,MarshalAs(UnmanagedType.IUnknown)]out object ppIUnknown)137 internal delegate int GetDemultiplexedStub([In,MarshalAs(UnmanagedType.IUnknown)]object pIUnknown, [In]bool isLocal, [Out,MarshalAs(UnmanagedType.IUnknown)]out object ppIUnknown); CreateInstanceEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strFilter, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )138 internal delegate int CreateInstanceEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strFilter, 139 [In] Int32 lFlags, 140 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 141 [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, 142 [In] Int32 impLevel, 143 [In] Int32 authnLevel, 144 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 145 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 146 [In]IntPtr strPassword, 147 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 148 ); CreateClassEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )149 internal delegate int CreateClassEnumWmi([In][MarshalAs(UnmanagedType.BStr)] string strSuperclass, 150 [In] Int32 lFlags, 151 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 152 [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, 153 [In] Int32 impLevel, 154 [In] Int32 authnLevel, 155 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 156 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 157 [In]IntPtr strPassword, 158 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 159 ); ExecQueryWmi([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )160 internal delegate int ExecQueryWmi([In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, 161 [In][MarshalAs(UnmanagedType.BStr)] string strQuery, 162 [In] Int32 lFlags, 163 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 164 [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, 165 [In] Int32 impLevel, 166 [In] Int32 authnLevel, 167 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 168 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 169 [In]IntPtr strPassword, 170 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 171 ); ExecNotificationQueryWmi( [In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, [In][MarshalAs(UnmanagedType.BStr)] string strQuery, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )172 internal delegate int ExecNotificationQueryWmi( [In][MarshalAs(UnmanagedType.BStr)] string strQueryLanguage, 173 [In][MarshalAs(UnmanagedType.BStr)] string strQuery, 174 [In] Int32 lFlags, 175 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 176 [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, 177 [In] Int32 impLevel, 178 [In] Int32 authnLevel, 179 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 180 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 181 [In]IntPtr strPassword, 182 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 183 ); PutInstanceWmi([In] IntPtr pInst, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )184 internal delegate int PutInstanceWmi([In] IntPtr pInst, 185 [In] Int32 lFlags, 186 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 187 [In] IntPtr ppCallResult, 188 [In] Int32 impLevel, 189 [In] Int32 authnLevel, 190 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 191 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 192 [In]IntPtr strPassword, 193 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 194 ); PutClassWmi([In] IntPtr pObject, [In] Int32 lFlags, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [In] IntPtr ppCallResult, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )195 internal delegate int PutClassWmi([In] IntPtr pObject, 196 [In] Int32 lFlags, 197 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 198 [In] IntPtr ppCallResult, 199 [In] Int32 impLevel, 200 [In] Int32 authnLevel, 201 [In] [MarshalAs(UnmanagedType.Interface)] IWbemServices pCurrentNamespace, 202 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 203 [In]IntPtr strPassword, 204 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 205 ); CloneEnumWbemClassObject( [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, [In] Int32 impLevel, [In] Int32 authnLevel, [In] [MarshalAs(UnmanagedType.Interface)] IEnumWbemClassObject pCurrentEnumWbemClassObject, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In]IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority )206 internal delegate int CloneEnumWbemClassObject( 207 [Out][MarshalAs(UnmanagedType.Interface)] out IEnumWbemClassObject ppEnum, 208 [In] Int32 impLevel, 209 [In] Int32 authnLevel, 210 [In] [MarshalAs(UnmanagedType.Interface)] IEnumWbemClassObject pCurrentEnumWbemClassObject, 211 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 212 [In]IntPtr strPassword, 213 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority 214 ); ConnectServerWmi( [In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource, [In][MarshalAs(UnmanagedType.BStr)] string strUser, [In] IntPtr strPassword, [In][MarshalAs(UnmanagedType.BStr)] string strLocale, [In] Int32 lSecurityFlags, [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace, int impersonationLevel, int authenticationLevel)215 internal delegate int ConnectServerWmi( 216 [In][MarshalAs(UnmanagedType.BStr)] string strNetworkResource, 217 [In][MarshalAs(UnmanagedType.BStr)] string strUser, 218 [In] IntPtr strPassword, 219 [In][MarshalAs(UnmanagedType.BStr)] string strLocale, 220 [In] Int32 lSecurityFlags, 221 [In][MarshalAs(UnmanagedType.BStr)] string strAuthority, 222 [In][MarshalAs(UnmanagedType.Interface)] IWbemContext pCtx, 223 [Out][MarshalAs(UnmanagedType.Interface)] out IWbemServices ppNamespace, 224 int impersonationLevel, 225 int authenticationLevel); 226 GetErrorInfo()227 internal delegate IntPtr GetErrorInfo(); 228 Initialize([In]bool AllowIManagementObjectQI)229 internal delegate int Initialize([In]bool AllowIManagementObjectQI); 230 231 232 233 234 // 'Apartment Type' returned by IComThreadingInfo::GetCurrentApartmentType() 235 internal enum APTTYPE 236 { 237 APTTYPE_CURRENT = -1, 238 APTTYPE_STA = 0, 239 APTTYPE_MTA = 1, 240 APTTYPE_NA = 2, 241 APTTYPE_MAINSTA = 3 242 } 243 internal static ResetSecurity ResetSecurity_f; 244 internal static SetSecurity SetSecurity_f; 245 internal static BlessIWbemServices BlessIWbemServices_f; 246 internal static BlessIWbemServicesObject BlessIWbemServicesObject_f; 247 internal static GetPropertyHandle GetPropertyHandle_f27; 248 internal static WritePropertyValue WritePropertyValue_f28; 249 internal static GetQualifierSet GetQualifierSet_f; 250 internal static Get Get_f; 251 internal static Put Put_f; 252 internal static Delete Delete_f; 253 internal static GetNames GetNames_f; 254 internal static BeginEnumeration BeginEnumeration_f; 255 internal static Next Next_f; 256 internal static EndEnumeration EndEnumeration_f; 257 internal static GetPropertyQualifierSet GetPropertyQualifierSet_f; 258 internal static Clone Clone_f; 259 internal static GetObjectText GetObjectText_f; 260 internal static SpawnDerivedClass SpawnDerivedClass_f; 261 internal static SpawnInstance SpawnInstance_f; 262 internal static CompareTo CompareTo_f; 263 internal static GetPropertyOrigin GetPropertyOrigin_f; 264 internal static InheritsFrom InheritsFrom_f; 265 internal static GetMethod GetMethod_f; 266 internal static PutMethod PutMethod_f; 267 internal static DeleteMethod DeleteMethod_f; 268 internal static BeginMethodEnumeration BeginMethodEnumeration_f; 269 internal static NextMethod NextMethod_f; 270 internal static EndMethodEnumeration EndMethodEnumeration_f; 271 internal static GetMethodQualifierSet GetMethodQualifierSet_f; 272 internal static GetMethodOrigin GetMethodOrigin_f; 273 internal static QualifierSet_Get QualifierGet_f; 274 internal static QualifierSet_Put QualifierPut_f; 275 internal static QualifierSet_Delete QualifierDelete_f; 276 internal static QualifierSet_GetNames QualifierGetNames_f; 277 internal static QualifierSet_BeginEnumeration QualifierBeginEnumeration_f; 278 internal static QualifierSet_Next QualifierNext_f; 279 internal static QualifierSet_EndEnumeration QualifierEndEnumeration_f; 280 internal static GetCurrentApartmentType GetCurrentApartmentType_f; 281 internal static VerifyClientKey VerifyClientKey_f; 282 internal static Clone Clone_f12; 283 internal static GetDemultiplexedStub GetDemultiplexedStub_f; 284 internal static CreateInstanceEnumWmi CreateInstanceEnumWmi_f; 285 internal static CreateClassEnumWmi CreateClassEnumWmi_f; 286 internal static ExecQueryWmi ExecQueryWmi_f; 287 internal static ExecNotificationQueryWmi ExecNotificationQueryWmi_f; 288 internal static PutInstanceWmi PutInstanceWmi_f; 289 internal static PutClassWmi PutClassWmi_f; 290 internal static CloneEnumWbemClassObject CloneEnumWbemClassObject_f; 291 internal static ConnectServerWmi ConnectServerWmi_f; 292 internal static GetErrorInfo GetErrorInfo_f; 293 internal static Initialize Initialize_f; 294 WmiNetUtilsHelper()295 static WmiNetUtilsHelper() 296 { 297 RegistryKey netFrameworkSubKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework\"); 298 string netFrameworkInstallRoot = (string)netFrameworkSubKey?.GetValue("InstallRoot"); 299 300 if (netFrameworkInstallRoot == null) 301 { 302 // In some Windows versions, like Nano Server, the .Net Framework is not installed by default. 303 // It is possible that general failure to access the registry get to this code branch but it is 304 // very unlikely. 305 // Load PNSE delegates. This way it will throw PNSE when methods are used not when type is loaded. 306 LoadPlatformNotSupportedDelegates(SR.PlatformNotSupported_FullFrameworkRequired); 307 return; 308 } 309 310 string wminet_utilsPath = Path.Combine( 311 netFrameworkInstallRoot, 312 CompatSwitches.DotNetVersion, // The same value is hard coded on Environment.Version and quirks for WMI 313 "wminet_utils.dll"); 314 315 IntPtr hModule = Interop.Kernel32.LoadLibrary(wminet_utilsPath); 316 if (hModule == IntPtr.Zero) 317 { 318 // This is unlikely, so having the TypeInitializationException wrapping it is fine. 319 throw new Win32Exception(Marshal.GetLastWin32Error(), string.Format(SR.LoadLibraryFailed, wminet_utilsPath)); 320 } 321 322 if (LoadDelegate(ref ResetSecurity_f, hModule, "ResetSecurity") && 323 LoadDelegate(ref SetSecurity_f, hModule, "SetSecurity") && 324 LoadDelegate(ref BlessIWbemServices_f, hModule, "BlessIWbemServices") && 325 LoadDelegate(ref BlessIWbemServicesObject_f, hModule, "BlessIWbemServicesObject") && 326 LoadDelegate(ref GetPropertyHandle_f27, hModule, "GetPropertyHandle") && 327 LoadDelegate(ref WritePropertyValue_f28, hModule, "WritePropertyValue") && 328 LoadDelegate(ref Clone_f12, hModule, "Clone") && 329 LoadDelegate(ref VerifyClientKey_f, hModule, "VerifyClientKey") && 330 LoadDelegate(ref GetQualifierSet_f, hModule, "GetQualifierSet") && 331 LoadDelegate(ref Get_f, hModule, "Get") && 332 LoadDelegate(ref Put_f, hModule, "Put") && 333 LoadDelegate(ref Delete_f, hModule, "Delete") && 334 LoadDelegate(ref GetNames_f, hModule, "GetNames") && 335 LoadDelegate(ref BeginEnumeration_f, hModule, "BeginEnumeration") && 336 LoadDelegate(ref Next_f, hModule, "Next") && 337 LoadDelegate(ref EndEnumeration_f, hModule, "EndEnumeration") && 338 LoadDelegate(ref GetPropertyQualifierSet_f, hModule, "GetPropertyQualifierSet") && 339 LoadDelegate(ref Clone_f, hModule, "Clone") && 340 LoadDelegate(ref GetObjectText_f, hModule, "GetObjectText") && 341 LoadDelegate(ref SpawnDerivedClass_f, hModule, "SpawnDerivedClass") && 342 LoadDelegate(ref SpawnInstance_f, hModule, "SpawnInstance") && 343 LoadDelegate(ref CompareTo_f, hModule, "CompareTo") && 344 LoadDelegate(ref GetPropertyOrigin_f, hModule, "GetPropertyOrigin") && 345 LoadDelegate(ref InheritsFrom_f, hModule, "InheritsFrom") && 346 LoadDelegate(ref GetMethod_f, hModule, "GetMethod") && 347 LoadDelegate(ref PutMethod_f, hModule, "PutMethod") && 348 LoadDelegate(ref DeleteMethod_f, hModule, "DeleteMethod") && 349 LoadDelegate(ref BeginMethodEnumeration_f, hModule, "BeginMethodEnumeration") && 350 LoadDelegate(ref NextMethod_f, hModule, "NextMethod") && 351 LoadDelegate(ref EndMethodEnumeration_f, hModule, "EndMethodEnumeration") && 352 LoadDelegate(ref GetMethodQualifierSet_f, hModule, "GetMethodQualifierSet") && 353 LoadDelegate(ref GetMethodOrigin_f, hModule, "GetMethodOrigin") && 354 LoadDelegate(ref QualifierGet_f, hModule, "QualifierSet_Get") && 355 LoadDelegate(ref QualifierPut_f, hModule, "QualifierSet_Put") && 356 LoadDelegate(ref QualifierDelete_f, hModule, "QualifierSet_Delete") && 357 LoadDelegate(ref QualifierGetNames_f, hModule, "QualifierSet_GetNames") && 358 LoadDelegate(ref QualifierBeginEnumeration_f, hModule, "QualifierSet_BeginEnumeration") && 359 LoadDelegate(ref QualifierNext_f, hModule, "QualifierSet_Next") && 360 LoadDelegate(ref QualifierEndEnumeration_f, hModule, "QualifierSet_EndEnumeration") && 361 LoadDelegate(ref GetCurrentApartmentType_f, hModule, "GetCurrentApartmentType") && 362 LoadDelegate(ref GetDemultiplexedStub_f, hModule, "GetDemultiplexedStub") && 363 LoadDelegate(ref CreateInstanceEnumWmi_f, hModule, "CreateInstanceEnumWmi") && 364 LoadDelegate(ref CreateClassEnumWmi_f, hModule, "CreateClassEnumWmi") && 365 LoadDelegate(ref ExecQueryWmi_f, hModule, "ExecQueryWmi") && 366 LoadDelegate(ref ExecNotificationQueryWmi_f, hModule, "ExecNotificationQueryWmi") && 367 LoadDelegate(ref PutInstanceWmi_f, hModule, "PutInstanceWmi") && 368 LoadDelegate(ref PutClassWmi_f, hModule, "PutClassWmi") && 369 LoadDelegate(ref CloneEnumWbemClassObject_f, hModule, "CloneEnumWbemClassObject") && 370 LoadDelegate(ref ConnectServerWmi_f, hModule, "ConnectServerWmi") && 371 LoadDelegate(ref GetErrorInfo_f, hModule, "GetErrorInfo") && 372 LoadDelegate(ref Initialize_f, hModule, "Initialize")) 373 { 374 // All required delegates were loaded. 375 Initialize_f(CompatSwitches.AllowIManagementObjectQI); 376 } 377 else 378 { 379 LoadPlatformNotSupportedDelegates(string.Format(SR.PlatformNotSupported_FrameworkUpdatedRequired, wminet_utilsPath)); 380 } 381 } 382 static bool LoadDelegate<TDelegate>(ref TDelegate delegate_f, IntPtr hModule, string procName) where TDelegate : class 383 { 384 IntPtr procAddr = Interop.Kernel32.GetProcAddress(hModule, procName); 385 return procAddr != null && 386 (delegate_f = Marshal.GetDelegateForFunctionPointer<TDelegate>(procAddr)) != null; 387 } 388 LoadPlatformNotSupportedDelegates(string exceptionMessage)389 static void LoadPlatformNotSupportedDelegates(string exceptionMessage) 390 { 391 ResetSecurity_f = (_) => throw new PlatformNotSupportedException(exceptionMessage); 392 SetSecurity_f = (ref bool _, ref IntPtr __) => throw new PlatformNotSupportedException(exceptionMessage); 393 BlessIWbemServices_f = (_, __, ___, ____, _____, ______) => throw new PlatformNotSupportedException(exceptionMessage); 394 BlessIWbemServicesObject_f = (_, __, ___, ____, _____, ______) => throw new PlatformNotSupportedException(exceptionMessage); 395 GetPropertyHandle_f27 = (int _, IntPtr __, string ___, out int ____, out int _____) => throw new PlatformNotSupportedException(exceptionMessage); 396 WritePropertyValue_f28 = (_, __, ___, ____, _____) => throw new PlatformNotSupportedException(exceptionMessage); 397 Clone_f12 = (int _, IntPtr __, out IntPtr ___) => throw new PlatformNotSupportedException(exceptionMessage); 398 VerifyClientKey_f = () => throw new PlatformNotSupportedException(exceptionMessage); 399 GetQualifierSet_f = (int _, IntPtr __, out IntPtr ___) => throw new PlatformNotSupportedException(exceptionMessage); 400 Get_f = (int _, IntPtr __, string ___, int ____, ref object _____, ref int ______, ref int _______) => throw new PlatformNotSupportedException(exceptionMessage); 401 Put_f = (int _, IntPtr __, string ___, int ____, ref object _____, int ______) => throw new PlatformNotSupportedException(exceptionMessage); 402 Delete_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 403 GetNames_f = (int _, IntPtr __, string ___, int ____, ref object _____, out string[] ______) => throw new PlatformNotSupportedException(exceptionMessage); 404 BeginEnumeration_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 405 Next_f = (int _, IntPtr __, int ___, ref string ____, ref object _____, ref int ______, ref int _______) => throw new PlatformNotSupportedException(exceptionMessage); 406 EndEnumeration_f = (_, __) => throw new PlatformNotSupportedException(exceptionMessage); 407 GetPropertyQualifierSet_f = (int _, IntPtr __, string ___, out IntPtr ____) => throw new PlatformNotSupportedException(exceptionMessage); 408 Clone_f = (int _, IntPtr __, out IntPtr ___) => throw new PlatformNotSupportedException(exceptionMessage); 409 GetObjectText_f = (int _, IntPtr __, int ___, out string ____) => throw new PlatformNotSupportedException(exceptionMessage); 410 SpawnDerivedClass_f = (int _, IntPtr __, int ___, out IntPtr ____) => throw new PlatformNotSupportedException(exceptionMessage); 411 SpawnInstance_f = (int _, IntPtr __, int ___, out IntPtr ____) => throw new PlatformNotSupportedException(exceptionMessage); 412 CompareTo_f = (_, __, ___, ____) => throw new PlatformNotSupportedException(exceptionMessage); 413 GetPropertyOrigin_f = (int _, IntPtr __, string ___, out string ____) => throw new PlatformNotSupportedException(exceptionMessage); 414 InheritsFrom_f = (int _, IntPtr __, string ___) => throw new PlatformNotSupportedException(exceptionMessage); 415 GetMethod_f = (int _, IntPtr __, string ___, int ____, out IntPtr _____, out IntPtr ______) => throw new PlatformNotSupportedException(exceptionMessage); 416 PutMethod_f = (_, __, ___, ____, _____, ______) => throw new PlatformNotSupportedException(exceptionMessage); 417 DeleteMethod_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 418 BeginMethodEnumeration_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 419 NextMethod_f = (int _, IntPtr __, int ___, out string ____, out IntPtr _____, out IntPtr ______) => throw new PlatformNotSupportedException(exceptionMessage); 420 EndMethodEnumeration_f = (_, __) => throw new PlatformNotSupportedException(exceptionMessage); 421 GetMethodQualifierSet_f = (int _, IntPtr __, string ___, out IntPtr ____) => throw new PlatformNotSupportedException(exceptionMessage); 422 GetMethodOrigin_f = (int _, IntPtr __, string ___, out string ____) => throw new PlatformNotSupportedException(exceptionMessage); 423 QualifierGet_f = (int _, IntPtr __, string ___, int ____, ref object _____, ref int ______) => throw new PlatformNotSupportedException(exceptionMessage); 424 QualifierPut_f = (int _, IntPtr __, string ___, ref object ____, int _____) => throw new PlatformNotSupportedException(exceptionMessage); 425 QualifierDelete_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 426 QualifierGetNames_f = (int _, IntPtr __, int ___, out string[] ____) => throw new PlatformNotSupportedException(exceptionMessage); 427 QualifierBeginEnumeration_f = (_, __, ___) => throw new PlatformNotSupportedException(exceptionMessage); 428 QualifierNext_f = (int _, IntPtr __, int ___, out string ____, out object _____, out int ______) => throw new PlatformNotSupportedException(exceptionMessage); 429 QualifierEndEnumeration_f = (_, __) => throw new PlatformNotSupportedException(exceptionMessage); 430 GetCurrentApartmentType_f = (int _, IntPtr __, out APTTYPE ___) => throw new PlatformNotSupportedException(exceptionMessage); 431 GetDemultiplexedStub_f = (object _, bool __, out object ___) => throw new PlatformNotSupportedException(exceptionMessage); 432 CreateInstanceEnumWmi_f = (string _, int __, IWbemContext ___, out IEnumWbemClassObject ____, int _____, int ______, IWbemServices _______, string ________, IntPtr _________, string __________) => throw new PlatformNotSupportedException(exceptionMessage); 433 CreateClassEnumWmi_f = (string _, int __, IWbemContext ___, out IEnumWbemClassObject ____, int _____, int ______, IWbemServices _______, string ________, IntPtr _________, string __________) => throw new PlatformNotSupportedException(exceptionMessage); 434 ExecQueryWmi_f = (string _, string __, int ___, IWbemContext ____, out IEnumWbemClassObject _____, int ______, int _______, IWbemServices ________, string _________, IntPtr __________, string ___________) => throw new PlatformNotSupportedException(exceptionMessage); 435 ExecNotificationQueryWmi_f = (string _, string __, int ___, IWbemContext ____, out IEnumWbemClassObject _____, int ______, int _______, IWbemServices ________, string _________, IntPtr __________, string ___________) => throw new PlatformNotSupportedException(exceptionMessage); 436 PutInstanceWmi_f = (_, __, ___, ____, _____, ______, _______, ________, _________, __________) => throw new PlatformNotSupportedException(exceptionMessage); 437 PutClassWmi_f = (_, __, ___, ____, _____, ______, _______, ________, _________, __________) => throw new PlatformNotSupportedException(exceptionMessage); 438 CloneEnumWbemClassObject_f = (out IEnumWbemClassObject _, int __, int ____, IEnumWbemClassObject _____, string ______, IntPtr _______, string ________) => throw new PlatformNotSupportedException(exceptionMessage); 439 ConnectServerWmi_f = (string _, string __, IntPtr ___, string ____, int _____, string ______, IWbemContext _______, out IWbemServices ________, int _________, int __________) => throw new PlatformNotSupportedException(exceptionMessage); 440 GetErrorInfo_f = () => throw new PlatformNotSupportedException(exceptionMessage); 441 Initialize_f = (_) => throw new PlatformNotSupportedException(exceptionMessage); 442 } 443 } 444 445 /// <summary> 446 /// <para>Represents a scope for management operations. In v1.0 the scope defines the WMI namespace in which management operations are performed.</para> 447 /// </summary> 448 /// <example> 449 /// <code lang='C#'>using System; 450 /// using System.Management; 451 /// 452 /// // This sample demonstrates how to connect to root/default namespace 453 /// // using ManagmentScope object. 454 /// class Sample_ManagementScope 455 /// { 456 /// public static int Main(string[] args) 457 /// { 458 /// ManagementScope scope = new ManagementScope("root\\default"); 459 /// scope.Connect(); 460 /// ManagementClass newClass = new ManagementClass( 461 /// scope, 462 /// new ManagementPath(), 463 /// null); 464 /// return 0; 465 /// } 466 /// } 467 /// </code> 468 /// <code lang='VB'>Imports System 469 /// Imports System.Management 470 /// 471 /// ' This sample demonstrates how to connect to root/default namespace 472 /// ' using ManagmentScope object. 473 /// Class Sample_ManagementScope 474 /// Overloads Public Shared Function Main(args() As String) As Integer 475 /// Dim scope As New ManagementScope("root\default") 476 /// scope.Connect() 477 /// Dim newClass As New ManagementClass(scope, _ 478 /// New ManagementPath(), _ 479 /// Nothing) 480 /// Return 0 481 /// End Function 482 /// End Class 483 /// </code> 484 /// </example> 485 [TypeConverter(typeof(ManagementScopeConverter))] 486 public class ManagementScope : ICloneable 487 { 488 private ManagementPath validatedPath; 489 private IWbemServices wbemServices; 490 private ConnectionOptions options; 491 internal event IdentifierChangedEventHandler IdentifierChanged; 492 internal bool IsDefaulted; //used to tell whether the current scope has been created from the default 493 //scope or not - this information is used to tell whether it can be overridden 494 //when a new path is set or not. 495 496 //Fires IdentifierChanged event FireIdentifierChanged()497 private void FireIdentifierChanged() 498 { 499 if (IdentifierChanged != null) 500 IdentifierChanged(this,null); 501 } 502 503 //Called when IdentifierChanged() event fires HandleIdentifierChange(object sender, IdentifierChangedEventArgs args)504 private void HandleIdentifierChange(object sender, 505 IdentifierChangedEventArgs args) 506 { 507 // Since our object has changed we had better signal to ourself that 508 // an connection needs to be established 509 wbemServices = null; 510 511 //Something inside ManagementScope changed, we need to fire an event 512 //to the parent object 513 FireIdentifierChanged(); 514 } 515 516 // Private path property accessor which performs minimal validation on the 517 // namespace path. IWbemPath cannot differentiate between a class or a name- 518 // space if path separators are not present in the path. Therefore, IWbemPath 519 // will allow a namespace of "rootBeer" vs "root". Since it is established 520 // that the scope path is indeed a namespace path, we perform this validation. 521 private ManagementPath prvpath 522 { 523 get 524 { 525 return validatedPath; 526 } 527 set 528 { 529 if (value != null) 530 { 531 string pathValue = value.Path; 532 if (!ManagementPath.IsValidNamespaceSyntax(pathValue)) 533 ManagementException.ThrowWithExtendedInfo((ManagementStatus)tag_WBEMSTATUS.WBEM_E_INVALID_NAMESPACE); 534 } 535 536 validatedPath = value; 537 } 538 } 539 GetIWbemServices()540 internal IWbemServices GetIWbemServices () 541 { 542 IWbemServices localCopy = wbemServices; 543 //IWbemServices is always created in MTA context. Only if call is made through non MTA context we need to use IWbemServices in right context. 544 // Lets start by assuming that we'll return the RCW that we already have. When WMINet_Utils.dll wraps the real COM proxy, credentials don't get 545 // lost when the CLR marshals the wrapped object to a different COM apartment. The wrap was added to prevent marshalling of IManagedObject from native 546 // to managed code. 547 548 if (CompatSwitches.AllowIManagementObjectQI) 549 { 550 // Get an IUnknown for this apartment 551 IntPtr pUnk = Marshal.GetIUnknownForObject(wbemServices); 552 553 // Get an 'IUnknown RCW' for this apartment 554 Object unknown = Marshal.GetObjectForIUnknown(pUnk); 555 556 // Release the ref count on the IUnknwon 557 Marshal.Release(pUnk); 558 559 // See if we are in the same apartment as where the original IWbemServices lived 560 // If we are in a different apartment, give the caller an RCW generated just for their 561 // apartment, and set the proxy blanket appropriately 562 if(!object.ReferenceEquals(unknown, wbemServices)) 563 { 564 // We need to set the proxy blanket on 'unknown' or else the QI for IWbemServices may 565 // fail if we are running under a local user account. The QI has to be done by 566 // someone who is a member of the 'Everyone' group on the target machine, or DCOM 567 // won't let the call through. 568 SecurityHandler securityHandler = GetSecurityHandler (); 569 securityHandler.SecureIUnknown(unknown); 570 571 // Now, we can QI and secure the IWbemServices 572 localCopy = (IWbemServices)unknown; 573 574 // We still need to bless the IWbemServices in this apartment 575 securityHandler.Secure(localCopy); 576 } 577 } 578 579 return localCopy; // STRANGE: Why does it still work if I return 'wbemServices'? 580 } 581 582 /// <summary> 583 /// <para> Gets or sets a value indicating whether the <see cref='System.Management.ManagementScope'/> is currently bound to a 584 /// WMI server and namespace.</para> 585 /// </summary> 586 /// <value> 587 /// <para><see langword='true'/> if a connection is alive (bound 588 /// to a server and namespace); otherwise, <see langword='false'/>.</para> 589 /// </value> 590 /// <remarks> 591 /// <para> A scope is disconnected after creation until someone 592 /// explicitly calls <see cref='System.Management.ManagementScope.Connect'/>(), or uses the scope for any 593 /// operation that requires a live connection. Also, the scope is 594 /// disconnected from the previous connection whenever the identifying properties of the scope are 595 /// changed.</para> 596 /// </remarks> 597 public bool IsConnected 598 { 599 get 600 { 601 return (null != wbemServices); 602 } 603 } 604 605 //Internal constructor ManagementScope(ManagementPath path, IWbemServices wbemServices, ConnectionOptions options)606 internal ManagementScope (ManagementPath path, IWbemServices wbemServices, 607 ConnectionOptions options) 608 { 609 if (null != path) 610 this.Path = path; 611 612 if (null != options) { 613 this.Options = options; 614 } 615 616 // We set this.wbemServices after setting Path and Options 617 // because the latter operations can cause wbemServices to be NULLed. 618 this.wbemServices = wbemServices; 619 } 620 ManagementScope(ManagementPath path, ManagementScope scope)621 internal ManagementScope (ManagementPath path, ManagementScope scope) 622 : this (path, (null != scope) ? scope.options : null) {} 623 _Clone(ManagementScope scope)624 internal static ManagementScope _Clone(ManagementScope scope) 625 { 626 return ManagementScope._Clone(scope, null); 627 } 628 _Clone(ManagementScope scope, IdentifierChangedEventHandler handler)629 internal static ManagementScope _Clone(ManagementScope scope, IdentifierChangedEventHandler handler) 630 { 631 ManagementScope scopeTmp = new ManagementScope(null, null, null); 632 633 // Wire up change handler chain. Use supplied handler, if specified; 634 // otherwise, default to that of the scope argument. 635 if (handler != null) 636 scopeTmp.IdentifierChanged = handler; 637 else if (scope != null) 638 scopeTmp.IdentifierChanged = new IdentifierChangedEventHandler(scope.HandleIdentifierChange); 639 640 // Set scope path. 641 if (scope == null) 642 { 643 // No path specified. Default. 644 scopeTmp.prvpath = ManagementPath._Clone(ManagementPath.DefaultPath, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); 645 scopeTmp.IsDefaulted = true; 646 647 scopeTmp.wbemServices = null; 648 scopeTmp.options = null; 649 } 650 else 651 { 652 if (scope.prvpath == null) 653 { 654 // No path specified. Default. 655 scopeTmp.prvpath = ManagementPath._Clone(ManagementPath.DefaultPath, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); 656 scopeTmp.IsDefaulted = true; 657 } 658 else 659 { 660 // Use scope-supplied path. 661 scopeTmp.prvpath = ManagementPath._Clone(scope.prvpath, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); 662 scopeTmp.IsDefaulted = scope.IsDefaulted; 663 } 664 665 scopeTmp.wbemServices = scope.wbemServices; 666 if (scope.options != null) 667 scopeTmp.options = ConnectionOptions._Clone(scope.options, new IdentifierChangedEventHandler(scopeTmp.HandleIdentifierChange)); 668 } 669 670 return scopeTmp; 671 } 672 673 //Default constructor 674 /// <overload> 675 /// Initializes a new instance 676 /// of the <see cref='System.Management.ManagementScope'/> class. 677 /// </overload> 678 /// <summary> 679 /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class, with default values. This is the 680 /// default constructor.</para> 681 /// </summary> 682 /// <remarks> 683 /// <para> If the object doesn't have any 684 /// properties set before connection, it will be initialized with default values 685 /// (for example, the local machine and the root\cimv2 namespace).</para> 686 /// </remarks> 687 /// <example> 688 /// <code lang='C#'>ManagementScope s = new ManagementScope(); 689 /// </code> 690 /// <code lang='VB'>Dim s As New ManagementScope() 691 /// </code> 692 /// </example> ManagementScope()693 public ManagementScope () : 694 this (new ManagementPath (ManagementPath.DefaultPath.Path)) 695 { 696 //Flag that this scope uses the default path 697 IsDefaulted = true; 698 } 699 700 //Parameterized constructors 701 /// <summary> 702 /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing 703 /// the specified scope path.</para> 704 /// </summary> 705 /// <param name='path'>A <see cref='System.Management.ManagementPath'/> containing the path to a server and namespace for the <see cref='System.Management.ManagementScope'/>.</param> 706 /// <example> 707 /// <code lang='C#'>ManagementScope s = new ManagementScope(new ManagementPath("\\\\MyServer\\root\\default")); 708 /// </code> 709 /// <code lang='VB'>Dim p As New ManagementPath("\\MyServer\root\default") 710 /// Dim s As New ManagementScope(p) 711 /// </code> 712 /// </example> ManagementScope(ManagementPath path)713 public ManagementScope (ManagementPath path) : this(path, (ConnectionOptions)null) {} 714 715 /// <summary> 716 /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope 717 /// path.</para> 718 /// </summary> 719 /// <param name='path'>The server and namespace path for the <see cref='System.Management.ManagementScope'/>.</param> 720 /// <example> 721 /// <code lang='C#'>ManagementScope s = new ManagementScope("\\\\MyServer\\root\\default"); 722 /// </code> 723 /// <code lang='VB'>Dim s As New ManagementScope("\\MyServer\root\default") 724 /// </code> 725 /// </example> ManagementScope(string path)726 public ManagementScope (string path) : this(new ManagementPath(path), (ConnectionOptions)null) {} 727 /// <summary> 728 /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope path, 729 /// with the specified options.</para> 730 /// </summary> 731 /// <param name='path'>The server and namespace for the <see cref='System.Management.ManagementScope'/>.</param> 732 /// <param name=' options'>A <see cref='System.Management.ConnectionOptions'/> containing options for the connection.</param> 733 /// <example> 734 /// <code lang='C#'>ConnectionOptions opt = new ConnectionOptions(); 735 /// opt.Username = "Me"; 736 /// opt.Password = "MyPassword"; 737 /// ManagementScope s = new ManagementScope("\\\\MyServer\\root\\default", opt); 738 /// </code> 739 /// <code lang='VB'>Dim opt As New ConnectionOptions() 740 /// opt.Username = "Me" 741 /// opt.Password = "MyPassword" 742 /// Dim s As New ManagementScope("\\MyServer\root\default", opt); 743 /// </code> 744 /// </example> ManagementScope(string path, ConnectionOptions options)745 public ManagementScope (string path, ConnectionOptions options) : this (new ManagementPath(path), options) {} 746 747 /// <summary> 748 /// <para>Initializes a new instance of the <see cref='System.Management.ManagementScope'/> class representing the specified scope path, 749 /// with the specified options.</para> 750 /// </summary> 751 /// <param name='path'>A <see cref='System.Management.ManagementPath'/> containing the path to the server and namespace for the <see cref='System.Management.ManagementScope'/>.</param> 752 /// <param name=' options'>The <see cref='System.Management.ConnectionOptions'/> containing options for the connection.</param> 753 /// <example> 754 /// <code lang='C#'>ConnectionOptions opt = new ConnectionOptions(); 755 /// opt.Username = "Me"; 756 /// opt.Password = "MyPassword"; 757 /// 758 /// ManagementPath p = new ManagementPath("\\\\MyServer\\root\\default"); 759 /// ManagementScope = new ManagementScope(p, opt); 760 /// </code> 761 /// <code lang='VB'>Dim opt As New ConnectionOptions() 762 /// opt.UserName = "Me" 763 /// opt.Password = "MyPassword" 764 /// 765 /// Dim p As New ManagementPath("\\MyServer\root\default") 766 /// Dim s As New ManagementScope(p, opt) 767 /// </code> 768 /// </example> ManagementScope(ManagementPath path, ConnectionOptions options)769 public ManagementScope (ManagementPath path, ConnectionOptions options) 770 { 771 if (null != path) 772 this.prvpath = ManagementPath._Clone(path, new IdentifierChangedEventHandler(HandleIdentifierChange)); 773 else 774 this.prvpath = ManagementPath._Clone(null); 775 776 if (null != options) 777 { 778 this.options = ConnectionOptions._Clone(options, new IdentifierChangedEventHandler(HandleIdentifierChange)); 779 } 780 else 781 this.options = null; 782 783 IsDefaulted = false; //assume that this scope is not initialized by the default path 784 } 785 786 /// <summary> 787 /// <para> Gets or sets options for making the WMI connection.</para> 788 /// </summary> 789 /// <value> 790 /// <para>The valid <see cref='System.Management.ConnectionOptions'/> 791 /// containing options for the WMI connection.</para> 792 /// </value> 793 /// <example> 794 /// <code lang='C#'>//This constructor creates a scope object with default options 795 /// ManagementScope s = new ManagementScope("root\\MyApp"); 796 /// 797 /// //Change default connection options - 798 /// //In this example, set the system privileges to enabled for operations that require system privileges. 799 /// s.Options.EnablePrivileges = true; 800 /// </code> 801 /// <code lang='VB'>'This constructor creates a scope object with default options 802 /// Dim s As New ManagementScope("root\\MyApp") 803 /// 804 /// 'Change default connection options - 805 /// 'In this example, set the system privileges to enabled for operations that require system privileges. 806 /// s.Options.EnablePrivileges = True 807 /// </code> 808 /// </example> 809 public ConnectionOptions Options 810 { 811 get 812 { 813 if (options == null) 814 return options = ConnectionOptions._Clone(null, new IdentifierChangedEventHandler(HandleIdentifierChange)); 815 else 816 return options; 817 } 818 set 819 { 820 if (null != value) 821 { 822 if (null != options) 823 options.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); 824 825 options = ConnectionOptions._Clone((ConnectionOptions)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); 826 827 //the options property has changed so act like we fired the event 828 HandleIdentifierChange(this,null); 829 } 830 else 831 throw new ArgumentNullException ("value"); 832 } 833 } 834 835 /// <summary> 836 /// <para>Gets or sets the path for the <see cref='System.Management.ManagementScope'/>.</para> 837 /// </summary> 838 /// <value> 839 /// <para> A <see cref='System.Management.ManagementPath'/> containing 840 /// the path to a server and namespace.</para> 841 /// </value> 842 /// <example> 843 /// <code lang='C#'>ManagementScope s = new ManagementScope(); 844 /// s.Path = new ManagementPath("root\\MyApp"); 845 /// </code> 846 /// <code lang='VB'>Dim s As New ManagementScope() 847 /// s.Path = New ManagementPath("root\MyApp") 848 /// </code> 849 /// </example> 850 public ManagementPath Path 851 { 852 get 853 { 854 if (prvpath == null) 855 return prvpath = ManagementPath._Clone(null); 856 else 857 return prvpath; 858 } 859 set 860 { 861 if (null != value) 862 { 863 if (null != prvpath) 864 prvpath.IdentifierChanged -= new IdentifierChangedEventHandler(HandleIdentifierChange); 865 866 IsDefaulted = false; //someone is specifically setting the scope path so it's not defaulted any more 867 868 prvpath = ManagementPath._Clone((ManagementPath)value, new IdentifierChangedEventHandler(HandleIdentifierChange)); 869 870 //the path property has changed so act like we fired the event 871 HandleIdentifierChange(this,null); 872 } 873 else 874 throw new ArgumentNullException ("value"); 875 } 876 } 877 878 /// <summary> 879 /// <para>Returns a copy of the object.</para> 880 /// </summary> 881 /// <returns> 882 /// <para>A new copy of the <see cref='System.Management.ManagementScope'/>.</para> 883 /// </returns> Clone()884 public ManagementScope Clone() 885 { 886 return ManagementScope._Clone(this); 887 } 888 889 /// <summary> 890 /// <para>Clone a copy of this object.</para> 891 /// </summary> 892 /// <returns> 893 /// A new copy of this object. 894 /// object. 895 /// </returns> ICloneable.Clone()896 Object ICloneable.Clone() 897 { 898 return Clone(); 899 } 900 901 /// <summary> 902 /// <para>Connects this <see cref='System.Management.ManagementScope'/> to the actual WMI 903 /// scope.</para> 904 /// </summary> 905 /// <remarks> 906 /// <para>This method is called implicitly when the 907 /// scope is used in an operation that requires it to be connected. Calling it 908 /// explicitly allows the user to control the time of connection.</para> 909 /// </remarks> 910 /// <example> 911 /// <code lang='C#'>ManagementScope s = new ManagementScope("root\\MyApp"); 912 /// 913 /// //Explicit call to connect the scope object to the WMI namespace 914 /// s.Connect(); 915 /// 916 /// //The following doesn't do any implicit scope connections because s is already connected. 917 /// ManagementObject o = new ManagementObject(s, "Win32_LogicalDisk='C:'", null); 918 /// </code> 919 /// <code lang='VB'>Dim s As New ManagementScope("root\\MyApp") 920 /// 921 /// 'Explicit call to connect the scope object to the WMI namespace 922 /// s.Connect() 923 /// 924 /// 'The following doesn't do any implicit scope connections because s is already connected. 925 /// Dim o As New ManagementObject(s, "Win32_LogicalDisk=""C:""", null) 926 /// </code> 927 /// </example> Connect()928 public void Connect () 929 { 930 Initialize (); 931 } 932 Initialize()933 internal void Initialize () 934 { 935 //If the path is not set yet we can't do it 936 if (null == prvpath) 937 throw new InvalidOperationException(); 938 939 940 /* 941 * If we're not connected yet, this is the time to do it... We lock 942 * the state to prevent 2 threads simultaneously doing the same 943 * connection. To avoid taking the lock unnecessarily we examine 944 * isConnected first 945 */ 946 if (!IsConnected) 947 { 948 #pragma warning disable CA2002 949 lock (this) 950 #pragma warning restore CA2002 951 { 952 if (!IsConnected) 953 { 954 // The locator cannot be marshalled accross apartments, so we must create the locator 955 // and get the IWbemServices from an MTA thread 956 if(!MTAHelper.IsNoContextMTA()) 957 { 958 // 959 // Ensure we are able to trap exceptions from worker thread. 960 // 961 ThreadDispatch disp = new ThreadDispatch ( new ThreadDispatch.ThreadWorkerMethodWithParam ( InitializeGuts ) ) ; 962 disp.Parameter = this ; 963 disp.Start ( ) ; 964 } 965 else 966 InitializeGuts(this); 967 } 968 } 969 } 970 } 971 InitializeGuts(object o)972 void InitializeGuts(object o) 973 { 974 ManagementScope threadParam = (ManagementScope) o ; 975 IWbemLocator loc = (IWbemLocator) new WbemLocator(); 976 IntPtr punk = IntPtr.Zero; 977 978 if (null == threadParam.options) 979 { 980 threadParam.Options = new ConnectionOptions(); 981 } 982 983 string nsPath = threadParam.prvpath.GetNamespacePath((int)tag_WBEM_GET_TEXT_FLAGS.WBEMPATH_GET_SERVER_AND_NAMESPACE_ONLY); 984 985 // If no namespace specified, fill in the default one 986 if ((null == nsPath) || (0 == nsPath.Length)) 987 { 988 // NB: we use a special method to set the namespace 989 // path here as we do NOT want to trigger an 990 // IdentifierChanged event as a result of this set 991 992 bool bUnused; 993 nsPath = threadParam.prvpath.SetNamespacePath(ManagementPath.DefaultPath.Path, out bUnused); 994 } 995 996 int status = (int)ManagementStatus.NoError; 997 threadParam.wbemServices = null; 998 999 //If we're on XP or higher, always use the "max_wait" flag to avoid hanging 1000 if (Environment.OSVersion.Platform == PlatformID.Win32NT) 1001 { 1002 1003 if( ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1)) || (Environment.OSVersion.Version.Major >= 6) ) 1004 { 1005 threadParam.options.Flags |= (int)tag_WBEM_CONNECT_OPTIONS.WBEM_FLAG_CONNECT_USE_MAX_WAIT; 1006 } 1007 } 1008 1009 try 1010 { 1011 status = GetSecuredConnectHandler().ConnectNSecureIWbemServices(nsPath, ref threadParam.wbemServices); 1012 } 1013 catch (COMException e) 1014 { 1015 ManagementException.ThrowWithExtendedInfo (e); 1016 } 1017 1018 if ((status & 0xfffff000) == 0x80041000) 1019 { 1020 ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); 1021 } 1022 else if ((status & 0x80000000) != 0) 1023 { 1024 Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); 1025 } 1026 } 1027 GetSecurityHandler()1028 internal SecurityHandler GetSecurityHandler () 1029 { 1030 return new SecurityHandler(this); 1031 } GetSecuredConnectHandler()1032 internal SecuredConnectHandler GetSecuredConnectHandler () 1033 { 1034 return new SecuredConnectHandler(this); 1035 } GetSecuredIEnumWbemClassObjectHandler(IEnumWbemClassObject pEnumWbemClassObject)1036 internal SecuredIEnumWbemClassObjectHandler GetSecuredIEnumWbemClassObjectHandler (IEnumWbemClassObject pEnumWbemClassObject) 1037 { 1038 return new SecuredIEnumWbemClassObjectHandler (this, pEnumWbemClassObject); 1039 } GetSecuredIWbemServicesHandler( IWbemServices pWbemServiecs)1040 internal SecuredIWbemServicesHandler GetSecuredIWbemServicesHandler( IWbemServices pWbemServiecs) 1041 { 1042 return new SecuredIWbemServicesHandler(this, pWbemServiecs); 1043 } 1044 1045 }//ManagementScope 1046 1047 internal class SecuredIEnumWbemClassObjectHandler 1048 { 1049 private IEnumWbemClassObject pEnumWbemClassObjectsecurityHelper; 1050 private ManagementScope scope; SecuredIEnumWbemClassObjectHandler(ManagementScope theScope, IEnumWbemClassObject pEnumWbemClassObject)1051 internal SecuredIEnumWbemClassObjectHandler (ManagementScope theScope, IEnumWbemClassObject pEnumWbemClassObject) 1052 { 1053 this.scope = theScope; 1054 pEnumWbemClassObjectsecurityHelper = pEnumWbemClassObject; 1055 } Reset_()1056 internal int Reset_() 1057 { 1058 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1059 status = pEnumWbemClassObjectsecurityHelper.Reset_(); 1060 return status; 1061 } Next_( int lTimeout, uint uCount, IWbemClassObject_DoNotMarshal[] ppOutParams, ref uint puReturned)1062 internal int Next_( int lTimeout, uint uCount, IWbemClassObject_DoNotMarshal[] ppOutParams, ref uint puReturned) 1063 { 1064 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1065 status = pEnumWbemClassObjectsecurityHelper.Next_( lTimeout, uCount, ppOutParams, out puReturned); 1066 return status; 1067 } NextAsync_( uint uCount, IWbemObjectSink pSink)1068 internal int NextAsync_( uint uCount, IWbemObjectSink pSink) 1069 { 1070 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1071 status = pEnumWbemClassObjectsecurityHelper.NextAsync_(uCount, pSink); 1072 return status; 1073 } Clone_(ref IEnumWbemClassObject ppEnum)1074 internal int Clone_(ref IEnumWbemClassObject ppEnum) 1075 { 1076 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1077 if( null != scope) 1078 { 1079 IntPtr password = scope.Options.GetPassword(); 1080 status = WmiNetUtilsHelper.CloneEnumWbemClassObject_f( 1081 out ppEnum, 1082 (int)scope.Options.Authentication, 1083 (int)scope.Options.Impersonation, 1084 pEnumWbemClassObjectsecurityHelper, 1085 scope.Options.Username, 1086 password, 1087 scope.Options.Authority); 1088 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1089 } 1090 return status; 1091 } Skip_( int lTimeout, uint nCount)1092 internal int Skip_( int lTimeout, uint nCount) 1093 { 1094 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1095 status = pEnumWbemClassObjectsecurityHelper.Skip_(lTimeout, nCount); 1096 return status; 1097 } 1098 } 1099 1100 1101 internal class SecuredConnectHandler 1102 { 1103 private ManagementScope scope; 1104 SecuredConnectHandler(ManagementScope theScope)1105 internal SecuredConnectHandler (ManagementScope theScope) 1106 { 1107 this.scope = theScope; 1108 } ConnectNSecureIWbemServices(string path, ref IWbemServices pServices)1109 internal int ConnectNSecureIWbemServices(string path, ref IWbemServices pServices) 1110 { 1111 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1112 if( null != scope ) 1113 { 1114 bool needToReset = false; 1115 IntPtr handle = IntPtr.Zero; 1116 1117 try 1118 { 1119 if (scope.Options.EnablePrivileges && !CompatSwitches.AllowIManagementObjectQI) 1120 { 1121 WmiNetUtilsHelper.SetSecurity_f(ref needToReset, ref handle); 1122 } 1123 1124 IntPtr password = scope.Options.GetPassword(); 1125 status = WmiNetUtilsHelper.ConnectServerWmi_f( 1126 path, 1127 scope.Options.Username, 1128 password, 1129 scope.Options.Locale, 1130 scope.Options.Flags, 1131 scope.Options.Authority, 1132 scope.Options.GetContext(), 1133 out pServices, 1134 (int)scope.Options.Impersonation, 1135 (int)scope.Options.Authentication); 1136 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1137 } 1138 finally 1139 { 1140 if (needToReset) 1141 { 1142 needToReset = false; 1143 WmiNetUtilsHelper.ResetSecurity_f(handle); 1144 } 1145 } 1146 } 1147 return status; 1148 } 1149 } 1150 1151 internal class SecuredIWbemServicesHandler 1152 { 1153 private IWbemServices pWbemServiecsSecurityHelper; 1154 private ManagementScope scope; SecuredIWbemServicesHandler(ManagementScope theScope, IWbemServices pWbemServiecs)1155 internal SecuredIWbemServicesHandler (ManagementScope theScope, IWbemServices pWbemServiecs) 1156 { 1157 this.scope = theScope; 1158 pWbemServiecsSecurityHelper = pWbemServiecs; 1159 } OpenNamespace_(string strNamespace, Int32 lFlags, ref IWbemServices ppWorkingNamespace, IntPtr ppCallResult)1160 internal int OpenNamespace_(string strNamespace, Int32 lFlags, ref IWbemServices ppWorkingNamespace, IntPtr ppCallResult) 1161 { 1162 int status = (int)tag_WBEMSTATUS.WBEM_E_NOT_SUPPORTED; 1163 //This should go through WMINET_utils layer and ppWorkingNamespace should be secured. See implementation of CreateInstanceEnum method. 1164 return status; 1165 } 1166 CancelAsyncCall_( IWbemObjectSink pSink)1167 internal int CancelAsyncCall_( IWbemObjectSink pSink) 1168 { 1169 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1170 status = pWbemServiecsSecurityHelper.CancelAsyncCall_(pSink); 1171 return status; 1172 } QueryObjectSink_( Int32 lFlags, ref IWbemObjectSink ppResponseHandler)1173 internal int QueryObjectSink_( Int32 lFlags, ref IWbemObjectSink ppResponseHandler) 1174 { 1175 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1176 status = pWbemServiecsSecurityHelper.QueryObjectSink_(lFlags, out ppResponseHandler); 1177 return status; 1178 } GetObject_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, ref IWbemClassObjectFreeThreaded ppObject, IntPtr ppCallResult)1179 internal int GetObject_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, ref IWbemClassObjectFreeThreaded ppObject, IntPtr ppCallResult) 1180 { 1181 //It is assumed that caller always passes ppCallResult as IntPtr.Zero. 1182 //If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information. 1183 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1184 if( !Object.ReferenceEquals(ppCallResult, IntPtr.Zero) ) 1185 status = pWbemServiecsSecurityHelper.GetObject_(strObjectPath, lFlags, pCtx, out ppObject, ppCallResult); 1186 return status; 1187 } 1188 GetObjectAsync_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1189 internal int GetObjectAsync_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1190 { 1191 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1192 status = pWbemServiecsSecurityHelper.GetObjectAsync_(strObjectPath, lFlags, pCtx, pResponseHandler); 1193 return status; 1194 } PutClass_(IWbemClassObjectFreeThreaded pObject, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult)1195 internal int PutClass_(IWbemClassObjectFreeThreaded pObject, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult) 1196 { 1197 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1198 if( null != scope) 1199 { 1200 IntPtr password = scope.Options.GetPassword(); 1201 status = WmiNetUtilsHelper.PutClassWmi_f(pObject, 1202 lFlags, 1203 pCtx, 1204 ppCallResult, 1205 (int)scope.Options.Authentication, 1206 (int)scope.Options.Impersonation, 1207 pWbemServiecsSecurityHelper, 1208 scope.Options.Username, 1209 password, 1210 scope.Options.Authority); 1211 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1212 } 1213 return status; 1214 } PutClassAsync_(IWbemClassObjectFreeThreaded pObject, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1215 internal int PutClassAsync_(IWbemClassObjectFreeThreaded pObject, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1216 { 1217 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1218 status = pWbemServiecsSecurityHelper.PutClassAsync_(pObject, lFlags,pCtx, pResponseHandler); 1219 return status; 1220 } DeleteClass_( string strClass, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult)1221 internal int DeleteClass_( string strClass, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult) 1222 { 1223 //It is assumed that caller always passes ppCallResult as IntPtr.Zero. 1224 //If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information. 1225 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1226 if( !Object.ReferenceEquals(ppCallResult, IntPtr.Zero) ) 1227 status = pWbemServiecsSecurityHelper.DeleteClass_(strClass, lFlags, pCtx, ppCallResult); 1228 return status; 1229 } DeleteClassAsync_(string strClass, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1230 internal int DeleteClassAsync_(string strClass, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1231 { 1232 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1233 status = pWbemServiecsSecurityHelper.DeleteClassAsync_(strClass, lFlags, pCtx,pResponseHandler); 1234 return status; 1235 } CreateClassEnum_(string strSuperClass, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)1236 internal int CreateClassEnum_(string strSuperClass, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) 1237 { 1238 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1239 if( null != scope ) 1240 { 1241 IntPtr password = scope.Options.GetPassword(); 1242 status = WmiNetUtilsHelper.CreateClassEnumWmi_f(strSuperClass, 1243 lFlags, 1244 pCtx, 1245 out ppEnum, 1246 (int)scope.Options.Authentication, 1247 (int)scope.Options.Impersonation, 1248 pWbemServiecsSecurityHelper, 1249 scope.Options.Username, 1250 password, 1251 scope.Options.Authority); 1252 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1253 } 1254 return status; 1255 } CreateClassEnumAsync_(string strSuperClass, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1256 internal int CreateClassEnumAsync_(string strSuperClass, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1257 { 1258 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1259 status = pWbemServiecsSecurityHelper.CreateClassEnumAsync_(strSuperClass, lFlags, pCtx, pResponseHandler); 1260 return status; 1261 } PutInstance_( IWbemClassObjectFreeThreaded pInst, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult)1262 internal int PutInstance_( IWbemClassObjectFreeThreaded pInst, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult) 1263 { 1264 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1265 if( null != scope) 1266 { 1267 IntPtr password = scope.Options.GetPassword(); 1268 status = WmiNetUtilsHelper.PutInstanceWmi_f(pInst, 1269 lFlags, 1270 pCtx, 1271 ppCallResult, 1272 (int)scope.Options.Authentication, 1273 (int)scope.Options.Impersonation, 1274 pWbemServiecsSecurityHelper, 1275 scope.Options.Username, 1276 password, 1277 scope.Options.Authority); 1278 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1279 } 1280 return status; 1281 } PutInstanceAsync_(IWbemClassObjectFreeThreaded pInst, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1282 internal int PutInstanceAsync_(IWbemClassObjectFreeThreaded pInst, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1283 { 1284 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1285 status = pWbemServiecsSecurityHelper.PutInstanceAsync_(pInst, lFlags, pCtx, pResponseHandler); 1286 return status; 1287 } DeleteInstance_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult)1288 internal int DeleteInstance_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IntPtr ppCallResult) 1289 { 1290 //It is assumed that caller always passes ppCallResult as IntPtr.Zero. 1291 //If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information. 1292 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1293 if( !Object.ReferenceEquals(ppCallResult, IntPtr.Zero) ) 1294 status = pWbemServiecsSecurityHelper.DeleteInstance_(strObjectPath, lFlags, pCtx, ppCallResult); 1295 return status; 1296 } DeleteInstanceAsync_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1297 internal int DeleteInstanceAsync_(string strObjectPath, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1298 { 1299 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1300 status = pWbemServiecsSecurityHelper.DeleteInstanceAsync_(strObjectPath, lFlags, pCtx, pResponseHandler); 1301 return status; 1302 } 1303 CreateInstanceEnum_(string strFilter, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)1304 internal int CreateInstanceEnum_(string strFilter, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) 1305 { 1306 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1307 if( null != scope) 1308 { 1309 IntPtr password = scope.Options.GetPassword(); 1310 status = WmiNetUtilsHelper.CreateInstanceEnumWmi_f(strFilter, 1311 lFlags, 1312 pCtx, 1313 out ppEnum, 1314 (int)scope.Options.Authentication, 1315 (int)scope.Options.Impersonation, 1316 pWbemServiecsSecurityHelper, 1317 scope.Options.Username, 1318 password, 1319 scope.Options.Authority); 1320 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1321 } 1322 return status; 1323 } CreateInstanceEnumAsync_(string strFilter, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1324 internal int CreateInstanceEnumAsync_(string strFilter, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1325 { 1326 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1327 status = pWbemServiecsSecurityHelper.CreateInstanceEnumAsync_(strFilter, lFlags, pCtx, pResponseHandler); 1328 return status; 1329 } ExecQuery_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)1330 internal int ExecQuery_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) 1331 { 1332 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1333 if( null != scope) 1334 { 1335 IntPtr password = scope.Options.GetPassword(); 1336 status = WmiNetUtilsHelper.ExecQueryWmi_f(strQueryLanguage, 1337 strQuery, 1338 lFlags, 1339 pCtx, 1340 out ppEnum, 1341 (int)scope.Options.Authentication, 1342 (int)scope.Options.Impersonation, 1343 pWbemServiecsSecurityHelper, 1344 scope.Options.Username, 1345 password, 1346 scope.Options.Authority); 1347 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1348 } 1349 return status; 1350 } ExecQueryAsync_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1351 internal int ExecQueryAsync_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1352 { 1353 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1354 status = pWbemServiecsSecurityHelper.ExecQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler); 1355 return status; 1356 } ExecNotificationQuery_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum)1357 internal int ExecNotificationQuery_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, ref IEnumWbemClassObject ppEnum) 1358 { 1359 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1360 if( null != scope) 1361 { 1362 IntPtr password = scope.Options.GetPassword(); 1363 status = WmiNetUtilsHelper.ExecNotificationQueryWmi_f(strQueryLanguage, 1364 strQuery, 1365 lFlags, 1366 pCtx, 1367 out ppEnum, 1368 (int)scope.Options.Authentication, 1369 (int)scope.Options.Impersonation, 1370 pWbemServiecsSecurityHelper, 1371 scope.Options.Username, 1372 password, 1373 scope.Options.Authority); 1374 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1375 } 1376 return status; 1377 } ExecNotificationQueryAsync_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler)1378 internal int ExecNotificationQueryAsync_(string strQueryLanguage, string strQuery, Int32 lFlags, IWbemContext pCtx, IWbemObjectSink pResponseHandler) 1379 { 1380 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1381 status = pWbemServiecsSecurityHelper.ExecNotificationQueryAsync_(strQueryLanguage, strQuery, lFlags, pCtx, pResponseHandler); 1382 return status; 1383 } ExecMethod_( string strObjectPath, string strMethodName, Int32 lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, ref IWbemClassObjectFreeThreaded ppOutParams, IntPtr ppCallResult)1384 internal int ExecMethod_( string strObjectPath, string strMethodName, Int32 lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, ref IWbemClassObjectFreeThreaded ppOutParams, IntPtr ppCallResult) 1385 { 1386 //It is assumed that caller always passes ppCallResult as IntPtr.Zero. 1387 //If it changes let this call go through wminet_utils.dll. Check implementation of CreateInstanceEnum_ for more information. 1388 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1389 if( !Object.ReferenceEquals(ppCallResult, IntPtr.Zero) ) 1390 status = pWbemServiecsSecurityHelper.ExecMethod_(strObjectPath, strMethodName, lFlags, pCtx, pInParams, out ppOutParams, ppCallResult); 1391 return status; 1392 } ExecMethodAsync_(string strObjectPath, string strMethodName, Int32 lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, IWbemObjectSink pResponseHandler)1393 internal int ExecMethodAsync_(string strObjectPath, string strMethodName, Int32 lFlags, IWbemContext pCtx, IWbemClassObjectFreeThreaded pInParams, IWbemObjectSink pResponseHandler) 1394 { 1395 int status = (int)tag_WBEMSTATUS.WBEM_E_FAILED; 1396 status = pWbemServiecsSecurityHelper.ExecMethodAsync_(strObjectPath, strMethodName, lFlags, pCtx, pInParams, pResponseHandler); 1397 return status; 1398 } 1399 } 1400 1401 1402 internal class SecurityHandler 1403 { 1404 private bool needToReset = false; 1405 private IntPtr handle; 1406 private ManagementScope scope; 1407 SecurityHandler(ManagementScope theScope)1408 internal SecurityHandler (ManagementScope theScope) 1409 { 1410 this.scope = theScope; 1411 if (null != scope) 1412 { 1413 if (scope.Options.EnablePrivileges) 1414 { 1415 WmiNetUtilsHelper.SetSecurity_f(ref needToReset, ref handle); 1416 } 1417 } 1418 } 1419 Reset()1420 internal void Reset () 1421 { 1422 if (needToReset) 1423 { 1424 needToReset = false; 1425 1426 if (null != scope) 1427 { 1428 WmiNetUtilsHelper.ResetSecurity_f ( handle); 1429 } 1430 } 1431 1432 } 1433 1434 Secure(IWbemServices services)1435 internal void Secure (IWbemServices services) 1436 { 1437 if (null != scope) 1438 { 1439 IntPtr password = scope.Options.GetPassword(); 1440 int status = WmiNetUtilsHelper.BlessIWbemServices_f 1441 ( 1442 services, 1443 scope.Options.Username, 1444 password, 1445 scope.Options.Authority, 1446 (int)scope.Options.Impersonation, 1447 (int)scope.Options.Authentication 1448 ); 1449 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1450 if (status < 0) 1451 { 1452 Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); 1453 } 1454 } 1455 } 1456 SecureIUnknown(object unknown)1457 internal void SecureIUnknown(object unknown) 1458 { 1459 // We use a hack to call BlessIWbemServices with an IUnknown instead of an IWbemServices 1460 // In VNext, we should really change the implementation of WMINet_Utils.dll so that it has 1461 // a method which explicitly takes an IUnknown. We rely on the fact that the implementation 1462 // of BlessIWbemServices actually casts the first parameter to IUnknown before blessing 1463 if (null != scope) 1464 { 1465 IntPtr password = scope.Options.GetPassword(); 1466 int status = WmiNetUtilsHelper.BlessIWbemServicesObject_f 1467 ( 1468 unknown, 1469 scope.Options.Username, 1470 password, 1471 scope.Options.Authority, 1472 (int)scope.Options.Impersonation, 1473 (int)scope.Options.Authentication 1474 ); 1475 System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(password); 1476 if (status < 0) 1477 { 1478 Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); 1479 } 1480 } 1481 } 1482 1483 1484 } //SecurityHandler 1485 1486 1487 /// <summary> 1488 /// Converts a String to a ManagementScope 1489 /// </summary> 1490 class ManagementScopeConverter : ExpandableObjectConverter 1491 { 1492 1493 /// <summary> 1494 /// Determines if this converter can convert an object in the given source type to the native type of the converter. 1495 /// </summary> 1496 /// <param name='context'>An ITypeDescriptorContext that provides a format context.</param> 1497 /// <param name='sourceType'>A Type that represents the type you wish to convert from.</param> 1498 /// <returns> 1499 /// <para>true if this converter can perform the conversion; otherwise, false.</para> 1500 /// </returns> CanConvertFrom(ITypeDescriptorContext context, Type sourceType)1501 public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) 1502 { 1503 if ((sourceType == typeof(ManagementScope))) 1504 { 1505 return true; 1506 } 1507 return base.CanConvertFrom(context,sourceType); 1508 } 1509 1510 /// <summary> 1511 /// Gets a value indicating whether this converter can convert an object to the given destination type using the context. 1512 /// </summary> 1513 /// <param name='context'>An ITypeDescriptorContext that provides a format context.</param> 1514 /// <param name='destinationType'>A Type that represents the type you wish to convert to.</param> 1515 /// <returns> 1516 /// <para>true if this converter can perform the conversion; otherwise, false.</para> 1517 /// </returns> CanConvertTo(ITypeDescriptorContext context, Type destinationType)1518 public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType) 1519 { 1520 if ((destinationType == typeof(InstanceDescriptor))) 1521 { 1522 return true; 1523 } 1524 return base.CanConvertTo(context,destinationType); 1525 } 1526 1527 /// <summary> 1528 /// Converts the given object to another type. The most common types to convert 1529 /// are to and from a string object. The default implementation will make a call 1530 /// to ToString on the object if the object is valid and if the destination 1531 /// type is string. If this cannot convert to the desitnation type, this will 1532 /// throw a NotSupportedException. 1533 /// </summary> 1534 /// <param name='context'>An ITypeDescriptorContext that provides a format context.</param> 1535 /// <param name='culture'>A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> 1536 /// <param name='value'>The Object to convert.</param> 1537 /// <param name='destinationType'>The Type to convert the value parameter to.</param> 1538 /// <returns>An Object that represents the converted value.</returns> ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)1539 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 1540 { 1541 1542 if (destinationType == null) 1543 { 1544 throw new ArgumentNullException("destinationType"); 1545 } 1546 1547 if (value is ManagementScope && destinationType == typeof(InstanceDescriptor)) 1548 { 1549 ManagementScope obj = ((ManagementScope)(value)); 1550 ConstructorInfo ctor = typeof(ManagementScope).GetConstructor(new Type[] {typeof(System.String)}); 1551 if (ctor != null) 1552 { 1553 return new InstanceDescriptor(ctor, new object[] {obj.Path.Path}); 1554 } 1555 } 1556 return base.ConvertTo(context,culture,value,destinationType); 1557 } 1558 } 1559 } 1560