Active Directory. Work with DACL

1.1k views Asked by At

I'm trying to make my own static class to work with AD. I wrote a static method:

    public static void AddReadingAceForGroup(DirectoryEntry dirEntry, string groupName)
    {
        dirEntry.RefreshCache();
        DirectoryEntry root = new DirectoryEntry("LDAP://192.168.1.1/       dc=mydomain,dc=ru");
        using (DirectorySearcher ds = new DirectorySearcher(root, "CN="+groupName))
        {
            SearchResult sr = ds.FindOne();
            root = sr.GetDirectoryEntry();
        }
        try
        {
            ActiveDirectoryAccessRule accessRule =
                new ActiveDirectoryAccessRule(root.ObjectSecurity.GetGroup(typeof(SecurityIdentifier)),
                                              ActiveDirectoryRights.GenericRead, AccessControlType.Allow);
            dirEntry.ObjectSecurity.AddAccessRule(accessRule);
            dirEntry.CommitChanges();
        }
        catch(Exception e)
        {
        }
    }

Before using this function I do impersonate user with remote credentials, then code works without exceptions, but have no result. The similar function which removes ACE works fine.

1

There are 1 answers

0
Jonik On

The final working code is:

public static SecurityIdentifier GetGroupSid(string groupName, string domainControllerIp)
{
    SecurityIdentifier sid = null;
    using (PrincipalContext dcx = new PrincipalContext(ContextType.Domain, domainControllerIp))
    {
        GroupPrincipal group = GroupPrincipal.FindByIdentity(dcx, groupName);
        if (group != null)
        {
            sid = group.Sid;
            group.Dispose();
        }
    }
    return sid;
}
public static void AddDaclsAceForGroup(DirectoryEntry dirEntry, string groupName, string ip)
{
    SecurityIdentifier sid = GetGroupSid(groupName,ip);
    try
    {
        ActiveDirectoryAccessRule accessRule =
            new ActiveDirectoryAccessRule(sid,ActiveDirectoryRights.GenericRead, AccessControlType.Allow);
        dirEntry.ObjectSecurity.AddAccessRule(accessRule);
        dirEntry.CommitChanges();
    }
    catch(Exception e)
    {
    }
}

I just had error with group SID. The code works perfect, but do not that what I'm expecting for. Sorry my bad english.