Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not use AllocHGlobal in Pkcs12Reader #97447

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
<ItemGroup Condition="'$(GeneratePlatformNotSupportedAssemblyMessage)' == ''">
<Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"
Link="Common\DisableRuntimeMarshalling.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeCrypt32Handle.cs"
Link="Common\Microsoft\Win32\SafeHandles\SafeCrypt32Handle.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeHandleCache.cs"
Link="Common\Microsoft\Win32\SafeHandles\SafeHandleCache.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeX509ChainHandle.cs"
Expand Down Expand Up @@ -902,10 +904,12 @@
<Compile Include="System\Security\Cryptography\X509Certificates\OpenSslX509ChainEventSource.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\OpenSslX509ChainProcessor.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\OpenSslX509Encoder.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\SafeLocalAllocWithClearOnDisposeHandle.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\StorePal.OpenSsl.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixChainVerifier.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixExportProvider.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixPkcs12Reader.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnmanagedCryptoBufferMemoryManager.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnsupportedDisallowedStore.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.ManagedDecode.cs" />
Expand Down Expand Up @@ -1036,6 +1040,7 @@
<Compile Include="System\Security\Cryptography\X509Certificates\ManagedX509ExtensionProcessor.cs" />
<Compile Include="System\Security\Cryptography\Shake128.NonWindows.cs" />
<Compile Include="System\Security\Cryptography\Shake256.NonWindows.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\SafeLocalAllocWithClearOnDisposeHandle.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\StorePal.Android.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\StorePal.Android.AndroidKeyStore.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\StorePal.Android.ExportPal.cs" />
Expand All @@ -1044,6 +1049,7 @@
<Compile Include="System\Security\Cryptography\X509Certificates\UnixChainVerifier.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixExportProvider.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixPkcs12Reader.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnmanagedCryptoBufferMemoryManager.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnsupportedDisallowedStore.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.ManagedDecode.cs" />
Expand Down Expand Up @@ -1157,9 +1163,11 @@
<Compile Include="System\Security\Cryptography\X509Certificates\FindPal.Apple.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\ManagedCertificateFinder.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\ManagedX509ExtensionProcessor.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\SafeLocalAllocWithClearOnDisposeHandle.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixChainVerifier.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixExportProvider.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnixPkcs12Reader.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\UnmanagedCryptoBufferMemoryManager.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X500NameEncoder.ManagedDecode.cs" />
<Compile Include="System\Security\Cryptography\X509Certificates\X509Pal.Apple.ECKey.cs" />
Expand Down Expand Up @@ -1633,8 +1641,6 @@
Link="Common\Microsoft\Win32\SafeHandles\SafeCertStoreHandle.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeChainEngineHandle.cs"
Link="Common\Microsoft\Win32\SafeHandles\SafeChainEngineHandle.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeCrypt32Handle.cs"
Link="Common\Microsoft\Win32\SafeHandles\SafeCrypt32Handle.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeCryptMsgHandle.cs"
Link="Common\Microsoft\Win32\SafeHandles\SafeCryptMsgHandle.cs" />
<Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeUnicodeStringHandle.cs"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace System.Security.Cryptography.X509Certificates
{
/// <summary>
/// SafeHandle for LocalAlloc'd memory which calls ZeroMemory when releasing handle.
/// </summary>
internal sealed class SafeLocalAllocWithClearOnDisposeHandle : SafeCrypt32Handle<SafeLocalAllocWithClearOnDisposeHandle>
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
internal int Length { get; private set; }

public static SafeLocalAllocWithClearOnDisposeHandle Create(int cb)
{
var h = new SafeLocalAllocWithClearOnDisposeHandle();
h.SetHandle(Marshal.AllocHGlobal(cb));
h.Length = cb;
return h;
}

internal unsafe Span<byte> DangerousGetSpan()
=> new Span<byte>((void*)handle, Length);

protected sealed override unsafe bool ReleaseHandle()
{
CryptographicOperations.ZeroMemory(DangerousGetSpan());
Marshal.FreeHGlobal(handle);
return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal abstract class UnixPkcs12Reader : IDisposable
private ContentInfoAsn[]? _safeContentsValues;
private CertAndKey[]? _certs;
private int _certCount;
private PointerMemoryManager<byte>? _tmpManager;
private UnmanagedCryptoBufferMemoryManager? _tmpManager;
private bool _allowDoubleBind;

protected abstract ICertificatePalCore ReadX509Der(ReadOnlyMemory<byte> data);
Expand All @@ -40,13 +40,10 @@ protected void ParsePkcs12(ReadOnlySpan<byte> data)
// Windows compatibility: Ignore trailing data.
ReadOnlySpan<byte> encodedData = reader.PeekEncodedValue();

unsafe
{
IntPtr tmpPtr = Marshal.AllocHGlobal(encodedData.Length);
Span<byte> tmpSpan = new Span<byte>((byte*)tmpPtr, encodedData.Length);
encodedData.CopyTo(tmpSpan);
_tmpManager = new PointerMemoryManager<byte>((void*)tmpPtr, encodedData.Length);
}
// We use unmanaged buffer to avoid GC compaction clones of the private key material
_tmpManager = new UnmanagedCryptoBufferMemoryManager(encodedData.Length);
Span<byte> tmpSpan = _tmpManager.GetSpan();
encodedData.CopyTo(tmpSpan);

ReadOnlyMemory<byte> tmpMemory = _tmpManager.Memory;
reader = new AsnValueReader(tmpMemory.Span, AsnEncodingRules.BER);
Expand Down Expand Up @@ -112,26 +109,8 @@ internal IEnumerable<CertAndKey> EnumerateAll()

public void Dispose()
{
// Generally, having a MemoryManager cleaned up in a Dispose is a bad practice.
// In this case, the UnixPkcs12Reader is only ever created in a using statement,
// never accessed by a second thread, and there isn't a manual call to Dispose
// mixed in anywhere.
if (_tmpManager != null)
{
unsafe
{
Span<byte> tmp = _tmpManager.GetSpan();
CryptographicOperations.ZeroMemory(tmp);

fixed (byte* ptr = tmp)
{
Marshal.FreeHGlobal((IntPtr)ptr);
}
}

((IDisposable)_tmpManager).Dispose();
_tmpManager = null;
}
((IDisposable?)_tmpManager)?.Dispose();
_tmpManager = null;

ContentInfoAsn[]? rentedContents = Interlocked.Exchange(ref _safeContentsValues, null);
CertAndKey[]? rentedCerts = Interlocked.Exchange(ref _certs, null);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;

namespace System.Security.Cryptography.X509Certificates
{
/// <summary>
/// Unmanaged memory manager backed by buffer allocated with Marshal.AllocHGlobal ensuring memory is cleared on Dispose.
/// </summary>
internal sealed unsafe class UnmanagedCryptoBufferMemoryManager : MemoryManager<byte>
{
private readonly SafeLocalAllocWithClearOnDisposeHandle _handle;

internal UnmanagedCryptoBufferMemoryManager(int length)
{
_handle = SafeLocalAllocWithClearOnDisposeHandle.Create(length);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
_handle.Dispose();
}
}

public override Span<byte> GetSpan()
=> _handle.DangerousGetSpan();

public override MemoryHandle Pin(int elementIndex = 0)
{
throw new NotSupportedException();
}

public override void Unpin()
{
}
}
}
Loading