forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSecureStringHelper.cs
619 lines (524 loc) · 21.5 KB
/
SecureStringHelper.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;
namespace Microsoft.PowerShell
{
/// <summary>
/// helper class for secure string related functionality
/// </summary>
internal static class SecureStringHelper
{
// Some random hex characters to identify the beginning of a
// V2-exported SecureString.
internal static string SecureStringExportHeader = "76492d1116743f0423413b16050a5345";
/// <summary>
/// Create a new SecureString based on the specified binary data.
///
/// The binary data must be byte[] version of unicode char[],
/// otherwise the results are unpredictable.
/// </summary>
/// <param name="data"> input data </param>
/// <returns>A SecureString .</returns>
private static SecureString New(byte[] data)
{
if ((data.Length % 2) != 0)
{
// If the data is not an even length, they supplied an invalid key
string error = Serialization.InvalidKey;
throw new PSArgumentException(error);
}
char ch;
SecureString ss = new SecureString();
//
// each unicode char is 2 bytes.
//
int len = data.Length / 2;
for (int i = 0; i < len; i++)
{
ch = (char)(data[2 * i + 1] * 256 + data[2 * i]);
ss.AppendChar(ch);
//
// zero out the data slots as soon as we use them
//
data[2 * i] = 0;
data[2 * i + 1] = 0;
}
return ss;
}
/// <summary>
/// get the contents of a SecureString as byte[]
/// </summary>
/// <param name="s"> input string </param>
/// <returns>Contents of s (char[]) converted to byte[].</returns>
[ArchitectureSensitive]
internal static byte[] GetData(SecureString s)
{
//
// each unicode char is 2 bytes.
//
byte[] data = new byte[s.Length * 2];
if (s.Length > 0)
{
IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(s);
try
{
Marshal.Copy(ptr, data, 0, data.Length);
}
finally
{
Marshal.ZeroFreeCoTaskMemUnicode(ptr);
}
}
return data;
}
/// <summary>
/// Encode the specified byte[] as a unicode string.
///
/// Currently we use simple hex encoding but this
/// method can be changed to use a better encoding
/// such as base64.
/// </summary>
/// <param name="data"> binary data to encode </param>
/// <returns>A string representing encoded data.</returns>
internal static string ByteArrayToString(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString("x2", System.Globalization.CultureInfo.InvariantCulture));
}
return sb.ToString();
}
/// <summary>
/// Convert a string obtained using ByteArrayToString()
/// back to byte[] format.
/// </summary>
/// <param name="s"> encoded input string </param>
/// <returns>Bin data as byte[].</returns>
internal static byte[] ByteArrayFromString(string s)
{
//
// two hex chars per byte
//
int dataLen = s.Length / 2;
byte[] data = new byte[dataLen];
if (s.Length > 0)
{
for (int i = 0; i < dataLen; i++)
{
data[i] = byte.Parse(s.Substring(2 * i, 2),
NumberStyles.AllowHexSpecifier,
System.Globalization.CultureInfo.InvariantCulture);
}
}
return data;
}
/// <summary>
/// return contents of the SecureString after encrypting
/// using DPAPI and encoding the encrypted blob as a string
/// </summary>
/// <param name="input"> SecureString to protect </param>
/// <returns>A string (see summary) .</returns>
internal static string Protect(SecureString input)
{
Utils.CheckSecureStringArg(input, "input");
string output = string.Empty;
byte[] data = null;
byte[] protectedData = null;
data = GetData(input);
protectedData = ProtectedData.Protect(data, null,
DataProtectionScope.CurrentUser);
for (int i = 0; i < data.Length; i++)
{
data[i] = 0;
}
output = ByteArrayToString(protectedData);
return output;
}
/// <summary>
/// Decrypts the specified string using DPAPI and return
/// equivalent SecureString.
///
/// The string must be obtained earlier by a call to Protect()
/// </summary>
/// <param name="input"> encrypted string </param>
/// <returns>SecureString .</returns>
internal static SecureString Unprotect(string input)
{
Utils.CheckArgForNullOrEmpty(input, "input");
if ((input.Length % 2) != 0)
{
throw PSTraceSource.NewArgumentException("input", Serialization.InvalidEncryptedString, input);
}
byte[] data = null;
byte[] protectedData = null;
SecureString s;
protectedData = ByteArrayFromString(input);
data = ProtectedData.Unprotect(protectedData, null,
DataProtectionScope.CurrentUser);
s = New(data);
return s;
}
/// <summary>
/// return contents of the SecureString after encrypting
/// using the specified key and encoding the encrypted blob as a string
/// </summary>
/// <param name="input"> input string to encrypt </param>
/// <param name="key"> encryption key </param>
/// <returns>A string (see summary).</returns>
internal static EncryptionResult Encrypt(SecureString input, SecureString key)
{
EncryptionResult output = null;
//
// get clear text key from the SecureString key
//
byte[] keyBlob = GetData(key);
//
// encrypt the data
//
output = Encrypt(input, keyBlob);
//
// clear the clear text key
//
Array.Clear(keyBlob, 0, keyBlob.Length);
return output;
}
/// <summary>
/// return contents of the SecureString after encrypting
/// using the specified key and encoding the encrypted blob as a string
/// </summary>
/// <param name="input"> input string to encrypt </param>
/// <param name="key"> encryption key </param>
/// <returns>A string (see summary).</returns>
internal static EncryptionResult Encrypt(SecureString input, byte[] key)
{
return Encrypt(input, key, null);
}
internal static EncryptionResult Encrypt(SecureString input, byte[] key, byte[] iv)
{
Utils.CheckSecureStringArg(input, "input");
Utils.CheckKeyArg(key, "key");
byte[] encryptedData = null;
MemoryStream ms = null;
ICryptoTransform encryptor = null;
CryptoStream cs = null;
//
// prepare the crypto stuff. Initialization Vector is
// randomized by default.
//
Aes aes = Aes.Create();
if (iv == null)
iv = aes.IV;
encryptor = aes.CreateEncryptor(key, iv);
ms = new MemoryStream();
using (cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
//
// get clear text data from the input SecureString
//
byte[] data = GetData(input);
//
// encrypt it
//
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
//
// clear the clear text data array
//
Array.Clear(data, 0, data.Length);
//
// convert the encrypted blob to a string
//
encryptedData = ms.ToArray();
EncryptionResult output = new EncryptionResult(ByteArrayToString(encryptedData), Convert.ToBase64String(iv));
return output;
}
}
/// <summary>
/// Decrypts the specified string using the specified key
/// and return equivalent SecureString.
///
/// The string must be obtained earlier by a call to Encrypt()
/// </summary>
/// <param name="input"> encrypted string </param>
/// <param name="key"> encryption key </param>
/// <param name="IV"> encryption initialization vector. If this is set to null, the method uses internally computed strong random number as IV </param>
/// <returns>SecureString .</returns>
internal static SecureString Decrypt(string input, SecureString key, byte[] IV)
{
SecureString output = null;
//
// get clear text key from the SecureString key
//
byte[] keyBlob = GetData(key);
//
// decrypt the data
//
output = Decrypt(input, keyBlob, IV);
//
// clear the clear text key
//
Array.Clear(keyBlob, 0, keyBlob.Length);
return output;
}
/// <summary>
/// Decrypts the specified string using the specified key
/// and return equivalent SecureString.
///
/// The string must be obtained earlier by a call to Encrypt()
/// </summary>
/// <param name="input"> encrypted string </param>
/// <param name="key"> encryption key </param>
/// <param name="IV"> encryption initialization vector. If this is set to null, the method uses internally computed strong random number as IV </param>
/// <returns>SecureString .</returns>
internal static SecureString Decrypt(string input, byte[] key, byte[] IV)
{
Utils.CheckArgForNullOrEmpty(input, "input");
Utils.CheckKeyArg(key, "key");
byte[] decryptedData = null;
byte[] encryptedData = null;
SecureString s = null;
//
// prepare the crypto stuff
//
Aes aes = Aes.Create();
encryptedData = ByteArrayFromString(input);
var decryptor = aes.CreateDecryptor(key, IV ?? aes.IV);
MemoryStream ms = new MemoryStream(encryptedData);
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
byte[] tempDecryptedData = new byte[encryptedData.Length];
int numBytesRead = 0;
//
// decrypt the data
//
numBytesRead = cs.Read(tempDecryptedData, 0,
tempDecryptedData.Length);
decryptedData = new byte[numBytesRead];
for (int i = 0; i < numBytesRead; i++)
{
decryptedData[i] = tempDecryptedData[i];
}
s = New(decryptedData);
Array.Clear(decryptedData, 0, decryptedData.Length);
Array.Clear(tempDecryptedData, 0, tempDecryptedData.Length);
return s;
}
}
}
/// <summary>
/// Helper class to return encryption results, and the IV used to
/// do the encryption
/// </summary>
internal class EncryptionResult
{
internal EncryptionResult(string encrypted, string IV)
{
EncryptedData = encrypted;
this.IV = IV;
}
/// <summary>
/// Gets the encrypted data
/// </summary>
internal string EncryptedData { get; }
/// <summary>
/// Gets the IV used to encrypt the data
/// </summary>
internal string IV { get; }
}
#if CORECLR
// The DPAPIs implemented in this section are temporary workaround.
// CoreCLR team will bring 'ProtectedData' type to Project K eventually.
#region DPAPI
internal enum DataProtectionScope
{
CurrentUser = 0x00,
LocalMachine = 0x01
}
internal static class ProtectedData
{
/// <summary>
/// Protect
/// </summary>
public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
{
if (userData == null)
throw new ArgumentNullException("userData");
GCHandle pbDataIn = new GCHandle();
GCHandle pOptionalEntropy = new GCHandle();
CAPI.CRYPTOAPI_BLOB blob = new CAPI.CRYPTOAPI_BLOB();
try
{
pbDataIn = GCHandle.Alloc(userData, GCHandleType.Pinned);
CAPI.CRYPTOAPI_BLOB dataIn = new CAPI.CRYPTOAPI_BLOB();
dataIn.cbData = (uint)userData.Length;
dataIn.pbData = pbDataIn.AddrOfPinnedObject();
CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB();
if (optionalEntropy != null)
{
pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned);
entropy.cbData = (uint)optionalEntropy.Length;
entropy.pbData = pOptionalEntropy.AddrOfPinnedObject();
}
uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN;
if (scope == DataProtectionScope.LocalMachine)
dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE;
unsafe
{
if (!CAPI.CryptProtectData(new IntPtr(&dataIn),
String.Empty,
new IntPtr(&entropy),
IntPtr.Zero,
IntPtr.Zero,
dwFlags,
new IntPtr(&blob)))
{
int lastWin32Error = Marshal.GetLastWin32Error();
// One of the most common reasons that DPAPI operations fail is that the user
// profile is not loaded (for instance in the case of impersonation or running in a
// service. In those cases, throw an exception that provides more specific details
// about what happened.
if (CAPI.ErrorMayBeCausedByUnloadedProfile(lastWin32Error))
{
throw new CryptographicException("Cryptography_DpApi_ProfileMayNotBeLoaded");
}
else
{
throw new CryptographicException(lastWin32Error);
}
}
}
// In some cases, the API would fail due to OOM but simply return a null pointer.
if (blob.pbData == IntPtr.Zero)
throw new OutOfMemoryException();
byte[] encryptedData = new byte[(int)blob.cbData];
Marshal.Copy(blob.pbData, encryptedData, 0, encryptedData.Length);
return encryptedData;
}
finally
{
if (pbDataIn.IsAllocated)
pbDataIn.Free();
if (pOptionalEntropy.IsAllocated)
pOptionalEntropy.Free();
if (blob.pbData != IntPtr.Zero)
{
CAPI.ZeroMemory(blob.pbData, blob.cbData);
CAPI.LocalFree(blob.pbData);
}
}
}
/// <summary>
/// Unprotect
/// </summary>
public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
{
#if UNIX
throw new PlatformNotSupportedException(Serialization.DeserializeSecureStringNotSupported);
#else
if (encryptedData == null)
throw new ArgumentNullException("encryptedData");
GCHandle pbDataIn = new GCHandle();
GCHandle pOptionalEntropy = new GCHandle();
CAPI.CRYPTOAPI_BLOB userData = new CAPI.CRYPTOAPI_BLOB();
try
{
pbDataIn = GCHandle.Alloc(encryptedData, GCHandleType.Pinned);
CAPI.CRYPTOAPI_BLOB dataIn = new CAPI.CRYPTOAPI_BLOB();
dataIn.cbData = (uint)encryptedData.Length;
dataIn.pbData = pbDataIn.AddrOfPinnedObject();
CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB();
if (optionalEntropy != null)
{
pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned);
entropy.cbData = (uint)optionalEntropy.Length;
entropy.pbData = pOptionalEntropy.AddrOfPinnedObject();
}
uint dwFlags = CAPI.CRYPTPROTECT_UI_FORBIDDEN;
if (scope == DataProtectionScope.LocalMachine)
dwFlags |= CAPI.CRYPTPROTECT_LOCAL_MACHINE;
unsafe
{
if (!CAPI.CryptUnprotectData(new IntPtr(&dataIn),
IntPtr.Zero,
new IntPtr(&entropy),
IntPtr.Zero,
IntPtr.Zero,
dwFlags,
new IntPtr(&userData)))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
// In some cases, the API would fail due to OOM but simply return a null pointer.
if (userData.pbData == IntPtr.Zero)
throw new OutOfMemoryException();
byte[] data = new byte[(int)userData.cbData];
Marshal.Copy(userData.pbData, data, 0, data.Length);
return data;
}
finally
{
if (pbDataIn.IsAllocated)
pbDataIn.Free();
if (pOptionalEntropy.IsAllocated)
pOptionalEntropy.Free();
if (userData.pbData != IntPtr.Zero)
{
CAPI.ZeroMemory(userData.pbData, userData.cbData);
CAPI.LocalFree(userData.pbData);
}
}
#endif
}
}
internal static class CAPI
{
internal const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
internal const uint CRYPTPROTECT_LOCAL_MACHINE = 0x4;
internal const int E_FILENOTFOUND = unchecked((int)0x80070002); // File not found
internal const int ERROR_FILE_NOT_FOUND = 2; // File not found
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CRYPTOAPI_BLOB
{
internal uint cbData;
internal IntPtr pbData;
}
internal static bool ErrorMayBeCausedByUnloadedProfile(int errorCode)
{
// CAPI returns a file not found error if the user profile is not yet loaded
return errorCode == E_FILENOTFOUND ||
errorCode == ERROR_FILE_NOT_FOUND;
}
[DllImport("CRYPT32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool CryptProtectData(
[In] IntPtr pDataIn,
[In] string szDataDescr,
[In] IntPtr pOptionalEntropy,
[In] IntPtr pvReserved,
[In] IntPtr pPromptStruct,
[In] uint dwFlags,
[In, Out] IntPtr pDataBlob);
[DllImport("CRYPT32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool CryptUnprotectData(
[In] IntPtr pDataIn,
[In] IntPtr ppszDataDescr,
[In] IntPtr pOptionalEntropy,
[In] IntPtr pvReserved,
[In] IntPtr pPromptStruct,
[In] uint dwFlags,
[In, Out] IntPtr pDataBlob);
[DllImport("ntdll.dll", EntryPoint = "RtlZeroMemory", SetLastError = true)]
internal static extern void ZeroMemory(IntPtr handle, uint length);
[DllImport(PinvokeDllNames.LocalFreeDllName, SetLastError = true)]
internal static extern IntPtr LocalFree(IntPtr handle);
}
#endregion DPAPI
#endif
}