public GroupSidClaimCollection(WindowsIdentity windowsIdentity)
 {
     if (windowsIdentity.Token != IntPtr.Zero)
     {
         SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;
         try
         {
             uint num;
             invalidHandle = WindowsClaimSet.GetTokenInformation(windowsIdentity.Token, System.IdentityModel.TokenInformationClass.TokenGroups, out num);
             int    num2 = Marshal.ReadInt32(invalidHandle.DangerousGetHandle());
             IntPtr ptr  = new IntPtr(((long)invalidHandle.DangerousGetHandle()) + ((long)Marshal.OffsetOf(typeof(TOKEN_GROUPS), "Groups")));
             for (int i = 0; i < num2; i++)
             {
                 SID_AND_ATTRIBUTES sid_and_attributes = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(ptr, typeof(SID_AND_ATTRIBUTES));
                 uint num4 = 0xc0000014;
                 if ((sid_and_attributes.Attributes & num4) == 4)
                 {
                     base.Add(Claim.CreateWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid)));
                 }
                 else if ((sid_and_attributes.Attributes & num4) == 0x10)
                 {
                     base.Add(Claim.CreateDenyOnlyWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid)));
                 }
                 ptr = new IntPtr(((long)ptr) + SID_AND_ATTRIBUTES.SizeOf);
             }
         }
         finally
         {
             invalidHandle.Close();
         }
     }
 }
Esempio n. 2
0
        static bool TryCreateWindowsSidClaim(WindowsIdentity windowsIdentity, out Claim claim)
        {
            SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle;

            try
            {
                uint dwLength;
                safeAllocHandle = GetTokenInformation(windowsIdentity.Token, TokenInformationClass.TokenUser, out dwLength);
                SID_AND_ATTRIBUTES user = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(safeAllocHandle.DangerousGetHandle(), typeof(SID_AND_ATTRIBUTES));
                uint mask = NativeMethods.SE_GROUP_USE_FOR_DENY_ONLY;
                if (user.Attributes == 0)
                {
                    claim = Claim.CreateWindowsSidClaim(new SecurityIdentifier(user.Sid));
                    return(true);
                }
                else if ((user.Attributes & mask) == NativeMethods.SE_GROUP_USE_FOR_DENY_ONLY)
                {
                    claim = Claim.CreateDenyOnlyWindowsSidClaim(new SecurityIdentifier(user.Sid));
                    return(true);
                }
            }
            finally
            {
                safeAllocHandle.Close();
            }
            claim = null;
            return(false);
        }
Esempio n. 3
0
 public GroupSidClaimCollection(WindowsIdentity windowsIdentity)
 {
     if (windowsIdentity.Token != IntPtr.Zero)
     {
         SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle;
         try
         {
             uint dwLength;
             safeAllocHandle = GetTokenInformation(windowsIdentity.Token, TokenInformationClass.TokenGroups, out dwLength);
             int    count             = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
             IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(TOKEN_GROUPS), "Groups"));
             for (int i = 0; i < count; ++i)
             {
                 SID_AND_ATTRIBUTES group = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(pSidAndAttributes, typeof(SID_AND_ATTRIBUTES));
                 uint mask = NativeMethods.SE_GROUP_ENABLED | NativeMethods.SE_GROUP_LOGON_ID | NativeMethods.SE_GROUP_USE_FOR_DENY_ONLY;
                 if ((group.Attributes & mask) == NativeMethods.SE_GROUP_ENABLED)
                 {
                     base.Add(Claim.CreateWindowsSidClaim(new SecurityIdentifier(group.Sid)));
                 }
                 else if ((group.Attributes & mask) == NativeMethods.SE_GROUP_USE_FOR_DENY_ONLY)
                 {
                     base.Add(Claim.CreateDenyOnlyWindowsSidClaim(new SecurityIdentifier(group.Sid)));
                 }
                 pSidAndAttributes = new IntPtr((long)pSidAndAttributes + SID_AND_ATTRIBUTES.SizeOf);
             }
         }
         finally
         {
             safeAllocHandle.Close();
         }
     }
 }
        private static bool TryCreateWindowsSidClaim(System.Security.Principal.WindowsIdentity windowsIdentity, out Claim claim)
        {
            SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;

            try
            {
                uint num;
                invalidHandle = GetTokenInformation(windowsIdentity.Token, System.IdentityModel.TokenInformationClass.TokenUser, out num);
                SID_AND_ATTRIBUTES sid_and_attributes = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(SID_AND_ATTRIBUTES));
                uint num2 = 0x10;
                if (sid_and_attributes.Attributes == 0)
                {
                    claim = Claim.CreateWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid));
                    return(true);
                }
                if ((sid_and_attributes.Attributes & num2) == 0x10)
                {
                    claim = Claim.CreateDenyOnlyWindowsSidClaim(new SecurityIdentifier(sid_and_attributes.Sid));
                    return(true);
                }
            }
            finally
            {
                invalidHandle.Close();
            }
            claim = null;
            return(false);
        }
        private static SafeHGlobalHandle GetTokenInformation(IntPtr tokenHandle, System.IdentityModel.TokenInformationClass tokenInformationClass, out uint dwLength)
        {
            SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;

            dwLength = (uint)Marshal.SizeOf(typeof(uint));
            bool flag  = System.IdentityModel.NativeMethods.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, 0, out dwLength);
            int  error = Marshal.GetLastWin32Error();

            switch (error)
            {
            case (0x18 && 0x7a):
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
            }
            invalidHandle = SafeHGlobalHandle.AllocHGlobal(dwLength);
            flag          = System.IdentityModel.NativeMethods.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, dwLength, out dwLength);
            error         = Marshal.GetLastWin32Error();
            if (flag)
            {
                return(invalidHandle);
            }
            invalidHandle.Close();
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
        }
Esempio n. 6
0
        static SafeHGlobalHandle GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, out uint dwLength)
        {
            SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle;

            dwLength = (uint)Marshal.SizeOf(typeof(uint));
            bool result = NativeMethods.GetTokenInformation(tokenHandle,
                                                            (uint)tokenInformationClass,
                                                            safeAllocHandle,
                                                            0,
                                                            out dwLength);
            int dwErrorCode = Marshal.GetLastWin32Error();

            switch (dwErrorCode)
            {
            case NativeMethods.ERROR_BAD_LENGTH:
            // special case for TokenSessionId. Falling through
            case NativeMethods.ERROR_INSUFFICIENT_BUFFER:
                safeAllocHandle = SafeHGlobalHandle.AllocHGlobal(dwLength);
                result          = NativeMethods.GetTokenInformation(tokenHandle,
                                                                    (uint)tokenInformationClass,
                                                                    safeAllocHandle,
                                                                    dwLength,
                                                                    out dwLength);
                dwErrorCode = Marshal.GetLastWin32Error();
                if (!result)
                {
                    safeAllocHandle.Close();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
            }
            return(safeAllocHandle);
        }
Esempio n. 7
0
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle;

            System.IdentityModel.SafeCertContextHandle pPrevCertContext = System.IdentityModel.SafeCertContextHandle.InvalidHandle;
            X509Certificate2Collection certificates = new X509Certificate2Collection();
            SafeHGlobalHandle          handle3      = SafeHGlobalHandle.InvalidHandle;

            try
            {
                uint   num;
                string str;
                byte[] buffer;
                System.IdentityModel.CAPI.CRYPTOAPI_BLOB cryptoapi_blob;
                switch (findType)
                {
                case X509FindType.FindByThumbprint:
                    buffer = findValue as byte[];
                    if (buffer == null)
                    {
                        str = findValue as string;
                        if (str == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatchMulti", new object[] { findType, typeof(string), typeof(byte[]), findValue.GetType() })));
                        }
                        goto Label_011A;
                    }
                    goto Label_0123;

                case X509FindType.FindBySubjectName:
                    str = findValue as string;
                    if (str == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatch", new object[] { findType, typeof(string), findValue.GetType() })));
                    }
                    break;

                case X509FindType.FindBySubjectDistinguishedName:
                    if (!(findValue is string))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatch", new object[] { findType, typeof(string), findValue.GetType() })));
                    }
                    goto Label_01C4;

                case X509FindType.FindByIssuerName:
                    str = findValue as string;
                    if (str == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatch", new object[] { findType, typeof(string), findValue.GetType() })));
                    }
                    goto Label_021D;

                case X509FindType.FindByIssuerDistinguishedName:
                    if (!(findValue is string))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatch", new object[] { findType, typeof(string), findValue.GetType() })));
                    }
                    goto Label_027E;

                case X509FindType.FindBySerialNumber:
                    buffer = findValue as byte[];
                    if (buffer == null)
                    {
                        str = findValue as string;
                        if (str == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatchMulti", new object[] { findType, typeof(string), typeof(byte[]), findValue.GetType() })));
                        }
                        goto Label_02F4;
                    }
                    goto Label_033C;

                case X509FindType.FindBySubjectKeyIdentifier:
                    buffer = findValue as byte[];
                    if (buffer == null)
                    {
                        str = findValue as string;
                        if (str == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.IdentityModel.SR.GetString("X509FindValueMismatchMulti", new object[] { findType, typeof(string), typeof(byte[]), findValue.GetType() })));
                        }
                        buffer = System.IdentityModel.SecurityUtils.DecodeHexString(str);
                    }
                    findValue = buffer;
                    num       = 0;
                    goto Label_03F4;

                default:
                {
                    X509Store store = new X509Store(this.certStoreHandle.DangerousGetHandle());
                    try
                    {
                        return(store.Certificates.Find(findType, findValue, validOnly));
                    }
                    finally
                    {
                        store.Close();
                    }
                    goto Label_03F4;
                }
                }
                num           = 0x80007;
                invalidHandle = SafeHGlobalHandle.AllocHGlobal(str);
                goto Label_03F4;
Label_011A:
                buffer = System.IdentityModel.SecurityUtils.DecodeHexString(str);
Label_0123:
                cryptoapi_blob        = new System.IdentityModel.CAPI.CRYPTOAPI_BLOB();
                handle3               = SafeHGlobalHandle.AllocHGlobal(buffer);
                cryptoapi_blob.pbData = handle3.DangerousGetHandle();
                cryptoapi_blob.cbData = (uint)buffer.Length;
                num = 0x10000;
                Marshal.StructureToPtr(cryptoapi_blob, SafeHGlobalHandle.AllocHGlobal(System.IdentityModel.CAPI.CRYPTOAPI_BLOB.Size).DangerousGetHandle(), false);
                goto Label_03F4;
Label_01C4:
                num = 0;
                goto Label_03F4;
Label_021D:
                num           = 0x80004;
                invalidHandle = SafeHGlobalHandle.AllocHGlobal(str);
                goto Label_03F4;
Label_027E:
                num = 0;
                goto Label_03F4;
Label_02F4:
                buffer = System.IdentityModel.SecurityUtils.DecodeHexString(str);
                int length = buffer.Length;
                int index  = 0;
                for (int i = length - 1; index < (buffer.Length / 2); i--)
                {
                    byte num5 = buffer[index];
                    buffer[index] = buffer[i];
                    buffer[i]     = num5;
                    index++;
                }
Label_033C:
                findValue = buffer;
                num       = 0;
Label_03F4:
                pPrevCertContext = System.IdentityModel.CAPI.CertFindCertificateInStore(this.certStoreHandle, 0x10001, 0, num, invalidHandle, pPrevCertContext);
                while ((pPrevCertContext != null) && !pPrevCertContext.IsInvalid)
                {
                    X509Certificate2 certificate;
                    if (this.TryGetMatchingX509Certificate(pPrevCertContext.DangerousGetHandle(), findType, num, findValue, validOnly, out certificate))
                    {
                        certificates.Add(certificate);
                    }
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                        continue;
                    }
                    finally
                    {
                        GC.SuppressFinalize(pPrevCertContext);
                        pPrevCertContext = System.IdentityModel.CAPI.CertFindCertificateInStore(this.certStoreHandle, 0x10001, 0, num, invalidHandle, pPrevCertContext);
                    }
                }
            }
            finally
            {
                if (pPrevCertContext != null)
                {
                    pPrevCertContext.Close();
                }
                invalidHandle.Close();
                handle3.Close();
            }
            return(certificates);
        }
Esempio n. 8
0
        internal static WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            int status;
            SafeHGlobalHandle         pSourceName   = null;
            SafeHGlobalHandle         pPackageName  = null;
            SafeHGlobalHandle         pLogonInfo    = null;
            SafeLsaLogonProcessHandle logonHandle   = null;
            SafeLsaReturnBufferHandle profileHandle = null;
            SafeCloseHandle           tokenHandle   = null;

            try
            {
                pSourceName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaSourceName.Length + 1);
                Marshal.Copy(NativeMethods.LsaSourceName, 0, pSourceName.DangerousGetHandle(), NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING sourceName = new UNICODE_INTPTR_STRING(NativeMethods.LsaSourceName.Length, NativeMethods.LsaSourceName.Length + 1, pSourceName.DangerousGetHandle());

                Privilege privilege = null;

                RuntimeHelpers.PrepareConstrainedRegions();
                // Try to get an impersonation token.
                try
                {
                    // Try to enable the TCB privilege if possible
                    try
                    {
                        privilege = new Privilege(Privilege.SeTcbPrivilege);
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
                    }

                    IntPtr dummy = IntPtr.Zero;
                    status = NativeMethods.LsaRegisterLogonProcess(ref sourceName, out logonHandle, out dummy);
                    if (NativeMethods.ERROR_ACCESS_DENIED == NativeMethods.LsaNtStatusToWinError(status))
                    {
                        // We don't have the Tcb privilege. The best we can hope for is to get an Identification token.
                        status = NativeMethods.LsaConnectUntrusted(out logonHandle);
                    }
                    if (status < 0) // non-negative numbers indicate success
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                    }
                }
                finally
                {
                    // if reverting privilege fails, fail fast!
                    int    revertResult = -1;
                    string message      = null;
                    try
                    {
                        revertResult = privilege.Revert();
                        if (revertResult != 0)
                        {
                            message = SR.GetString(SR.RevertingPrivilegeFailed, new Win32Exception(revertResult));
                        }
                    }
                    finally
                    {
                        if (revertResult != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }

                // package name ("Kerberos")
                pPackageName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaKerberosName.Length + 1);
                Marshal.Copy(NativeMethods.LsaKerberosName, 0, pPackageName.DangerousGetHandle(), NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(NativeMethods.LsaKerberosName.Length, NativeMethods.LsaKerberosName.Length + 1, pPackageName.DangerousGetHandle());

                uint packageId = 0;
                status = NativeMethods.LsaLookupAuthenticationPackage(logonHandle, ref packageName, out packageId);
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }

                // source context
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int dwErrorCode = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }

                // SourceContext
                sourceContext.Name    = new char[8];
                sourceContext.Name[0] = 'W'; sourceContext.Name[1] = 'C'; sourceContext.Name[2] = 'F';

                // LogonInfo
                byte[] certRawData   = certificate.RawData;
                int    logonInfoSize = KERB_CERTIFICATE_S4U_LOGON.Size + certRawData.Length;
                pLogonInfo = SafeHGlobalHandle.AllocHGlobal(logonInfoSize);
                unsafe
                {
                    KERB_CERTIFICATE_S4U_LOGON *pInfo = (KERB_CERTIFICATE_S4U_LOGON *)pLogonInfo.DangerousGetHandle().ToPointer();
                    pInfo->MessageType       = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                    pInfo->Flags             = NativeMethods.KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS;
                    pInfo->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->DomainName        = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->CertificateLength = (uint)certRawData.Length;
                    pInfo->Certificate       = new IntPtr(pLogonInfo.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                    Marshal.Copy(certRawData, 0, pInfo->Certificate, certRawData.Length);
                }

                QUOTA_LIMITS quotas  = new QUOTA_LIMITS();
                LUID         logonId = new LUID();
                uint         profileBufferLength;
                int          subStatus = 0;

                // Call LsaLogonUser
                status = NativeMethods.LsaLogonUser(
                    logonHandle,
                    ref sourceName,
                    SecurityLogonType.Network,
                    packageId,
                    pLogonInfo.DangerousGetHandle(),
                    (uint)logonInfoSize,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileHandle,
                    out profileBufferLength,
                    out logonId,
                    out tokenHandle,
                    out quotas,
                    out subStatus
                    );

                // LsaLogon has restriction (eg. password expired).  SubStatus indicates the reason.
                if ((uint)status == NativeMethods.STATUS_ACCOUNT_RESTRICTION && subStatus < 0)
                {
                    status = subStatus;
                }
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }
                if (subStatus < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(subStatus)));
                }

                return(new WindowsIdentity(tokenHandle.DangerousGetHandle(), SecurityUtils.AuthTypeCertMap));
            }
            finally
            {
                if (tokenHandle != null)
                {
                    tokenHandle.Close();
                }
                if (pLogonInfo != null)
                {
                    pLogonInfo.Close();
                }
                if (profileHandle != null)
                {
                    profileHandle.Close();
                }
                if (pSourceName != null)
                {
                    pSourceName.Close();
                }
                if (pPackageName != null)
                {
                    pPackageName.Close();
                }
                if (logonHandle != null)
                {
                    logonHandle.Close();
                }
            }
        }
Esempio n. 9
0
        public static SyncStateUpgradeResult CheckAndUpgradeSyncStates(MailboxSession mailboxSession, DeviceIdentity deviceIdentity)
        {
            if (mailboxSession == null)
            {
                throw new ArgumentNullException("mailboxSession");
            }
            SafeHGlobalHandle   safeHGlobalHandle   = SafeHGlobalHandle.InvalidHandle;
            TiFolderSyncUpgrade tiFolderSyncUpgrade = new TiFolderSyncUpgrade();

            tiFolderSyncUpgrade.MailboxSession = mailboxSession;
            MailboxUtility           mailboxUtility           = new MailboxUtility();
            MailboxUtilityDeviceInfo mailboxUtilityDeviceInfo = null;
            MemoryStream             memoryStream             = null;

            try
            {
                mailboxUtility.MailboxSessionForUtility = mailboxSession;
                mailboxUtilityDeviceInfo = mailboxUtility.GetDevice(deviceIdentity);
                if (mailboxUtilityDeviceInfo == null)
                {
                    AirSyncDiagnostics.TraceDebug <DeviceIdentity>(ExTraceGlobals.TiUpgradeTracer, null, "Failed to retrieve device info for: {0}", deviceIdentity);
                    return(SyncStateUpgradeResult.NoTiSyncState);
                }
                AirSyncDiagnostics.TraceDebug <DeviceIdentity>(ExTraceGlobals.TiUpgradeTracer, null, "Starting sync state upgrade for device: {0}", deviceIdentity);
                safeHGlobalHandle = NativeMethods.AllocHGlobal(Marshal.SizeOf(typeof(FolderInfo)));
                StoreObjectId storeObjectId = null;
                storeObjectId = mailboxUtilityDeviceInfo.StoreObjectId;
                HashSet <string> folderList             = mailboxUtilityDeviceInfo.FolderList;
                FolderInfo       folderInfo             = default(FolderInfo);
                bool             containsFoldersyncFile = false;
                memoryStream = mailboxUtility.GetSyncState(storeObjectId, "FolderSyncFile");
                if (memoryStream != null)
                {
                    using (SafeHGlobalHandle safeHGlobalHandle2 = NativeMethods.AllocHGlobal((int)memoryStream.Length))
                    {
                        Marshal.Copy(memoryStream.GetBuffer(), 0, safeHGlobalHandle2.DangerousGetHandle(), (int)memoryStream.Length);
                        int num = SyncStateUpgrader.Foldersync_upgrade(safeHGlobalHandle2, (uint)memoryStream.Length, safeHGlobalHandle);
                        if (num != 0)
                        {
                            throw new AirSyncPermanentException(false);
                        }
                    }
                    folderInfo             = (FolderInfo)Marshal.PtrToStructure(safeHGlobalHandle.DangerousGetHandle(), typeof(FolderInfo));
                    containsFoldersyncFile = true;
                    MailboxUtility.ReclaimStream(memoryStream);
                    memoryStream = null;
                }
                Dictionary <string, StoreObjectType> dictionary2;
                Dictionary <string, StoreObjectId>   dictionary = SyncStateUpgrader.UpgradeFolderSyncHierarchySyncState(tiFolderSyncUpgrade, containsFoldersyncFile, folderInfo, deviceIdentity, out dictionary2);
                if (dictionary == null)
                {
                    mailboxUtility.DeleteFolder(mailboxUtilityDeviceInfo.StoreObjectId, true);
                }
                else
                {
                    SyncStateUpgradeHelper syncStateUpgradeHelper = new SyncStateUpgradeHelper(mailboxSession, tiFolderSyncUpgrade.SyncStateStorage);
                    foreach (string key in dictionary2.Keys)
                    {
                        StoreObjectType storeObjectType = dictionary2[key];
                        if (storeObjectType != StoreObjectType.Folder && storeObjectType != StoreObjectType.ContactsFolder && storeObjectType != StoreObjectType.CalendarFolder && storeObjectType != StoreObjectType.TasksFolder)
                        {
                            AirSyncDiagnostics.TraceDebug <StoreObjectType>(ExTraceGlobals.TiUpgradeTracer, null, "Removing unknown Ti folder of type {0}", storeObjectType);
                            dictionary.Remove(key);
                        }
                    }
                    if (!syncStateUpgradeHelper.UpgradeSyncState(dictionary, dictionary2, folderList, mailboxUtility, storeObjectId))
                    {
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.TiUpgradeTracer, null, "Failed to upgrade folders for {0}", mailboxUtilityDeviceInfo.DisplayName);
                        mailboxUtility.DeleteFolder(mailboxUtilityDeviceInfo.StoreObjectId, true);
                        return(SyncStateUpgradeResult.UpgradeFailed);
                    }
                    tiFolderSyncUpgrade.UpdateLastFolderId(syncStateUpgradeHelper.MaxFolderSeen);
                }
                AirSyncDiagnostics.FaultInjectionTracer.TraceTest(3236310333U);
            }
            catch (Exception arg)
            {
                if (mailboxUtilityDeviceInfo != null)
                {
                    mailboxUtility.DeleteSyncStateStorage(new DeviceIdentity(mailboxUtilityDeviceInfo.DisplayName, mailboxUtilityDeviceInfo.ParentDisplayName, "AirSync"));
                }
                AirSyncDiagnostics.TraceDebug <DeviceIdentity, Exception>(ExTraceGlobals.TiUpgradeTracer, null, "Sync state upgrade failed for device: {0}\r\nException:\r\n{1}", deviceIdentity, arg);
                throw;
            }
            finally
            {
                if (memoryStream != null)
                {
                    MailboxUtility.ReclaimStream(memoryStream);
                    memoryStream = null;
                }
                if (mailboxUtilityDeviceInfo != null)
                {
                    mailboxUtility.DeleteFolder(mailboxUtilityDeviceInfo.StoreObjectId, true);
                }
                if (tiFolderSyncUpgrade != null)
                {
                    tiFolderSyncUpgrade.Close();
                    tiFolderSyncUpgrade = null;
                }
                safeHGlobalHandle.Close();
            }
            AirSyncDiagnostics.TraceDebug <DeviceIdentity>(ExTraceGlobals.TiUpgradeTracer, null, "Finished sync state upgrade for device: {0}", deviceIdentity);
            return(SyncStateUpgradeResult.UpgradeComplete);
        }
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            DiagnosticUtility.DebugAssert(!this.certStoreHandle.IsInvalid, "");

            uint dwFindType;
            SafeHGlobalHandle          pvFindPara   = SafeHGlobalHandle.InvalidHandle;
            SafeCertContextHandle      pCertContext = SafeCertContextHandle.InvalidHandle;
            X509Certificate2Collection result       = new X509Certificate2Collection();
            SafeHGlobalHandle          pvTemp       = SafeHGlobalHandle.InvalidHandle;
            string strFindValue;

            byte[] bytes;

            try
            {
                switch (findType)
                {
                case X509FindType.FindBySubjectName:
                    strFindValue = findValue as string;
                    if (strFindValue == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatch, findType, typeof(string), findValue.GetType())));
                    }

                    dwFindType = CAPI.CERT_FIND_SUBJECT_STR;
                    pvFindPara = SafeHGlobalHandle.AllocHGlobal(strFindValue);
                    break;

                case X509FindType.FindByThumbprint:
                    bytes = findValue as byte[];
                    if (bytes == null)
                    {
                        strFindValue = findValue as string;
                        if (strFindValue == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatchMulti, findType, typeof(string), typeof(byte[]), findValue.GetType())));
                        }

                        bytes = SecurityUtils.DecodeHexString(strFindValue);
                    }

                    CAPI.CRYPTOAPI_BLOB blob = new CAPI.CRYPTOAPI_BLOB();
                    pvTemp      = SafeHGlobalHandle.AllocHGlobal(bytes);
                    blob.pbData = pvTemp.DangerousGetHandle();
                    blob.cbData = (uint)bytes.Length;
                    dwFindType  = CAPI.CERT_FIND_HASH;
                    pvFindPara  = SafeHGlobalHandle.AllocHGlobal(CAPI.CRYPTOAPI_BLOB.Size);
                    Marshal.StructureToPtr(blob, pvFindPara.DangerousGetHandle(), false);
                    break;

                case X509FindType.FindBySubjectDistinguishedName:
                    if (!(findValue is string))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatch, findType, typeof(string), findValue.GetType())));
                    }

                    dwFindType = CAPI.CERT_FIND_ANY;
                    break;

                case X509FindType.FindByIssuerName:
                    strFindValue = findValue as string;
                    if (strFindValue == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatch, findType, typeof(string), findValue.GetType())));
                    }

                    dwFindType = CAPI.CERT_FIND_ISSUER_STR;
                    pvFindPara = SafeHGlobalHandle.AllocHGlobal(strFindValue);
                    break;

                case X509FindType.FindByIssuerDistinguishedName:
                    if (!(findValue is string))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatch, findType, typeof(string), findValue.GetType())));
                    }

                    dwFindType = CAPI.CERT_FIND_ANY;
                    break;

                case X509FindType.FindBySerialNumber:
                    bytes = findValue as byte[];
                    if (bytes == null)
                    {
                        strFindValue = findValue as string;
                        if (strFindValue == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatchMulti, findType, typeof(string), typeof(byte[]), findValue.GetType())));
                        }

                        bytes = SecurityUtils.DecodeHexString(strFindValue);

                        // reverse bits
                        int len = bytes.Length;
                        for (int i = 0, j = len - 1; i < bytes.Length / 2; ++i, --j)
                        {
                            byte tmp = bytes[i];
                            bytes[i] = bytes[j];
                            bytes[j] = tmp;
                        }
                    }
                    findValue  = bytes;
                    dwFindType = CAPI.CERT_FIND_ANY;
                    break;

                case X509FindType.FindBySubjectKeyIdentifier:
                    bytes = findValue as byte[];
                    if (bytes == null)
                    {
                        strFindValue = findValue as string;
                        if (strFindValue == null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.X509FindValueMismatchMulti, findType, typeof(string), typeof(byte[]), findValue.GetType())));
                        }

                        bytes = SecurityUtils.DecodeHexString(strFindValue);
                    }
                    findValue  = bytes;
                    dwFindType = CAPI.CERT_FIND_ANY;
                    break;

                default:
                    // Fallback to CLR implementation
                    X509Store store = new X509Store(this.certStoreHandle.DangerousGetHandle());
                    try
                    {
                        return(store.Certificates.Find(findType, findValue, validOnly));
                    }
                    finally
                    {
                        store.Close();
                    }
                }

#pragma warning suppress 56523 // We are not interested in CRYPT_E_NOT_FOUND error, it return null anyway.
                pCertContext = CAPI.CertFindCertificateInStore(this.certStoreHandle,
                                                               CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                               0,
                                                               dwFindType,
                                                               pvFindPara,
                                                               pCertContext);

                while (pCertContext != null && !pCertContext.IsInvalid)
                {
                    X509Certificate2 cert;
                    if (TryGetMatchingX509Certificate(pCertContext.DangerousGetHandle(), findType,
                                                      dwFindType, findValue, validOnly, out cert))
                    {
                        result.Add(cert);
                    }

                    // CER
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try { }
                    finally
                    {
                        // Suppress the finalizer
#pragma warning suppress 56508 // CertFindCertificateInStore will release the prev one.
                        GC.SuppressFinalize(pCertContext);
#pragma warning suppress 56523 // We are not interested in CRYPT_E_NOT_FOUND error, it return null anyway.
                        pCertContext = CAPI.CertFindCertificateInStore(this.certStoreHandle,
                                                                       CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                                       0,
                                                                       dwFindType,
                                                                       pvFindPara,
                                                                       pCertContext);
                    }
                }
            }
            finally
            {
                if (pCertContext != null)
                {
                    pCertContext.Close();
                }
                pvFindPara.Close();
                pvTemp.Close();
            }
            return(result);
        }
        private static unsafe WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            SafeHGlobalHandle         handle        = null;
            SafeHGlobalHandle         handle2       = null;
            SafeHGlobalHandle         handle3       = null;
            SafeLsaLogonProcessHandle lsaHandle     = null;
            SafeLsaReturnBufferHandle profileBuffer = null;
            SafeCloseHandle           token         = null;
            WindowsIdentity           identity;

            try
            {
                int  num;
                uint num6;
                handle = SafeHGlobalHandle.AllocHGlobal((int)(System.IdentityModel.NativeMethods.LsaSourceName.Length + 1));
                Marshal.Copy(System.IdentityModel.NativeMethods.LsaSourceName, 0, handle.DangerousGetHandle(), System.IdentityModel.NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING          logonProcessName = new UNICODE_INTPTR_STRING(System.IdentityModel.NativeMethods.LsaSourceName.Length, System.IdentityModel.NativeMethods.LsaSourceName.Length + 1, handle.DangerousGetHandle());
                System.IdentityModel.Privilege privilege        = null;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    try
                    {
                        privilege = new System.IdentityModel.Privilege("SeTcbPrivilege");
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException exception)
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                        }
                    }
                    IntPtr zero = IntPtr.Zero;
                    num = System.IdentityModel.NativeMethods.LsaRegisterLogonProcess(ref logonProcessName, out lsaHandle, out zero);
                    if (5 == System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num))
                    {
                        num = System.IdentityModel.NativeMethods.LsaConnectUntrusted(out lsaHandle);
                    }
                    if (num < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                    }
                }
                finally
                {
                    int    error   = -1;
                    string message = null;
                    try
                    {
                        error = privilege.Revert();
                        if (error != 0)
                        {
                            message = System.IdentityModel.SR.GetString("RevertingPrivilegeFailed", new object[] { new Win32Exception(error) });
                        }
                    }
                    finally
                    {
                        if (error != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }
                handle2 = SafeHGlobalHandle.AllocHGlobal((int)(System.IdentityModel.NativeMethods.LsaKerberosName.Length + 1));
                Marshal.Copy(System.IdentityModel.NativeMethods.LsaKerberosName, 0, handle2.DangerousGetHandle(), System.IdentityModel.NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(System.IdentityModel.NativeMethods.LsaKerberosName.Length, System.IdentityModel.NativeMethods.LsaKerberosName.Length + 1, handle2.DangerousGetHandle());
                uint authenticationPackage        = 0;
                num = System.IdentityModel.NativeMethods.LsaLookupAuthenticationPackage(lsaHandle, ref packageName, out authenticationPackage);
                if (num < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                }
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!System.IdentityModel.NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int num4 = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num4));
                }
                sourceContext.Name    = new char[8];
                sourceContext.Name[0] = 'W';
                sourceContext.Name[1] = 'C';
                sourceContext.Name[2] = 'F';
                byte[] rawData = certificate.RawData;
                int    cb      = KERB_CERTIFICATE_S4U_LOGON.Size + rawData.Length;
                handle3 = SafeHGlobalHandle.AllocHGlobal(cb);
                KERB_CERTIFICATE_S4U_LOGON *kerb_certificate_su_logonPtr = (KERB_CERTIFICATE_S4U_LOGON *)handle3.DangerousGetHandle().ToPointer();
                kerb_certificate_su_logonPtr->MessageType       = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                kerb_certificate_su_logonPtr->Flags             = 2;
                kerb_certificate_su_logonPtr->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                kerb_certificate_su_logonPtr->DomainName        = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                kerb_certificate_su_logonPtr->CertificateLength = (uint)rawData.Length;
                kerb_certificate_su_logonPtr->Certificate       = new IntPtr(handle3.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                Marshal.Copy(rawData, 0, kerb_certificate_su_logonPtr->Certificate, rawData.Length);
                QUOTA_LIMITS quotas    = new QUOTA_LIMITS();
                LUID         logonId   = new LUID();
                int          subStatus = 0;
                num = System.IdentityModel.NativeMethods.LsaLogonUser(lsaHandle, ref logonProcessName, System.IdentityModel.SecurityLogonType.Network, authenticationPackage, handle3.DangerousGetHandle(), (uint)cb, IntPtr.Zero, ref sourceContext, out profileBuffer, out num6, out logonId, out token, out quotas, out subStatus);
                if ((num == -1073741714) && (subStatus < 0))
                {
                    num = subStatus;
                }
                if (num < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                }
                if (subStatus < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(subStatus)));
                }
                identity = new WindowsIdentity(token.DangerousGetHandle(), "SSL/PCT");
            }
            finally
            {
                if (token != null)
                {
                    token.Close();
                }
                if (handle3 != null)
                {
                    handle3.Close();
                }
                if (profileBuffer != null)
                {
                    profileBuffer.Close();
                }
                if (handle != null)
                {
                    handle.Close();
                }
                if (handle2 != null)
                {
                    handle2.Close();
                }
                if (lsaHandle != null)
                {
                    lsaHandle.Close();
                }
            }
            return(identity);
        }
        private static void WriteAuditEvent(uint auditType, uint auditId, params string[] parameters)
        {
            if (!IsSecurityAuditSupported)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PlatformNotSupportedException(System.ServiceModel.SR.GetString("SecurityAuditPlatformNotSupported")));
            }
            Privilege privilege = new Privilege("SeAuditPrivilege");

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                try
                {
                    SafeSecurityAuditHandle handle;
                    privilege.Enable();
                    if (!NativeMethods.AuthzRegisterSecurityEventSource(0, "ServiceModel 4.0.0.0", out handle))
                    {
                        int error = Marshal.GetLastWin32Error();
                        Utility.CloseInvalidOutSafeHandle(handle);
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
                    }
                    SafeHGlobalHandle   handle2     = null;
                    SafeHGlobalHandle[] handleArray = new SafeHGlobalHandle[parameters.Length];
                    try
                    {
                        NativeMethods.AUDIT_PARAM  audit_param;
                        NativeMethods.AUDIT_PARAMS audit_params;
                        handle2 = SafeHGlobalHandle.AllocHGlobal((int)(parameters.Length * NativeMethods.AUDIT_PARAM.Size));
                        long num2 = handle2.DangerousGetHandle().ToInt64();
                        audit_param.Type   = NativeMethods.AUDIT_PARAM_TYPE.APT_String;
                        audit_param.Length = 0;
                        audit_param.Flags  = 0;
                        audit_param.Data1  = IntPtr.Zero;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(parameters[i]))
                            {
                                string s = System.ServiceModel.Diagnostics.EventLogger.NormalizeEventLogParameter(parameters[i]);
                                handleArray[i]    = SafeHGlobalHandle.AllocHGlobal(s);
                                audit_param.Data0 = handleArray[i].DangerousGetHandle();
                            }
                            else
                            {
                                audit_param.Data0 = IntPtr.Zero;
                            }
                            Marshal.StructureToPtr(audit_param, new IntPtr(num2 + (i * NativeMethods.AUDIT_PARAM.Size)), false);
                        }
                        audit_params.Length     = 0;
                        audit_params.Flags      = auditType;
                        audit_params.Parameters = handle2;
                        audit_params.Count      = (ushort)parameters.Length;
                        if (!NativeMethods.AuthzReportSecurityEventFromParams(auditType, handle, auditId, null, ref audit_params))
                        {
                            int num4 = Marshal.GetLastWin32Error();
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num4));
                        }
                    }
                    finally
                    {
                        for (int j = 0; j < handleArray.Length; j++)
                        {
                            if (handleArray[j] != null)
                            {
                                handleArray[j].Close();
                            }
                        }
                        if (handle2 != null)
                        {
                            handle2.Close();
                        }
                        handle.Close();
                    }
                }
                finally
                {
                    int    num6    = -1;
                    string message = null;
                    try
                    {
                        num6 = privilege.Revert();
                        if (num6 != 0)
                        {
                            message = System.ServiceModel.SR.GetString("RevertingPrivilegeFailed", new object[] { new Win32Exception(num6) });
                        }
                    }
                    finally
                    {
                        if (num6 != 0)
                        {
                            System.ServiceModel.DiagnosticUtility.FailFast(message);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }