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(); } } }
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(); } } }
static SafeHGlobalHandle CopyOidsToUnmanagedMemory(OidCollection oids) { SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle; if (oids == null || oids.Count == 0) { return(safeAllocHandle); } // Copy the oid strings to a local list to prevent a security race condition where // the OidCollection or individual oids can be modified by another thread and // potentially cause a buffer overflow List <string> oidStrs = new List <string>(); foreach (Oid oid in oids) { oidStrs.Add(oid.Value); } IntPtr pOid = IntPtr.Zero; IntPtr pNullTerminator = IntPtr.Zero; // Needs to be checked to avoid having large sets of oids overflow the sizes and allow // a potential buffer overflow checked { int ptrSize = oidStrs.Count * Marshal.SizeOf(typeof(IntPtr)); int oidSize = 0; foreach (string oidStr in oidStrs) { oidSize += (oidStr.Length + 1); } safeAllocHandle = SafeHGlobalHandle.AllocHGlobal(ptrSize + oidSize); pOid = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + ptrSize); } for (int index = 0; index < oidStrs.Count; index++) { Marshal.WriteIntPtr(new IntPtr((long)safeAllocHandle.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))), pOid); byte[] ansiOid = Encoding.ASCII.GetBytes(oidStrs[index]); if (ansiOid.Length != oidStrs[index].Length) { // We assumed single byte characters, fail if this is not the case. The exception is not ideal. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CollectionWasModified))); } Marshal.Copy(ansiOid, 0, pOid, ansiOid.Length); pNullTerminator = new IntPtr((long)pOid + ansiOid.Length); Marshal.WriteByte(pNullTerminator, 0); pOid = new IntPtr((long)pOid + oidStrs[index].Length + 1); } return(safeAllocHandle); }
public string GetPathName() { if (Handle.IsClosed || Handle.IsInvalid) { return(string.Empty); } var pointerToPathName = new IntPtr(IntPtr.Size == 4 ? Handle.DangerousGetHandle().ToInt32() + 4 : Handle.DangerousGetHandle().ToInt64() + 4); // Skip structure size field (4 bytes) return(Marshal.PtrToStringAuto(pointerToPathName)); }
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); }
// Token: 0x0600178C RID: 6028 RVA: 0x0008BC0C File Offset: 0x00089E0C private static bool MakeCppCall(SafeHGlobalHandle pciInfo, byte[] bytes, int length, Dictionary <string, StoreObjectType> contentTypeTable, string serverId) { int num = 0; using (SafeHGlobalHandle safeHGlobalHandle = NativeMethods.AllocHGlobal(length)) { Marshal.Copy(bytes, 0, safeHGlobalHandle.DangerousGetHandle(), length); switch (contentTypeTable[serverId]) { case StoreObjectType.Folder: num = SyncStateUpgradeHelper.Email_upgrade(safeHGlobalHandle, (uint)length, pciInfo); break; case StoreObjectType.CalendarFolder: num = SyncStateUpgradeHelper.Cal_upgrade(safeHGlobalHandle, (uint)length, pciInfo); break; case StoreObjectType.ContactsFolder: num = SyncStateUpgradeHelper.Con_upgrade(safeHGlobalHandle, (uint)length, pciInfo); break; case StoreObjectType.TasksFolder: num = SyncStateUpgradeHelper.Task_upgrade(safeHGlobalHandle, (uint)length, pciInfo); break; default: return(false); } } return(num == 0); }
public unsafe SafeHGlobalHandle ReadImage() { SafeHGlobalHandle result = new SafeHGlobalHandle(GetImageSize()); byte * ptr = (byte *)result.DangerousGetHandle().ToPointer(); using (DisposableAction insurance = new DisposableAction(result.Dispose)) { for (int y = 0; y < _header.BlockCount; y++) { byte *blockPtr = ptr + y * _header.BlockSize * 2; for (int x = 0, i = 0; x < _header.BlockSize; x++) { byte b = (byte)_input.ReadByte(); *(blockPtr + i) = (byte)(b & 0x33); *(blockPtr + i + 8) = (byte)((b >> 2) & 0x33); if (++i % 8 == 0) { i += 8; } } } insurance.Cancel(); } return(result); }
public static SafeHGlobalHandle AllocHGlobal(byte[] bytes) { SafeHGlobalHandle handle = AllocHGlobal(bytes.Length); Marshal.Copy(bytes, 0, handle.DangerousGetHandle(), bytes.Length); return(handle); }
public void StructMarshalTest() { bool allGood = true; using (var mem = new SafeHGlobalHandle(4096)) { //foreach (var asm in Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(n => n.Name.StartsWith("Vanara")).Select(n => Assembly.Load(n))) //{ var asm = typeof(Vanara.PInvoke.AdvApi32).Assembly; foreach (var tstr in asm.GetTypes().Where(t => t.IsValueType && !t.IsPrimitive && !t.IsEnum && !t.IsGenericType)) { if (tstr.Name.StartsWith("<>")) { continue; } try { Marshal.PtrToStructure(mem.DangerousGetHandle(), tstr); } catch (Exception e) { TestContext.WriteLine(e); allGood = false; } } //} } Assert.That(allGood); }
public string GetInstanceIdString() { if (Handle.IsClosed || Handle.IsInvalid) { return(string.Empty); } return(Marshal.PtrToStringAuto(Handle.DangerousGetHandle())); }
/// <summary> /// Reads the Unicode string from the memory block. /// </summary> /// <param name="length"> The length of the string to read, in characters. </param> /// <returns> The string read from the memory block. </returns> public string ReadString(int length) { if (0 >= length || _memoryBlock.IsInvalid) { return(null); } if (length > _memoryBlock.Size) { length = _memoryBlock.Size; } return(Marshal.PtrToStringUni(_memoryBlock.DangerousGetHandle(), length)); }
private static SafeHGlobalHandle CopyOidsToUnmanagedMemory(OidCollection oids) { SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle; if ((oids != null) && (oids.Count != 0)) { List <string> list = new List <string>(); OidEnumerator enumerator = oids.GetEnumerator(); while (enumerator.MoveNext()) { Oid current = enumerator.Current; list.Add(current.Value); } IntPtr zero = IntPtr.Zero; IntPtr ptr = IntPtr.Zero; int num = list.Count * Marshal.SizeOf(typeof(IntPtr)); int num2 = 0; foreach (string str in list) { num2 += str.Length + 1; } invalidHandle = SafeHGlobalHandle.AllocHGlobal((int)(num + num2)); zero = new IntPtr(((long)invalidHandle.DangerousGetHandle()) + num); for (int i = 0; i < list.Count; i++) { Marshal.WriteIntPtr(new IntPtr(((long)invalidHandle.DangerousGetHandle()) + (i * Marshal.SizeOf(typeof(IntPtr)))), zero); byte[] bytes = Encoding.ASCII.GetBytes(list[i]); if (bytes.Length != list[i].Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.IdentityModel.SR.GetString("ObjectIsReadOnly"))); } Marshal.Copy(bytes, 0, zero, bytes.Length); ptr = new IntPtr(((long)zero) + bytes.Length); Marshal.WriteByte(ptr, 0); zero = new IntPtr((((long)zero) + list[i].Length) + 1L); } } return(invalidHandle); }
public SafeHGlobalHandle GetUnmanagedPixelsArray(PixelFormatDescriptor format) { SafeHGlobalHandle result = new SafeHGlobalHandle(Width * Height * format.BytesPerPixel); using (GLService.AcquireContext()) using (DisposableAction insurance = new DisposableAction(result.Dispose)) { GL.BindTexture(TextureTarget.Texture2D, Id); GL.GetTexImage(TextureTarget.Texture2D, 0, format, format, result.DangerousGetHandle()); insurance.Cancel(); } return(result); }
public unsafe void AsUnmanagedArrayPointerTest() { var h = new SafeHGlobalHandle(Marshal.SizeOf(typeof(RECT)) * 2 + i); var rs = new[] { new RECT(), new RECT(10, 11, 12, 13) }; ((IntPtr)h).Write(rs, i, h.Size); RECT *r = h.DangerousGetHandle().AsUnmanagedArrayPointer <RECT>(Marshal.SizeOf <RECT>(), i); Assert.That(r->left, Is.EqualTo(10)); Assert.That(r->top, Is.EqualTo(11)); Assert.That(r->right, Is.EqualTo(12)); Assert.That(r->bottom, Is.EqualTo(13)); }
private static unsafe void BuildChain(IntPtr hChainEngine, IntPtr pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, out System.IdentityModel.SafeCertChainHandle ppChainContext) { System.IdentityModel.SafeCertStoreHandle hAdditionalStore = ExportToMemoryStore(extraStore, pCertContext); System.IdentityModel.CAPI.CERT_CHAIN_PARA pChainPara = new System.IdentityModel.CAPI.CERT_CHAIN_PARA { cbSize = (uint)Marshal.SizeOf(typeof(System.IdentityModel.CAPI.CERT_CHAIN_PARA)) }; SafeHGlobalHandle invalidHandle = SafeHGlobalHandle.InvalidHandle; SafeHGlobalHandle handle3 = SafeHGlobalHandle.InvalidHandle; try { if ((applicationPolicy != null) && (applicationPolicy.Count > 0)) { pChainPara.RequestedUsage.dwType = 0; pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count; invalidHandle = CopyOidsToUnmanagedMemory(applicationPolicy); pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = invalidHandle.DangerousGetHandle(); } if ((certificatePolicy != null) && (certificatePolicy.Count > 0)) { pChainPara.RequestedIssuancePolicy.dwType = 0; pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count; handle3 = CopyOidsToUnmanagedMemory(certificatePolicy); pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle(); } pChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds; System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME(); *((long *)&pTime) = verificationTime.ToFileTime(); uint dwFlags = MapRevocationFlags(revocationMode, revocationFlag); if (!System.IdentityModel.CAPI.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext)) { int hr = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(hr)); } } finally { if (invalidHandle != null) { invalidHandle.Dispose(); } if (handle3 != null) { handle3.Dispose(); } hAdditionalStore.Close(); } }
// Token: 0x06001786 RID: 6022 RVA: 0x0008BA3C File Offset: 0x00089C3C public bool UpgradeSyncState(Dictionary <string, StoreObjectId> mapping, Dictionary <string, StoreObjectType> contentTypeTable, HashSet <string> folderList, MailboxUtility box, StoreObjectId parentStoreObjectId) { using (SafeHGlobalHandle safeHGlobalHandle = NativeMethods.AllocHGlobal(Marshal.SizeOf(typeof(CommonInfo)))) { foreach (string text in mapping.Keys) { StoreObjectId storeId = mapping[text]; if (folderList.Contains(text)) { MemoryStream memoryStream = null; try { memoryStream = box.GetSyncState(parentStoreObjectId, text); if (memoryStream == null) { continue; } if (!SyncStateUpgradeHelper.MakeCppCall(safeHGlobalHandle, memoryStream.GetBuffer(), (int)memoryStream.Length, contentTypeTable, text)) { return(false); } } finally { if (memoryStream != null) { MailboxUtility.ReclaimStream(memoryStream); } } CommonInfo commonInfo = (CommonInfo)Marshal.PtrToStructure(safeHGlobalHandle.DangerousGetHandle(), typeof(CommonInfo)); if (!this.CopyAndUpgradeCommon(commonInfo, storeId, text, contentTypeTable[text], safeHGlobalHandle)) { return(false); } } } this.maxFolderSeen++; foreach (TiSyncUpgrade tiSyncUpgrade in this.needsParentId) { string shortParentId = string.Empty + this.maxFolderSeen; tiSyncUpgrade.UpdateMappingWithParent(shortParentId); this.maxFolderSeen++; } } return(true); }
internal static byte[] PersistIPersistStreamToByteArray(IPersistStream persistableObject) { byte[] buffer; IStream pStm = SafeNativeMethods.CreateStreamOnHGlobal(SafeHGlobalHandle.InvalidHandle, false); try { persistableObject.Save(pStm, true); SafeHGlobalHandle hGlobalFromStream = SafeNativeMethods.GetHGlobalFromStream(pStm); if ((hGlobalFromStream == null) || (IntPtr.Zero == hGlobalFromStream.DangerousGetHandle())) { throw Fx.AssertAndThrow("HGlobal returned from GetHGlobalFromStream is NULL"); } buffer = ConvertHGlobalToByteArray(hGlobalFromStream); } finally { Marshal.ReleaseComObject(pStm); } return(buffer); }
public void WriteObjectTest() { using var mem = new SafeHGlobalHandle(4096); var h = mem.DangerousGetHandle(); // null Assert.That(h.Write((object)null), Is.EqualTo(0)); // bytes Assert.That(h.Write((object)new byte[] { 1, 2, 4, 5 }), Is.EqualTo(4)); // marshaled //Assert.That(h.Write(), ResultIs.Successful); // string Assert.That(h.Write((object)"abcde"), Is.EqualTo(12)); // blitted Assert.That(h.Write((object)1234L), Is.EqualTo(8)); Assert.That(h.Write((object)Guid.NewGuid()), Is.EqualTo(16)); Assert.That(h.Write((object)OSPlatform.Windows), Is.EqualTo(4)); // string enum Assert.That(h.Write((object)new[] { "abcde", "abcde" }), Is.EqualTo(26)); // array Assert.That(h.Write((object)new[] { 1234, 1234 }), Is.EqualTo(8)); // ienum Assert.That(h.Write((object)new List <int>() { 1234, 1234 }), Is.EqualTo(8)); // iserial Assert.That(h.Write((object)DateTime.Now), Is.EqualTo(78)); }
private static IEnumerable <AdvApi32.LUID_AND_ATTRIBUTES> ExtractPrivileges(SafeHGlobalHandle hMem) { lock (hMem) return(AdvApi32.PTOKEN_PRIVILEGES.FromPtr(hMem.DangerousGetHandle()).Privileges); }
private void LogInstalledCategoryNames(string iniFileName, string action_prefix) { int num = 40000; SafeHGlobalHandle safeHGlobalHandle2; SafeHGlobalHandle safeHGlobalHandle = safeHGlobalHandle2 = new SafeHGlobalHandle(Marshal.AllocHGlobal(num * 2)); try { int privateProfileStringSpecial = LoadUnloadPerfCounterLocalizedText.GetPrivateProfileStringSpecial("objects", null, null, safeHGlobalHandle, num, iniFileName); if (privateProfileStringSpecial > 0 && privateProfileStringSpecial < num - 2) { int num2 = 160000; SafeHGlobalHandle safeHGlobalHandle4; SafeHGlobalHandle safeHGlobalHandle3 = safeHGlobalHandle4 = new SafeHGlobalHandle(Marshal.AllocHGlobal(num2 * 2)); try { int privateProfileStringSpecial2 = LoadUnloadPerfCounterLocalizedText.GetPrivateProfileStringSpecial("text", null, null, safeHGlobalHandle3, num2, iniFileName); if (privateProfileStringSpecial2 > 0 && privateProfileStringSpecial2 < num2 - 2) { StringBuilder stringBuilder = new StringBuilder(10000); string path = Path.Combine(ConfigurationContext.Setup.LoggingPath, "lodctr_backups\\InstalledPerfCategories.log"); IntPtr ptr = safeHGlobalHandle.DangerousGetHandle(); for (;;) { string text = Marshal.PtrToStringUni(ptr); if (string.IsNullOrEmpty(text)) { break; } int num3 = text.LastIndexOf('_'); if (num3 > 0) { int num4 = text.LastIndexOf('_', num3 - 1, num3); if (num4 > 0) { string strA = text.Substring(0, num4); IntPtr ptr2 = safeHGlobalHandle3.DangerousGetHandle(); for (;;) { string text2 = Marshal.PtrToStringUni(ptr2); if (string.IsNullOrEmpty(text2)) { break; } int num5 = text2.LastIndexOf('_'); if (num5 > 0) { int num6 = text2.LastIndexOf('_', num5 - 1, num5); if (num6 > 0) { string strB = text2.Substring(0, num6); if (string.Compare(strA, strB) == 0 && !text2.EndsWith("_HELP") && LoadUnloadPerfCounterLocalizedText.GetPrivateProfileString("text", text2, null, stringBuilder, stringBuilder.Capacity, iniFileName) != 0) { File.AppendAllText(path, string.Format("{0}-{1}-{2}={3}\r\n", new object[] { action_prefix, Path.GetFileName(iniFileName), text2, stringBuilder }), new UnicodeEncoding()); } } } ptr2 = (IntPtr)(ptr2.ToInt64() + (long)((text2.Length + 1) * 2)); } } } ptr = (IntPtr)(ptr.ToInt64() + (long)((text.Length + 1) * 2)); } } } finally { if (safeHGlobalHandle4 != null) { ((IDisposable)safeHGlobalHandle4).Dispose(); } } } } finally { if (safeHGlobalHandle2 != null) { ((IDisposable)safeHGlobalHandle2).Dispose(); } } }
public ProtectedSecret ProtectSecret(string secret, CommonSecurityDescriptor securityDescriptor) { this.licenseManager.ThrowOnMissingFeature(LicensedFeatures.DpapiNgSecretEncryption); var result = NCrypt.NCryptCreateProtectionDescriptor($"SDDL={securityDescriptor.GetSddlForm(AccessControlSections.All)}", 0, out NCrypt.SafeNCRYPT_DESCRIPTOR_HANDLE handle); result.ThrowIfFailed(); using (handle) { using SafeHGlobalHandle f = new SafeHGlobalHandle(Encoding.Unicode.GetBytes(secret)); result = NCrypt.NCryptProtectSecret(handle, NCrypt.ProtectFlags.NCRYPT_SILENT_FLAG, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr protectedData, out uint protectedDataSize); result.ThrowIfFailed(); using SafeHGlobalHandle d = new SafeHGlobalHandle(protectedData, protectedDataSize, true); return(new ProtectedSecret { Data = Convert.ToBase64String(d.GetBytes(0, (int)protectedDataSize)), Mode = 3 }); } }
public string GetSecurityDescriptorFromSecret(ProtectedSecret data) { if (data.Mode != 3) { throw new ArgumentException("The protected data was of the incorrect format"); } byte[] rawProtectedData = Convert.FromBase64String(data.Data); using SafeHGlobalHandle f = new SafeHGlobalHandle(rawProtectedData); var result = NCrypt.NCryptUnprotectSecret(out NCrypt.SafeNCRYPT_DESCRIPTOR_HANDLE dh, NCrypt.UnprotectSecretFlags.NCRYPT_SILENT_FLAG | NCrypt.UnprotectSecretFlags.NCRYPT_UNPROTECT_NO_DECRYPT, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr unprotectedData, out uint unprotectedDataSize); result.ThrowIfFailed(); IntPtr ruleStringHandle = IntPtr.Zero; try { result = NCrypt.NCryptGetProtectionDescriptorInfo( dh, IntPtr.Zero, NCrypt.ProtectionDescriptorInfoType.NCRYPT_PROTECTION_INFO_TYPE_DESCRIPTOR_STRING, out ruleStringHandle); result.ThrowIfFailed(); return(Marshal.PtrToStringUni(ruleStringHandle)); } finally { if (ruleStringHandle != IntPtr.Zero) { Marshal.FreeHGlobal(ruleStringHandle); } } }
private string UnprotectSecretv3(ProtectedSecret data) { byte[] rawProtectedData = Convert.FromBase64String(data.Data); using SafeHGlobalHandle f = new SafeHGlobalHandle(rawProtectedData); var result = NCrypt.NCryptUnprotectSecret(out _, NCrypt.UnprotectSecretFlags.NCRYPT_SILENT_FLAG, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr unprotectedData, out uint unprotectedDataSize); result.ThrowIfFailed(); using SafeHGlobalHandle d = new SafeHGlobalHandle(unprotectedData, unprotectedDataSize, true); return(Encoding.Unicode.GetString(d.GetBytes(0, (int)unprotectedDataSize))); }
static unsafe void BuildChain(IntPtr hChainEngine, IntPtr pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, out SafeCertChainHandle ppChainContext) { SafeCertStoreHandle hCertStore = ExportToMemoryStore(extraStore, pCertContext); CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA(); ChainPara.cbSize = (uint)Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_PARA)); // Application policy SafeHGlobalHandle applicationPolicyHandle = SafeHGlobalHandle.InvalidHandle; SafeHGlobalHandle certificatePolicyHandle = SafeHGlobalHandle.InvalidHandle; try { if (applicationPolicy != null && applicationPolicy.Count > 0) { ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count; applicationPolicyHandle = CopyOidsToUnmanagedMemory(applicationPolicy); ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle(); } // Certificate policy if (certificatePolicy != null && certificatePolicy.Count > 0) { ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count; certificatePolicyHandle = CopyOidsToUnmanagedMemory(certificatePolicy); ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle(); } ChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds; FILETIME ft = new FILETIME(); *((long *)&ft) = verificationTime.ToFileTime(); uint flags = MapRevocationFlags(revocationMode, revocationFlag); // Build the chain. if (!CAPI.CertGetCertificateChain(hChainEngine, pCertContext, ref ft, hCertStore, ref ChainPara, flags, IntPtr.Zero, out ppChainContext)) { int error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(error)); } } finally { if (applicationPolicyHandle != null) { applicationPolicyHandle.Dispose(); } if (certificatePolicyHandle != null) { certificatePolicyHandle.Dispose(); } hCertStore.Close(); } }
public DeviceInterfaceDetailData(int size) { Handle = new SafeHGlobalHandle(size); Marshal.WriteInt32(Handle.DangerousGetHandle(), IntPtr.Size != 8 ? 4 + Marshal.SystemDefaultCharSize : 8); // Fill structure size field }
public async override Task <GLTexture> ReadTextureAsync(CancellationToken cancelationToken) { if (cancelationToken.IsCancellationRequested) { return(RaiseTextureReaded(null)); } using (SafeHGlobalHandle pixels = new SafeHGlobalHandle(_map.Width * _map.Height * 3)) { using (Stream stream = pixels.OpenStream(FileAccess.ReadWrite)) { if (cancelationToken.IsCancellationRequested) { return(RaiseTextureReaded(null)); } CreateBackground(stream); foreach (MimTile tile in _map.LayredTiles[0]) { if (cancelationToken.IsCancellationRequested) { return(RaiseTextureReaded(null)); } //if (tile.Layered.Z < _map.LayredTiles[0][0].Layered.Z) // break; int position = tile.Layered.GetPositionInImage(_map, _map.Width * 3); stream.Seek(position, SeekOrigin.Begin); Color[] colors = ReadTileColors(tile); for (int i = 0; i < 16; i++) { for (int k = 0; k < 16; k++) { WriteColor(colors[i * 16 + k], tile.Layered.BlendType, stream); } if (i < 15) { stream.Seek((_map.Width - 16) * 3, SeekOrigin.Current); } } } } if (cancelationToken.IsCancellationRequested) { return(RaiseTextureReaded(null)); } PixelFormatDescriptor pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb; int textureId; using (GLService.AcquireContext()) { GL.GenTextures(1, out textureId); GL.BindTexture(TextureTarget.Texture2D, textureId); GL.TexImage2D(TextureTarget.Texture2D, 0, pixelFormat, _map.Width, _map.Height, 0, pixelFormat, pixelFormat, pixels.DangerousGetHandle()); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat); } if (cancelationToken.IsCancellationRequested) { return(RaiseTextureReaded(null)); } return(new GLTexture(textureId, _map.Width, _map.Height, pixelFormat)); } }
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(); } } }
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); }
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); }