Esempio n. 1
0
        private void InsertDelegationRelation(ADItem aditem)
        {
            ActiveDirectorySecurity sd = aditem.msDSAllowedToActOnBehalfOfOtherIdentity;

            foreach (ActiveDirectoryAccessRule rule in sd.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                Storage.InsertRelation(((SecurityIdentifier)rule.IdentityReference).Value, MappingType.Sid, aditem.DistinguishedName, MappingType.DistinguishedName, RelationType.msDS_Allowed_To_Act_On_Behalf_Of_Other_Identity);
            }
        }
Esempio n. 2
0
        public List <SecurityIdentifier> GetPrincipalsForComputer(SearchResult computer, bool filterLocalAccounts)
        {
            byte[] sd = computer.GetPropertyBytes("ntSecurityDescriptor");

            if (sd == null)
            {
                throw new InvalidOperationException($"Security descriptor for computer {computer.GetPropertyString("msDS-PrincipalName")} was empty");
            }

            var sec = new ActiveDirectorySecurity();

            sec.SetSecurityDescriptorBinaryForm(sd);

            string domain     = this.discoveryServices.GetDomainNameDns(computer.GetPropertySid("objectSid"));
            Guid   mslapsGuid = this.discoveryServices.GetSchemaAttributeGuid(domain, "ms-Mcs-AdmPwd") ?? throw new ObjectNotFoundException("The ms-Mcs-AdmPwd attribute was not found in the schema");

            List <SecurityIdentifier> results = new List <SecurityIdentifier>();

            foreach (ActiveDirectoryAccessRule accessRule in sec.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                var sid = accessRule.IdentityReference as SecurityIdentifier;
                if (sid == null)
                {
                    continue;
                }

                if (sid.IsWellKnown(WellKnownSidType.LocalSystemSid))
                {
                    continue;
                }

                if (accessRule.ActiveDirectoryRights == ActiveDirectoryRights.GenericAll)
                {
                    results.Add(sid);
                    continue;
                }

                if (accessRule.ObjectType == mslapsGuid)
                {
                    if (accessRule.AccessControlType != AccessControlType.Allow)
                    {
                        continue;
                    }

                    if (!accessRule.ActiveDirectoryRights.HasFlag((ActiveDirectoryRights)0x110))
                    {
                        continue;
                    }

                    results.Add(sid);
                }
            }


            return(results);
        }
Esempio n. 3
0
        internal static List <ADRecipient> GetUsersGrantedSendAsPermission(ADRecipient mailbox, IRecipientSession galSession)
        {
            TraceWrapper.SearchLibraryTracer.TraceDebug <ADRecipient>(0, "Reading users who have SendAs rights for: {0}", mailbox);
            RawSecurityDescriptor rawSecurityDescriptor = galSession.ReadSecurityDescriptor(mailbox.Id);

            if (rawSecurityDescriptor == null)
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug(0, "Null security-descriptor returned for mailbox", new object[0]);
                return(null);
            }
            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array);
            AuthorizationRuleCollection accessRules = activeDirectorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));

            if (accessRules == null)
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug(0, "No rules on ACL for this mailbox", new object[0]);
                return(null);
            }
            List <ADRecipient> list = null;

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
                if (activeDirectoryAccessRule.AccessControlType == AccessControlType.Allow && object.Equals(activeDirectoryAccessRule.ObjectType, WellKnownGuid.SendAsExtendedRightGuid))
                {
                    IdentityReference identityReference = activeDirectoryAccessRule.IdentityReference;
                    string            value             = identityReference.Value;
                    try
                    {
                        ADRecipient adrecipient = galSession.FindBySid(new SecurityIdentifier(value));
                        if (adrecipient == null)
                        {
                            TraceWrapper.SearchLibraryTracer.TraceError <string>(0, "User not found for SID: {0}", value);
                        }
                        else
                        {
                            if (list == null)
                            {
                                list = new List <ADRecipient>();
                            }
                            list.Add(adrecipient);
                            TraceWrapper.SearchLibraryTracer.TraceDebug <string, string>(0, "Added {0} to list of users who have Send-As permission for {1}.", adrecipient.DisplayName, mailbox.DisplayName);
                        }
                    }
                    catch (NonUniqueRecipientException arg)
                    {
                        TraceWrapper.SearchLibraryTracer.TraceError <string, string, NonUniqueRecipientException>(0, "Caught NonUniqueRecipientException when attempting to look up user with SID {0} while reading list of users granted Send-As permission to {1}: {2}", value, mailbox.Name, arg);
                    }
                }
            }
            return(list);
        }
Esempio n. 4
0
        /// <summary>
        /// Processes the msds-groupmsamembership property, and determines who can read the password
        /// </summary>
        /// <param name="wrapper"></param>
        /// <returns></returns>
        private static async Task <List <ACL> > ProcessGMSA(LdapWrapper wrapper)
        {
            var aces = new List <ACL>();
            //Grab the property as a byte array
            var securityDescriptor = wrapper.SearchResult.GetPropertyAsBytes("msds-groupmsamembership");

            //If the property is null, its either not a GMSA or something went wrong, so just exit out
            if (securityDescriptor == null)
            {
                return(aces);
            }

            //Create a new ActiveDirectorySecurity object and set the bytes to the descriptor
            var descriptor = new ActiveDirectorySecurity();

            descriptor.SetSecurityDescriptorBinaryForm(securityDescriptor);

            // Loop over the entries in the security descriptor
            foreach (ActiveDirectoryAccessRule ace in descriptor.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                //Ignore null aces
                if (ace == null)
                {
                    continue;
                }

                //Ignore deny aces (although this should never show up in GMSAs
                if (ace.AccessControlType == AccessControlType.Deny)
                {
                    continue;
                }

                //Pre-process the principal for the SID
                var principalSid = FilterAceSids(ace.IdentityReference.Value);

                //Ignore null SIDs
                if (principalSid == null)
                {
                    continue;
                }

                //Resolve the principal SID and grab its type
                var(finalSid, type) = await ResolutionHelpers.ResolveSidAndGetType(principalSid, wrapper.Domain);

                aces.Add(new ACL
                {
                    RightName     = "ReadGMSAPassword",
                    AceType       = "",
                    PrincipalSID  = finalSid,
                    PrincipalType = type,
                    IsInherited   = false
                });
            }

            return(aces);
        }
Esempio n. 5
0
        //Only print the first attribute in the attrReturned array list

        public static void PrintMulti(SearchResponse response, string attr)
        {
            foreach (SearchResultEntry entry in response.Entries)
            {
                //Only if the attribute is specified to be returned, then "Attributes" contains it

                Console.WriteLine("  * {0}", entry.Attributes["sAMAccountName"][0]);
                Console.WriteLine("    {0}\n", entry.DistinguishedName);

                //in case the attribute value is null
                try
                {
                    if (attr == "")
                    {
                    }

                    else if (entry.Attributes[attr][0] is string)
                    {
                        for (int i = 0; i < entry.Attributes[attr].Count; i++)
                        {
                            Console.WriteLine("    - {0}: {1}", attr.ToUpper(), entry.Attributes[attr][i]);
                        }
                    }
                    else if (entry.Attributes[attr][0] is byte[])
                    {
                        //Resolve Security Descriptor
                        //From The .Net Developer Guide to Directory Services Programming Listing 8.2. Listing the DACL
                        ActiveDirectorySecurity ads = new ActiveDirectorySecurity();
                        ads.SetSecurityDescriptorBinaryForm((byte[])entry.Attributes[attr][0]);
                        var rules = ads.GetAccessRules(true, true, typeof(NTAccount));
                        foreach (ActiveDirectoryAccessRule rule in rules)
                        {
                            Console.WriteLine("    - {0}: {1} ([ControlType: {2}] Rights: {3})",
                                              attr.ToUpper(),
                                              rule.IdentityReference.ToString(),
                                              rule.AccessControlType.ToString(),
                                              rule.ActiveDirectoryRights.ToString());
                        }
                        //for (int i = 0; i < entry.Attributes[attr].Count; i++)
                        //{
                        //    Console.WriteLine("    - {0}: {1}",
                        //        attr.ToUpper(),
                        //        System.Text.Encoding.ASCII.GetString((byte[])entry.Attributes[attr][i]));
                        //}
                    }
                    else
                    {
                        Console.WriteLine("Unexpected multi-valued type {0}", entry.Attributes[attr][0].GetType().Name);
                    }
                }
                catch { }

                Console.WriteLine();
            }
        }
Esempio n. 6
0
        protected override void WriteResult(IConfigurable dataObject)
        {
            TaskLogger.LogEnter();
            this.HasObjectMatchingIdentity = true;
            ADUser aduser = (ADUser)dataObject;

            if (aduser.Database == null || aduser.ExchangeGuid == Guid.Empty)
            {
                base.Validate(aduser);
            }
            else
            {
                ActiveDirectorySecurity activeDirectorySecurity = PermissionTaskHelper.ReadMailboxSecurityDescriptor((ADUser)dataObject, PermissionTaskHelper.GetReadOnlySession(base.DomainController), new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), new Task.ErrorLoggerDelegate(base.WriteError));
                if (!this.Owner.IsPresent)
                {
                    AuthorizationRuleCollection accessRules = activeDirectorySecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));
                    int num = 0;
                    while (accessRules.Count > num)
                    {
                        ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)accessRules[num];
                        if (this.SecurityPrincipal == null || this.SecurityPrincipal.Sid == activeDirectoryAccessRule.IdentityReference || this.SecurityPrincipal.SidHistory.Contains(activeDirectoryAccessRule.IdentityReference as SecurityIdentifier))
                        {
                            MailboxAcePresentationObject mailboxAcePresentationObject = new MailboxAcePresentationObject(activeDirectoryAccessRule, ((ADRawEntry)dataObject).Id);
                            if (Globals.IsDatacenter && base.TenantGlobalCatalogSession != null)
                            {
                                SecurityIdentifier securityIdentifier = (SecurityIdentifier)activeDirectoryAccessRule.IdentityReference;
                                ADRecipient        adrecipient        = null;
                                try
                                {
                                    adrecipient = base.TenantGlobalCatalogSession.FindBySid(securityIdentifier);
                                }
                                catch
                                {
                                }
                                if (adrecipient != null)
                                {
                                    string friendlyName = (!string.IsNullOrEmpty(adrecipient.DisplayName)) ? adrecipient.DisplayName : adrecipient.Name;
                                    mailboxAcePresentationObject.User = new SecurityPrincipalIdParameter(securityIdentifier, friendlyName);
                                }
                            }
                            mailboxAcePresentationObject.ResetChangeTracking(true);
                            base.WriteResult(mailboxAcePresentationObject);
                        }
                        num++;
                    }
                }
                else
                {
                    IdentityReference       owner       = activeDirectorySecurity.GetOwner(typeof(NTAccount));
                    OwnerPresentationObject dataObject2 = new OwnerPresentationObject(((ADUser)dataObject).Id, owner.ToString());
                    base.WriteResult(dataObject2);
                }
            }
            TaskLogger.LogExit();
        }
Esempio n. 7
0
        public static void PrintDirectoryAttrDict(Dictionary <string, DirectoryAttribute> myDict, string banner)
        {
            PrintGreen(string.Format("\n[-] {0}:\n", banner));

            if (myDict == null)
            {
                return;
            }

            foreach (var obj in myDict)
            {
                Console.WriteLine("    * {0}", obj.Key);


                if (obj.Value[0] is string)
                {
                    for (int i = 0; i < obj.Value.Count; i++)
                    {
                        Console.WriteLine("      - {0}", obj.Value[i]);
                    }
                }
                else if (obj.Value[0] is byte[])
                {
                    //Resolve Security Descriptor
                    //From The .Net Developer Guide to Directory Services Programming Listing 8.2. Listing the DACL

                    for (int i = 0; i < obj.Value.Count; i++)
                    {
                        ActiveDirectorySecurity ads = new ActiveDirectorySecurity();

                        ads.SetSecurityDescriptorBinaryForm((byte[])obj.Value[i]);

                        var rules = ads.GetAccessRules(true, true, typeof(NTAccount));

                        foreach (ActiveDirectoryAccessRule rule in rules)
                        {
                            string name = rule.IdentityReference.ToString();

                            if (name.ToUpper().Contains("S-1-5"))
                            {
                                name = ConvertSIDToName(name);
                            }

                            Console.WriteLine("      - {0} ([ControlType: {1}] Rights: {2})",
                                              name,
                                              rule.AccessControlType.ToString(),
                                              rule.ActiveDirectoryRights.ToString());
                        }
                    }
                }
                Console.WriteLine();
            }
        }
Esempio n. 8
0
        public virtual List <ActiveDirectoryRuleDescriptor> GetAccessRules(bool includeExplicit, bool includeInherited,
                                                                           Type targetType)
        {
            var result = new List <ActiveDirectoryRuleDescriptor>();

            foreach (ActiveDirectoryAccessRule ace in _sd.GetAccessRules(includeExplicit, includeInherited, targetType))
            {
                result.Add(new ActiveDirectoryRuleDescriptor(ace));
            }

            return(result);
        }
Esempio n. 9
0
        private static void GetSendas(UserInfo utente)
        {
            string pathNameDomain    = "LDAP://" + sDomain + "/" + utente.Distinguishedname;
            var    direcotyEntry     = new DirectoryEntry(pathNameDomain, username, password);
            var    directorySearcher = new DirectorySearcher(direcotyEntry);

            directorySearcher.PropertiesToLoad.Add("msExchRecipientTypeDetails");
            directorySearcher.PropertiesToLoad.Add("distinguishedname");
            directorySearcher.PropertiesToLoad.Add("mail");
            var res = directorySearcher.FindOne();

            DirectoryEntry              ssStoreObj  = res.GetDirectoryEntry();
            ActiveDirectorySecurity     StoreobjSec = ssStoreObj.ObjectSecurity;
            AuthorizationRuleCollection Storeacls   = StoreobjSec.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            foreach (ActiveDirectoryAccessRule ace in Storeacls)
            {
                if (ace.IdentityReference.Value != "S-1-5-7" & ace.IdentityReference.Value != "S-1-1-0" & ace.IsInherited != true & ace.IdentityReference.Value != "S-1-5-10")
                {
                    if (ace.ActiveDirectoryRights.ToString() == "ExtendedRight")
                    {
                        bool found = false;

                        try
                        {
                            filead.WriteLine(utente.Mail + "," + Utenti.Find(x => x.ObjectSID.Contains(ace.IdentityReference.Value)).Mail + ",SendAS," + exRighthash[ace.ObjectType.ToString()].ToString() + ",,");
                            Trace.WriteLine(DateTime.Now.ToString("yyyyMMddHHmmss") + "::INF::SendAS::OK::SendAS permission of --> " + utente.Mail + " exported successfully");
                            found = true;
                        }
                        catch
                        {
                        }

                        try
                        {
                            filead.WriteLine(utente.Mail + "," + GruppiInfo.Find(x => x.ObjectSID.Contains(ace.IdentityReference.Value)).samaccountname + ",SendAS," + exRighthash[ace.ObjectType.ToString()].ToString() + ",,");
                            Trace.WriteLine(DateTime.Now.ToString("yyyyMMddHHmmss") + "::INF::SendAS::OK::SendAS permission of --> " + utente.Mail + " exported successfully");
                            found = true;
                        }
                        catch
                        {
                        }

                        if (!found)
                        {
                            Trace.WriteLine(DateTime.Now.ToString("yyyyMMddHHmmss") + "::WRN::Cannot resolve SID " + ace.IdentityReference.Value);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        private static ActiveDirectoryAccessRule FindAce(ActiveDirectoryAccessRule ace, ActiveDirectorySecurity acl, bool includeInherited, bool subsetInsteadOfSuperset)
        {
            AuthorizationRuleCollection accessRules = acl.GetAccessRules(true, includeInherited, typeof(SecurityIdentifier));

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
                if (DirectoryCommon.AceMatches(ace, activeDirectoryAccessRule, subsetInsteadOfSuperset))
                {
                    return(activeDirectoryAccessRule);
                }
            }
            return(null);
        }
Esempio n. 11
0
        public static int CountAce(ActiveDirectoryAccessRule ace, ActiveDirectorySecurity acl)
        {
            int num = 0;
            AuthorizationRuleCollection accessRules = acl.GetAccessRules(true, false, typeof(SecurityIdentifier));

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule ace2 = (ActiveDirectoryAccessRule)obj;
                if (DirectoryCommon.AceMatches(ace, ace2, false))
                {
                    num++;
                }
            }
            return(num);
        }
        static void GetPrivilege()
        {
            DirectoryEntry ldap_connect = new DirectoryEntry("gh0st.com");

            ldap_connect.Path = "LDAP://CN=Computers,DC=gh0st,DC=com";
            ldap_connect.Options.SecurityMasks = SecurityMasks.Dacl;
            ldap_connect.RefreshCache();

            ActiveDirectorySecurity sec = ldap_connect.ObjectSecurity;

            foreach (ActiveDirectoryAccessRule ar in sec.GetAccessRules(true, true, typeof(NTAccount)))
            {
                Console.WriteLine(ar.IdentityReference.ToString() + " -> " + ar.ActiveDirectoryRights.ToString() + "\n");
            }
        }
Esempio n. 13
0
        protected override void WriteResult(IConfigurable dataObject)
        {
            TaskLogger.LogEnter();
            IDirectorySession directorySession = (IDirectorySession)base.DataSession;

            if (TaskHelper.ShouldUnderscopeDataSessionToOrganization(directorySession, (ADObject)dataObject))
            {
                directorySession = TaskHelper.UnderscopeSessionToOrganization(directorySession, ((ADObject)dataObject).OrganizationId, true);
            }
            ActiveDirectorySecurity     activeDirectorySecurity = PermissionTaskHelper.ReadAdSecurityDescriptor((ADRawEntry)dataObject, directorySession, new Task.TaskErrorLoggingDelegate(base.WriteError));
            AuthorizationRuleCollection accessRules             = activeDirectorySecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
                if (this.Trustee == null || this.trusteeSid == activeDirectoryAccessRule.IdentityReference)
                {
                    RecipientAccessRight?recipientAccessRight = this.FilterByRecipientAccessRights(activeDirectoryAccessRule, this.AccessRights);
                    if (recipientAccessRight != null)
                    {
                        string text = string.Empty;
                        if (Globals.IsDatacenter && base.TenantGlobalCatalogSession != null)
                        {
                            try
                            {
                                SecurityIdentifier sId         = (SecurityIdentifier)activeDirectoryAccessRule.IdentityReference;
                                ADRecipient        adrecipient = base.TenantGlobalCatalogSession.FindBySid(sId);
                                if (adrecipient != null)
                                {
                                    text = ((!string.IsNullOrEmpty(adrecipient.DisplayName)) ? adrecipient.DisplayName : adrecipient.Name);
                                }
                            }
                            catch
                            {
                            }
                        }
                        if (string.IsNullOrEmpty(text))
                        {
                            text = RecipientPermissionTaskHelper.GetFriendlyNameOfSecurityIdentifier((SecurityIdentifier)activeDirectoryAccessRule.IdentityReference, base.TenantGlobalCatalogSession, new Task.TaskErrorLoggingDelegate(base.WriteError), new Task.TaskVerboseLoggingDelegate(base.WriteVerbose));
                        }
                        RecipientPermission dataObject2 = new RecipientPermission(activeDirectoryAccessRule, ((ADRawEntry)dataObject).Id, text, recipientAccessRight.Value);
                        base.WriteResult(dataObject2);
                    }
                }
            }
            TaskLogger.LogExit();
        }
Esempio n. 14
0
        internal static SecurityIdentifier[] GetServerAdmins(Server server, IDirectorySession session, Task.TaskErrorLoggingDelegate logError)
        {
            List <SecurityIdentifier>   list = new List <SecurityIdentifier>();
            ActiveDirectorySecurity     activeDirectorySecurity = PermissionTaskHelper.ReadAdSecurityDescriptor(server, session, logError);
            AuthorizationRuleCollection accessRules             = activeDirectorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
                if (activeDirectoryAccessRule.ActiveDirectoryRights == ActiveDirectoryRights.GenericAll)
                {
                    SecurityIdentifier item = (SecurityIdentifier)activeDirectoryAccessRule.IdentityReference;
                    list.Add(item);
                }
            }
            return(list.ToArray());
        }
        private static void CanonicalizeAcl(ActiveDirectorySecurity ads)
        {
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            foreach (object obj in ads.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                ActiveDirectoryAccessRule rule = (ActiveDirectoryAccessRule)obj;
                activeDirectorySecurity.AddAccessRule(rule);
            }
            RawSecurityDescriptor rawSecurityDescriptor  = new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access));
            RawSecurityDescriptor rawSecurityDescriptor2 = new RawSecurityDescriptor(ads.GetSecurityDescriptorSddlForm(AccessControlSections.Access))
            {
                DiscretionaryAcl = rawSecurityDescriptor.DiscretionaryAcl
            };

            ads.SetSecurityDescriptorSddlForm(rawSecurityDescriptor2.GetSddlForm(AccessControlSections.Access), AccessControlSections.Access);
        }
Esempio n. 16
0
        public static AuthorizationRuleCollection GetAuthorizationRules(string targetDn)
        {
            try
            {
                using (var aclEntry = GetSingleEntry(targetDn))
                {
                    ActiveDirectorySecurity sec = aclEntry.ObjectSecurity;

                    AuthorizationRuleCollection rules = null;

                    rules = sec.GetAccessRules(true, true, typeof(NTAccount));

                    return(rules);
                }
            }
            catch { return(null); }
        }
Esempio n. 17
0
        public void GetObjectSecurity()
        {
            DirectoryEntry entry = TestUtils.GetDefaultPartition();

            ActiveDirectorySecurity sec = entry.ObjectSecurity;

            PrintSD(sec);

            AuthorizationRuleCollection rules = null;

            rules = sec.GetAccessRules(
                true, true, typeof(NTAccount));

            foreach (ActiveDirectoryAccessRule rule in rules)
            {
                PrintAce(rule);
            }
        }
Esempio n. 18
0
        public static void PrintSD(SearchResultEntry entry, string attr)
        {
            //Resolve Security Descriptor
            //From The .Net Developer Guide to Directory Services Programming Listing 8.2. Listing the DACL
            ActiveDirectorySecurity ads = new ActiveDirectorySecurity();

            ads.SetSecurityDescriptorBinaryForm((byte[])entry.Attributes[attr][0]);
            var rules = ads.GetAccessRules(true, true, typeof(NTAccount));

            foreach (ActiveDirectoryAccessRule rule in rules)
            {
                Console.WriteLine("    - {0}: {1} ([ControlType: {2}] Rights: {3})",
                                  attr.ToUpper(),
                                  rule.IdentityReference.ToString(),
                                  rule.AccessControlType.ToString(),
                                  rule.ActiveDirectoryRights.ToString());
            }
        }
Esempio n. 19
0
        public static void GetInterestingAcls(string targetDn, string forestDn)
        {
            using (var entry = new DirectoryEntry("LDAP://" + targetDn))
            {
                ActiveDirectorySecurity sec = entry.ObjectSecurity;

                AuthorizationRuleCollection rules = null;

                rules = sec.GetAccessRules(true, true, typeof(NTAccount));

                Console.WriteLine("  * Object DN: {0}", targetDn);
                Console.WriteLine();

                foreach (ActiveDirectoryAccessRule rule in rules)
                {
                    Outputs.PrintAce(rule, forestDn);
                }
            }
        }
Esempio n. 20
0
 public static AuthorizationRuleCollection GetAuthorizationRules(string targetDn, out string ownerSID)
 {
     logger.Debug($"Getting Authorization Rules for {targetDn}");
     try
     {
         using (var aclEntry = Searcher.GetDirectoryEntry(targetDn))
         {
             ActiveDirectorySecurity sec = aclEntry.ObjectSecurity;
             ownerSID = sec.GetOwner(typeof(SecurityIdentifier)).ToString();
             AuthorizationRuleCollection rules = sec.GetAccessRules(true, true, typeof(SecurityIdentifier));
             return(rules);
         }
     }
     catch
     {
         logger.Error($"Cannot get authorization data on {targetDn}");
         ownerSID = null;
         return(null);
     }
 }
Esempio n. 21
0
        private static bool EveryoneDeniedDeleteChild(ADEntity directoryObj)
        {
            bool flag;
            ActiveDirectorySecurity   value = (ActiveDirectorySecurity)directoryObj["nTSecurityDescriptor"].Value;
            ActiveDirectoryAccessRule deleteChildAccessRule = ProtectedFromDeletionUtil.ACEConstants.DeleteChildAccessRule;
            IEnumerator enumerator = value.GetAccessRules(true, true, typeof(SecurityIdentifier)).GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    ActiveDirectoryAccessRule current = (ActiveDirectoryAccessRule)enumerator.Current;
                    if (current.AccessControlType != AccessControlType.Allow || !Utils.HasFlagsSet((int)current.ActiveDirectoryRights, 2))
                    {
                        if (current.InheritanceFlags != deleteChildAccessRule.InheritanceFlags || !(current.IdentityReference == deleteChildAccessRule.IdentityReference) || current.AccessControlType != deleteChildAccessRule.AccessControlType || !Utils.HasFlagsSet((int)current.ActiveDirectoryRights, (int)deleteChildAccessRule.ActiveDirectoryRights))
                        {
                            continue;
                        }
                        flag = true;
                        return(flag);
                    }
                    else
                    {
                        flag = false;
                        return(flag);
                    }
                }
                return(false);
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(flag);
        }
Esempio n. 22
0
        /// <summary>
        /// Adds a new SID to the SD that controls access to read the password blob
        /// </summary>
        /// <param name="currentSddlBytes">current SDDL SD</param>
        /// <param name="newSID">sid as string, SDDL form</param>
        /// <returns>bigger SD bytes</returns>
        public byte[] addSIDtoSD(byte[] currentSddlBytes, string newSID)
        {
            ActiveDirectorySecurity ads     = new ActiveDirectorySecurity();
            SecurityIdentifier      realSID = new SecurityIdentifier(newSID);

            byte[] sddlOut = new byte[2];

            try
            {
                ads.SetSecurityDescriptorBinaryForm(currentSddlBytes);
                AuthorizationRuleCollection bb = ads.GetAccessRules(true, true, typeof(SecurityIdentifier));
                bool bAlreadyInSD = false;

                //skip the add if the SID is already on the list
                foreach (AuthorizationRule ar in bb)
                {
                    if (ar.IdentityReference.Value.ToString() == realSID.ToString())
                    {
                        bAlreadyInSD = true;
                        break;
                    }
                }

                if (!bAlreadyInSD)
                {
                    //add it to the SD
                    ads.AddAccessRule(new ActiveDirectoryAccessRule(realSID, ActiveDirectoryRights.GenericAll, AccessControlType.Allow));

                    //output the new SD in bytes
                    sddlOut = ads.GetSecurityDescriptorBinaryForm();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(sddlOut);
        }
Esempio n. 23
0
        public List <string> readgMSAPwdReadersACL(byte[] currentSddlBytes)
        {
            List <string> readers = new List <string>();

            ActiveDirectorySecurity ads = new ActiveDirectorySecurity();


            try
            {
                ads.SetSecurityDescriptorBinaryForm(currentSddlBytes);
                AuthorizationRuleCollection bb = ads.GetAccessRules(true, true, typeof(SecurityIdentifier));


                //skip the add if the SID is already on the list
                foreach (AuthorizationRule ar in bb)
                {
                    //get SID
                    string acctName = ar.IdentityReference.Value.ToString();
                    try
                    {
                        //try and resolve to Account
                        IdentityReference dude = ar.IdentityReference;
                        acctName = dude.Translate(typeof(NTAccount)).ToString();
                    }
                    catch (Exception ex)
                    {
                    }

                    readers.Add(acctName);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(readers);
        }
Esempio n. 24
0
        private void GetAccessRules()
        {
            try
            {
                ActiveDirectorySecurity Sec = DirEntry.ObjectSecurity;
                foreach (ActiveDirectoryAccessRule ADRule in Sec.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    ADCertificateTemplateAccessRule CurrRule = new ADCertificateTemplateAccessRule(ADRule);

                    if (AccessRules.FirstOrDefault(p => p.Identity.Matches(CurrRule.Identity)) == null)
                    {
                        AccessRules.Add(CurrRule);
                    }
                    else
                    {
                        AccessRules.ForEach(p => p.MergeIf(CurrRule));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CertificateTemplateAccessRuleException(this, ex);
            }
        }
Esempio n. 25
0
 public static void RemoveAccessRule(ActiveDirectorySecurity acl, ActiveDirectoryAccessRule ace)
 {
     if (!acl.RemoveAccessRule(ace))
     {
         AuthorizationRuleCollection accessRules = acl.GetAccessRules(true, false, typeof(SecurityIdentifier));
         foreach (object obj in accessRules)
         {
             ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
             if (DirectoryCommon.AceMatches(ace, activeDirectoryAccessRule, false))
             {
                 if ((~(ace.ActiveDirectoryRights != (ActiveDirectoryRights)0) & activeDirectoryAccessRule.ActiveDirectoryRights) == (ActiveDirectoryRights)0)
                 {
                     acl.RemoveAccessRuleSpecific(activeDirectoryAccessRule);
                 }
                 else
                 {
                     ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(activeDirectoryAccessRule.IdentityReference, ~ace.ActiveDirectoryRights & activeDirectoryAccessRule.ActiveDirectoryRights, activeDirectoryAccessRule.AccessControlType, activeDirectoryAccessRule.ObjectType, activeDirectoryAccessRule.InheritanceType, activeDirectoryAccessRule.InheritedObjectType);
                     acl.RemoveAccessRuleSpecific(activeDirectoryAccessRule);
                     acl.AddAccessRule(rule);
                 }
             }
         }
     }
 }
Esempio n. 26
0
        private void InsertSecurityDescriptorRelation(ADItem aditem)
        {
            ActiveDirectorySecurity sd = aditem.NTSecurityDescriptor;

            Storage.InsertRelation(sd.GetOwner(typeof(SecurityIdentifier)).Value, MappingType.Sid, aditem.DistinguishedName, MappingType.DistinguishedName, RelationType.AD_OWNER);
            // relations can be duplicated - will slow down import
            Dictionary <string, List <RelationType> > relationToAdd = new Dictionary <string, List <RelationType> >();

            foreach (ActiveDirectoryAccessRule accessrule in sd.GetAccessRules(true, false, typeof(SecurityIdentifier)))
            {
                // ignore audit / denied ace
                if (accessrule.AccessControlType != AccessControlType.Allow)
                {
                    continue;
                }

                RelationType restrictedObject = RelationType.container_hierarchy;
                if ((accessrule.ObjectFlags & ObjectAceFlags.ObjectAceTypePresent) != 0)
                {
                    switch (accessrule.ObjectType.ToString().ToLowerInvariant())
                    {
                    case "4828cc14-1437-45bc-9b07-ad6f015e5f28":     // inetorg
                    case "bf967aba-0de6-11d0-a285-00aa003049e2":     // user
                        restrictedObject = RelationType.RestrictedToUser;
                        break;

                    case "bf967a86-0de6-11d0-a285-00aa003049e2":
                        restrictedObject = RelationType.RestrictedToComputer;
                        break;

                    case "bf967aa5-0de6-11d0-a285-00aa003049e2":
                        restrictedObject = RelationType.RestrictedToOU;
                        break;

                    case "bf967a9c-0de6-11d0-a285-00aa003049e2":
                        restrictedObject = RelationType.RestrictedToGroup;
                        break;

                    case "ce206244-5827-4a86-ba1c-1c0c386c1b64":
                    case "7b8b558a-93a5-4af7-adca-c017e67f1057":
                        restrictedObject = RelationType.RestrictedToMsaOrGmsa;
                        break;

                    case "f30e3bc2-9ff0-11d1-b603-0000f80367c1":
                        restrictedObject = RelationType.RestrictedToGpo;
                        break;

                    default:
                        continue;
                    }
                }

                // ADS_RIGHT_GENERIC_ALL
                if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.GenericAll))
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.GEN_RIGHT_ALL);
                }
                else
                {
                    // ADS_RIGHT_GENERIC_WRITE
                    if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.GenericWrite))
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.GEN_RIGHT_WRITE);
                    }
                    // ADS_RIGHT_WRITE_DAC
                    if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.WriteDacl))
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.ADS_RIGHT_WRITE_DAC);
                    }
                    // ADS_RIGHT_WRITE_OWNER
                    if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.WriteOwner))
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.ADS_RIGHT_WRITE_OWNER);
                    }
                    if (accessrule.ObjectFlags == ObjectAceFlags.None)
                    {
                        // ADS_RIGHT_DS_CONTROL_ACCESS
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.ExtendedRight))
                        {
                            IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.EXT_RIGHT_ALL);
                        }
                        // ADS_RIGHT_DS_SELF
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.Self))
                        {
                            IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.VAL_WRITE_ALL);
                        }
                        // ADS_RIGHT_DS_WRITE_PROP
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.WriteProperty))
                        {
                            IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.WRITE_PROP_ALL);
                        }
                    }
                    else if ((accessrule.ObjectFlags & ObjectAceFlags.ObjectAceTypePresent) == ObjectAceFlags.ObjectAceTypePresent)
                    {
                        // ADS_RIGHT_DS_CONTROL_ACCESS
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.ExtendedRight))
                        {
                            foreach (KeyValuePair <Guid, RelationType> extendedright in GuidsControlExtendedRights)
                            {
                                if (extendedright.Key == accessrule.ObjectType)
                                {
                                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, extendedright.Value);
                                }
                            }
                        }
                        // ADS_RIGHT_DS_SELF
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.Self))
                        {
                            foreach (KeyValuePair <Guid, RelationType> validatewrite in GuidsControlValidatedWrites)
                            {
                                if (validatewrite.Key == accessrule.ObjectType)
                                {
                                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, validatewrite.Value);
                                }
                            }
                        }
                        // ADS_RIGHT_DS_WRITE_PROP
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.WriteProperty))
                        {
                            foreach (KeyValuePair <Guid, RelationType> controlproperty in GuidsControlProperties)
                            {
                                if (controlproperty.Key == accessrule.ObjectType)
                                {
                                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, controlproperty.Value);
                                }
                            }
                            foreach (KeyValuePair <Guid, RelationType> controlpropertyset in GuidsControlPropertiesSets)
                            {
                                if (controlpropertyset.Key == accessrule.ObjectType)
                                {
                                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, controlpropertyset.Value);
                                }
                            }
                        }
                        if (IsRightSetinAccessRule(accessrule, ActiveDirectoryRights.ReadProperty))
                        {
                            foreach (KeyValuePair <Guid, RelationType> controlproperty in GuidsReadProperties)
                            {
                                if (controlproperty.Key == accessrule.ObjectType)
                                {
                                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, controlproperty.Value);
                                }
                            }
                        }
                    }
                }
                if (restrictedObject != RelationType.container_hierarchy && relationToAdd.ContainsKey(accessrule.IdentityReference.Value))
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, restrictedObject);
                }
            }
            foreach (string target in relationToAdd.Keys)
            {
                foreach (RelationType link in relationToAdd[target])
                {
                    Storage.InsertRelation(target, MappingType.Sid, aditem.DistinguishedName, MappingType.DistinguishedName, link);
                }
            }
        }
        public ActionResult getADAccessRules()
        {
            DirectoryEntry entry = new DirectoryEntry(
                userOU,
                null,
                null,
                AuthenticationTypes.Secure
                );


            //var sid = (SecurityIdentifier)user.ProviderUserKey;
            ActiveDirectorySecurity sec = entry.ObjectSecurity;

            //  PrintSD(sec);

            try
            {
                // respective user
                PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName, userOU);
                GroupPrincipal   user          = GroupPrincipal.FindByIdentity(domainContext, "developer");
                var sid = user.Sid;

                ViewBag.Message += "</br></br> SID: " + user.Sid.ToString();
                NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));
                foreach (ActiveDirectoryAccessRule rule in sec.GetAccessRules(true, false, typeof(NTAccount)))
                {
                    if (rule.ObjectType.ToString() == sid.ToString())
                    {
                        ViewBag.Message += "</br> Identity: " + rule.IdentityReference.ToString()
                                           + "</br> AccessControlType: " + rule.AccessControlType.ToString()
                                           + "</br> ActiveDirectoryRights: " + rule.ActiveDirectoryRights.ToString()
                                           + "</br> InheritanceType: " + rule.InheritanceType.ToString()
                                           + "</br> ObjectFlags: " + rule.ObjectFlags.ToString() + "</br>";
                    }
                }
                // ViewBag.Message += sec.GetOwner(typeof(ntAccount));
                //  ViewBag.Message += " Owner: " + sec.GetOwner(typeof(NTAccount("mylab.user", "user1")));
                //  ViewBag.Message += " Group: " + sec.GetOwner(typeof(Account));
            }
            catch
            {
                //throw;
            }

            ViewBag.Message += "</br></br>=====Security Descriptor=====";
            ViewBag.Message += " Owner: " + sec.GetOwner(typeof(NTAccount));
            ViewBag.Message += " Group: " + sec.GetOwner(typeof(NTAccount));


            AuthorizationRuleCollection rules = null;

            rules = sec.GetAccessRules(true, true, typeof(NTAccount));

            foreach (ActiveDirectoryAccessRule rule in rules)
            {
                PrintAce(rule);
                ViewBag.Message += "</br> Identity: " + rule.IdentityReference.ToString()
                                   + "</br> AccessControlType: " + rule.AccessControlType.ToString()
                                   + "</br> ActiveDirectoryRights: " + rule.ActiveDirectoryRights.ToString()
                                   + "</br> InheritanceType: " + rule.InheritanceType.ToString()
                                   + "</br> ObjectFlags: " + rule.ObjectFlags.ToString() + "</br>"
                                   + "</br> ObjectType: " + rule.ObjectType.ToString() + "</br>";
            }

            return(View());
        }
Esempio n. 28
0
        private void InsertSecurityDescriptorRelation(ADItem aditem)
        {
            ActiveDirectorySecurity sd = aditem.NTSecurityDescriptor;

            Storage.InsertRelation(sd.GetOwner(typeof(SecurityIdentifier)).Value, MappingType.Sid, aditem.DistinguishedName, MappingType.Name, RelationType.AD_OWNER);
            // relations can be duplicated - will slow down import
            Dictionary <string, List <RelationType> > relationToAdd = new Dictionary <string, List <RelationType> >();

            foreach (ActiveDirectoryAccessRule accessrule in sd.GetAccessRules(true, false, typeof(SecurityIdentifier)))
            {
                // ignore audit / denied ace
                if (accessrule.AccessControlType != AccessControlType.Allow)
                {
                    continue;
                }

                // ADS_RIGHT_GENERIC_ALL
                if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.GenericAll) == ActiveDirectoryRights.GenericAll)
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.GEN_RIGHT_ALL);
                }
                // ADS_RIGHT_GENERIC_WRITE
                if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.GenericWrite) == ActiveDirectoryRights.GenericWrite)
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.GEN_RIGHT_WRITE);
                }
                // ADS_RIGHT_WRITE_DAC
                if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.WriteDacl) == ActiveDirectoryRights.WriteDacl)
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.ADS_RIGHT_WRITE_DAC);
                }
                // ADS_RIGHT_WRITE_OWNER
                if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.WriteOwner) == ActiveDirectoryRights.WriteOwner)
                {
                    IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.ADS_RIGHT_WRITE_OWNER);
                }
                if (accessrule.ObjectFlags == ObjectAceFlags.None)
                {
                    // ADS_RIGHT_DS_CONTROL_ACCESS
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.ExtendedRight) == ActiveDirectoryRights.ExtendedRight)
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.EXT_RIGHT_ALL);
                    }
                    // ADS_RIGHT_DS_SELF
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.Self) == ActiveDirectoryRights.Self)
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.VAL_WRITE_ALL);
                    }
                    // ADS_RIGHT_DS_WRITE_PROP
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.WriteProperty) == ActiveDirectoryRights.WriteProperty)
                    {
                        IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, RelationType.WRITE_PROP_ALL);
                    }
                }
                else if ((accessrule.ObjectFlags & ObjectAceFlags.ObjectAceTypePresent) == ObjectAceFlags.ObjectAceTypePresent)
                {
                    if (new Guid("00299570-246d-11d0-a768-00aa006e0529") == accessrule.ObjectType)
                    {
                    }
                    // ADS_RIGHT_DS_CONTROL_ACCESS
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.ExtendedRight) == ActiveDirectoryRights.ExtendedRight)
                    {
                        foreach (KeyValuePair <Guid, RelationType> extendedright in GuidsControlExtendedRights)
                        {
                            if (extendedright.Key == accessrule.ObjectType)
                            {
                                IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, extendedright.Value);
                            }
                        }
                    }
                    // ADS_RIGHT_DS_SELF
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.Self) == ActiveDirectoryRights.Self)
                    {
                        foreach (KeyValuePair <Guid, RelationType> validatewrite in GuidsControlValidatedWrites)
                        {
                            if (validatewrite.Key == accessrule.ObjectType)
                            {
                                IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, validatewrite.Value);
                            }
                        }
                    }
                    // ADS_RIGHT_DS_WRITE_PROP
                    if ((accessrule.ActiveDirectoryRights & ActiveDirectoryRights.WriteProperty) == ActiveDirectoryRights.WriteProperty)
                    {
                        foreach (KeyValuePair <Guid, RelationType> controlproperty in GuidsControlProperties)
                        {
                            if (controlproperty.Key == accessrule.ObjectType)
                            {
                                IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, controlproperty.Value);
                            }
                        }
                        foreach (KeyValuePair <Guid, RelationType> controlpropertyset in GuidsControlPropertiesSets)
                        {
                            if (controlpropertyset.Key == accessrule.ObjectType)
                            {
                                IncludeRelationInDictionary(relationToAdd, accessrule.IdentityReference.Value, controlpropertyset.Value);
                            }
                        }
                    }
                }
            }
            foreach (string target in relationToAdd.Keys)
            {
                foreach (RelationType link in relationToAdd[target])
                {
                    Storage.InsertRelation(target, MappingType.Sid, aditem.DistinguishedName, MappingType.Name, link);
                }
            }
        }
Esempio n. 29
0
        public static void GetObjectAces(SearchResultEntry entry, ResolvedEntry resolved, ref Computer obj)
        {
            if (!Utils.IsMethodSet(ResolvedCollectionMethod.ACL))
            {
                return;
            }

            var aces = new List <ACL>();
            var ntSecurityDescriptor = entry.GetPropBytes("ntsecuritydescriptor");

            //If the ntsecuritydescriptor is null, no point in continuing
            //I'm still not entirely sure what causes this, but it can happen
            if (ntSecurityDescriptor == null)
            {
                return;
            }

            var domainName = Utils.ConvertDnToDomain(entry.DistinguishedName);

            var newDescriptor = new ActiveDirectorySecurity();

            newDescriptor.SetSecurityDescriptorBinaryForm(ntSecurityDescriptor);
            var owner = GetAclOwner(newDescriptor, domainName);

            if (owner != null)
            {
                aces.Add(new ACL
                {
                    AceType       = "",
                    RightName     = "Owner",
                    PrincipalName = owner.PrincipalName,
                    PrincipalType = owner.ObjectType
                });
            }


            foreach (ActiveDirectoryAccessRule ace in newDescriptor.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                //Ignore null aces
                if (ace == null)
                {
                    continue;
                }

                //Ignore Deny aces
                if (!ace.AccessControlType.Equals(AccessControlType.Allow))
                {
                    continue;
                }

                //Resolve the principal in the ACE
                var principal = GetAcePrincipal(ace, domainName);

                //If its null, we don't care so move on
                if (principal == null)
                {
                    continue;
                }

                //Check if our ACE applies through inheritance rules
                if (!CheckAceInheritanceRules(ace, resolved.ObjectType))
                {
                    continue;
                }

                //Interesting Computer ACEs - GenericAll, WriteDacl, GenericWrite, WriteProperty (AllowedToAct), WriteOwner, ExtendedRight (LAPS)
                var rights        = ace.ActiveDirectoryRights;
                var objectAceType = ace.ObjectType.ToString();

                _guidMap.TryGetValue(objectAceType, out var mappedGuid);

                if (rights.HasFlag(ActiveDirectoryRights.GenericAll))
                {
                    if (objectAceType == AllGuid || objectAceType == "")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "",
                            RightName     = "GenericAll",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    else if (mappedGuid != null && mappedGuid == "ms-Mcs-AdmPwd")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "",
                            RightName     = "ReadLAPSPassword",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    //GenericAll includes every other flag, so continue here so we don't duplicate privs
                    continue;
                }

                if (rights.HasFlag(ActiveDirectoryRights.GenericWrite) ||
                    rights.HasFlag(ActiveDirectoryRights.WriteProperty))
                {
                    //GenericWrite encapsulates WriteProperty
                    if (rights.HasFlag(ActiveDirectoryRights.GenericWrite) &&
                        (objectAceType == AllGuid || objectAceType == ""))
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "",
                            RightName     = "GenericWrite",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    else if (rights.HasFlag(ActiveDirectoryRights.WriteProperty))
                    {
                        if (objectAceType == AllGuid || objectAceType == "")
                        {
                            aces.Add(new ACL
                            {
                                AceType       = "",
                                RightName     = "GenericWrite",
                                PrincipalName = principal.PrincipalName,
                                PrincipalType = principal.ObjectType
                            });
                        }
                        else if (objectAceType == "3f78c3e5-f79a-46bd-a0b8-9d18116ddc79")
                        {
                            aces.Add(new ACL
                            {
                                AceType       = "AllowedToAct",
                                PrincipalName = principal.PrincipalName,
                                PrincipalType = principal.ObjectType,
                                RightName     = "WriteProperty"
                            });
                        }
                    }
                }

                if (rights.HasFlag(ActiveDirectoryRights.WriteDacl))
                {
                    aces.Add(new ACL
                    {
                        AceType       = "",
                        RightName     = "WriteDacl",
                        PrincipalName = principal.PrincipalName,
                        PrincipalType = principal.ObjectType
                    });
                }

                if (rights.HasFlag(ActiveDirectoryRights.WriteOwner))
                {
                    aces.Add(new ACL
                    {
                        AceType       = "",
                        RightName     = "WriteOwner",
                        PrincipalName = principal.PrincipalName,
                        PrincipalType = principal.ObjectType
                    });
                }

                if (rights.HasFlag(ActiveDirectoryRights.ExtendedRight))
                {
                    if (mappedGuid != null && mappedGuid == "ms-Mcs-AdmPwd" && entry.GetProp("ms-mcs-admpwdexpirationtime") != null)
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "",
                            RightName     = "ReadLAPSPassword",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    else if (objectAceType == AllGuid || objectAceType == "")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "All",
                            RightName     = "ExtendedRight",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                }
            }

            obj.Aces = aces.Distinct().ToArray();
        }
Esempio n. 30
0
        public static void GetObjectAces(SearchResultEntry entry, ResolvedEntry resolved, ref Domain obj)
        {
            if (!Utils.IsMethodSet(ResolvedCollectionMethod.ACL))
            {
                return;
            }

            var aces = new List <ACL>();
            var ntSecurityDescriptor = entry.GetPropBytes("ntsecuritydescriptor");

            //If the ntsecuritydescriptor is null, no point in continuing
            //I'm still not entirely sure what causes this, but it can happen
            if (ntSecurityDescriptor == null)
            {
                return;
            }

            var domainName = Utils.ConvertDnToDomain(entry.DistinguishedName);

            var newDescriptor = new ActiveDirectorySecurity();

            newDescriptor.SetSecurityDescriptorBinaryForm(ntSecurityDescriptor);
            var owner = GetAclOwner(newDescriptor, domainName);

            if (owner != null)
            {
                aces.Add(new ACL
                {
                    AceType       = "",
                    RightName     = "Owner",
                    PrincipalName = owner.PrincipalName,
                    PrincipalType = owner.ObjectType
                });
            }

            foreach (ActiveDirectoryAccessRule ace in newDescriptor.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                //Ignore null aces
                if (ace == null)
                {
                    continue;
                }

                //Ignore Deny aces
                if (!ace.AccessControlType.Equals(AccessControlType.Allow))
                {
                    continue;
                }

                //Resolve the principal in the ACE
                var principal = GetAcePrincipal(ace, domainName);

                //If its null, we don't care so move on
                if (principal == null)
                {
                    continue;
                }

                //Check if our ACE applies through inheritance rules
                if (!CheckAceInheritanceRules(ace, resolved.ObjectType))
                {
                    continue;
                }

                //Interesting Domain ACEs - GenericAll, WriteDacl, WriteOwner, Replication Rights, AllExtendedRights
                var rights        = ace.ActiveDirectoryRights;
                var objectAceType = ace.ObjectType.ToString();

                if (rights.HasFlag(ActiveDirectoryRights.GenericAll))
                {
                    if (objectAceType == AllGuid || objectAceType == "")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "",
                            RightName     = "GenericAll",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    //GenericAll includes every other flag, so continue here so we don't duplicate privs
                    continue;
                }

                if (rights.HasFlag(ActiveDirectoryRights.WriteDacl))
                {
                    aces.Add(new ACL
                    {
                        AceType       = "",
                        RightName     = "WriteDacl",
                        PrincipalName = principal.PrincipalName,
                        PrincipalType = principal.ObjectType
                    });
                }

                if (rights.HasFlag(ActiveDirectoryRights.WriteOwner))
                {
                    aces.Add(new ACL
                    {
                        AceType       = "",
                        RightName     = "WriteOwner",
                        PrincipalName = principal.PrincipalName,
                        PrincipalType = principal.ObjectType
                    });
                }

                if (rights.HasFlag(ActiveDirectoryRights.ExtendedRight))
                {
                    if (objectAceType == "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "GetChanges",
                            RightName     = "ExtendedRight",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    else if (objectAceType == "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "GetChangesAll",
                            RightName     = "ExtendedRight",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                    else if (objectAceType == AllGuid || objectAceType == "")
                    {
                        aces.Add(new ACL
                        {
                            AceType       = "All",
                            RightName     = "ExtendedRight",
                            PrincipalName = principal.PrincipalName,
                            PrincipalType = principal.ObjectType
                        });
                    }
                }
            }

            obj.Aces = aces.Distinct().ToArray();
        }