Skip to content

Commit 8688afa

Browse files
authored
Remove use of POH for cryptographic primitives
The Pinned Object Heap has undesirable performance characteristics for what it was being used for. Instead, use native memory to hold key material that should not be moved around by the garbage collector.
1 parent 964394d commit 8688afa

6 files changed

Lines changed: 338 additions & 252 deletions

File tree

‎src/libraries/System.Security.Cryptography/src/System.Security.Cryptography.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@
403403
<Compile Include="System\Security\Cryptography\ECKeyXmlFormat.cs" />
404404
<Compile Include="System\Security\Cryptography\ECParameters.cs" />
405405
<Compile Include="System\Security\Cryptography\ECPoint.cs" />
406+
<Compile Include="System\Security\Cryptography\FixedMemoryKeyBox.cs" />
406407
<Compile Include="System\Security\Cryptography\HashAlgorithm.cs" />
407408
<Compile Include="System\Security\Cryptography\HashAlgorithmName.cs" />
408409
<Compile Include="System\Security\Cryptography\HashAlgorithmNames.cs" />

‎src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.Android.cs‎

Lines changed: 130 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,16 @@ namespace System.Security.Cryptography
99
{
1010
public sealed partial class AesCcm
1111
{
12-
private byte[]? _key;
12+
private FixedMemoryKeyBox _keyBox;
1313

1414
public static bool IsSupported => true;
1515

16-
[MemberNotNull(nameof(_key))]
16+
[MemberNotNull(nameof(_keyBox))]
1717
private void ImportKey(ReadOnlySpan<byte> key)
1818
{
19-
// Pin the array on the POH so that the GC doesn't move it around to allow zeroing to be more effective.
20-
_key = GC.AllocateArray<byte>(key.Length, pinned: true);
21-
key.CopyTo(_key);
19+
// We should only be calling this in the constructor, so there shouldn't be a previous key.
20+
Debug.Assert(_keyBox is null);
21+
_keyBox = new FixedMemoryKeyBox(key);
2222
}
2323

2424
private void EncryptCore(
@@ -28,82 +28,95 @@ private void EncryptCore(
2828
Span<byte> tag,
2929
ReadOnlySpan<byte> associatedData = default)
3030
{
31-
CheckDisposed();
31+
bool acquired = false;
3232

33-
// Convert key length to bits.
34-
using (SafeEvpCipherCtxHandle ctx = Interop.Crypto.EvpCipherCreatePartial(GetCipher(_key.Length * 8)))
33+
try
3534
{
36-
if (ctx.IsInvalid)
37-
{
38-
throw new CryptographicException();
39-
}
40-
41-
if (!Interop.Crypto.CipherSetTagLength(ctx, tag.Length))
42-
{
43-
throw new CryptographicException();
44-
}
45-
46-
Interop.Crypto.CipherSetNonceLength(ctx, nonce.Length);
47-
Interop.Crypto.EvpCipherSetKeyAndIV(ctx, _key, nonce, Interop.Crypto.EvpCipherDirection.Encrypt);
48-
49-
if (associatedData.Length != 0)
50-
{
51-
Interop.Crypto.CipherUpdateAAD(ctx, associatedData);
52-
}
35+
_keyBox.DangerousAddRef(ref acquired);
36+
ReadOnlySpan<byte> key = _keyBox.DangerousKeySpan;
5337

54-
byte[]? rented = null;
55-
try
38+
// Convert key length to bits.
39+
using (SafeEvpCipherCtxHandle ctx = Interop.Crypto.EvpCipherCreatePartial(GetCipher(key.Length * 8)))
5640
{
57-
scoped Span<byte> ciphertextAndTag;
58-
59-
// Arbitrary limit.
60-
const int StackAllocMax = 128;
61-
if (checked(ciphertext.Length + tag.Length) <= StackAllocMax)
62-
{
63-
ciphertextAndTag = stackalloc byte[ciphertext.Length + tag.Length];
64-
}
65-
else
66-
{
67-
rented = CryptoPool.Rent(ciphertext.Length + tag.Length);
68-
ciphertextAndTag = new Span<byte>(rented, 0, ciphertext.Length + tag.Length);
69-
}
70-
71-
if (!Interop.Crypto.EvpCipherUpdate(ctx, ciphertextAndTag, out int ciphertextBytesWritten, plaintext))
41+
if (ctx.IsInvalid)
7242
{
7343
throw new CryptographicException();
7444
}
7545

76-
if (!Interop.Crypto.EvpAeadCipherFinalEx(
77-
ctx,
78-
ciphertextAndTag.Slice(ciphertextBytesWritten),
79-
out int bytesWritten,
80-
out bool authTagMismatch))
46+
if (!Interop.Crypto.CipherSetTagLength(ctx, tag.Length))
8147
{
82-
Debug.Assert(!authTagMismatch);
8348
throw new CryptographicException();
8449
}
8550

86-
ciphertextBytesWritten += bytesWritten;
51+
Interop.Crypto.CipherSetNonceLength(ctx, nonce.Length);
52+
Interop.Crypto.EvpCipherSetKeyAndIV(ctx, key, nonce, Interop.Crypto.EvpCipherDirection.Encrypt);
8753

88-
// NOTE: Android appends tag to the end of the ciphertext in case of CCM/GCM and "encryption" mode
89-
90-
if (ciphertextBytesWritten != ciphertextAndTag.Length)
54+
if (associatedData.Length != 0)
9155
{
92-
Debug.Fail($"CCM encrypt wrote {ciphertextBytesWritten} of {ciphertextAndTag.Length} bytes.");
93-
throw new CryptographicException();
56+
Interop.Crypto.CipherUpdateAAD(ctx, associatedData);
9457
}
9558

96-
ciphertextAndTag[..ciphertext.Length].CopyTo(ciphertext);
97-
ciphertextAndTag[ciphertext.Length..].CopyTo(tag);
98-
}
99-
finally
100-
{
101-
if (rented != null)
59+
byte[]? rented = null;
60+
try
10261
{
103-
CryptoPool.Return(rented, ciphertext.Length + tag.Length);
62+
scoped Span<byte> ciphertextAndTag;
63+
64+
// Arbitrary limit.
65+
const int StackAllocMax = 128;
66+
if (checked(ciphertext.Length + tag.Length) <= StackAllocMax)
67+
{
68+
ciphertextAndTag = stackalloc byte[ciphertext.Length + tag.Length];
69+
}
70+
else
71+
{
72+
rented = CryptoPool.Rent(ciphertext.Length + tag.Length);
73+
ciphertextAndTag = new Span<byte>(rented, 0, ciphertext.Length + tag.Length);
74+
}
75+
76+
if (!Interop.Crypto.EvpCipherUpdate(ctx, ciphertextAndTag, out int ciphertextBytesWritten, plaintext))
77+
{
78+
throw new CryptographicException();
79+
}
80+
81+
if (!Interop.Crypto.EvpAeadCipherFinalEx(
82+
ctx,
83+
ciphertextAndTag.Slice(ciphertextBytesWritten),
84+
out int bytesWritten,
85+
out bool authTagMismatch))
86+
{
87+
Debug.Assert(!authTagMismatch);
88+
throw new CryptographicException();
89+
}
90+
91+
ciphertextBytesWritten += bytesWritten;
92+
93+
// NOTE: Android appends tag to the end of the ciphertext in case of CCM/GCM and "encryption" mode
94+
95+
if (ciphertextBytesWritten != ciphertextAndTag.Length)
96+
{
97+
Debug.Fail($"CCM encrypt wrote {ciphertextBytesWritten} of {ciphertextAndTag.Length} bytes.");
98+
throw new CryptographicException();
99+
}
100+
101+
ciphertextAndTag[..ciphertext.Length].CopyTo(ciphertext);
102+
ciphertextAndTag[ciphertext.Length..].CopyTo(tag);
103+
}
104+
finally
105+
{
106+
if (rented != null)
107+
{
108+
CryptoPool.Return(rented, ciphertext.Length + tag.Length);
109+
}
104110
}
105111
}
106112
}
113+
finally
114+
{
115+
if (acquired)
116+
{
117+
_keyBox.DangerousRelease();
118+
}
119+
}
107120
}
108121

109122
private void DecryptCore(
@@ -113,64 +126,77 @@ private void DecryptCore(
113126
Span<byte> plaintext,
114127
ReadOnlySpan<byte> associatedData)
115128
{
116-
CheckDisposed();
129+
bool acquired = false;
117130

118-
using (SafeEvpCipherCtxHandle ctx = Interop.Crypto.EvpCipherCreatePartial(GetCipher(_key.Length * 8)))
131+
try
119132
{
120-
if (ctx.IsInvalid)
121-
{
122-
throw new CryptographicException();
123-
}
124-
Interop.Crypto.CipherSetNonceLength(ctx, nonce.Length);
133+
_keyBox.DangerousAddRef(ref acquired);
134+
ReadOnlySpan<byte> key = _keyBox.DangerousKeySpan;
125135

126-
if (!Interop.Crypto.CipherSetTagLength(ctx, tag.Length))
136+
using (SafeEvpCipherCtxHandle ctx = Interop.Crypto.EvpCipherCreatePartial(GetCipher(key.Length * 8)))
127137
{
128-
throw new CryptographicException();
129-
}
138+
if (ctx.IsInvalid)
139+
{
140+
throw new CryptographicException();
141+
}
142+
Interop.Crypto.CipherSetNonceLength(ctx, nonce.Length);
130143

131-
Interop.Crypto.EvpCipherSetKeyAndIV(ctx, _key, nonce, Interop.Crypto.EvpCipherDirection.Decrypt);
144+
if (!Interop.Crypto.CipherSetTagLength(ctx, tag.Length))
145+
{
146+
throw new CryptographicException();
147+
}
132148

133-
if (associatedData.Length != 0)
134-
{
135-
Interop.Crypto.CipherUpdateAAD(ctx, associatedData);
136-
}
149+
Interop.Crypto.EvpCipherSetKeyAndIV(ctx, key, nonce, Interop.Crypto.EvpCipherDirection.Decrypt);
137150

138-
if (!Interop.Crypto.EvpCipherUpdate(ctx, plaintext, out int plaintextBytesWritten, ciphertext))
139-
{
140-
CryptographicOperations.ZeroMemory(plaintext);
141-
throw new CryptographicException();
142-
}
151+
if (associatedData.Length != 0)
152+
{
153+
Interop.Crypto.CipherUpdateAAD(ctx, associatedData);
154+
}
143155

144-
if (!Interop.Crypto.EvpCipherUpdate(ctx, plaintext.Slice(plaintextBytesWritten), out int bytesWritten, tag))
145-
{
146-
CryptographicOperations.ZeroMemory(plaintext);
147-
throw new CryptographicException();
148-
}
156+
if (!Interop.Crypto.EvpCipherUpdate(ctx, plaintext, out int plaintextBytesWritten, ciphertext))
157+
{
158+
CryptographicOperations.ZeroMemory(plaintext);
159+
throw new CryptographicException();
160+
}
149161

150-
plaintextBytesWritten += bytesWritten;
162+
if (!Interop.Crypto.EvpCipherUpdate(ctx, plaintext.Slice(plaintextBytesWritten), out int bytesWritten, tag))
163+
{
164+
CryptographicOperations.ZeroMemory(plaintext);
165+
throw new CryptographicException();
166+
}
151167

152-
if (!Interop.Crypto.EvpAeadCipherFinalEx(
153-
ctx,
154-
plaintext.Slice(plaintextBytesWritten),
155-
out bytesWritten,
156-
out bool authTagMismatch))
157-
{
158-
CryptographicOperations.ZeroMemory(plaintext);
168+
plaintextBytesWritten += bytesWritten;
159169

160-
if (authTagMismatch)
170+
if (!Interop.Crypto.EvpAeadCipherFinalEx(
171+
ctx,
172+
plaintext.Slice(plaintextBytesWritten),
173+
out bytesWritten,
174+
out bool authTagMismatch))
161175
{
162-
throw new AuthenticationTagMismatchException();
163-
}
176+
CryptographicOperations.ZeroMemory(plaintext);
164177

165-
throw new CryptographicException(SR.Arg_CryptographyException);
166-
}
178+
if (authTagMismatch)
179+
{
180+
throw new AuthenticationTagMismatchException();
181+
}
167182

168-
plaintextBytesWritten += bytesWritten;
183+
throw new CryptographicException(SR.Arg_CryptographyException);
184+
}
169185

170-
if (plaintextBytesWritten != plaintext.Length)
186+
plaintextBytesWritten += bytesWritten;
187+
188+
if (plaintextBytesWritten != plaintext.Length)
189+
{
190+
Debug.Fail($"CCM decrypt wrote {plaintextBytesWritten} of {plaintext.Length} bytes.");
191+
throw new CryptographicException();
192+
}
193+
}
194+
}
195+
finally
196+
{
197+
if (acquired)
171198
{
172-
Debug.Fail($"CCM decrypt wrote {plaintextBytesWritten} of {plaintext.Length} bytes.");
173-
throw new CryptographicException();
199+
_keyBox.DangerousRelease();
174200
}
175201
}
176202
}
@@ -186,16 +212,6 @@ private static IntPtr GetCipher(int keySizeInBits)
186212
};
187213
}
188214

189-
[MemberNotNull(nameof(_key))]
190-
private void CheckDisposed()
191-
{
192-
ObjectDisposedException.ThrowIf(_key is null, this);
193-
}
194-
195-
public void Dispose()
196-
{
197-
CryptographicOperations.ZeroMemory(_key);
198-
_key = null;
199-
}
215+
public void Dispose() => _keyBox.Dispose();
200216
}
201217
}

0 commit comments

Comments
 (0)