Пример #1
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle handle         = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle invalidHandle1 = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle invalidHandle2 = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                Win32Native.UNICODE_STRING[] names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int index1 = 0;
                foreach (IdentityReference sourceAccount in sourceAccounts)
                {
                    NTAccount ntAccount = sourceAccount as NTAccount;
                    if (ntAccount == (NTAccount)null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    names[index1].Buffer = ntAccount.ToString();
                    if (names[index1].Buffer.Length * 2 + 2 > (int)ushort.MaxValue)
                    {
                        throw new SystemException();
                    }
                    names[index1].Length        = (ushort)(names[index1].Buffer.Length * 2);
                    names[index1].MaximumLength = (ushort)((uint)names[index1].Length + 2U);
                    ++index1;
                }
                handle     = System.Security.Principal.Win32.LsaOpenPolicy((string)null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed = false;
                uint num = !System.Security.Principal.Win32.LsaLookupNames2Supported ? Win32Native.LsaLookupNames(handle, sourceAccounts.Count, names, ref invalidHandle1, ref invalidHandle2) : Win32Native.LsaLookupNames2(handle, 0, sourceAccounts.Count, names, ref invalidHandle1, ref invalidHandle2);
                if ((int)num == -1073741801 || (int)num == -1073741670)
                {
                    throw new OutOfMemoryException();
                }
                if ((int)num == -1073741790)
                {
                    throw new UnauthorizedAccessException();
                }
                if ((int)num == -1073741709 || (int)num == 263)
                {
                    someFailed = true;
                }
                else if ((int)num != 0)
                {
                    throw new SystemException(Win32Native.GetMessage(Win32Native.LsaNtStatusToWinError((int)num)));
                }
                IdentityReferenceCollection referenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
                if ((int)num == 0 || (int)num == 263)
                {
                    if (System.Security.Principal.Win32.LsaLookupNames2Supported)
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        System.Security.Principal.Win32.InitializeReferencedDomainsPointer(invalidHandle1);
                        Win32Native.LSA_TRANSLATED_SID2[] array = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0UL, array, 0, array.Length);
                        for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsaTranslatedSiD2 = array[index2];
                            switch (lsaTranslatedSiD2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                referenceCollection.Add((IdentityReference) new SecurityIdentifier(lsaTranslatedSiD2.Sid, true));
                                break;

                            default:
                                someFailed = true;
                                referenceCollection.Add(sourceAccounts[index2]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        System.Security.Principal.Win32.InitializeReferencedDomainsPointer(invalidHandle1);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST referencedDomainList = invalidHandle1.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                        SecurityIdentifier[] securityIdentifierArray = new SecurityIdentifier[referencedDomainList.Entries];
                        for (int index2 = 0; index2 < referencedDomainList.Entries; ++index2)
                        {
                            Win32Native.LSA_TRUST_INFORMATION trustInformation = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)referencedDomainList.Domains + (long)(index2 * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            securityIdentifierArray[index2] = new SecurityIdentifier(trustInformation.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] array = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0UL, array, 0, array.Length);
                        for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsaTranslatedSid = array[index2];
                            switch (lsaTranslatedSid.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                referenceCollection.Add((IdentityReference) new SecurityIdentifier(securityIdentifierArray[lsaTranslatedSid.DomainIndex], lsaTranslatedSid.Rid));
                                break;

                            default:
                                someFailed = true;
                                referenceCollection.Add(sourceAccounts[index2]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                    {
                        referenceCollection.Add(sourceAccounts[index2]);
                    }
                }
                return(referenceCollection);
            }
            finally
            {
                handle.Dispose();
                invalidHandle1.Dispose();
                invalidHandle2.Dispose();
            }
        }
Пример #2
0
Файл: SID.cs Проект: jnm2/corefx
        private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
        {
            if (sourceSids == null)
            {
                throw new ArgumentNullException(nameof(sourceSids));
            }

            if (sourceSids.Count == 0)
            {
                throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids));
            }
            Contract.EndContractBlock();

            IntPtr[]            SidArrayPtr          = new IntPtr[sourceSids.Count];
            GCHandle[]          HandleArray          = new GCHandle[sourceSids.Count];
            SafeLsaPolicyHandle LsaHandle            = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle NamesPtr             = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                //
                // Pin all elements in the array of SIDs
                //

                int currentSid = 0;
                foreach (IdentityReference id in sourceSids)
                {
                    SecurityIdentifier sid = id as SecurityIdentifier;

                    if (sid == null)
                    {
                        throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids));
                    }

                    HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned);
                    SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject();
                    currentSid++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;
                ReturnCode = Interop.Advapi32.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr);

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
                    ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
                         ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    int win32ErrorCode = Interop.NtDll.RtlNtStatusToDosError(unchecked ((int)ReturnCode));

                    Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode));
                    throw new Win32Exception(win32ErrorCode);
                }


                NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf <Interop.LSA_TRANSLATED_NAME>());
                Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);

                //
                // Interpret the results and generate NTAccount objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count);

                if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    //
                    // Interpret the results and generate NT Account objects
                    //

                    Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read <Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
                    string[] ReferencedDomains             = new string[rdl.Entries];

                    for (int i = 0; i < rdl.Entries; i++)
                    {
                        Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure <Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf <Interop.LSA_TRUST_INFORMATION>()));
                        ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char));
                    }

                    Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
                    NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length);

                    for (int i = 0; i < sourceSids.Count; i++)
                    {
                        Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i];

                        switch ((SidNameUse)Ltn.Use)
                        {
                        case SidNameUse.User:
                        case SidNameUse.Group:
                        case SidNameUse.Alias:
                        case SidNameUse.Computer:
                        case SidNameUse.WellKnownGroup:
                            string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char));;
                            string domain  = ReferencedDomains[Ltn.DomainIndex];
                            Result.Add(new NTAccount(domain, account));
                            break;

                        default:
                            someFailed = true;
                            Result.Add(sourceSids[i]);
                            break;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceSids.Count; i++)
                    {
                        Result.Add(sourceSids[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                for (int i = 0; i < sourceSids.Count; i++)
                {
                    if (HandleArray[i].IsAllocated)
                    {
                        HandleArray[i].Free();
                    }
                }

                LsaHandle.Dispose();
                ReferencedDomainsPtr.Dispose();
                NamesPtr.Dispose();
            }
        }
Пример #3
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException(nameof(sourceAccounts));
            }

            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceAccounts));
            }

            SafeLsaPolicyHandle?LsaHandle            = null;
            SafeLsaMemoryHandle?ReferencedDomainsPtr = null;
            SafeLsaMemoryHandle?SidsPtr = null;

            try
            {
                //
                // Construct an array of unicode strings
                //

                Interop.Advapi32.MARSHALLED_UNICODE_STRING[] Names = new Interop.Advapi32.MARSHALLED_UNICODE_STRING[sourceAccounts.Count];

                int currentName = 0;
                foreach (IdentityReference id in sourceAccounts)
                {
                    if (!(id is NTAccount nta))
                    {
                        throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceAccounts));
                    }

                    Names[currentName].Buffer = nta.ToString();

                    if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue)
                    {
                        // this should never happen since we are already validating account name length in constructor and
                        // it is less than this limit
                        Debug.Fail("NTAccount::TranslateToSids - source account name is too long.");
                        throw new InvalidOperationException();
                    }

                    Names[currentName].Length        = (ushort)(Names[currentName].Buffer.Length * 2);
                    Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2);
                    currentName++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, Interop.Advapi32.PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

                ReturnCode = Interop.Advapi32.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, out ReferencedDomainsPtr, out SidsPtr);

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
                    ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
                         ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);

                    if (unchecked ((int)win32ErrorCode) != Interop.Errors.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
                    {
                        Debug.Fail($"Interop.LsaLookupNames(2) returned unrecognized error {win32ErrorCode}");
                    }

                    throw new Win32Exception(unchecked ((int)win32ErrorCode));
                }

                //
                // Interpret the results and generate SID objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

                if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf <Interop.LSA_TRANSLATED_SID2>());
                    ReferencedDomainsPtr.InitializeReferencedDomainsList();
                    Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                    SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Interop.LSA_TRANSLATED_SID2 Lts = translatedSids[i];

                        //
                        // Only some names are recognized as NTAccount objects
                        //

                        switch ((SidNameUse)Lts.Use)
                        {
                        case SidNameUse.User:
                        case SidNameUse.Group:
                        case SidNameUse.Alias:
                        case SidNameUse.Computer:
                        case SidNameUse.WellKnownGroup:
                            Result.Add(new SecurityIdentifier(Lts.Sid));
                            break;

                        default:
                            someFailed = true;
                            Result.Add(sourceAccounts[i]);
                            break;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Result.Add(sourceAccounts[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                LsaHandle?.Dispose();
                ReferencedDomainsPtr?.Dispose();
                SidsPtr?.Dispose();
            }
        }
Пример #4
0
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException(nameof(targetType));
            }

            //
            // Target type must be a subclass of IdentityReference
            //

            if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
            }

            //
            // if the source collection is empty, just return an empty collection
            //
            if (Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }

            int SourceSidsCount       = 0;
            int SourceNTAccountsCount = 0;

            //
            // First, see how many of each of the source types we have.
            // The cases where source type == target type require no conversion.
            //

            for (int i = 0; i < Identities.Count; i++)
            {
                Type type = Identities[i].GetType();

                if (type == targetType)
                {
                    continue;
                }
                else if (type == typeof(SecurityIdentifier))
                {
                    SourceSidsCount += 1;
                }
                else if (type == typeof(NTAccount))
                {
                    SourceNTAccountsCount += 1;
                }
                else
                {
                    //
                    // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                    // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                    //
                    Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                    throw new NotSupportedException();
                }
            }

            bool Homogeneous = false;
            IdentityReferenceCollection SourceSids       = null;
            IdentityReferenceCollection SourceNTAccounts = null;

            if (SourceSidsCount == Count)
            {
                Homogeneous = true;
                SourceSids  = this;
            }
            else if (SourceSidsCount > 0)
            {
                SourceSids = new IdentityReferenceCollection(SourceSidsCount);
            }

            if (SourceNTAccountsCount == Count)
            {
                Homogeneous      = true;
                SourceNTAccounts = this;
            }
            else if (SourceNTAccountsCount > 0)
            {
                SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount);
            }
            //
            // Repackage only if the source is not homogeneous (contains different source types)
            //

            IdentityReferenceCollection Result = null;

            if (!Homogeneous)
            {
                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        continue;
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        SourceSids.Add(id);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        SourceNTAccounts.Add(id);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                        // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                        //
                        Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new NotSupportedException();
                    }
                }
            }

            bool someFailed = false;
            IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null;

            if (SourceSidsCount > 0)
            {
                TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetSids;
                }
            }

            if (SourceNTAccountsCount > 0)
            {
                TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetNTAccounts;
                }
            }

            if (forceSuccess && someFailed)
            {
                //
                // Need to throw an exception here and provide information regarding
                // which identity references could not be translated to the target type
                //

                Result = new IdentityReferenceCollection();

                if (TargetSids != null)
                {
                    foreach (IdentityReference id in TargetSids)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                if (TargetNTAccounts != null)
                {
                    foreach (IdentityReference id in TargetNTAccounts)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result);
            }
            else if (!Homogeneous)
            {
                SourceSidsCount       = 0;
                SourceNTAccountsCount = 0;

                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        Result.Add(id);
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        Result.Add(TargetSids[SourceSidsCount++]);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        Result.Add(TargetNTAccounts[SourceNTAccountsCount++]);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                        // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                        //
                        Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new NotSupportedException();
                    }
                }
            }

            return(Result);
        }
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int capacity = 0;
            int num2     = 0;

            for (int i = 0; i < this.Identities.Count; i++)
            {
                Type type = this.Identities[i].GetType();
                if (type != targetType)
                {
                    if (type != typeof(SecurityIdentifier))
                    {
                        if (type != typeof(NTAccount))
                        {
                            throw new SystemException();
                        }
                        num2++;
                    }
                    else
                    {
                        capacity++;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection sourceSids     = null;
            IdentityReferenceCollection sourceAccounts = null;

            if (capacity == this.Count)
            {
                flag       = true;
                sourceSids = this;
            }
            else if (capacity > 0)
            {
                sourceSids = new IdentityReferenceCollection(capacity);
            }
            if (num2 == this.Count)
            {
                flag           = true;
                sourceAccounts = this;
            }
            else if (num2 > 0)
            {
                sourceAccounts = new IdentityReferenceCollection(num2);
            }
            IdentityReferenceCollection unmappedIdentities = null;

            if (!flag)
            {
                unmappedIdentities = new IdentityReferenceCollection(this.Identities.Count);
                for (int j = 0; j < this.Identities.Count; j++)
                {
                    IdentityReference identity = this[j];
                    Type type2 = identity.GetType();
                    if (type2 != targetType)
                    {
                        if (type2 != typeof(SecurityIdentifier))
                        {
                            if (type2 != typeof(NTAccount))
                            {
                                throw new SystemException();
                            }
                            sourceAccounts.Add(identity);
                        }
                        else
                        {
                            sourceSids.Add(identity);
                        }
                    }
                }
            }
            bool someFailed = false;
            IdentityReferenceCollection references4 = null;
            IdentityReferenceCollection references5 = null;

            if (capacity > 0)
            {
                references4 = SecurityIdentifier.Translate(sourceSids, targetType, out someFailed);
                if (flag && (!forceSuccess || !someFailed))
                {
                    unmappedIdentities = references4;
                }
            }
            if (num2 > 0)
            {
                references5 = NTAccount.Translate(sourceAccounts, targetType, out someFailed);
                if (flag && (!forceSuccess || !someFailed))
                {
                    unmappedIdentities = references5;
                }
            }
            if (forceSuccess && someFailed)
            {
                unmappedIdentities = new IdentityReferenceCollection();
                if (references4 != null)
                {
                    foreach (IdentityReference reference2 in references4)
                    {
                        if (reference2.GetType() != targetType)
                        {
                            unmappedIdentities.Add(reference2);
                        }
                    }
                }
                if (references5 != null)
                {
                    foreach (IdentityReference reference3 in references5)
                    {
                        if (reference3.GetType() != targetType)
                        {
                            unmappedIdentities.Add(reference3);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), unmappedIdentities);
            }
            if (!flag)
            {
                capacity           = 0;
                num2               = 0;
                unmappedIdentities = new IdentityReferenceCollection(this.Identities.Count);
                for (int k = 0; k < this.Identities.Count; k++)
                {
                    IdentityReference reference4 = this[k];
                    Type type3 = reference4.GetType();
                    if (type3 == targetType)
                    {
                        unmappedIdentities.Add(reference4);
                    }
                    else if (type3 == typeof(SecurityIdentifier))
                    {
                        unmappedIdentities.Add(references4[capacity++]);
                    }
                    else
                    {
                        if (type3 != typeof(NTAccount))
                        {
                            throw new SystemException();
                        }
                        unmappedIdentities.Add(references5[num2++]);
                    }
                }
            }
            return(unmappedIdentities);
        }
Пример #6
0
        private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
        {
            IdentityReferenceCollection references2;

            if (sourceSids == null)
            {
                throw new ArgumentNullException("sourceSids");
            }
            if (sourceSids.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceSids");
            }
            IntPtr[]            sids              = new IntPtr[sourceSids.Count];
            GCHandle[]          handleArray       = new GCHandle[sourceSids.Count];
            SafeLsaPolicyHandle invalidHandle     = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle referencedDomains = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle names             = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                int index = 0;
                foreach (IdentityReference reference in sourceSids)
                {
                    SecurityIdentifier identifier = reference as SecurityIdentifier;
                    if (identifier == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceSids");
                    }
                    handleArray[index] = GCHandle.Alloc(identifier.BinaryForm, GCHandleType.Pinned);
                    sids[index]        = handleArray[index].AddrOfPinnedObject();
                    index++;
                }
                invalidHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed    = false;
                uint num2 = Win32Native.LsaLookupSids(invalidHandle, sourceSids.Count, sids, ref referencedDomains, ref names);
                switch (num2)
                {
                case 0xc0000017:
                case 0xc000009a:
                    throw new OutOfMemoryException();

                case 0xc0000022:
                    throw new UnauthorizedAccessException();
                }
                if ((num2 == 0xc0000073) || (num2 == 0x107))
                {
                    someFailed = true;
                }
                else if (num2 != 0)
                {
                    throw new SystemException(Win32Native.GetMessage(Win32Native.LsaNtStatusToWinError((int)num2)));
                }
                names.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_NAME)));
                Win32.InitializeReferencedDomainsPointer(referencedDomains);
                IdentityReferenceCollection references = new IdentityReferenceCollection(sourceSids.Count);
                if ((num2 == 0) || (num2 == 0x107))
                {
                    Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_referenced_domain_list = referencedDomains.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0L);
                    string[] strArray = new string[lsa_referenced_domain_list.Entries];
                    for (int i = 0; i < lsa_referenced_domain_list.Entries; i++)
                    {
                        Win32Native.LSA_TRUST_INFORMATION lsa_trust_information = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr(((long)lsa_referenced_domain_list.Domains) + (i * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                        strArray[i] = Marshal.PtrToStringUni(lsa_trust_information.Name.Buffer, lsa_trust_information.Name.Length / 2);
                    }
                    Win32Native.LSA_TRANSLATED_NAME[] array = new Win32Native.LSA_TRANSLATED_NAME[sourceSids.Count];
                    names.ReadArray <Win32Native.LSA_TRANSLATED_NAME>(0L, array, 0, array.Length);
                    for (int j = 0; j < sourceSids.Count; j++)
                    {
                        Win32Native.LSA_TRANSLATED_NAME lsa_translated_name = array[j];
                        switch (lsa_translated_name.Use)
                        {
                        case 1:
                        case 2:
                        case 4:
                        case 5:
                        case 9:
                        {
                            string accountName = Marshal.PtrToStringUni(lsa_translated_name.Name.Buffer, lsa_translated_name.Name.Length / 2);
                            string domainName  = strArray[lsa_translated_name.DomainIndex];
                            references.Add(new NTAccount(domainName, accountName));
                            continue;
                        }
                        }
                        someFailed = true;
                        references.Add(sourceSids[j]);
                    }
                }
                else
                {
                    for (int k = 0; k < sourceSids.Count; k++)
                    {
                        references.Add(sourceSids[k]);
                    }
                }
                references2 = references;
            }
            finally
            {
                for (int m = 0; m < sourceSids.Count; m++)
                {
                    if (handleArray[m].IsAllocated)
                    {
                        handleArray[m].Free();
                    }
                }
                invalidHandle.Dispose();
                referencedDomains.Dispose();
                names.Dispose();
            }
            return(references2);
        }
Пример #7
0
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == (Type)null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int capacity1 = 0;
            int capacity2 = 0;

            for (int index = 0; index < this.Identities.Count; ++index)
            {
                Type type = this.Identities[index].GetType();
                if (!(type == targetType))
                {
                    if (type == typeof(SecurityIdentifier))
                    {
                        ++capacity1;
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        ++capacity2;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection sourceSids     = (IdentityReferenceCollection)null;
            IdentityReferenceCollection sourceAccounts = (IdentityReferenceCollection)null;

            if (capacity1 == this.Count)
            {
                flag       = true;
                sourceSids = this;
            }
            else if (capacity1 > 0)
            {
                sourceSids = new IdentityReferenceCollection(capacity1);
            }
            if (capacity2 == this.Count)
            {
                flag           = true;
                sourceAccounts = this;
            }
            else if (capacity2 > 0)
            {
                sourceAccounts = new IdentityReferenceCollection(capacity2);
            }
            IdentityReferenceCollection referenceCollection1 = (IdentityReferenceCollection)null;

            if (!flag)
            {
                referenceCollection1 = new IdentityReferenceCollection(this.Identities.Count);
                for (int index = 0; index < this.Identities.Count; ++index)
                {
                    IdentityReference identity = this[index];
                    Type type = identity.GetType();
                    if (!(type == targetType))
                    {
                        if (type == typeof(SecurityIdentifier))
                        {
                            sourceSids.Add(identity);
                        }
                        else
                        {
                            if (!(type == typeof(NTAccount)))
                            {
                                throw new SystemException();
                            }
                            sourceAccounts.Add(identity);
                        }
                    }
                }
            }
            bool someFailed = false;
            IdentityReferenceCollection referenceCollection2 = (IdentityReferenceCollection)null;
            IdentityReferenceCollection referenceCollection3 = (IdentityReferenceCollection)null;

            if (capacity1 > 0)
            {
                referenceCollection2 = SecurityIdentifier.Translate(sourceSids, targetType, out someFailed);
                if (flag && !(forceSuccess & someFailed))
                {
                    referenceCollection1 = referenceCollection2;
                }
            }
            if (capacity2 > 0)
            {
                referenceCollection3 = NTAccount.Translate(sourceAccounts, targetType, out someFailed);
                if (flag && !(forceSuccess & someFailed))
                {
                    referenceCollection1 = referenceCollection3;
                }
            }
            if (forceSuccess & someFailed)
            {
                IdentityReferenceCollection unmappedIdentities = new IdentityReferenceCollection();
                if (referenceCollection2 != null)
                {
                    foreach (IdentityReference identity in referenceCollection2)
                    {
                        if (identity.GetType() != targetType)
                        {
                            unmappedIdentities.Add(identity);
                        }
                    }
                }
                if (referenceCollection3 != null)
                {
                    foreach (IdentityReference identity in referenceCollection3)
                    {
                        if (identity.GetType() != targetType)
                        {
                            unmappedIdentities.Add(identity);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), unmappedIdentities);
            }
            if (!flag)
            {
                int num1 = 0;
                int num2 = 0;
                referenceCollection1 = new IdentityReferenceCollection(this.Identities.Count);
                for (int index = 0; index < this.Identities.Count; ++index)
                {
                    IdentityReference identity = this[index];
                    Type type = identity.GetType();
                    if (type == targetType)
                    {
                        referenceCollection1.Add(identity);
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        referenceCollection1.Add(referenceCollection2[num1++]);
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        referenceCollection1.Add(referenceCollection3[num2++]);
                    }
                }
            }
            return(referenceCollection1);
        }
Пример #8
0
        private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
        {
            if (sourceSids == null)
            {
                throw new ArgumentNullException("sourceSids");
            }
            if (sourceSids.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceSids");
            }
            IntPtr[]                    array  = new IntPtr[sourceSids.Count];
            GCHandle[]                  array2 = new GCHandle[sourceSids.Count];
            SafeLsaPolicyHandle         safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle       = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle2      = SafeLsaMemoryHandle.InvalidHandle;
            IdentityReferenceCollection result;

            try
            {
                int num = 0;
                foreach (IdentityReference identityReference in sourceSids)
                {
                    SecurityIdentifier securityIdentifier = identityReference as SecurityIdentifier;
                    if (securityIdentifier == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceSids");
                    }
                    array2[num] = GCHandle.Alloc(securityIdentifier.BinaryForm, GCHandleType.Pinned);
                    array[num]  = array2[num].AddrOfPinnedObject();
                    num++;
                }
                safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed          = false;
                uint num2 = Win32Native.LsaLookupSids(safeLsaPolicyHandle, sourceSids.Count, array, ref invalidHandle, ref invalidHandle2);
                if (num2 == 3221225495U || num2 == 3221225626U)
                {
                    throw new OutOfMemoryException();
                }
                if (num2 == 3221225506U)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num2 == 3221225587U || num2 == 263U)
                {
                    someFailed = true;
                }
                else if (num2 != 0U)
                {
                    int errorCode = Win32Native.LsaNtStatusToWinError((int)num2);
                    throw new SystemException(Win32Native.GetMessage(errorCode));
                }
                invalidHandle2.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_NAME)));
                Win32.InitializeReferencedDomainsPointer(invalidHandle);
                IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceSids.Count);
                if (num2 == 0U || num2 == 263U)
                {
                    Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_REFERENCED_DOMAIN_LIST = invalidHandle.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                    string[] array3 = new string[lsa_REFERENCED_DOMAIN_LIST.Entries];
                    for (int i = 0; i < lsa_REFERENCED_DOMAIN_LIST.Entries; i++)
                    {
                        Win32Native.LSA_TRUST_INFORMATION lsa_TRUST_INFORMATION = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)lsa_REFERENCED_DOMAIN_LIST.Domains + (long)(i * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                        array3[i] = Marshal.PtrToStringUni(lsa_TRUST_INFORMATION.Name.Buffer, (int)(lsa_TRUST_INFORMATION.Name.Length / 2));
                    }
                    Win32Native.LSA_TRANSLATED_NAME[] array4 = new Win32Native.LSA_TRANSLATED_NAME[sourceSids.Count];
                    invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_NAME>(0UL, array4, 0, array4.Length);
                    int j = 0;
                    while (j < sourceSids.Count)
                    {
                        Win32Native.LSA_TRANSLATED_NAME lsa_TRANSLATED_NAME = array4[j];
                        switch (lsa_TRANSLATED_NAME.Use)
                        {
                        case 1:
                        case 2:
                        case 4:
                        case 5:
                        case 9:
                        {
                            string accountName = Marshal.PtrToStringUni(lsa_TRANSLATED_NAME.Name.Buffer, (int)(lsa_TRANSLATED_NAME.Name.Length / 2));
                            string domainName  = array3[lsa_TRANSLATED_NAME.DomainIndex];
                            identityReferenceCollection.Add(new NTAccount(domainName, accountName));
                            break;
                        }

                        case 3:
                        case 6:
                        case 7:
                        case 8:
                            goto IL_2C4;

                        default:
                            goto IL_2C4;
                        }
IL_2D6:
                        j++;
                        continue;
IL_2C4:
                        someFailed = true;
                        identityReferenceCollection.Add(sourceSids[j]);
                        goto IL_2D6;
                    }
                }
                else
                {
                    for (int k = 0; k < sourceSids.Count; k++)
                    {
                        identityReferenceCollection.Add(sourceSids[k]);
                    }
                }
                result = identityReferenceCollection;
            }
            finally
            {
                for (int l = 0; l < sourceSids.Count; l++)
                {
                    if (array2[l].IsAllocated)
                    {
                        array2[l].Free();
                    }
                }
                safeLsaPolicyHandle.Dispose();
                invalidHandle.Dispose();
                invalidHandle2.Dispose();
            }
            return(result);
        }
Пример #9
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle         safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle       = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle2      = SafeLsaMemoryHandle.InvalidHandle;
            IdentityReferenceCollection result;

            try
            {
                Win32Native.UNICODE_STRING[] array = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int num = 0;
                foreach (IdentityReference identityReference in sourceAccounts)
                {
                    NTAccount ntaccount = identityReference as NTAccount;
                    if (ntaccount == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    array[num].Buffer = ntaccount.ToString();
                    if (array[num].Buffer.Length * 2 + 2 > 65535)
                    {
                        throw new SystemException();
                    }
                    array[num].Length        = (ushort)(array[num].Buffer.Length * 2);
                    array[num].MaximumLength = array[num].Length + 2;
                    num++;
                }
                safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed          = false;
                uint num2;
                if (Win32.LsaLookupNames2Supported)
                {
                    num2 = Win32Native.LsaLookupNames2(safeLsaPolicyHandle, 0, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                else
                {
                    num2 = Win32Native.LsaLookupNames(safeLsaPolicyHandle, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                if (num2 == 3221225495U || num2 == 3221225626U)
                {
                    throw new OutOfMemoryException();
                }
                if (num2 == 3221225506U)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num2 == 3221225587U || num2 == 263U)
                {
                    someFailed = true;
                }
                else if (num2 != 0U)
                {
                    int errorCode = Win32Native.LsaNtStatusToWinError((int)num2);
                    throw new SystemException(Win32Native.GetMessage(errorCode));
                }
                IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
                if (num2 == 0U || num2 == 263U)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_TRANSLATED_SID2[] array2 = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0UL, array2, 0, array2.Length);
                        int i = 0;
                        while (i < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsa_TRANSLATED_SID = array2[i];
                            switch (lsa_TRANSLATED_SID.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(lsa_TRANSLATED_SID.Sid, true));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_282;

                            default:
                                goto IL_282;
                            }
IL_294:
                            i++;
                            continue;
IL_282:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[i]);
                            goto IL_294;
                        }
                    }
                    else
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_REFERENCED_DOMAIN_LIST = invalidHandle.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                        SecurityIdentifier[] array3 = new SecurityIdentifier[lsa_REFERENCED_DOMAIN_LIST.Entries];
                        for (int j = 0; j < lsa_REFERENCED_DOMAIN_LIST.Entries; j++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION lsa_TRUST_INFORMATION = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)lsa_REFERENCED_DOMAIN_LIST.Domains + (long)(j * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            array3[j] = new SecurityIdentifier(lsa_TRUST_INFORMATION.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] array4 = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0UL, array4, 0, array4.Length);
                        int k = 0;
                        while (k < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsa_TRANSLATED_SID2 = array4[k];
                            switch (lsa_TRANSLATED_SID2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(array3[lsa_TRANSLATED_SID2.DomainIndex], lsa_TRANSLATED_SID2.Rid));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_3C8;

                            default:
                                goto IL_3C8;
                            }
IL_3DA:
                            k++;
                            continue;
IL_3C8:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[k]);
                            goto IL_3DA;
                        }
                    }
                }
                else
                {
                    for (int l = 0; l < sourceAccounts.Count; l++)
                    {
                        identityReferenceCollection.Add(sourceAccounts[l]);
                    }
                }
                result = identityReferenceCollection;
            }
            finally
            {
                safeLsaPolicyHandle.Dispose();
                invalidHandle.Dispose();
                invalidHandle2.Dispose();
            }
            return(result);
        }
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int num  = 0;
            int num2 = 0;

            for (int i = 0; i < this.Identities.Count; i++)
            {
                Type type = this.Identities[i].GetType();
                if (!(type == targetType))
                {
                    if (type == typeof(SecurityIdentifier))
                    {
                        num++;
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        num2++;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection identityReferenceCollection  = null;
            IdentityReferenceCollection identityReferenceCollection2 = null;

            if (num == this.Count)
            {
                flag = true;
                identityReferenceCollection = this;
            }
            else if (num > 0)
            {
                identityReferenceCollection = new IdentityReferenceCollection(num);
            }
            if (num2 == this.Count)
            {
                flag = true;
                identityReferenceCollection2 = this;
            }
            else if (num2 > 0)
            {
                identityReferenceCollection2 = new IdentityReferenceCollection(num2);
            }
            IdentityReferenceCollection identityReferenceCollection3 = null;

            if (!flag)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int j = 0; j < this.Identities.Count; j++)
                {
                    IdentityReference identityReference = this[j];
                    Type type2 = identityReference.GetType();
                    if (!(type2 == targetType))
                    {
                        if (type2 == typeof(SecurityIdentifier))
                        {
                            identityReferenceCollection.Add(identityReference);
                        }
                        else
                        {
                            if (!(type2 == typeof(NTAccount)))
                            {
                                throw new SystemException();
                            }
                            identityReferenceCollection2.Add(identityReference);
                        }
                    }
                }
            }
            bool flag2 = false;
            IdentityReferenceCollection identityReferenceCollection4 = null;
            IdentityReferenceCollection identityReferenceCollection5 = null;

            if (num > 0)
            {
                identityReferenceCollection4 = SecurityIdentifier.Translate(identityReferenceCollection, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection4;
                }
            }
            if (num2 > 0)
            {
                identityReferenceCollection5 = NTAccount.Translate(identityReferenceCollection2, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection5;
                }
            }
            if (forceSuccess && flag2)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection();
                if (identityReferenceCollection4 != null)
                {
                    foreach (IdentityReference identityReference2 in identityReferenceCollection4)
                    {
                        if (identityReference2.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference2);
                        }
                    }
                }
                if (identityReferenceCollection5 != null)
                {
                    foreach (IdentityReference identityReference3 in identityReferenceCollection5)
                    {
                        if (identityReference3.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference3);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), identityReferenceCollection3);
            }
            if (!flag)
            {
                num  = 0;
                num2 = 0;
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int k = 0; k < this.Identities.Count; k++)
                {
                    IdentityReference identityReference4 = this[k];
                    Type type3 = identityReference4.GetType();
                    if (type3 == targetType)
                    {
                        identityReferenceCollection3.Add(identityReference4);
                    }
                    else if (type3 == typeof(SecurityIdentifier))
                    {
                        identityReferenceCollection3.Add(identityReferenceCollection4[num++]);
                    }
                    else
                    {
                        if (!(type3 == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        identityReferenceCollection3.Add(identityReferenceCollection5[num2++]);
                    }
                }
            }
            return(identityReferenceCollection3);
        }
        [System.Security.SecurityCritical]  // auto-generated
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }

            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            Contract.EndContractBlock();

            SafeLsaPolicyHandle LsaHandle            = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle SidsPtr = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                //
                // Construct an array of unicode strings
                //

                Win32Native.UNICODE_STRING[] Names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];

                int currentName = 0;
                foreach (IdentityReference id in sourceAccounts)
                {
                    NTAccount nta = id as NTAccount;

                    if (nta == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }

                    Names[currentName].Buffer = nta.ToString();

                    if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue)
                    {
                        // this should never happen since we are already validating account name length in constructor and
                        // it is less than this limit
                        Contract.Assert(false, "NTAccount::TranslateToSids - source account name is too long.");
                        throw new SystemException();
                    }

                    Names[currentName].Length        = (ushort)(Names[currentName].Buffer.Length * 2);
                    Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2);
                    currentName++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

                if (Win32.LsaLookupNames2Supported)
                {
                    ReturnCode = Win32Native.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }
                else
                {
                    ReturnCode = Win32Native.LsaLookupNames(LsaHandle, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Win32Native.STATUS_NO_MEMORY ||
                    ReturnCode == Win32Native.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Win32Native.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Win32Native.STATUS_NONE_MAPPED ||
                         ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    int win32ErrorCode = Win32Native.LsaNtStatusToWinError(unchecked ((int)ReturnCode));

                    if (win32ErrorCode != Win32Native.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
                    {
                        Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32Native.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode));
                    }

                    throw new SystemException(Win32Native.GetMessage(win32ErrorCode));
                }

                //
                // Interpret the results and generate SID objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

                if (ReturnCode == 0 || ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_TRANSLATED_SID2[] translatedSids = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 Lts = translatedSids[i];

                            //
                            // Only some names are recognized as NTAccount objects
                            //

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(Lts.Sid, true));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0);
                        SecurityIdentifier[] ReferencedDomains     = new SecurityIdentifier[rdl.Entries];

                        for (int i = 0; i < rdl.Entries; i++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION ti = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr(( long )rdl.Domains + i * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION))), typeof(Win32Native.LSA_TRUST_INFORMATION));

                            ReferencedDomains[i] = new SecurityIdentifier(ti.Sid, true);
                        }

                        Win32Native.LSA_TRANSLATED_SID[] translatedSids = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID Lts = translatedSids[i];

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(ReferencedDomains[Lts.DomainIndex], Lts.Rid));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Result.Add(sourceAccounts[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                LsaHandle.Dispose();
                ReferencedDomainsPtr.Dispose();
                SidsPtr.Dispose();
            }
        }