private SecurityDescriptorTarget ConvertToTarget(ComputerPrincipalMapping computer, HashSet <SecurityIdentifier> admins)
        {
            this.logger.LogTrace("Creating new target for computer {computer} with the following principals\r\n{admins}", computer.PrincipalName, string.Join(", ", admins));

            SecurityDescriptorTarget target = new SecurityDescriptorTarget()
            {
                AuthorizationMode = AuthorizationMode.SecurityDescriptor,
                Description       = settings.RuleDescription?.Replace("{targetName}", computer.PrincipalName, StringComparison.OrdinalIgnoreCase),
                Target            = computer.Sid.ToString(),
                Type          = TargetType.Computer,
                Id            = Guid.NewGuid().ToString(),
                Notifications = settings.Notifications,
                Jit           = new SecurityDescriptorTargetJitDetails()
                {
                    AuthorizingGroup = settings.JitAuthorizingGroup,
                    ExpireAfter      = settings.JitExpireAfter
                },
                Laps = new SecurityDescriptorTargetLapsDetails()
                {
                    ExpireAfter = settings.LapsExpireAfter
                }
            };

            AccessMask mask = 0;

            mask |= settings.AllowLaps ? AccessMask.LocalAdminPassword : 0;
            mask |= settings.AllowJit ? AccessMask.Jit : 0;
            mask |= settings.AllowLapsHistory ? AccessMask.LocalAdminPasswordHistory : 0;
            mask |= settings.AllowBitLocker ? AccessMask.BitLocker : 0;

            DiscretionaryAcl acl = new DiscretionaryAcl(false, false, admins.Count);

            foreach (var sid in admins)
            {
                acl.AddAccess(AccessControlType.Allow, sid, (int)mask, InheritanceFlags.None, PropagationFlags.None);
            }

            CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false, false, ControlFlags.DiscretionaryAclPresent, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), null, null, acl);

            target.SecurityDescriptor = sd.GetSddlForm(AccessControlSections.All);

            return(target);
        }
        private void PerformComputerDiscovery(OUPrincipalMapping ou, IComputerPrincipalProvider principalProvider, List <DiscoveryError> discoveryErrors)
        {
            settings.CancellationToken.ThrowIfCancellationRequested();

            foreach (SearchResult computer in this.GetComputersFromOU(ou.AdsPath, false, principalProvider))
            {
                settings.CancellationToken.ThrowIfCancellationRequested();
                string computerName = computer.GetPropertyString("msDS-PrincipalName");
                try
                {
                    this.OnItemProcessStart?.Invoke(this, new ImportProcessingEventArgs(computerName));

                    if (this.ShouldFilterComputer(computer))
                    {
                        this.logger.LogTrace("Filtering computer {computer}", computerName);
                        continue;
                    }

                    this.logger.LogTrace("Found computer {computer} in ou {ou}", computerName, ou.OUName);

                    ComputerPrincipalMapping ce = new ComputerPrincipalMapping(computer, ou);

                    ou.Computers.Add(ce);

                    try
                    {
                        HashSet <SecurityIdentifier> principalsForComputer = new HashSet <SecurityIdentifier>(principalProvider.GetPrincipalsForComputer(computer, settings.FilterLocalAccounts));

                        this.logger.LogTrace("Got {number} principals from computer {computer}", principalsForComputer.Count, computerName);

                        foreach (var principal in principalsForComputer)
                        {
                            settings.CancellationToken.ThrowIfCancellationRequested();

                            if (this.ShouldFilter(principal, out DiscoveryError filterReason))
                            {
                                if (filterReason != null)
                                {
                                    filterReason.Target = computerName;
                                    ce.DiscoveryErrors.Add(filterReason);
                                    this.logger.LogTrace("Filtering principal {principal} with reason: {reason}", principal.ToString(), filterReason);
                                }
                            }
                            else
                            {
                                ce.Principals.Add(principal);
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        return;
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogTrace(ex, "Failed to get principals from computer {computer}", computerName);
                        ce.HasError  = true;
                        ce.Exception = ex;
                        ce.IsMissing = ex is ObjectNotFoundException;
                        ce.DiscoveryErrors.Add(new DiscoveryError()
                        {
                            Target = computerName, Message = ex.Message, Type = DiscoveryErrorType.Error
                        });
                    }

                    if (ce.DiscoveryErrors.Count > 0)
                    {
                        discoveryErrors.AddRange(ce.DiscoveryErrors);
                    }
                }
                finally
                {
                    this.OnItemProcessFinish?.Invoke(this, new ImportProcessingEventArgs(computerName));
                }
            }

            foreach (var childOU in this.GetOUs(ou.AdsPath, false))
            {
                settings.CancellationToken.ThrowIfCancellationRequested();

                this.logger.LogTrace("Found ou {ou}", childOU.GetPropertyString("distinguishedName"));

                OUPrincipalMapping childou = new OUPrincipalMapping(childOU, ou);

                ou.DescendantOUs.Add(childou);
                this.PerformComputerDiscovery(childou, principalProvider, discoveryErrors);
            }
        }