public void RegisterNonAssemblySpecificSchema(InstallContext installContext)
        {
            SecurityHelper.UnmanagedCode.Demand();
            WmiNetUtilsHelper.VerifyClientKey_f();
            InstallLogWrapper context = new InstallLogWrapper(installContext);

            EnsureNamespace(context, this.GlobalRegistrationNamespace);
            EnsureClassExists(context, this.GlobalInstrumentationClassPath, new ClassMaker(this.MakeGlobalInstrumentationClass));
            EnsureClassExists(context, this.GlobalRegistrationClassPath, new ClassMaker(this.MakeNamespaceRegistrationClass));
            EnsureClassExists(context, this.GlobalNamingClassPath, new ClassMaker(this.MakeNamingClass));
            EnsureNamespace(context, this.NamespaceName);
            EnsureClassExists(context, this.InstrumentationClassPath, new ClassMaker(this.MakeInstrumentationClass));
            EnsureClassExists(context, this.RegistrationClassPath, new ClassMaker(this.MakeRegistrationClass));
            try
            {
                ManagementClass class2 = new ManagementClass(this.DecoupledProviderClassPath);
                if (class2["HostingModel"].ToString() != "Decoupled:Com")
                {
                    class2.Delete();
                }
            }
            catch (ManagementException exception)
            {
                if (exception.ErrorCode != ManagementStatus.NotFound)
                {
                    throw exception;
                }
            }
            EnsureClassExists(context, this.DecoupledProviderClassPath, new ClassMaker(this.MakeDecoupledProviderClass));
            EnsureClassExists(context, this.ProviderClassPath, new ClassMaker(this.MakeProviderClass));
            if (!DoesInstanceExist(this.GlobalRegistrationPath))
            {
                this.RegisterNamespaceAsInstrumented();
            }
        }
 /// <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);
     }
 }
Ejemplo 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);
            }
        }
Ejemplo n.º 4
0
        public static void DeleteClass(string namespacePath, string path)
        {
            const string method = "DeleteClass";

            if (namespacePath == null)
            {
                throw new NullParameterException(typeof(WmiUtil), method, "namespacePath");
            }
            if (path == null)
            {
                throw new NullParameterException(typeof(WmiUtil), method, "path");
            }

            ManagementScope scope;

            try
            {
                scope = new ManagementScope(namespacePath);
                scope.Connect();
            }
            catch (System.Exception)
            {
                // On an error assume that there is no class.

                return;
            }

            ManagementClass managementClass = new ManagementClass(scope, new ManagementPath(path), new ObjectGetOptions());

            if (GetObject(managementClass))
            {
                managementClass.Delete();
            }
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        private void PowerControl(string flag)
        {
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");

            try
            {
                mcWin32.Get();

                mcWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

                //"0" 注销 "1" 关机, "2" 重启 "8" 关闭计算机电源
                mboShutdownParams["Flags"]    = flag;
                mboShutdownParams["Reserved"] = "0";
                foreach (ManagementObject manObj in mcWin32.GetInstances())
                {
                    ManagementBaseObject mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mcWin32.Delete();
                mcWin32.Dispose();
            }
        }
Ejemplo n.º 9
0
        public static void delete_consumer(string target, string consumerName)
        {
            ManagementScope scope          = getScope(target, true);
            ManagementClass wmiEventFilter = new ManagementClass(scope, new
                                                                 ManagementPath("__EventFilter"), null);
            ManagementObject filter = wmiEventFilter.CreateInstance();

            filter["Name"] = consumerName + "Filter";
            filter.Delete();
            ManagementObject consumer = new ManagementClass(scope, new ManagementPath("LogFileEventConsumer"), null).CreateInstance();

            consumer["Name"] = consumerName + "Consumer";
            consumer.Delete();
        }
Ejemplo n.º 10
0
        public void RegisterNonAssemblySpecificSchema(InstallContext installContext)
        {
            SecurityHelper.UnmanagedCode.Demand(); // Bug#112640 - Close off any potential use from anything but fully trusted code

            // Make sure the 'Client' key has the correct permissions
            WmiNetUtilsHelper.VerifyClientKey_f();

            InstallLogWrapper context = new InstallLogWrapper(installContext);

            EnsureNamespace(context, GlobalRegistrationNamespace);

            EnsureClassExists(context, GlobalInstrumentationClassPath, new ClassMaker(MakeGlobalInstrumentationClass));

            EnsureClassExists(context, GlobalRegistrationClassPath, new ClassMaker(MakeNamespaceRegistrationClass));

            EnsureClassExists(context, GlobalNamingClassPath, new ClassMaker(MakeNamingClass));

            EnsureNamespace(context, NamespaceName);

            EnsureClassExists(context, InstrumentationClassPath, new ClassMaker(MakeInstrumentationClass));

            EnsureClassExists(context, RegistrationClassPath, new ClassMaker(MakeRegistrationClass));

            // Make sure Hosting model is set correctly by default.  If not, we blow away the class definition
            try
            {
                ManagementClass cls = new ManagementClass(DecoupledProviderClassPath);
                if (cls["HostingModel"].ToString() != "Decoupled:Com")
                {
                    cls.Delete();
                }
            }
            catch (ManagementException e)
            {
                if (e.ErrorCode != ManagementStatus.NotFound)
                {
                    throw e;
                }
            }

            EnsureClassExists(context, DecoupledProviderClassPath, new ClassMaker(MakeDecoupledProviderClass));

            EnsureClassExists(context, ProviderClassPath, new ClassMaker(MakeProviderClass));

            if (!DoesInstanceExist(GlobalRegistrationPath))
            {
                RegisterNamespaceAsInstrumented();
            }
        }
Ejemplo n.º 11
0
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                ManagementClass MC = new ManagementClass(@"root\cimv2:Win32_Evil");
                MC.Delete();
            }
            catch { }

            try
            {
                base.Uninstall(savedState);
            }
            catch { }
        }
Ejemplo n.º 12
0
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                new System.EnterpriseServices.Internal.Publish().GacRemove("WhereMyImplant.dll");
                ManagementClass managementClass = new ManagementClass(@"root\cimv2:Win32_Implant");
                managementClass.Delete();
            }
            catch { }

            try
            {
                base.Uninstall(savedState);
            }
            catch { }
        }
Ejemplo n.º 13
0
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                new System.EnterpriseServices.Internal.Publish().GacRemove("WMIKatz.dll");
                ManagementClass MC = new ManagementClass(@"root\cimv2:Win32_WMIKatz");
                MC.Delete();
            }
            catch { }

            try
            {
                base.Uninstall(savedState);
            }
            catch { }
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
0
        static void RemoveWMIClass(string host, string username, string password, string wnamespace, string classname)
        {
            if (!String.IsNullOrEmpty(wnamespace))
            {
                wnamespace = "root\\CIMv2";
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            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 rmclass = new ManagementClass(scope, new ManagementPath(classname), new ObjectGetOptions());
                rmclass.Delete();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }
Ejemplo n.º 16
0
        public void RegisterNonAssemblySpecificSchema(InstallContext context)
        {
            EnsureNamespace(context, GlobalRegistrationNamespace);

            EnsureClassExists(context, GlobalInstrumentationClassPath, new ClassMaker(MakeGlobalInstrumentationClass));

            EnsureClassExists(context, GlobalRegistrationClassPath, new ClassMaker(MakeNamespaceRegistrationClass));

            EnsureClassExists(context, GlobalNamingClassPath, new ClassMaker(MakeNamingClass));

            EnsureNamespace(context, NamespaceName);

            EnsureClassExists(context, InstrumentationClassPath, new ClassMaker(MakeInstrumentationClass));

            EnsureClassExists(context, RegistrationClassPath, new ClassMaker(MakeRegistrationClass));

            // Make sure Hosting model is set correctly by default.  If not, we blow away the class definition
            try
            {
                ManagementClass cls = new ManagementClass(DecoupledProviderClassPath);
                if (cls["HostingModel"].ToString() != "Decoupled:Com")
                {
                    cls.Delete();
                }
            }
            catch (ManagementException e)
            {
                if (e.ErrorCode != ManagementStatus.NotFound)
                {
                    throw e;
                }
            }

            EnsureClassExists(context, DecoupledProviderClassPath, new ClassMaker(MakeDecoupledProviderClass));

            EnsureClassExists(context, ProviderClassPath, new ClassMaker(MakeProviderClass));

            if (!DoesInstanceExist(GlobalRegistrationPath))
            {
                RegisterNamespaceAsInstrumented();
            }
        }
Ejemplo n.º 17
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)
        {
            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();
                }
            }
        }
 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);
     }
 }
Ejemplo n.º 19
0
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                ManagementClass MC = new ManagementClass(@"root\cimv2:Win32_MonitorDetails");
                MC.Delete();
            }
            catch { }

            try
            {
                base.Uninstall(savedState);
            }
            catch { }

            try
            {
                new System.EnterpriseServices.Internal.Publish().GacRemove(System.Reflection.Assembly.GetExecutingAssembly().Location);
            }
            catch { }
        }
Ejemplo n.º 20
0
        public static int Main(string[] args)
        {
            try
            {
                // Create a class with a NULL key and five instances
                // Create class
                ManagementClass mClass = new ManagementClass("root/default", "", null);
                mClass.SystemProperties["__Class"].Value = "test";
                mClass.Properties.Add("foo", CIMType.Uint16, false);         // Create a NULL
                mClass.Properties["foo"].Qualifiers.Add("key", true);        // key
                mClass.Put();

                ManagementObject mObj = mClass.CreateInstance();
                mObj["foo"] = 10;
                mObj.Put();

                ManagementObject m = new ManagementObject("root/cimv2:Win32_process");
                Console.WriteLine("RELPATH is " + m["__RELPATH"]);
                Console.WriteLine("PATH is " + m["__PATH"]);         // nothing displayed
                Console.WriteLine("PATH is " + m.Path.ToString());   // InvalidCastException

                // Attempt to display info from newly created ManagementObject
                Console.WriteLine("RELPATH is " + mObj["__RELPATH"]);
                Console.WriteLine("PATH is " + mObj["__PATH"]);         // nothing displayed
                Console.WriteLine("PATH is " + mObj.Path.Path);         // InvalidCastException

                // Attempt to display info from newly created ManagementClass
                //Console.WriteLine("RELPATH is " + mClass["__RELPATH"]);
                //Console.WriteLine("PATH is " + mClass.Path);	// compile error: lacks get accessor
                Console.Read();
                mClass.Delete();
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Test : " + e.GetType().ToString());
                Console.WriteLine(e.Message + e.StackTrace);
                return(0);
            }
        }
Ejemplo n.º 21
0
        public override void Uninstall(IDictionary savedState)
        {
            try
            {
                Publish publish = new Publish();
                publish.GacRemove("WhereMyImplant.dll");
                ManagementClass managementClass = new ManagementClass(@"root\cimv2:Win32_Implant");
                managementClass.Delete();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                base.Uninstall(savedState);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 22
0
        public static int Main(string[] args)
        {
            // Create a class
            ManagementClass dummyClass = new ManagementClass("root/default", "", null);

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

            mykeyprop.Add("MydelKey", "delHello");
            dummyClass.Put();

// Get the Class TestDelClassSync
            ManagementClass dummyDeleteCheck = new ManagementClass("root/default", "TestDelClassSync", null);

            dummyDeleteCheck.Get();

// Set the Delete Options on the Class TestDelClassSync
            //int Capacity = 8;
            CaseInsensitiveHashtable MyHash  = new CaseInsensitiveHashtable();
            DeleteOptions            Options = new DeleteOptions(MyHash);

            dummyDeleteCheck.Delete(Options);
            return(0);
        }
Ejemplo n.º 23
0
        public static void WMIEventSubscription(string log)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            Lib.Logger logger = new Lib.Logger(currentPath + log);
            logger.SimulationHeader("T1084");
            //string vbscript64 = "<INSIDE base64 encoded VBS here>";
            //string vbscript = Encoding.UTF8.GetString(Convert.FromBase64String(vbscript64));
            try
            {
                ManagementObject EventFilter   = null;
                ManagementObject EventConsumer = null;
                ManagementObject myBinder      = null;

                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);
                EventFilter                   = wmiEventFilter.CreateInstance();
                EventFilter["Name"]           = "MaliciousSubscription";
                EventFilter["Query"]          = myEventQuery.QueryString;
                EventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                EventFilter["EventNameSpace"] = @"\root\cimv2";
                EventFilter.Put();
                logger.TimestampInfo("Event filter 'MaliciousSubscription' created.");

                EventConsumer         = new ManagementClass(scope, new ManagementPath("CommandLineEventConsumer"), null).CreateInstance();
                EventConsumer["Name"] = "MaliciousSubscription";
                EventConsumer["CommandLineTemplate"] = "powershell.exe";
                EventConsumer.Put();

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

                logger.TimestampInfo("Event consumer 'MaliciousSubscription' created.");

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

                logger.TimestampInfo("WMI Subscription created successfully");
                Thread.Sleep(3 * 1000);
                EventFilter.Delete();
                EventConsumer.Delete();
                myBinder.Delete();
                logger.TimestampInfo("WMI Subscription Deleted");
                logger.SimulationFinished();
            }
            catch (Exception ex)
            {
                logger.SimulationFailed(ex);
            }
        }
Ejemplo n.º 24
0
        public static void WMIEventSubscription(string log, bool cleanup)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            Lib.Logger logger = new Lib.Logger(currentPath + log);
            logger.SimulationHeader("T1546.003");
            logger.TimestampInfo("Using the System.Management .NEt namespace to execute the technique");

            string wmiSubscription = "MaliciousWmiSubscription";

            //string vbscript64 = "<INSIDE base64 encoded VBS here>";
            //string vbscript = Encoding.UTF8.GetString(Convert.FromBase64String(vbscript64));
            try
            {
                ManagementObject EventFilter   = null;
                ManagementObject EventConsumer = null;
                ManagementObject myBinder      = null;

                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);
                EventFilter                   = wmiEventFilter.CreateInstance();
                EventFilter["Name"]           = wmiSubscription;
                EventFilter["Query"]          = myEventQuery.QueryString;
                EventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                EventFilter["EventNameSpace"] = @"\root\cimv2";
                EventFilter.Put();
                logger.TimestampInfo(String.Format("EventFilter '{0}' created.", wmiSubscription));

                EventConsumer         = new ManagementClass(scope, new ManagementPath("CommandLineEventConsumer"), null).CreateInstance();
                EventConsumer["Name"] = wmiSubscription;
                EventConsumer["CommandLineTemplate"] = "powershell.exe";
                EventConsumer.Put();
                logger.TimestampInfo(String.Format("CommandLineEventConnsumer '{0}' created.", wmiSubscription));

                /*
                 * EventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();
                 * EventConsumer["Name"] = "BadActiveScriptEventConsumer";
                 * EventConsumer["ScriptingEngine"] = "VBScript";
                 * EventConsumer["ScriptText"] = vbscript;
                 * EventConsumer.Put();
                 */
                myBinder             = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();
                myBinder["Filter"]   = EventFilter.Path.RelativePath;
                myBinder["Consumer"] = EventConsumer.Path.RelativePath;
                myBinder.Put();

                logger.TimestampInfo("FilterToConsumerBinding created.");

                if (cleanup)
                {
                    Thread.Sleep(3 * 1000);
                    EventFilter.Delete();
                    EventConsumer.Delete();
                    myBinder.Delete();
                    logger.TimestampInfo("WMI Subscription Deleted");
                }
                else
                {
                    logger.TimestampInfo("The created WMI Subscription was not deleted as part of the simulation");
                }

                logger.SimulationFinished();
            }
            catch (Exception ex)
            {
                logger.SimulationFailed(ex);
            }
        }
Ejemplo n.º 25
0
        public static int Main(string[] args)
        {
            // Ensure we delete any previous copies of the class and its subclasses
            try {
                ManagementClass testSubClass = new ManagementClass("root/default:URTNEWSUBCLASS");
                testSubClass.Delete();
            } catch (ManagementException) {}
            try {
                ManagementClass testClass = new ManagementClass("root/default:URTNEWCLASS");
                testClass.Delete();
            } catch (ManagementException) {}

            // Get an empty class
            ManagementClass emptyClass = new ManagementClass("root/default", "", null);

            // Set the class name
            emptyClass.SystemProperties ["__CLASS"].Value = "URTNEWCLASS";

            // Add some qualifiers
            QualifierCollection qualSet = emptyClass.Qualifiers;

            qualSet.Add("sint32", (int)132235);
            qualSet.Add("string", "Floxihoxibellification");
            qualSet.Add("real64", (double)-12.33434234);
            qualSet.Add("boolean", true);
            qualSet.Add("sint32Array", new int[] { 1, 2, 3 }, false, true, false, true);
            qualSet.Add("stringArray", new string[] { "il", "spezzio" }, false, false, false, false);
            qualSet.Add("real64Array", new double[] { 1.2, -1.3 }, true, true, true, true);
            qualSet.Add("booleanArray", new bool[] { false, true }, true, false, true, true);

            Console.WriteLine("sint32: " + qualSet["sint32"].Value);
            Console.WriteLine("string: " + qualSet["string"].Value);
            Console.WriteLine("real64: " + qualSet["real64"].Value);
            Console.WriteLine("boolean: " + qualSet["boolean"].Value);
            Console.WriteLine("sint32Array: " + ArrayToString((Array)qualSet["sint32Array"].Value));
            Console.WriteLine("stringArray: " + ArrayToString((Array)qualSet["stringArray"].Value));
            Console.WriteLine("real64Array: " + ArrayToString((Array)qualSet["real64Array"].Value));
            Console.WriteLine("booleanArray: " + ArrayToString((Array)qualSet["booleanArray"].Value));

            // Add some properties
            PropertyCollection propSet = emptyClass.Properties;

            // Use the simple Add that selects the right type
            propSet.Add("uint8", (byte)10);
            propSet.Add("uint16", (ushort)10);
            propSet.Add("uint32", (uint)10);
            propSet.Add("uint32x", (int)11);
            propSet.Add("uint32xx", (UInt32)123);
            propSet.Add("uint32xxx", "12");
            propSet.Add("uint64", (ulong)10);
            propSet.Add("sint8", (sbyte)10);
            propSet.Add("sint16", (short)10);
            propSet.Add("sint32", (int)10);
            propSet.Add("sint64", (long)10);
            propSet.Add("bool", true);
            propSet.Add("string", "Wibble");
            propSet.Add("real32", (float)10.23);
            propSet.Add("real64", (double)11.2222);

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

            embeddedClass.SystemProperties ["__CLASS"].Value = "URTEMBEDDEDCLASS";
            propSet.Add("object", embeddedClass);

            // For datetime/reference types, use the non-default Add
            propSet.Add("datetime", "20000728044535.000000-420", CimType.DateTime);
            propSet.Add("reference", "foo=10", CimType.Reference);

            // Echo the non-null property values
            Console.WriteLine("uint8: " + emptyClass["uint8"]);
            Console.WriteLine("uint16: " + emptyClass["uint16"]);
            Console.WriteLine("uint32: " + emptyClass["uint32"]);
            Console.WriteLine("uint32x: " + emptyClass["uint32x"]);
            Console.WriteLine("uint32xx: " + emptyClass["uint32xx"]);
            Console.WriteLine("uint32xxx: " + emptyClass["uint32xxx"]);
            Console.WriteLine("uint64: " + emptyClass["uint64"]);
            Console.WriteLine("sint8: " + emptyClass["sint8"]);
            Console.WriteLine("sint16: " + emptyClass["sint16"]);
            Console.WriteLine("sint32: " + emptyClass["sint32"]);
            Console.WriteLine("sint64: " + emptyClass["sint64"]);
            Console.WriteLine("bool: " + emptyClass["bool"]);
            Console.WriteLine("string: " + emptyClass["string"]);
            Console.WriteLine("real32: " + emptyClass["real32"]);
            Console.WriteLine("real64: " + emptyClass["real64"]);
            Console.WriteLine("datetime: " + emptyClass["datetime"]);
            Console.WriteLine("reference: " + emptyClass["reference"]);
            Console.WriteLine("object: " + ((ManagementBaseObject)emptyClass["object"]).GetText(TextFormat.Mof));


            // Add a null property and put some qualifiers on it
            propSet.Add("referenceNull", CimType.Reference, false);
            Property newProp = propSet["referenceNull"];

            newProp.Qualifiers.Add("read", true);

            // Add other simple null properties
            propSet.Add("uint8Null", CimType.UInt8, false);
            propSet.Add("uint16Null", CimType.UInt16, false);
            propSet.Add("uint32Null", CimType.UInt32, false);
            propSet.Add("uint64Null", CimType.UInt64, false);
            propSet.Add("sint8Null", CimType.SInt8, false);
            propSet.Add("sint16Null", CimType.SInt16, false);
            propSet.Add("sint32Null", CimType.SInt32, false);
            propSet.Add("sint64Null", CimType.SInt64, false);
            propSet.Add("boolNull", CimType.Boolean, false);
            propSet.Add("stringNull", CimType.String, false);
            propSet.Add("real32Null", CimType.Real32, false);
            propSet.Add("real64Null", CimType.Real64, false);
            propSet.Add("objectNull", CimType.Object, false);
            propSet.Add("datetimeNull", CimType.DateTime, false);


            // Add array null properties
            propSet.Add("uint8ArrayNull", CimType.UInt8, true);
            propSet.Add("uint16ArrayNull", CimType.UInt16, true);
            propSet.Add("uint32ArrayNull", CimType.UInt32, true);
            propSet.Add("uint64ArrayNull", CimType.UInt64, true);
            propSet.Add("sint8ArrayNull", CimType.SInt8, true);
            propSet.Add("sint16ArrayNull", CimType.SInt16, true);
            propSet.Add("sint32ArrayNull", CimType.SInt32, true);
            propSet.Add("sint64ArrayNull", CimType.SInt64, true);
            propSet.Add("boolArrayNull", CimType.Boolean, true);
            propSet.Add("stringArrayNull", CimType.String, true);
            propSet.Add("real32ArrayNull", CimType.Real32, true);
            propSet.Add("real64ArrayNull", CimType.Real64, true);
            propSet.Add("objectArrayNull", CimType.Object, true);
            propSet.Add("datetimeArrayNull", CimType.DateTime, true);

            // Add some array properties
            propSet.Add("uint8Array", new byte[] { 10, 20 });
            propSet.Add("uint16Array", new ushort[] { 10, 20 });
            propSet.Add("uint32Array", new uint[] { 10, 20 });
            propSet.Add("uint64Array", new ulong[] { 10, 20 });
            propSet.Add("sint8Array", new sbyte[] { 10, 20 });
            propSet.Add("sint16Array", new short[] { 10, 20 });
            propSet.Add("sint32Array", new int[] { 10, 20 });
            propSet.Add("sint64Array", new long[] { 10, 20 });
            propSet.Add("boolArray", new bool[] { true, false, true });
            propSet.Add("stringArray", new string[] { "Wibble", "Wobble" });
            propSet.Add("real32Array", new float[] { (float)10.23, (float)111.22 });
            propSet.Add("real64Array", new double[] { 11.2222, -23.32 });
            propSet.Add("datetimeArray", new string[] { "20000728044535.000000-420" }, CimType.DateTime);
            propSet.Add("referenceArray", new string[] { "Foo=10", "bar.Nonesuch=\"a\"" }, CimType.Reference);
            // BUGBUG following causes a TypeMismatch - RAID 45235 against runtime
            propSet.Add("objectArray", new ManagementClass[] { embeddedClass, embeddedClass });

            // Echo the non-null array property values
            Console.WriteLine("uint8Array: " + ArrayToString((Array)emptyClass["uint8Array"]));
            Console.WriteLine("uint16Array: " + ArrayToString((Array)emptyClass["uint16Array"]));
            Console.WriteLine("uint32Array: " + ArrayToString((Array)emptyClass["uint32Array"]));
            Console.WriteLine("uint64Array: " + ArrayToString((Array)emptyClass["uint64Array"]));
            Console.WriteLine("sint8Array: " + ArrayToString((Array)emptyClass["sint8Array"]));
            Console.WriteLine("sint16Array: " + ArrayToString((Array)emptyClass["sint16Array"]));
            Console.WriteLine("sint32Array: " + ArrayToString((Array)emptyClass["sint32Array"]));
            Console.WriteLine("sint64Array: " + ArrayToString((Array)emptyClass["sint64Array"]));
            Console.WriteLine("boolArray: " + ArrayToString((Array)emptyClass["boolArray"]));
            Console.WriteLine("stringArray: " + ArrayToString((Array)emptyClass["stringArray"]));
            Console.WriteLine("real32Array: " + ArrayToString((Array)emptyClass["real32Array"]));
            Console.WriteLine("real64Array: " + ArrayToString((Array)emptyClass["real64Array"]));
            Console.WriteLine("datetimeArray: " + ArrayToString((Array)emptyClass["datetimeArray"]));
            Console.WriteLine("referenceArray: " + ArrayToString((Array)emptyClass["referenceArray"]));
            Console.WriteLine("objectArray: " + ObjectArrayToString((Array)emptyClass["objectArray"]));

            emptyClass.Put();
            Console.WriteLine("Successfully saved new base class");

            // Create a derived class
            ManagementClass baseClass = new ManagementClass("root/default:URTNEWCLASS");
            ManagementClass newClass  = baseClass.Derive("URTNEWSUBCLASS");

            newClass.Put();
            Console.WriteLine("Successfully saved new subclass");
            return(0);
        }
Ejemplo n.º 26
0
        static void RemoteWMIExecuteVBS(string host, string eventName, string username, string password)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                if (!String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("[*] User credentials: {0}", username);
                    options.Username = username;
                    options.Password = password;
                }
                Console.WriteLine();

                // first create a 30 second timer on the remote host
                ManagementScope  timerScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", host), options);
                ManagementClass  timerClass = new ManagementClass(timerScope, new ManagementPath("__IntervalTimerInstruction"), null);
                ManagementObject myTimer    = timerClass.CreateInstance();
                myTimer["IntervalBetweenEvents"] = (UInt32)30000;
                myTimer["SkipIfPassed"]          = false;
                myTimer["TimerId"] = "Timer";
                try
                {
                    Console.WriteLine("[*] Creating 'Timer' object on {0}", host);
                    myTimer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in creating timer object: {0}", ex.Message);
                    return;
                }

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\subscription", host), options);

                // then install the __EventFilter for the timer object
                ManagementClass  wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null);
                WqlEventQuery    myEventQuery   = new WqlEventQuery(@"SELECT * FROM __TimerEvent WHERE TimerID = 'Timer'");
                ManagementObject myEventFilter  = wmiEventFilter.CreateInstance();
                myEventFilter["Name"]           = eventName;
                myEventFilter["Query"]          = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"]  = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                try
                {
                    Console.WriteLine("[*] Setting '{0}' event filter on {1}", eventName, host);
                    myEventFilter.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event filter: {0}", ex.Message);
                }


                // now create the ActiveScriptEventConsumer payload (VBS)
                ManagementObject myEventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();

                myEventConsumer["Name"]            = eventName;
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"]      = vbsPayload;
                myEventConsumer["KillTimeout"]     = (UInt32)45;

                try
                {
                    Console.WriteLine("[*] Setting '{0}' event consumer on {1}", eventName, host);
                    myEventConsumer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event consumer: {0}", ex.Message);
                }


                // finally bind them together with a __FilterToConsumerBinding
                ManagementObject myBinder = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

                myBinder["Filter"]   = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;

                try
                {
                    Console.WriteLine("[*] Binding '{0}' event filter and consumer on {1}", eventName, host);
                    myBinder.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting FilterToConsumerBinding: {0}", ex.Message);
                }


                // wait for everything to trigger
                Console.WriteLine("\r\n[*] Waiting 45 seconds for event to trigger on {0} ...\r\n", host);
                System.Threading.Thread.Sleep(45 * 1000);


                // finally, cleanup
                try
                {
                    Console.WriteLine("[*] Removing 'Timer' internal timer from {0}", host);
                    myTimer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing 'Timer' interval timer: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing FilterToConsumerBinding from {0}", host);
                    myBinder.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing FilterToConsumerBinding: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing '{0}' event filter from {1}", eventName, host);
                    myEventFilter.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event filter: {0}", ex.Message);
                }

                try
                {
                    Console.WriteLine("[*] Removing '{0}' event consumer from {0}\r\n", eventName, host);
                    myEventConsumer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event consumer: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("  Exception : {0}", ex.Message));
            }
        }