private bool IsThereGroupWithThisSID(string groupSID)
        {
            var wqlSearchWindowsGroupBySID = new WQLBuilder().WithWmiClass("Win32_Group").AddParameter("SID", groupSID).Build();
            var wmiResult = this.WmiDataProvider.ExecuteWQL(wqlSearchWindowsGroupBySID);

            return ((wmiResult == null) || (wmiResult.Count() == 0));
        }
Beispiel #2
0
        public string GetOperatingSystemFamily()
        {
            var wqlOperatingSystem = new WQLBuilder().WithWmiClass("Win32_OperatingSystem").Build();
            var foundOSName = this.WmiDataProvider.ExecuteWQL(wqlOperatingSystem).First().GetValueOf("Name").ToString();
            bool isWindowsFamily = foundOSName.IndexOf("windows", StringComparison.InvariantCultureIgnoreCase) >= 0;

            return isWindowsFamily ? "windows" : foundOSName;
        }
        public override IList<string> GetValues(Dictionary<string, object> parameters)
        {
            this.CheckWmiDataProviderInstance();
            var wqlAllGroupSIDs = new WQLBuilder().WithWmiClass("Win32_Group").Build();
            var wmiResult = this.WmiDataProvider.ExecuteWQL(wqlAllGroupSIDs);

            IList<String> allGroupSIDs = new List<String>();
            foreach (var userSID in wmiResult)
                allGroupSIDs.Add(userSID.GetValueOf("SID").ToString());

            return allGroupSIDs;
        }
Beispiel #4
0
        public void Should_be_possible_to_build_a_WMI_Query_Language()
        {
            string wql = new WQLBuilder()
                .WithWmiClass("cim_logicalfile")
                    .AddParameter("drive", "c:")
                    .AddParameter("path", "\\temp\\")
                .Build().ToLower().Trim();

            List<String> wqlLines = this.GetSplittedWQL(wql);

            Assert.AreEqual(3, wqlLines.Count);
            Assert.AreEqual("select * from cim_logicalfile", wqlLines[0].ToLower().Trim());
            Assert.AreEqual("where drive = 'c:'", wqlLines[1].ToLower().Trim());
            Assert.AreEqual("and path = '\\temp\\'", wqlLines[2].ToLower().Trim());
        }
Beispiel #5
0
        public void Should_be_possible_to_build_a_WMI_Query_Language_adding_all_parameters_at_once()
        {
            Dictionary<string, string> allParameters = new Dictionary<string, string>();
            allParameters.Add("drive", "d:");
            allParameters.Add("path", "\\fakedirectory\\");
            allParameters.Add("filename", "fakefile");
            allParameters.Add("extension", "fex");

            string wql = new WQLBuilder().WithWmiClass("cim_logicalfile").AddParameters(allParameters).Build();

            List<String> wqlLines = this.GetSplittedWQL(wql);
            Assert.AreEqual(5, wqlLines.Count);
            Assert.AreEqual("select * from cim_logicalfile", wqlLines[0].ToLower().Trim());
            Assert.AreEqual("where drive = 'd:'", wqlLines[1].ToLower().Trim());
            Assert.AreEqual("and path = '\\fakedirectory\\'", wqlLines[2].ToLower().Trim());
            Assert.AreEqual("and filename = 'fakefile'", wqlLines[3].ToLower().Trim());
            Assert.AreEqual("and extension = 'fex'", wqlLines[4].ToLower().Trim());
        }
        private bool DoesACLBelongToUser(ManagementBaseObject daclTrustee, string userTrusteeName, WmiDataProvider wmiProvider)
        {
            var winTrustee = this.getWinTrusteeFromManagementObject(daclTrustee);
            if (userTrusteeName.Equals(winTrustee.SIDString))
                return true;

            string username = this.getPropertyValueAsString(daclTrustee, "Name");
            var wql = new WQLBuilder().WithWmiClass("Win32_Account").AddParameter("SID", userTrusteeName).Build();
            var accountName = wmiProvider.ExecuteWQL(wql);

            if ((accountName.Count() > 0) && accountName.First().GetValueOf("Name").ToString().Equals(username, StringComparison.InvariantCultureIgnoreCase))
                return true;

            string userDomain = this.getPropertyValueAsString(daclTrustee, "Domain");
            string[] trusteeParts = userTrusteeName.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);

            bool matchUsername = username.Equals(trusteeParts.Last(), StringComparison.CurrentCultureIgnoreCase);
            bool matchUserDomain = userDomain.Equals(trusteeParts.First(), StringComparison.CurrentCultureIgnoreCase);

            bool isSystemAccount = (userTrusteeName.IndexOf(@"\") < 0);
            return isSystemAccount ? matchUsername : (matchUsername && matchUserDomain);
        }
 private void CreateExpectationForGetGroupComponent(WmiDataProvider fakeWmiProvider, string groupName)
 {
     var fakeWin32GroupUserRecords = new List<WmiObject>();
     var groupComponent = GroupComponent(FAKE_COMPUTER_NAME, groupName);
     var wqlAdministratorsUsers = new WQLBuilder().WithWmiClass("Win32_GroupUser").AddParameter("GroupComponent", groupComponent).Build();
     Expect.Call(fakeWmiProvider.ExecuteWQL(wqlAdministratorsUsers)).Return(new[] { NewWmiObjectForFakeGroupUser("fakeUser") });
 }
        private WmiDataProvider GetWmiProviderMockWithNoWmiResultBehavior()
        {
            // This mocked WmiDataProvider must be used in order to test GetAllGroupsByUser method.
            var mocks = new MockRepository();
            var fakeWmiProvider = mocks.StrictMock<WmiDataProvider>();
            
            // Create expectation for first calling (to get computer name).
            var wqlToGetComputerName = new WQLBuilder().WithWmiClass("Win32_ComputerSystem").Build();
            var fakeWin32ComputerSystemRecord = new WmiObject();
            fakeWin32ComputerSystemRecord.Add("Name", FAKE_COMPUTER_NAME);
            fakeWin32ComputerSystemRecord.Add("DomainRole", 1);
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetComputerName)).Return(new[] { fakeWin32ComputerSystemRecord });
            
            // Create expectation for second calling (to get all local groups);
            var wqlToGetAllLocalGroups = new WQLBuilder().WithWmiClass("Win32_Group").AddParameter("localaccount", "1").Build();
            var fakeWin32GroupRecords = new List<WmiObject>();
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Administrators", "S-1-5-32-544"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Backup Operators", "S-1-5-32-551"));
            fakeWin32GroupRecords.Add(NewWmiObjectForFakeLocalGroup("Users", "S-1-5-32-545"));
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlToGetAllLocalGroups)).Return(fakeWin32GroupRecords);
            
            // Create expectation for each get group component calling...
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Administrators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Backup Operators");
            CreateExpectationForGetGroupComponent(fakeWmiProvider, "Users");

            // Create expectation for each get user details calling (3 first times) and get user SID (3 last times)
            Expect.Call(fakeWmiProvider.ExecuteWQL(null)).IgnoreArguments().Repeat.Times(6).Return(null);

            var wqlAllGetBuiltinAccounts = new WQLBuilder().WithWmiClass("Win32_SystemAccount").Build();
            Expect.Call(fakeWmiProvider.ExecuteWQL(wqlAllGetBuiltinAccounts)).Return(null);

            mocks.ReplayAll();
            
            return fakeWmiProvider;
        }
Beispiel #9
0
        private string GetUserSID(string domain, string accountName)
        {
            var wqlGetAccountSid =
                new WQLBuilder()
                    .WithWmiClass("Win32_Account")
                        .AddParameter("Domain", domain)
                        .AddParameter("Name", accountName)
                .Build();

            var wqlResult = WmiProvider.ExecuteWQL(wqlGetAccountSid);

            if (wqlResult.HasItems())
                return wqlResult.First().GetFieldValueAsString("SID");

            if (this.TargetDomainRole > 3)
            {
                var wqlGetDomain = "select * from Win32_NTDomain";
                var domainName = WmiProvider.ExecuteWQL(wqlGetDomain).First().GetFieldValueAsString("DomainName");
                wqlGetAccountSid =
                    new WQLBuilder()
                        .WithWmiClass("Win32_Account")
                            .AddParameter("Domain", domainName)
                            .AddParameter("Name", accountName)
                        .Build();
                wqlResult = WmiProvider.ExecuteWQL(wqlGetAccountSid);
                if (wqlResult != null && wqlResult.Count() > 0)
                    return wqlResult.First().GetFieldValueAsString("SID");
            }

            return string.Empty;
        }
Beispiel #10
0
        private IEnumerable<WindowsAccount> GetAllLocalGroups()
        {
            var wqlToGetAllLocalGroups =
                new WQLBuilder()
                    .WithWmiClass("Win32_Group")
                    .AddParameter("localaccount", "1")
                .Build();

            var wqlResult = this.WmiProvider.ExecuteWQL(wqlToGetAllLocalGroups);

            return
                wqlResult
                    .Select(g =>
                        new WindowsAccount(
                            g.GetFieldValueAsString("Name"),
                            (bool?)g.GetValueOf("Disabled"),
                            g.GetFieldValueAsString("SID"),
                            AccountType.Group)
                 ).ToList();
        }
Beispiel #11
0
        private IEnumerable<WindowsAccount> GetAllBuiltinAccounts()
        {
            var wqlAllGetBuiltinAccounts = new WQLBuilder().WithWmiClass("Win32_SystemAccount").Build();

            var wqlResult = this.WmiProvider.ExecuteWQL(wqlAllGetBuiltinAccounts);

            if (wqlResult != null && wqlResult.Count() > 0)
            {
                return
                    wqlResult.Select(
                        wql =>
                            new WindowsAccount(
                                wql.GetFieldValueAsString("Name"),
                                (bool?)true,
                                wql.GetFieldValueAsString("SID"),
                                AccountType.User));
            }

            return new WindowsAccount[] { };
        }
Beispiel #12
0
        private string BuildWqlToGetUserDetails(string userCriteria, string domainCriteria)
        {
            var wqlGetUserWithoutFilter = new WQLBuilder().WithWmiClass("Win32_Account").Build();
            var wqlGetUserDetailsBuilder = new StringBuilder(wqlGetUserWithoutFilter);
            var wqlFilter = String.Format(" WHERE {0} and {1} ", domainCriteria, userCriteria);
            wqlGetUserDetailsBuilder.AppendLine(wqlFilter);

            return wqlGetUserDetailsBuilder.ToString();
        }
Beispiel #13
0
 public virtual IEnumerable<WmiObject> SearchWmiObjects(String wmiClassName, Dictionary<String, String> inParameters)
 {
     string wmiCommandQuery = new WQLBuilder().WithWmiClass(wmiClassName).AddParameters(inParameters).Build();
     return this.executeWQLCommandQuery(wmiCommandQuery);
 }
Beispiel #14
0
        public virtual IEnumerable <WmiObject> SearchWmiObjects(String wmiClassName, Dictionary <String, String> inParameters)
        {
            string wmiCommandQuery = new WQLBuilder().WithWmiClass(wmiClassName).AddParameters(inParameters).Build();

            return(this.executeWQLCommandQuery(wmiCommandQuery));
        }
Beispiel #15
0
        public bool FileExists(string localFilepath)
        {
            /* IMPORTANT
             * BEFORE CHANGING OR REFACTORING THIS METHOD, YOU MUST READ THIS NOTICE.
             * 
             * The code below sounds confusing, but there is a reason to be like that.
             * The first issue is that the System.IO.File.Exists and Directory.Exists behavior (see Remarks Session in http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx).
             * If an error such as "Acess Denied" or "Invalid Path" occurs during those methods calling,
             * .NET API will return FALSE instead of throwing an exception. Thus, when the return is false,
             * maybe the file or directory exists, but some error occurred.
             * The best way to find out if a file or directory exists is trying to open them. The methods
             * that open a file (or directory) will throw an exception if it does not exist.
             * 
             * Now, we have a second issue:
             * To do the above, it is necessary that the administrative share on the remote machine is enabled.
             * It´s very common that is not enabled.
             * The solution to this issue is to make another attempt in order to check file (or directory) existence.
             * You can make that through a WMI query.
             * 
             * So, we have three ways to check File Existence. Why not use only WMI ?
             * Because, we have a third issue: performance.
             * In some scenarios, this WMI Query can be really slow.
             * OK, but why the code below still using File.Exists and Directory.Exists methods?
             * When those methods return TRUE, we can safely say that file (or directory) really exists.
             * Besides, those methods are very fast. Hence, we can stop the method if one of those methods return TRUE.
             */

            try
            {
                var windowsConnectionProvider = new StraightNetworkConnectionProvider();
                var adminShareFilePath = GetAdministrativeSharePathFromLocalFilepath(TargetInfo.GetAddress(), localFilepath);
                try
                {
                    // To use Administrative Share resource, we need open a straight connection to remote machine.
                    windowsConnectionProvider.Connect(TargetInfo);
                    try
                    {
                        // If one of these methods return TRUE, we can return this result.
                        if (System.IO.File.Exists(adminShareFilePath) || System.IO.Directory.Exists(adminShareFilePath))
                            return true;

                        // If both methods above return FALSE, we CAN NOT rely on in this.
                        try
                        {
                            // So, we will try to open the file...
                            System.IO.File.Open(adminShareFilePath, FileMode.Open);
                            // If we could open it, the file exists.
                            return true;
                        }
                        catch (FileNotFoundException)
                        {
                            // obviously we can return FALSE if File.Open thrown FileNotFoundException.
                            return false;
                        }
                    }
                    catch (Exception)
                    {
                        try
                        {
                            // If any else Exception was thrown, maybe the passed path is a directory...
                            // So, we will try to open it.
                            System.IO.Directory.EnumerateFiles(adminShareFilePath, "*");
                            return true;
                        }
                        catch(FileNotFoundException)
                        {
                            return false;
                        }
                    }
                }
                finally
                {
                    windowsConnectionProvider.Disconnect();
                }
            }
            catch (Exception)
            {
                // At last, if it was not possible to check file (or directory) existence due to any error,
                // we will try to find this information out through WMI.
                var wmiParametersForFileSearching = this.CreateWmiParameters(localFilepath);
                var wqlForFileSearching = new WQLBuilder().WithWmiClass("CIM_LogicalFile").AddParameters(wmiParametersForFileSearching).Build();
                var wmiQueryResult = this.WmiDataProvider.ExecuteWQL(wqlForFileSearching);
                
                return ((wmiQueryResult != null) && (wmiQueryResult.Count() > 0));
            }
        }
Beispiel #16
0
        public virtual IEnumerable<String> GetChildrenFiles(string parentDirectory)
        {
            var wqlFilter = GeWqlFilter(parentDirectory);

            var wql = new WQLBuilder().WithWmiClass("CIM_DataFile").AddParameters(wqlFilter).Build();

            return this.WmiDataProvider.ExecuteWQL(wql).Select(row => row.GetFieldValueAsString("FileName"));
        }
Beispiel #17
0
        private string GetComputerSystemFromTarget()
        {
            var wqlToGetComputerName = new WQLBuilder().WithWmiClass("Win32_ComputerSystem").Build();
            var computerSystem = WmiProvider.ExecuteWQL(wqlToGetComputerName).First();
            this.TargetDomainRole = int.Parse(computerSystem.GetFieldValueAsString("DomainRole"));

            return computerSystem.GetFieldValueAsString("Name");
        }