/
PasswordHasher.cs
443 lines (381 loc) · 16.9 KB
/
PasswordHasher.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// 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 System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using ServiceStack.Logging;
#if NETCORE
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
#endif
namespace ServiceStack.Auth;
public delegate byte[] Pbkdf2DeriveKeyDelegate(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested);
/// <summary>
/// Allow utilizing an alternative PBKDF2 implementation.
/// </summary>
public static class Pbkdf2Provider
{
/// <summary>
/// The PBKDF2 strategy PasswordHasher implementation that's used for hashing PBKDF2 passwords.
/// </summary>
public static Pbkdf2DeriveKeyDelegate DeriveKey { get; set; }
#if NETCORE
= KeyDerivation.Pbkdf2; // .NET Core uses the most optimal implementation available for Windows
#else
= new ManagedPbkdf2Provider().DeriveKey; // Slowest managed implementation used by .NET Framework and all non-Windows OS's
#endif
}
/// <summary>
/// The Password Hasher provider used to hash users passwords which uses the same algorithm used by ASP.NET Identity v3:
/// PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
/// </summary>
public class PasswordHasher : IPasswordHasher
{
//from https://github.com/aspnet/Identity/blob/dev/src/Microsoft.Extensions.Identity.Core/PasswordHasher.cs
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
public static ILog Log = LogManager.GetLogger(typeof(PasswordHasher));
public const int DefaultIterationCount = 10000;
/// <summary>
/// Gets the number of iterations used when hashing passwords using PBKDF2. Default is 10,000.
/// </summary>
public int IterationCount { get; }
public PasswordHasher() : this(DefaultIterationCount) {}
/// <summary>
/// The number of iterations used when hashing passwords using PBKDF2. Default is 10,000.
/// </summary>
public PasswordHasher(int iterationCount)
{
if (iterationCount < 1)
throw new InvalidOperationException("Invalid iterationCount: " + iterationCount);
this.IterationCount = iterationCount;
}
/// <summary>
/// The Format Version specifier for this PasswordHasher embedded as the first byte in password hashes.
/// </summary>
public byte Version => 0x01;
public bool VerifyPassword(string hashedPassword, string providedPassword, out bool needsRehash)
{
needsRehash = false;
if (hashedPassword == null)
throw new ArgumentNullException(nameof(hashedPassword));
if (providedPassword == null)
throw new ArgumentNullException(nameof(providedPassword));
byte[] decodedHashedPassword = Convert.FromBase64String(hashedPassword);
// read the format marker from the hashed password
if (decodedHashedPassword.Length == 0)
{
if (Log.IsDebugEnabled)
Log.Debug("hashedPassword is empty");
return false;
}
var formatMarker = decodedHashedPassword[0];
switch (formatMarker)
{
case 0x01:
if (VerifyHashedPasswordV3(decodedHashedPassword, providedPassword, out int embeddedIterCount))
{
// If this hasher was configured with a higher iteration count, change the entry now.
if (embeddedIterCount < IterationCount)
needsRehash = true;
return true;
}
else
{
return false;
}
default:
if (Log.IsDebugEnabled)
Log.Debug($"Unknown Password Format Marker '{formatMarker}'");
return false;
}
}
/// <summary>
/// Returns a hashed representation of the supplied <paramref name="password"/> for the specified user.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <returns>A hashed representation of the supplied <paramref name="password"/> for the specified user.</returns>
public virtual string HashPassword(string password)
{
if (password == null)
throw new ArgumentNullException(nameof(password));
return Convert.ToBase64String(HashPasswordV3(password, _rng));
}
private static readonly RandomNumberGenerator _defaultRng = RandomNumberGenerator.Create(); // secure PRNG
private readonly RandomNumberGenerator _rng = _defaultRng;
// Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (a == null && b == null)
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
var areSame = true;
for (var i = 0; i < a.Length; i++)
{
areSame &= (a[i] == b[i]);
}
return areSame;
}
private byte[] HashPasswordV3(string password, RandomNumberGenerator rng)
{
return HashPasswordV3(password, rng,
prf: KeyDerivationPrf.HMACSHA256,
iterCount: IterationCount,
saltSize: 128 / 8,
numBytesRequested: 256 / 8);
}
private static byte[] HashPasswordV3(string password, RandomNumberGenerator rng, KeyDerivationPrf prf, int iterCount, int saltSize, int numBytesRequested)
{
// Produce a version 3 (see comment above) text hash.
byte[] salt = new byte[saltSize];
rng.GetBytes(salt);
byte[] subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
var outputBytes = new byte[13 + salt.Length + subkey.Length];
outputBytes[0] = 0x01; // format marker
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
WriteNetworkByteOrder(outputBytes, 5, (uint)iterCount);
WriteNetworkByteOrder(outputBytes, 9, (uint)saltSize);
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
return outputBytes;
}
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
return ((uint)(buffer[offset + 0]) << 24)
| ((uint)(buffer[offset + 1]) << 16)
| ((uint)(buffer[offset + 2]) << 8)
| ((uint)(buffer[offset + 3]));
}
private static bool VerifyHashedPasswordV3(byte[] hashedPassword, string password, out int iterCount)
{
iterCount = default(int);
try
{
// Read header information
KeyDerivationPrf prf = (KeyDerivationPrf)ReadNetworkByteOrder(hashedPassword, 1);
iterCount = (int)ReadNetworkByteOrder(hashedPassword, 5);
int saltLength = (int)ReadNetworkByteOrder(hashedPassword, 9);
// Read the salt: must be >= 128 bits
if (saltLength < 128 / 8)
{
return false;
}
byte[] salt = new byte[saltLength];
Buffer.BlockCopy(hashedPassword, 13, salt, 0, salt.Length);
// Read the subkey (the rest of the payload): must be >= 128 bits
int subkeyLength = hashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
return false;
}
byte[] expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(hashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// Hash the incoming password and verify it
byte[] actualSubkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, subkeyLength);
return ByteArraysEqual(actualSubkey, expectedSubkey);
}
catch
{
// This should never occur except in the case of a malformed payload, where
// we might go off the end of the array. Regardless, a malformed payload
// implies verification failed.
return false;
}
}
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
buffer[offset + 0] = (byte)(value >> 24);
buffer[offset + 1] = (byte)(value >> 16);
buffer[offset + 2] = (byte)(value >> 8);
buffer[offset + 3] = (byte)(value >> 0);
}
}
#if NETFX || NET472
//From: https://github.com/aspnet/DataProtection/
/// <summary>
/// Specifies the PRF which should be used for the key derivation algorithm.
/// </summary>
public enum KeyDerivationPrf
{
/// <summary>
/// The HMAC algorithm (RFC 2104) using the SHA-1 hash function (FIPS 180-4).
/// </summary>
HMACSHA1,
/// <summary>
/// The HMAC algorithm (RFC 2104) using the SHA-256 hash function (FIPS 180-4).
/// </summary>
HMACSHA256,
/// <summary>
/// The HMAC algorithm (RFC 2104) using the SHA-512 hash function (FIPS 180-4).
/// </summary>
HMACSHA512,
}
/// <summary>
/// Provides algorithms for performing key derivation.
/// </summary>
public static class KeyDerivation
{
/// <summary>
/// Performs key derivation using the PBKDF2 algorithm.
/// </summary>
/// <param name="password">The password from which to derive the key.</param>
/// <param name="salt">The salt to be used during the key derivation process.</param>
/// <param name="prf">The pseudo-random function to be used in the key derivation process.</param>
/// <param name="iterationCount">The number of iterations of the pseudo-random function to apply
/// during the key derivation process.</param>
/// <param name="numBytesRequested">The desired length (in bytes) of the derived key.</param>
/// <returns>The derived key.</returns>
/// <remarks>
/// The PBKDF2 algorithm is specified in RFC 2898.
/// </remarks>
public static byte[] Pbkdf2(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
{
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
if (salt == null)
{
throw new ArgumentNullException(nameof(salt));
}
// parameter checking
if (prf < KeyDerivationPrf.HMACSHA1 || prf > KeyDerivationPrf.HMACSHA512)
{
throw new ArgumentOutOfRangeException(nameof(prf));
}
if (iterationCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(iterationCount));
}
if (numBytesRequested <= 0)
{
throw new ArgumentOutOfRangeException(nameof(numBytesRequested));
}
return Pbkdf2Provider.DeriveKey(password, salt, prf, iterationCount, numBytesRequested);
}
}
/// <summary>
/// Internal interface used for abstracting away the PBKDF2 implementation since the implementation is OS-specific.
/// </summary>
internal interface IPbkdf2Provider
{
byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested);
}
/// <summary>
/// A PBKDF2 provider which utilizes the managed hash algorithm classes as PRFs.
/// This isn't the preferred provider since the implementation is slow, but it is provided as a fallback.
/// </summary>
internal sealed class ManagedPbkdf2Provider : IPbkdf2Provider
{
public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
{
Debug.Assert(password != null);
Debug.Assert(salt != null);
Debug.Assert(iterationCount > 0);
Debug.Assert(numBytesRequested > 0);
// PBKDF2 is defined in NIST SP800-132, Sec. 5.3.
// http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
byte[] retVal = new byte[numBytesRequested];
int numBytesWritten = 0;
int numBytesRemaining = numBytesRequested;
// For each block index, U_0 := Salt || block_index
byte[] saltWithBlockIndex = new byte[checked(salt.Length + sizeof(uint))];
Buffer.BlockCopy(salt, 0, saltWithBlockIndex, 0, salt.Length);
using (var hashAlgorithm = PrfToManagedHmacAlgorithm(prf, password))
{
for (uint blockIndex = 1; numBytesRemaining > 0; blockIndex++)
{
// write the block index out as big-endian
saltWithBlockIndex[saltWithBlockIndex.Length - 4] = (byte)(blockIndex >> 24);
saltWithBlockIndex[saltWithBlockIndex.Length - 3] = (byte)(blockIndex >> 16);
saltWithBlockIndex[saltWithBlockIndex.Length - 2] = (byte)(blockIndex >> 8);
saltWithBlockIndex[saltWithBlockIndex.Length - 1] = (byte)blockIndex;
// U_1 = PRF(U_0) = PRF(Salt || block_index)
// T_blockIndex = U_1
byte[] U_iter = hashAlgorithm.ComputeHash(saltWithBlockIndex); // this is U_1
byte[] T_blockIndex = U_iter;
for (int iter = 1; iter < iterationCount; iter++)
{
U_iter = hashAlgorithm.ComputeHash(U_iter);
XorBuffers(src: U_iter, dest: T_blockIndex);
// At this point, the 'U_iter' variable actually contains U_{iter+1} (due to indexing differences).
}
// At this point, we're done iterating on this block, so copy the transformed block into retVal.
int numBytesToCopy = Math.Min(numBytesRemaining, T_blockIndex.Length);
Buffer.BlockCopy(T_blockIndex, 0, retVal, numBytesWritten, numBytesToCopy);
numBytesWritten += numBytesToCopy;
numBytesRemaining -= numBytesToCopy;
}
}
// retVal := T_1 || T_2 || ... || T_n, where T_n may be truncated to meet the desired output length
return retVal;
}
private static KeyedHashAlgorithm PrfToManagedHmacAlgorithm(KeyDerivationPrf prf, string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
try
{
switch (prf)
{
case KeyDerivationPrf.HMACSHA1:
return new HMACSHA1(passwordBytes);
case KeyDerivationPrf.HMACSHA256:
return new HMACSHA256(passwordBytes);
case KeyDerivationPrf.HMACSHA512:
return new HMACSHA512(passwordBytes);
default:
throw CryptoUtil.Fail("Unrecognized PRF.");
}
}
finally
{
// The HMAC ctor makes a duplicate of this key; we clear original buffer to limit exposure to the GC.
Array.Clear(passwordBytes, 0, passwordBytes.Length);
}
}
private static void XorBuffers(byte[] src, byte[] dest)
{
// Note: dest buffer is mutated.
Debug.Assert(src.Length == dest.Length);
for (int i = 0; i < src.Length; i++)
{
dest[i] ^= src[i];
}
}
}
#endif
internal static class CryptoUtil
{
// This isn't a typical Debug.Fail; an error always occurs, even in retail builds.
// This method doesn't return, but since the CLR doesn't allow specifying a 'never'
// return type, we mimic it by specifying our return type as Exception. That way
// callers can write 'throw Fail(...);' to make the C# compiler happy, as the
// throw keyword is implicitly of type O.
[MethodImpl(MethodImplOptions.NoInlining)]
public static Exception Fail(string message)
{
Debug.Fail(message);
throw new CryptographicException("Assertion failed: " + message);
}
// Allows callers to write "var x = Method() ?? Fail<T>(message);" as a convenience to guard
// against a method returning null unexpectedly.
[MethodImpl(MethodImplOptions.NoInlining)]
public static T Fail<T>(string message) where T : class
{
throw Fail(message);
}
}