This repository has been archived by the owner on Oct 17, 2018. It is now read-only.
/
Secret.cs
284 lines (258 loc) · 10.8 KB
/
Secret.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Cryptography;
using Microsoft.AspNetCore.Cryptography.Cng;
using Microsoft.AspNetCore.Cryptography.SafeHandles;
using Microsoft.AspNetCore.DataProtection.Managed;
namespace Microsoft.AspNetCore.DataProtection
{
/// <summary>
/// Represents a secret value stored in memory.
/// </summary>
public unsafe sealed class Secret : IDisposable, ISecret
{
// from wincrypt.h
private const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;
private readonly SecureLocalAllocHandle _localAllocHandle;
private readonly uint _plaintextLength;
/// <summary>
/// Creates a new Secret from the provided input value, where the input value
/// is specified as an array segment.
/// </summary>
public Secret(ArraySegment<byte> value)
{
value.Validate();
_localAllocHandle = Protect(value);
_plaintextLength = (uint)value.Count;
}
/// <summary>
/// Creates a new Secret from the provided input value, where the input value
/// is specified as an array.
/// </summary>
public Secret(byte[] value)
: this(new ArraySegment<byte>(value))
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// Creates a new Secret from the provided input value, where the input value
/// is specified as a pointer to unmanaged memory.
/// </summary>
public Secret(byte* secret, int secretLength)
{
if (secret == null)
{
throw new ArgumentNullException(nameof(secret));
}
if (secretLength < 0)
{
throw Error.Common_ValueMustBeNonNegative(nameof(secretLength));
}
_localAllocHandle = Protect(secret, (uint)secretLength);
_plaintextLength = (uint)secretLength;
}
/// <summary>
/// Creates a new Secret from another secret object.
/// </summary>
public Secret(ISecret secret)
{
if (secret == null)
{
throw new ArgumentNullException(nameof(secret));
}
var other = secret as Secret;
if (other != null)
{
// Fast-track: simple deep copy scenario.
this._localAllocHandle = other._localAllocHandle.Duplicate();
this._plaintextLength = other._plaintextLength;
}
else
{
// Copy the secret to a temporary managed buffer, then protect the buffer.
// We pin the temp buffer and zero it out when we're finished to limit exposure of the secret.
var tempPlaintextBuffer = new byte[secret.Length];
fixed (byte* pbTempPlaintextBuffer = tempPlaintextBuffer)
{
try
{
secret.WriteSecretIntoBuffer(new ArraySegment<byte>(tempPlaintextBuffer));
_localAllocHandle = Protect(pbTempPlaintextBuffer, (uint)tempPlaintextBuffer.Length);
_plaintextLength = (uint)tempPlaintextBuffer.Length;
}
finally
{
UnsafeBufferUtil.SecureZeroMemory(pbTempPlaintextBuffer, tempPlaintextBuffer.Length);
}
}
}
}
/// <summary>
/// The length (in bytes) of the secret value.
/// </summary>
public int Length
{
get
{
return (int)_plaintextLength; // ctor guarantees the length fits into a signed int
}
}
/// <summary>
/// Wipes the secret from memory.
/// </summary>
public void Dispose()
{
_localAllocHandle.Dispose();
}
private static SecureLocalAllocHandle Protect(ArraySegment<byte> plaintext)
{
fixed (byte* pbPlaintextArray = plaintext.Array)
{
return Protect(&pbPlaintextArray[plaintext.Offset], (uint)plaintext.Count);
}
}
private static SecureLocalAllocHandle Protect(byte* pbPlaintext, uint cbPlaintext)
{
// If we're not running on a platform that supports CryptProtectMemory,
// shove the plaintext directly into a LocalAlloc handle. Ideally we'd
// mark this memory page as non-pageable, but this is fraught with peril.
if (!OSVersionUtil.IsWindows())
{
var handle = SecureLocalAllocHandle.Allocate((IntPtr)checked((int)cbPlaintext));
UnsafeBufferUtil.BlockCopy(from: pbPlaintext, to: handle, byteCount: cbPlaintext);
return handle;
}
// We need to make sure we're a multiple of CRYPTPROTECTMEMORY_BLOCK_SIZE.
var numTotalBytesToAllocate = cbPlaintext;
var numBytesPaddingRequired = CRYPTPROTECTMEMORY_BLOCK_SIZE - (numTotalBytesToAllocate % CRYPTPROTECTMEMORY_BLOCK_SIZE);
if (numBytesPaddingRequired == CRYPTPROTECTMEMORY_BLOCK_SIZE)
{
numBytesPaddingRequired = 0; // we're already a proper multiple of the block size
}
checked { numTotalBytesToAllocate += numBytesPaddingRequired; }
CryptoUtil.Assert(numTotalBytesToAllocate % CRYPTPROTECTMEMORY_BLOCK_SIZE == 0, "numTotalBytesToAllocate % CRYPTPROTECTMEMORY_BLOCK_SIZE == 0");
// Allocate and copy plaintext data; padding is uninitialized / undefined.
var encryptedMemoryHandle = SecureLocalAllocHandle.Allocate((IntPtr)numTotalBytesToAllocate);
UnsafeBufferUtil.BlockCopy(from: pbPlaintext, to: encryptedMemoryHandle, byteCount: cbPlaintext);
// Finally, CryptProtectMemory the whole mess.
if (numTotalBytesToAllocate != 0)
{
MemoryProtection.CryptProtectMemory(encryptedMemoryHandle, byteCount: numTotalBytesToAllocate);
}
return encryptedMemoryHandle;
}
/// <summary>
/// Returns a Secret comprised entirely of random bytes retrieved from
/// a cryptographically secure RNG.
/// </summary>
public static Secret Random(int numBytes)
{
if (numBytes < 0)
{
throw Error.Common_ValueMustBeNonNegative(nameof(numBytes));
}
if (numBytes == 0)
{
byte dummy;
return new Secret(&dummy, 0);
}
else
{
// Don't use CNG if we're not on Windows.
if (!OSVersionUtil.IsWindows())
{
return new Secret(ManagedGenRandomImpl.Instance.GenRandom(numBytes));
}
var bytes = new byte[numBytes];
fixed (byte* pbBytes = bytes)
{
try
{
BCryptUtil.GenRandom(pbBytes, (uint)numBytes);
return new Secret(pbBytes, numBytes);
}
finally
{
UnsafeBufferUtil.SecureZeroMemory(pbBytes, numBytes);
}
}
}
}
private void UnprotectInto(byte* pbBuffer)
{
// If we're not running on a platform that supports CryptProtectMemory,
// the handle contains plaintext bytes.
if (!OSVersionUtil.IsWindows())
{
UnsafeBufferUtil.BlockCopy(from: _localAllocHandle, to: pbBuffer, byteCount: _plaintextLength);
return;
}
if (_plaintextLength % CRYPTPROTECTMEMORY_BLOCK_SIZE == 0)
{
// Case 1: Secret length is an exact multiple of the block size. Copy directly to the buffer and decrypt there.
UnsafeBufferUtil.BlockCopy(from: _localAllocHandle, to: pbBuffer, byteCount: _plaintextLength);
MemoryProtection.CryptUnprotectMemory(pbBuffer, _plaintextLength);
}
else
{
// Case 2: Secret length is not a multiple of the block size. We'll need to duplicate the data and
// perform the decryption in the duplicate buffer, then copy the plaintext data over.
using (var duplicateHandle = _localAllocHandle.Duplicate())
{
MemoryProtection.CryptUnprotectMemory(duplicateHandle, checked((uint)duplicateHandle.Length));
UnsafeBufferUtil.BlockCopy(from: duplicateHandle, to: pbBuffer, byteCount: _plaintextLength);
}
}
}
/// <summary>
/// Writes the secret value to the specified buffer.
/// </summary>
/// <remarks>
/// The buffer size must exactly match the length of the secret value.
/// </remarks>
public void WriteSecretIntoBuffer(ArraySegment<byte> buffer)
{
// Parameter checking
buffer.Validate();
if (buffer.Count != Length)
{
throw Error.Common_BufferIncorrectlySized(nameof(buffer), actualSize: buffer.Count, expectedSize: Length);
}
// only unprotect if the secret is zero-length, as CLR doesn't like pinning zero-length buffers
if (Length != 0)
{
fixed (byte* pbBufferArray = buffer.Array)
{
UnprotectInto(&pbBufferArray[buffer.Offset]);
}
}
}
/// <summary>
/// Writes the secret value to the specified buffer.
/// </summary>
/// <param name="buffer">The buffer into which to write the secret value.</param>
/// <param name="bufferLength">The size (in bytes) of the provided buffer.</param>
/// <remarks>
/// The 'bufferLength' parameter must exactly match the length of the secret value.
/// </remarks>
public void WriteSecretIntoBuffer(byte* buffer, int bufferLength)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (bufferLength != Length)
{
throw Error.Common_BufferIncorrectlySized(nameof(bufferLength), actualSize: bufferLength, expectedSize: Length);
}
if (Length != 0)
{
UnprotectInto(buffer);
}
}
}
}