Exemplo n.º 1
0
        public string UpdateThisGroup(string newOU, string newName)
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain);
            GroupPrincipal   gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, Name);

            // zoek de OU op waarin deze groep zich bevindt
            DirectoryEntry dirEntryGroup = (DirectoryEntry)gp.GetUnderlyingObject();
            string         oldOU         = dirEntryGroup.Parent.Path;

            if (newOU.Substring(0, 4) != "LDAP")
            {
                newOU = ActiveDirectory.LDAPShort + newOU;
            }
            //indien nieuwe OU verschillend van oude OU : verplaatsen
            if (newOU != oldOU)
            {
                DirectoryEntry directoryEntryNewOU = new DirectoryEntry(newOU);
                dirEntryGroup.MoveTo(directoryEntryNewOU);
            }
            try
            {
                dirEntryGroup.Rename("CN=" + newName);
                dirEntryGroup.CommitChanges();
            }
            catch (Exception fout)
            {
                return(fout.Message);
            }
            return("");
        }
        public static string GetGroupOrganizationUnit(string groupName)
        {
            try
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                {
                    using (GroupPrincipal user = GroupPrincipal.FindByIdentity(context, groupName))
                    {
                        if (user != null)
                        {
                            using (DirectoryEntry deGroup = user.GetUnderlyingObject() as DirectoryEntry)
                            {
                                if (deGroup != null)
                                {
                                    using (DirectoryEntry deGroupContainer = deGroup.Parent)
                                    {
                                        return(deGroupContainer.Properties["Name"].Value.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                // ignored
            }

            return(null);
        }
Exemplo n.º 3
0
        public void SetPropertiesFromGroupPrincipal(GroupPrincipal gp, bool getAccessRules, bool getObjectProperties)
        {
            if (gp == null)
            {
                return;
            }

            SetPropertiesFromPrincipal(gp, getAccessRules);

            object obj = gp.GetUnderlyingObject();

            if (obj.GetType() == typeof(DirectoryEntry) && getObjectProperties)
            {
                DirectoryEntry gde = (DirectoryEntry)obj;
                Properties = DirectoryServices.GetProperties(gde);
            }


            GroupScope      = gp.GroupScope;
            IsSecurityGroup = gp.IsSecurityGroup;

            if (gp.Members?.Count > 0)
            {
                Members = new List <PrincipalObject>();
                foreach (Principal p in gp.Members)
                {
                    Members.Add(new PrincipalObject(p));
                }
            }
        }
Exemplo n.º 4
0
        public static List <string> ListImoGroups()
        {
            var            domainContext = new PrincipalContext(ContextType.Domain, null, "OU=Restricted Access Groups,OU=NETCOM,OU=Fort Carson,OU=Carson,OU=Installations,DC=nanw,DC=ds,DC=army,DC=mil");
            GroupPrincipal imoGroup      = null;

            try
            {
                using (imoGroup = GroupPrincipal.FindByIdentity(domainContext, "CARSON IMO Managers"))
                {
                    var directoryEntryObject = imoGroup.GetUnderlyingObject() as DirectoryEntry;
                    var parentContainer      = directoryEntryObject.Parent;
                    var imoGroups            = parentContainer.Children;
                    var imoGroupList         = new List <string>();
                    foreach (DirectoryEntry group in imoGroups)
                    {
                        imoGroupList.Add(group.Name);
                    }
                    return(imoGroupList);
                }
            }
            catch
            {
            }
            return(null);
        }
        public GroupsInOU(string OUPath)
        {
            if (OUPath.Substring(0, 4) != "LDAP")
            {
                OUPath = ActiveDirectory.LDAPShort + OUPath;
            }
            Groups = new List <Group>();
            DirectorySearcher zoeker = new DirectorySearcher(new DirectoryEntry(OUPath))
            {
                Filter      = "(objectCategory=group)",
                SearchScope = SearchScope.OneLevel
            };

            foreach (SearchResult resultaat in zoeker.FindAll())
            {
                PrincipalContext pc    = new PrincipalContext(ContextType.Domain);
                GroupPrincipal   gp    = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, resultaat.Properties["name"][0].ToString());
                Group            group = new Group();
                group.Name = Helper.HandleNull(resultaat.Properties["name"][0]);
                // zoek de OU op waarin deze groep zich bevindt
                DirectoryEntry dirEntryGroup = (DirectoryEntry)gp.GetUnderlyingObject();
                DirectoryEntry dirEntOU      = dirEntryGroup.Parent;
                group.OU = dirEntOU.Path.Replace("LDAP://", "");

                group.UserMembers  = new UsersInGroup(resultaat.Properties["sAMAccountName"][0].ToString()).Users;
                group.GroupMembers = new GroupsInGroups(resultaat.Properties["sAMAccountName"][0].ToString()).Groups;
                Groups.Add(group);
            }
        }
Exemplo n.º 6
0
        private static void AddUserToGroup(Session session, string account, string groupName)
        {
            bool isMachine;

            GroupPrincipal group = CustomActions.FindInDomainOrMachine(groupName, out isMachine) as GroupPrincipal;

            if (group == null)
            {
                throw new NoMatchingPrincipalException($"The group {groupName} could not be found");
            }

            UserPrincipal user = (UserPrincipal)CustomActions.FindInDomainOrMachine(account, out isMachine);

            if (user == null)
            {
                throw new NoMatchingPrincipalException($"The user {account} could not be found");
            }

            DirectoryEntry gde         = (DirectoryEntry)group.GetUnderlyingObject();
            IADsGroup      nativeGroup = (IADsGroup)gde.NativeObject;

            foreach (object item in nativeGroup.Members())
            {
                byte[]             s   = (byte[])item.GetType().InvokeMember("ObjectSid", System.Reflection.BindingFlags.GetProperty, null, item, null);
                SecurityIdentifier sid = new SecurityIdentifier(s, 0);
                if (user.Sid == sid)
                {
                    session.Log($"User {account} was already in group {groupName}");
                    return;
                }
            }

            session.Log($"User {account} was not in group {groupName}");

            try
            {
                if (gde.Path.StartsWith("winnt", StringComparison.OrdinalIgnoreCase))
                {
                    session.Log($"Adding WINNT://{user.Sid} to group {gde.Path}");
                    nativeGroup.Add($"WINNT://{user.Sid}");
                }
                else
                {
                    DirectoryEntry ude = (DirectoryEntry)user.GetUnderlyingObject();
                    session.Log($"Adding {ude.Path} to group {gde.Path}");
                    nativeGroup.Add(ude.Path);
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                if (e.HResult == -2147019886) //unchecked((int)0x80071392))
                {
                    session.Log($"User {account} was already in group {groupName} - 0x80071392");
                    return;
                }

                throw;
            }
        }
Exemplo n.º 7
0
        public void AddUserToGroups(string userId, List <string> groups)
        {
            using (PrincipalContext userContext = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword))
            {
                ADUser user = ADUser.FindByIdentity(userContext, userId);

                if (user != null)
                {
                    foreach (var grp in groups)
                    {
                        using (PrincipalContext groupContext = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword))
                        {
                            // This is the 'hack' I have implemented to get this application to
                            // run on a machine that is not part of the domain. We are basically
                            // bypassing the built in Group objects and relying on the good old
                            // DirectoryEntry objects to manipulate groups (i.e. adding users if
                            // needed). This is highly inefficient, but I'll just have to live
                            // with this for now while I work on this small application. If this
                            // were ever to go live on a server (or a machine that's on the domain)
                            // then the code you see below would need to be commented out and uncomment
                            // out the code where I am uysing a group principal object instead.
                            //
                            // See Github Issue #79 for more information on this issue and
                            // why I have employed this hack to get this application working on
                            // my machines at home.
                            GroupPrincipal group        = GroupPrincipal.FindByIdentity(groupContext, grp);
                            DirectoryEntry groupDE      = (DirectoryEntry)group.GetUnderlyingObject();
                            var            isUserMember = (bool)groupDE.Invoke("IsMember", new object[] { "LDAP://" + ServerName + "/" + user.DistinguishedName });

                            if (!isUserMember)
                            {
                                groupDE.Invoke("Add", new object[] { "LDAP://" + ServerName + "/" + user.DistinguishedName });
                            }

                            groupDE.Close();

                            /*if(group != null)
                             * {
                             *  // Github Issue #79 causes an error when this code runs
                             *  // when running on a computer that's not part of the domain.
                             *  // To get this to work property, I have to add the IP address
                             *  // of the domain controller which I don't want to do. I'll have
                             *  // to re-write this part of the application so that it uses
                             *  //if(!user.IsMemberOf(group))
                             *  if(!group.GetMembers().Contains(user))
                             *  {
                             *      group.Members.Add(user);
                             *      group.Save();
                             *  }
                             * }*/
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        public Group(string samAccountName)
        {
            SamAccountName = samAccountName;
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            GroupPrincipal = GroupPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountName);
            if (GroupPrincipal == null)
            {
                throw new Exception($"{samAccountName} kon niet gevonden worden in AD");
            }
            DirectoryEntry = (DirectoryEntry)GroupPrincipal.GetUnderlyingObject();
        }
        /// <summary>
        /// Adds the user for a given group
        /// </summary>
        /// <param name="sUserName">The user you want to add to a group</param>
        /// <param name="sGroupName">The group you want the user to be added in</param>
        /// <returns>Returns true if successful</returns>
        public bool AddUserToGroup(string sUserName, string sGroupName)
        {
            bool success = false;

            try
            {
                DirectoryEntry RootDirEntry      = new DirectoryEntry("LDAP://RootDSE");
                Object         distinguishedName = RootDirEntry.Properties["defaultNamingContext"].Value;
                string         strDN             = distinguishedName.ToString();
                using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
                                                                                 Environment.UserDomainName,
                                                                                 strDN))
                {
                    UserPrincipal  oUserPrincipal  = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
                    GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
                    if (oUserPrincipal != null && oGroupPrincipal != null)
                    {
                        bool isMember = oGroupPrincipal.Members.Contains(oUserPrincipal);
                        if (!isMember)
                        {
                            oGroupPrincipal.Members.Add(oUserPrincipal);
                            oGroupPrincipal.Save();
                            DirectoryEntry entry = (DirectoryEntry)oGroupPrincipal.GetUnderlyingObject();
                            entry.RefreshCache(new string[] { "member" });
                            success = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                List <string> logLines = new List <string>();
                DateTime      time     = DateTime.Now;
                string        header   = string.Format("###########################################################");
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), header));
                string message = string.Format("Exception while trying to add User: {0} to Group: {1}",
                                               sUserName, sGroupName);
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), message));
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.Message));
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.StackTrace));
                if (ex.InnerException != null)
                {
                    string innerMessage = string.Format("Inner Exception...");
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), innerMessage));
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.InnerException.Message));
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.InnerException.StackTrace));
                }

                System.IO.File.AppendAllLines("LogFile.txt", logLines);
            }

            return(success);
        }
        public JsonResult MembersOfGroup(string groupName = "_Agency_BI_Agency")
        {
            if (groupName != "")
            {
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
                GroupPrincipal   group            = GroupPrincipal.FindByIdentity(principalContext, groupName);

                //Grup yöneticisini bulma
                DirectoryEntry obj   = (DirectoryEntry)group.GetUnderlyingObject();
                var            owner = obj.Properties["managedBy"];

                // Grup üyelerinin tutulacağı liste
                var members = new List <ActiveDirectoryMember>();

                foreach (Principal principal in group.Members)
                {
                    // Admin hariç tüm üyeler üye listesine ekleniyor.
                    // Admin daha sonra bulunup, listenin en başına eklenecek.
                    if (owner.Value == null || principal.DistinguishedName.ToString() != owner.Value.ToString())
                    {
                        ActiveDirectoryMember currentMember = new ActiveDirectoryMember();
                        currentMember.userName = principal.Name;
                        currentMember.userMail = principal.UserPrincipalName;
                        currentMember.isAdmin  = false;

                        members.Add(currentMember);
                    }
                }

                if (owner.Value != null)
                {
                    // Admin'in mail adresinin bulunması için, kullanıcı aranıyor.
                    UserPrincipal         userAdmin = UserPrincipal.FindByIdentity(principalContext, owner.Value.ToString());
                    ActiveDirectoryMember admin     = new ActiveDirectoryMember();
                    admin.userName = userAdmin.Name;
                    admin.userMail = userAdmin.UserPrincipalName;
                    admin.isAdmin  = true;

                    if (!members.Contains(admin))
                    {
                        members.Insert(0, admin);
                    }
                }

                return(Json(members, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(true));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Removes user from a given group
        /// </summary>
        /// <param name="sUserName">The user you want to remove from a group</param>
        /// <param name="sGroupName">The group you want the user to be removed from</param>
        /// <returns>Returns true if successful</returns>
        public bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            bool success = false;

            try
            {
                using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
                                                                                 Environment.UserDomainName,
                                                                                 sServiceUser,
                                                                                 sServicePassword))
                {
                    UserPrincipal  oUserPrincipal  = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
                    GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
                    if (oUserPrincipal != null && oGroupPrincipal != null)
                    {
                        bool isMember = oGroupPrincipal.Members.Contains(oUserPrincipal);
                        if (isMember)
                        {
                            oGroupPrincipal.Members.Remove(oUserPrincipal);
                            oGroupPrincipal.Save();
                            DirectoryEntry entry = (DirectoryEntry)oGroupPrincipal.GetUnderlyingObject();
                            entry.RefreshCache(new string[] { "member" });
                            success = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                List <string> logLines = new List <string>();
                DateTime      time     = DateTime.Now;
                string        header   = string.Format("###########################################################");
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), header));
                string message = string.Format("Exception while trying to remove User: {0} from Group: {1}",
                                               sUserName, sGroupName);
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), message));
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.Message));
                logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.StackTrace));
                if (ex.InnerException != null)
                {
                    string innerMessage = string.Format("Inner Exception...");
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), innerMessage));
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.InnerException.Message));
                    logLines.Add(string.Format("{0,-20}{1}", time.ToLongTimeString(), ex.InnerException.StackTrace));
                }

                System.IO.File.AppendAllLines("LogFile.txt", logLines);
            }

            return(success);
        }
Exemplo n.º 12
0
        public bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            bool success = false;

            //bool isOwner = IsUserGroupOwner(sGroupName);
            //if (!isOwner)
            //return false;

            try
            {
                using (System.Web.Hosting.HostingEnvironment.Impersonate())
                {
                    string dlManagerUserName = AppCredentials.Instance.UserName;
                    string dlManagerPassword = AppCredentials.Instance.Password;

                    using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
                                                                                     Environment.UserDomainName,
                                                                                     dlManagerUserName,
                                                                                     dlManagerPassword))
                    {
                        UserPrincipal  oUserPrincipal  = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
                        GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
                        if (oUserPrincipal != null && oGroupPrincipal != null)
                        {
                            bool isMember = oGroupPrincipal.Members.Contains(oUserPrincipal);
                            if (isMember)
                            {
                                oGroupPrincipal.Members.Remove(oUserPrincipal);
                                oGroupPrincipal.Save();
                                DirectoryEntry entry = (DirectoryEntry)oGroupPrincipal.GetUnderlyingObject();
                                entry.RefreshCache(new string[] { "member" });
                                success = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                StringBuilder additionalInfo = new StringBuilder();
                additionalInfo.Append("Exception while trying to remove user: '******' from the group: '");
                additionalInfo.Append(sGroupName);
                additionalInfo.Append("'.");
                LoggingHelper.Instance.LogError(LogOptions.RemoveUsers, ex, additionalInfo.ToString());
            }

            return(success);
        }
Exemplo n.º 13
0
        public void UpdateGroupPrincipal(GroupPrincipal group)
        {
            if (this.SamAccountName != null)
            {
                group.SamAccountName = SetValueOrNull(this.SamAccountName);
            }
            if (this.Description != null)
            {
                group.Description = SetValueOrNull(this.Description);
            }

            if (this.IsSecurityGroup != null)
            {
                group.IsSecurityGroup = this.IsSecurityGroup;
            }

            if (this.Scope != null)
            {
                group.GroupScope = this.Scope;
            }

            // Get DistinguishedName from User or Group Identity for ManagedBy Property
            if (this.ManagedBy != null && group.GetUnderlyingObjectType() == typeof(DirectoryEntry))
            {
                String distinguishedName = DirectoryServices.GetDistinguishedName(this.ManagedBy);
                if (distinguishedName == null)
                {
                    distinguishedName = this.ManagedBy;     // Cant' Find As User Or Group, Pass Raw Value (Might Be ~null~)
                }
                DirectoryServices.SetProperty((DirectoryEntry)group.GetUnderlyingObject(), "managedby", distinguishedName);
            }

            if (group.GetUnderlyingObjectType() == typeof(DirectoryEntry) && this.Properties?.Count > 0)
            {
                DirectoryServices.SetProperties((DirectoryEntry)group.GetUnderlyingObject(), this.Properties);
            }
        }
Exemplo n.º 14
0
        public bool IsUserGroupOwner(string group)
        {
            bool isOwner = true;

            try
            {
                using (System.Web.Hosting.HostingEnvironment.Impersonate())
                {
                    string userName          = HttpContext.Current.User.Identity.Name;
                    string dlManagerUserName = AppCredentials.Instance.UserName;
                    string dlManagerPassword = AppCredentials.Instance.Password;

                    using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,
                                                                                     Environment.UserDomainName,
                                                                                     dlManagerUserName,
                                                                                     dlManagerPassword))
                    {
                        UserPrincipal  oUserPrincipal  = UserPrincipal.FindByIdentity(oPrincipalContext, userName);
                        GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, group);
                        if (oUserPrincipal != null && oGroupPrincipal != null)
                        {
                            DirectoryEntry dE = (DirectoryEntry)oGroupPrincipal.GetUnderlyingObject();
                            isOwner = dE.Properties["managedBy"].Value != null && ((string)dE.Properties["managedBy"].Value).Equals(oUserPrincipal.DistinguishedName);
                            if (dE.Properties["msexchcomanagedbylink"].Value != null)
                            {
                                object[] msExchangeValues = dE.Properties["msexchcomanagedbylink"].Value as object[];
                                foreach (object msExchangeValue in msExchangeValues)
                                {
                                    string value = (string)msExchangeValue;
                                    Console.WriteLine("MSExchange Managed By: " + value);
                                    isOwner = isOwner || value.Equals(oUserPrincipal.DistinguishedName);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Instance.LogError(LogOptions.CheckAdmin, ex);
            }

            return(isOwner);
        }
Exemplo n.º 15
0
        //Gets group details, identify if members of the group are of type user of it's a nested group
        public ADGroup GetADGroupDetails(string groupVal)
        {
            ADGroup adGroup = new ADGroup();

            adGroup.GroupName         = groupVal;
            adGroup.GroupObjects      = new List <ADGroupObject>();
            adGroup.GroupObjectsNames = new List <string>();
            PrincipalContext context = GetContext();

            if (context != null)
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupVal);
                if (group != null)
                {
                    DirectoryEntry deGroupObject = group.GetUnderlyingObject() as DirectoryEntry;
                    foreach (Principal p in group.GetMembers())
                    {
                        if (p.SamAccountName != AppAuth["Username"])
                        {
                            if (p.SamAccountName != null)
                            {
                                DirectoryEntry deP = p.GetUnderlyingObject() as DirectoryEntry;
                                adGroup.GroupObjectsNames.Add(p.SamAccountName);
                                ADGroupObject adGroupObject = new ADGroupObject();
                                adGroupObject.SamAccountName = p.SamAccountName;
                                adGroupObject.ObjectType     = (int)deP.Properties["sAMAccountType"].Value;
                                if (adGroupObject.ObjectType == 268435456 || adGroupObject.ObjectType == 268435457)
                                {
                                    adGroupObject.ObjectTypeString = "group";
                                }
                                else
                                {
                                    adGroupObject.ObjectTypeString = "user";
                                }
                                adGroup.GroupObjects.Add(adGroupObject);
                            }
                        }
                    }
                    group.Dispose();
                }
                context.Dispose();
            }
            return(adGroup);
        }
Exemplo n.º 16
0
        private IEnumerable <PrincipalInfo> EnumerateActiveDirectoryGroup(GroupPrincipal group)
        {
            List <PrincipalInfo> userInfos = new List <PrincipalInfo>();

            if (!resolvedIdentities.Contains(group.DistinguishedName))
            {
                resolvedIdentities.Add(group.DistinguishedName);
                try {
                    DirectoryEntry groupEntry = (DirectoryEntry)group.GetUnderlyingObject();
                    foreach (string dn in groupEntry.Properties["member"])
                    {
                        try {
                            DirectoryEntry     memberEntry = new DirectoryEntry("LDAP://" + dn);
                            PropertyCollection userProps   = memberEntry.Properties;
                            object[]           objectClass = (object[])userProps["objectClass"].Value;

                            if (objectClass.Contains("group"))
                            {
                                userInfos.AddRange(EnumerateActiveDirectoryGroup(IdentityType.DistinguishedName, userProps["distinguishedName"].Value.ToString()));
                                continue;
                            }
                            if (objectClass.Contains("foreignSecurityPrincipal"))
                            {
                                userInfos.AddRange(EnumerateForeignSecurityPrincipal(memberEntry));
                                continue;
                            }
                            PrincipalInfo userInfo = ResolveActiveDirectoryUser(IdentityType.DistinguishedName, dn);
                            if (userInfo != null)
                            {
                                userInfos.Add(userInfo);
                            }
                        } catch (Exception ex) {
                            userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.DistinguishedName, dn, ex)));
                        }
                    }
                } catch (ADPrincipalResolveException) {
                    throw;
                } catch (Exception ex) {
                    userInfos.Add(ExceptionHandler(new ADPrincipalResolveException(IdentityType.DistinguishedName, group.DistinguishedName, ex)));
                }
            }
            return(userInfos);
        }
        /// <summary>
        /// getNestedGroups will return an array with the DNs of all groups contained
        /// in the group that was passed in as a parameter
        /// </summary>
        /// <param name="strGroupDN">DN of the group, which the nested groups should be retrieved from</param>
        /// <returns>ArrayList containing the DNs of each group contained in the group apssed in asa parameter</returns>
        public ArrayList getNestedGroups(string strGroupDN)
        {
            ArrayList groupMembers = new ArrayList();

            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            {
                Principal         prototype = new GroupPrincipal(ctx);
                PrincipalSearcher searcher  = new PrincipalSearcher(prototype);

                PropertyValueCollection email;

                foreach (var gp in searcher.FindAll())
                {
                    using (gp)
                    {
                        GroupPrincipal group = gp as GroupPrincipal;

                        using (DirectoryEntry groupEntry = ((DirectoryEntry)group.GetUnderlyingObject()))
                        {
                            email = groupEntry.Properties["mail"];
                            //if (email.Value != null)
                            //{
                            groupMembers.Add(group.Name);
                            //}
                        }
                    }
                }
            }

            //// find all nested groups in this group
            ////string strDomains = "playasur,mtvn,mtvne,viacom_corp,mtvnasia,paramount,ad,corp";
            //ds.Filter = String.Format("(&(memberOf={0})(objectClass=group))", "CITRIX-CF-OFFSHORE REMOTE DESKTOP");

            //ds.PropertiesToLoad.Add("distinguishedName");

            //foreach (SearchResult sr in ds.FindAll())
            //{
            //    groupMembers.Add(sr.Properties["distinguishedName"][0].ToString());
            //}

            return(groupMembers);
        }
Exemplo n.º 18
0
        /// <summary>
        /// This method receives a GroupInfoResult object containing a groupname to check
        /// and get fields from the group's AD object
        /// </summary>
        /// <param name="infoResult">A GroupInfoResult object containing the groupname</param>
        /// <returns>A GroupInfoResult containing the groupname and additional AD fields</returns>
        public static GroupInfoResult GetGroupInfoByGroupname(GroupInfoResult infoResult)
        {
            // Set up domain context.
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain);

            // Find the group in AD.
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, infoResult.sAMAccountName);

            if (group != null)
            {
                infoResult.code = 0;
                // Get directory entry for group to extract extra properties.
                DirectoryEntry de = group.GetUnderlyingObject() as DirectoryEntry;
                // Checking extra properties to make sure they exist and add them to result.
                if (de.Properties.Contains("cn"))
                {
                    infoResult.cn = de.Properties["cn"].Value.ToString();
                }
                if (de.Properties.Contains("displayName"))
                {
                    infoResult.displayName = de.Properties["displayName"].Value.ToString();
                }
                if (de.Properties.Contains("description"))
                {
                    infoResult.description = de.Properties["description"].Value.ToString();
                }
                if (de.Properties.Contains("mail"))
                {
                    infoResult.mail = de.Properties["mail"].Value.ToString();
                }
            }
            else
            {
                // Group not found in AD.
                infoResult.code = 1;
            }

            return(infoResult);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Maps a given group principal to a new group object
        /// </summary>
        private BaseActiveDirectoryGroup MapGroupPrincipalToGroup(GroupPrincipal groupPrincipal, bool loadSubProperties)
        {
            var adGroup = new BaseActiveDirectoryGroup
            {
                Id = ConvertSidToString(groupPrincipal.Sid),
                NameOrDescription = groupPrincipal.Name,
            };

            //Check to load subproperties
            if (loadSubProperties)
            {
                //Load groups additional data
                var directoryEntry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();

                adGroup.Path         = directoryEntry.Path;
                adGroup.CreationDate = (DateTime?)directoryEntry.InvokeGet(whenCreatedKey);
                adGroup.Owner        = (string)directoryEntry.InvokeGet(managedByKey);

                if (!string.IsNullOrEmpty(adGroup.Owner))
                {
                    adGroup.Owner = adGroup.Owner.Substring(3, (adGroup.Owner.IndexOf("OU=") - 3)).RemoveSpecialChars();
                }

                //Load group users
                var groupUsersList = groupPrincipal.GetMembers()
                                     .Where(m => m.GetType() == typeof(UserPrincipal))
                                     .Cast <UserPrincipal>()
                                     .Select(gul => new BaseIdentification
                {
                    Id = ConvertSidToString(gul.Sid),
                    NameOrDescription = gul.SamAccountName
                });

                //Add users inside current AD group
                adGroup.Users.AddRange(groupUsersList);
            }

            return(adGroup);
        }
Exemplo n.º 20
0
        public static adGroups adGrpDetailsFinder(PrincipalContext context, string adGroup)
        {
            adGroups       ladGrp = new adGroups();
            GroupPrincipal grp    = GroupPrincipal.FindByIdentity(context, adGroup);

            if (grp != null)
            {
                System.DirectoryServices.DirectoryEntry underlayingFields = grp.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry;
                ladGrp.Name        = grp.Name;
                ladGrp.DN          = grp.DistinguishedName;
                ladGrp.Description = grp.Description;
                ladGrp.Scope       = grp.GroupScope.Value.ToString();

                if (grp.IsSecurityGroup == true)
                {
                    ladGrp.Type = "Security";
                }
                else
                {
                    ladGrp.Type = "Distribution";
                }

                if (underlayingFields.Properties.Contains("info"))
                {
                    ladGrp.Notes = underlayingFields.Properties["info"].Value.ToString();
                }

                if (underlayingFields.Properties.Contains("whenCreated"))
                {
                    ladGrp.CreationDate = underlayingFields.Properties["whenCreated"].Value.ToString();
                }

                if (underlayingFields.Properties.Contains("whenChanged"))
                {
                    ladGrp.ChangedDate = underlayingFields.Properties["whenChanged"].Value.ToString();
                }
            }
            return(ladGrp);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Displays the list of users in a group
        /// </summary>
        /// <param name="id"></param>
        /// <param name="id2">"1" if the sub groups are to display too, "0" otherwise</param>
        /// <returns></returns>
        public ActionResult DetailGroup(string id, string id2 = "0")
        {
            if (!string.IsNullOrEmpty(id))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, Settings.Default.ADPath), id);
                if (group != null)
                {
                    List <UserModel>  users  = new List <UserModel>();
                    List <GroupModel> groups = new List <GroupModel>();

                    var members = group.GetMembers(id2 != "0");
                    foreach (var member in members)
                    {
                        if (member is UserPrincipal)
                        {
                            users.Add(new UserModel(member.GetUnderlyingObject() as DirectoryEntry));
                        }
                    }

                    var subgroups = group.GetMembers();
                    foreach (var subgroup in subgroups)
                    {
                        if (subgroup is GroupPrincipal)
                        {
                            groups.Add(new GroupModel(subgroup.GetUnderlyingObject() as DirectoryEntry));
                        }
                    }

                    ViewBag.Group     = new GroupModel(group.GetUnderlyingObject() as DirectoryEntry);
                    ViewBag.Users     = users.ToArray();
                    ViewBag.Groups    = groups.ToArray();
                    ViewBag.Recursive = id2 != "0";
                    return(View());
                }
            }
            return(RedirectToAction("FindGroup"));
        }
Exemplo n.º 22
0
        public static void AddUserToGroup(string userId, string groupName)
        {
            var domainGroups = ConfigurationManager.AppSettings["domainForGroups"];
            var domainUsers  = ConfigurationManager.AppSettings["domain"];

            var adContextUser     = ConfigurationManager.AppSettings["adContextUser"];
            var adContextPassword = ConfigurationManager.AppSettings["adContextPassword"];

            userId = userId.Replace(domainUsers + "\\", "");


            using (PrincipalContext pcSMI = new PrincipalContext(ContextType.Domain, domainUsers))
            {
                using (PrincipalContext pcAPAC = new PrincipalContext(ContextType.Domain, domainGroups, adContextUser, adContextPassword))
                {
                    using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(pcSMI, IdentityType.SamAccountName, userId))
                    {
                        if (userPrincipal != null)
                        {
                            using (GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(pcAPAC, groupName))
                            {
                                if (groupPrincipal != null)
                                {
                                    if (!userPrincipal.IsMemberOf(groupPrincipal))
                                    {
                                        string         userSid             = string.Format("<SID={0}>", userPrincipal.Sid.ToString());
                                        DirectoryEntry groupDirectoryEntry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();
                                        groupDirectoryEntry.Properties["member"].Add(userSid);
                                        groupDirectoryEntry.CommitChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 23
0
        public void CreateUserWithTemplate(User user, UserTemplateSettings userTemplateSettings)
        {
            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ServerName, userTemplateSettings.DomainOU, ContextOptions.Negotiate, ServiceUser, ServicePassword))
            {
                using (ADUser newUser = new ADUser(context))
                {
                    newUser.SamAccountName = user.Username;
                    newUser.GivenName      = user.FirstName;
                    newUser.MiddleName     = user.MiddleName;
                    newUser.Surname        = user.LastName;
                    newUser.EmailAddress   = user.EmailAddress;
                    newUser.PhoneNumber    = user.PhoneNumber;
                    newUser.Title          = user.Title;
                    newUser.Department     = user.Department;
                    newUser.Notes          = "Created by ADWeb on " + DateTime.Now.ToString() + ".";
                    newUser.DisplayName    = user.LastName + ", " + user.FirstName;
                    //newUser.Name = user.LastName + ", " + user.FirstName;
                    //newUser.CommonName = "CN=" + user.LastName + "\\, " + user.FirstName + "," + userTemplateSettings.DomainOU;
                    newUser.UserPrincipalName = user.Username + UPNSuffix;
                    newUser.Enabled           = true;

                    // Settings from the User template
                    newUser.UserCannotChangePassword = userTemplateSettings.UserCannotChangePassword;

                    if (userTemplateSettings.ChangePasswordAtNextLogon)
                    {
                        // This will force the user to change their password
                        // the next time they login
                        newUser.ExpirePasswordNow();
                    }

                    newUser.PasswordNeverExpires = userTemplateSettings.PasswordNeverExpires;

                    if (userTemplateSettings.AccountExpires)
                    {
                        // We have to determine how long until the user's account
                        // will expire in relation to the date that it is being created.
                        DateTime?expirationDate = new DateTime();

                        switch (userTemplateSettings.ExpirationRange)
                        {
                        case UserExpirationRange.Days:
                            expirationDate = DateTime.Now.AddDays(userTemplateSettings.ExpirationValue.Value);
                            break;

                        case UserExpirationRange.Weeks:
                            int totalDays = 7 * userTemplateSettings.ExpirationValue.Value;
                            expirationDate = DateTime.Now.AddDays(totalDays);
                            break;

                        case UserExpirationRange.Months:
                            expirationDate = DateTime.Now.AddMonths(userTemplateSettings.ExpirationValue.Value);
                            break;

                        case UserExpirationRange.Years:
                            expirationDate = DateTime.Now.AddYears(userTemplateSettings.ExpirationValue.Value);
                            break;

                        default:
                            break;
                        }

                        newUser.AccountExpirationDate = expirationDate;
                    }

                    newUser.SetPassword(user.Password);
                    newUser.Save();

                    // Now now have to add the user to the groups associated with the user template.
                    // Note: We are using RootDSE for now because we are looking at the whole domain.
                    // This will need to be changed later on so that only certain OU's will be searched
                    // for groups
                    using (PrincipalContext groupContext = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword))
                    {
                        foreach (var grp in userTemplateSettings.Groups)
                        {
                            using (GroupPrincipal group = GroupPrincipal.FindByIdentity(groupContext, grp))
                            {
                                if (group != null)
                                {
                                    // This is being done to address Github Issue #79. For now we are using
                                    // the underlying DirectoryEntry object so that the application can be
                                    // hosted on a machine that is not part of the domain.
                                    DirectoryEntry groupDE = (DirectoryEntry)group.GetUnderlyingObject();
                                    groupDE.Invoke("Add", new object[] { "LDAP://" + ServerName + "/" + newUser.DistinguishedName });
                                    groupDE.Close();

                                    //group.Members.Add(newUser);
                                    //group.Save();
                                }
                            }
                        }
                    }
                }
            }
        }