public static bool IsExistingUser(string identity)
        {
            String idOnly = null;
            String domain = DirectoryServices.GetDomain(identity, out idOnly);

            return(GetUserPrincipal(idOnly, domain) != null);
        }
示例#2
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));
                }
            }
        }
        public static UserPrincipalObject GetUser(string identity, bool getGroups, bool getAccessRules, bool getObjectProperties)
        {
            UserPrincipalObject u = null;

            try
            {
                String        idOnly = null;
                String        domain = DirectoryServices.GetDomain(identity, out idOnly);
                UserPrincipal user   = GetUserPrincipal(idOnly, domain);

                if (user != null)
                {
                    u = new UserPrincipalObject(user, getAccessRules, getObjectProperties);
                    if (getGroups)
                    {
                        u.GetGroups();
                    }
                }
            }
            catch (MultipleMatchesException mme)
            {
                throw new AdException($"Multiple Users Contain The Identity [{identity}].", mme, AdStatusType.MultipleMatches);
            }

            return(u);
        }
示例#4
0
        public void SetPropertiesFromPrincipal(Principal p, bool getAccessRules)
        {
            _innerPrincipal = p;

            if (p == null)
            {
                return;
            }

            ContextType       = p.ContextType;
            Description       = p.Description;
            DisplayName       = p.DisplayName;
            DistinguishedName = p.DistinguishedName;
            Guid                  = p.Guid;
            Name                  = p.Name;
            SamAccountName        = p.SamAccountName;
            Sid                   = p.Sid.Value;
            StructuralObjectClass = p.StructuralObjectClass;
            UserPrincipalName     = p.UserPrincipalName;

            if (getAccessRules)
            {
                AccessRules = new List <AccessRuleObject>();
                AccessRules = DirectoryServices.GetAccessRules(p);
            }
        }
示例#5
0
        public static GroupPrincipalObject GetGroup(string identity, bool getGroups, bool getAccessRules, bool getObjectProperties)
        {
            GroupPrincipalObject g = null;

            try
            {
                String         idOnly = null;
                String         domain = DirectoryServices.GetDomain(identity, out idOnly);
                GroupPrincipal group  = GetGroupPrincipal(idOnly, domain);

                if (group != null)
                {
                    g = new GroupPrincipalObject(group, getAccessRules, getObjectProperties);
                    if (getGroups)
                    {
                        g.GetGroups();
                    }
                }
            }
            catch (MultipleMatchesException mme)
            {
                throw new AdException($"Multiple Groups Contain The Identity [{identity}].", mme, AdStatusType.MultipleMatches);
            }

            return(g);
        }
        public static string GetDistinguishedName(string identity)
        {
            String    idOnly    = null;
            String    domain    = GetDomain(identity, out idOnly);
            Principal principal = DirectoryServices.GetPrincipal(idOnly, domain);

            return(principal?.DistinguishedName);
        }
        public static void SetAccessRule(DirectoryEntry de, String identity, ActiveDirectoryRights rights, AccessControlType type, ActiveDirectorySecurityInheritance inherit = ActiveDirectorySecurityInheritance.None)
        {
            Principal principal = DirectoryServices.GetPrincipal(identity);

            if (principal == null)
            {
                throw new AdException($"Principal [{identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
            }
            SetAccessRule(de, principal, rights, type, inherit);
        }
        public static void PurgeAccessRules(DirectoryEntry de, String identity)
        {
            Principal principal = DirectoryServices.GetPrincipal(identity);

            if (principal == null)
            {
                throw new AdException($"Principal [{identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
            }
            PurgeAccessRules(de, principal);
        }
        public static UserPrincipal CreateUserPrincipal(string distinguishedName, string userPrincipalName = null, string samAccountName = null, bool saveOnCreate = true)
        {
            String name   = distinguishedName;
            String domain = DirectoryServices.GetDomain(distinguishedName, out name);
            String path   = domain;

            if (DirectoryServices.IsDistinguishedName(distinguishedName))
            {
                Regex regex = new Regex(@"cn=(.*?),(.*)$", RegexOptions.IgnoreCase);
                Match match = regex.Match(distinguishedName);
                if (match.Success)
                {
                    name = match.Groups[1]?.Value?.Trim();
                    path = match.Groups[2]?.Value?.Trim();
                }
                domain = DirectoryServices.GetDomain(distinguishedName);
            }
            else if (String.IsNullOrWhiteSpace(distinguishedName) || String.IsNullOrWhiteSpace(path))
            {
                throw new AdException("Unable To Create User Principal From Given Input.", AdStatusType.MissingInput);
            }

            path = path.Replace("LDAP://", "");
            PrincipalContext context = DirectoryServices.GetPrincipalContext(path);
            UserPrincipal    user    = new UserPrincipal(context)
            {
                Name = name,
                UserPrincipalName = userPrincipalName ?? $"{name}@{domain}"
            };

            if (samAccountName != null)
            {
                if (samAccountName.Length < 20)
                {
                    user.SamAccountName = samAccountName;
                }
                else
                {
                    throw new AdException($"SamAccountName [{samAccountName}] Is Longer than 20 Characters.", AdStatusType.InvalidAttribute);
                }
            }
            else if (name.Length < 20)
            {
                user.SamAccountName = name;
            }

            if (saveOnCreate)
            {
                SaveUser(user);
            }

            return(user);
        }
示例#10
0
        public static DirectoryEntry GetDirectoryEntry(string identity, string objectClass = null)
        {
            string searchString = null;

            if (String.IsNullOrWhiteSpace(identity))
            {
                return(null);
            }

            identity = identity.Replace("LDAP://", "");

            String id     = null;
            String domain = DirectoryServices.GetDomain(identity, out id);

            if (IsDistinguishedName(id))
            {
                searchString = $"(distinguishedName={id})";
            }
            else if (IsGuid(id))
            {
                searchString = $"(objectGuid={GetGuidSearchBytes(id)})";
            }
            else if (IsSid(id))
            {
                searchString = $"(objectSid={id})";
            }
            else
            {
                searchString = $"(|(name={id})(userPrincipalName={id})(sAMAccountName={id}))";
            }

            if (objectClass != null)
            {
                searchString = $"(&(objectClass={objectClass}){searchString})";
            }

            List <DirectoryEntry> results = GetDirectoryEntries(searchString, domain);

            if (results.Count > 1)
            {
                throw new AdException($"Multiple Objects Found With Identity [{identity}].", AdStatusType.MultipleMatches);
            }

            if (results.Count > 0)
            {
                return(results[0]);
            }
            else
            {
                return(null);
            }
        }
示例#11
0
        public static DirectoryEntry Rename(string identity, string newName)
        {
            DirectoryEntry de = GetDirectoryEntry(identity);
            String         distinguishedName = de.Properties["distinguishedName"].Value.ToString();
            String         prefix            = de.Name.Substring(0, de.Name.IndexOf("="));
            String         parentName        = DirectoryServices.GetParentPath(distinguishedName);
            DirectoryEntry parent            = GetDirectoryEntry(parentName);

            de.MoveTo(parent, $"{prefix}={newName}");

            String newPath = parent.Path.Replace("LDAP://", "");

            newPath = newPath.Substring(newPath.IndexOf("/") + 1);
            String newDN = $"{prefix}={newName},{newPath}";

            return(GetDirectoryEntry(newDN));
        }
        public static List <AccessRuleObject> GetAccessRules(DirectoryEntry de)
        {
            if (de == null)
            {
                throw new AdException($"DirectoryEntry Can Not Be NULL", AdStatusType.MissingInput);
            }

            List <AccessRuleObject>        accessRules = new List <AccessRuleObject>();
            Dictionary <string, Principal> principals  = new Dictionary <string, Principal>();

            AuthorizationRuleCollection rules = de?.ObjectSecurity?.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            if (rules != null)
            {
                foreach (AuthorizationRule rule in rules)
                {
                    ActiveDirectoryAccessRule accessRule = (ActiveDirectoryAccessRule)rule;
                    AccessRuleObject          aro        = new AccessRuleObject()
                    {
                        ControlType       = accessRule.AccessControlType,
                        Rights            = accessRule.ActiveDirectoryRights,
                        IdentityReference = accessRule.IdentityReference.Value,
                        InheritanceFlags  = accessRule.InheritanceFlags,
                        IsInherited       = accessRule.IsInherited,
                    };

                    Principal principal = null;
                    if (principals.ContainsKey(aro.IdentityReference))
                    {
                        principal = principals[aro.IdentityReference];
                    }
                    else
                    {
                        principal = DirectoryServices.GetPrincipal(aro.IdentityReference);
                        principals.Add(aro.IdentityReference, principal);
                    }

                    aro.IdentityName = principal.Name;
                    accessRules.Add(aro);
                }
            }

            return(accessRules);
        }
        public static List <AccessRuleObject> GetAccessRules(DirectoryEntry de)
        {
            if (de == null)
            {
                throw new AdException($"DirectoryEntry Can Not Be NULL", AdStatusType.MissingInput);
            }

            List <AccessRuleObject>     accessRules = new List <AccessRuleObject>();
            AuthorizationRuleCollection rules       = de?.ObjectSecurity?.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            if (rules != null)
            {
                foreach (AuthorizationRule rule in rules)
                {
                    ActiveDirectoryAccessRule accessRule = (ActiveDirectoryAccessRule)rule;
                    AccessRuleObject          aro        = new AccessRuleObject()
                    {
                        ControlType       = accessRule.AccessControlType,
                        Rights            = accessRule.ActiveDirectoryRights,
                        IdentityReference = accessRule.IdentityReference.Value,
                        InheritanceFlags  = accessRule.InheritanceFlags,
                        IsInherited       = accessRule.IsInherited,
                    };

                    String identity = aro.IdentityReference;

                    if (DirectoryServices.IsSid(aro.IdentityReference))
                    {
                        // Get User-Readable Principal Name from Sid
                        System.Security.Principal.SecurityIdentifier sid  = (System.Security.Principal.SecurityIdentifier)rule.IdentityReference;
                        System.Security.Principal.NTAccount          acct = (System.Security.Principal.NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount));
                        identity = acct.Value;
                    }

                    aro.IdentityName = identity;
                    accessRules.Add(aro);
                }
            }

            return(accessRules);
        }
        public static void PurgeAccessRules(Principal target, String identity)
        {
            Principal principal = DirectoryServices.GetPrincipal(identity);

            if (principal == null)
            {
                throw new AdException($"Principal [{identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
            }
            else if (target == null)
            {
                throw new AdException($"Target Principal Can Not Be NULL", AdStatusType.MissingInput);
            }
            else if (target.GetUnderlyingObjectType() == typeof(DirectoryEntry))
            {
                PurgeAccessRules((DirectoryEntry)target.GetUnderlyingObject(), principal);
            }
            else
            {
                throw new AdException($"PurgeAccessRules Not Available For Object Type [{target.GetUnderlyingObjectType()}]", AdStatusType.NotSupported);
            }
        }
        public static void SetAccessRule(Principal target, String identity, ActiveDirectoryRights rights, AccessControlType type, ActiveDirectorySecurityInheritance inherit = ActiveDirectorySecurityInheritance.None)
        {
            Principal principal = DirectoryServices.GetPrincipal(identity);

            if (principal == null)
            {
                throw new AdException($"Principal [{identity}] Can Not Be Found.", AdStatusType.DoesNotExist);
            }
            else if (target == null)
            {
                throw new AdException($"Target Principal Can Not Be NULL", AdStatusType.MissingInput);
            }
            else if (target.GetUnderlyingObjectType() == typeof(DirectoryEntry))
            {
                SetAccessRule((DirectoryEntry)target.GetUnderlyingObject(), principal, rights, type, inherit);
            }
            else
            {
                throw new AdException($"SetAccessRule Not Available For Object Type [{target.GetUnderlyingObjectType()}]", AdStatusType.NotSupported);
            }
        }
示例#16
0
        public void SetPropertiesFromDirectoryEntry(DirectoryEntry de, bool loadSchema, bool getAccessRules, bool getObjectProperties, bool getParent)
        {
            if (de == null)
            {
                return;
            }

            Guid       = de.Guid;
            Name       = de.Name;
            NativeGuid = de.NativeGuid;
            if (getParent)
            {
                Parent = new DirectoryEntryObject(de.Parent, false, false, false, false);
            }

            if (de.Properties != null && getObjectProperties)
            {
                Properties = new SerializableDictionary <string, List <string> >();
                IDictionaryEnumerator ide = de.Properties.GetEnumerator();
                while (ide.MoveNext())
                {
                    List <string> propValues = DirectoryServices.GetPropertyValues(ide.Key.ToString(), ide.Value);
                    Properties.Add(ide.Key.ToString(), propValues);
                }
            }

            Path            = de.Path;
            SchemaClassName = de.SchemaClassName;
            if (loadSchema)
            {
                SchemaEntry = new DirectoryEntryObject(de.SchemaEntry, false, false, false);
            }
            UsePropertyCache = de.UsePropertyCache;
            Username         = de.Username;

            if (getAccessRules)
            {
                AccessRules = DirectoryServices.GetAccessRules(de);
            }
        }
        public void SetPropertiesFromUserPrincipal(UserPrincipal up, bool getAccessRules, bool getObjectProperties)
        {
            if (up == null)
            {
                return;
            }

            SetPropertiesFromAuthenticablePrincipal(up, getAccessRules);

            EmailAddress         = up.EmailAddress;
            EmployeeId           = up.EmployeeId;
            GivenName            = up.GivenName;
            MiddleName           = up.MiddleName;
            Surname              = up.Surname;
            VoiceTelephoneNumber = up.VoiceTelephoneNumber;

            object obj = up.GetUnderlyingObject();

            if (obj.GetType() == typeof(DirectoryEntry) && getObjectProperties)
            {
                DirectoryEntry gde = (DirectoryEntry)obj;
                Properties = DirectoryServices.GetProperties(gde);
            }
        }
        public static string GetDistinguishedName(string identity)
        {
            Principal principal = DirectoryServices.GetPrincipal(identity);

            return(principal?.DistinguishedName);
        }