/
Utils.cs
1832 lines (1609 loc) · 71.7 KB
/
Utils.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Security;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
#if !UNIX
using System.Security.Principal;
#endif
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using TypeTable = System.Management.Automation.Runspaces.TypeTable;
namespace System.Management.Automation
{
/// <summary>
/// Helper fns.
/// </summary>
internal static class Utils
{
/// <summary>
/// Converts a given double value to BigInteger via Math.Round().
/// </summary>
/// <param name="d">The value to convert.</param>
/// <returns>Returns a BigInteger value equivalent to the input value rounded to nearest integer.</returns>
internal static BigInteger AsBigInt(this double d) => new BigInteger(Math.Round(d));
internal static bool TryCast(BigInteger value, out byte b)
{
if (value < byte.MinValue || value > byte.MaxValue)
{
b = 0;
return false;
}
b = (byte)value;
return true;
}
internal static bool TryCast(BigInteger value, out sbyte sb)
{
if (value < sbyte.MinValue || value > sbyte.MaxValue)
{
sb = 0;
return false;
}
sb = (sbyte)value;
return true;
}
internal static bool TryCast(BigInteger value, out short s)
{
if (value < short.MinValue || value > short.MaxValue)
{
s = 0;
return false;
}
s = (short)value;
return true;
}
internal static bool TryCast(BigInteger value, out ushort us)
{
if (value < ushort.MinValue || value > ushort.MaxValue)
{
us = 0;
return false;
}
us = (ushort)value;
return true;
}
internal static bool TryCast(BigInteger value, out int i)
{
if (value < int.MinValue || value > int.MaxValue)
{
i = 0;
return false;
}
i = (int)value;
return true;
}
internal static bool TryCast(BigInteger value, out uint u)
{
if (value < uint.MinValue || value > uint.MaxValue)
{
u = 0;
return false;
}
u = (uint)value;
return true;
}
internal static bool TryCast(BigInteger value, out long l)
{
if (value < long.MinValue || value > long.MaxValue)
{
l = 0;
return false;
}
l = (long)value;
return true;
}
internal static bool TryCast(BigInteger value, out ulong ul)
{
if (value < ulong.MinValue || value > ulong.MaxValue)
{
ul = 0;
return false;
}
ul = (ulong)value;
return true;
}
internal static bool TryCast(BigInteger value, out decimal dm)
{
if (value < (BigInteger)decimal.MinValue || (BigInteger)decimal.MaxValue < value)
{
dm = 0;
return false;
}
dm = (decimal)value;
return true;
}
internal static bool TryCast(BigInteger value, out double db)
{
if (value < (BigInteger)double.MinValue || (BigInteger)double.MaxValue < value)
{
db = 0;
return false;
}
db = (double)value;
return true;
}
/// <summary>
/// Parses a given string or ReadOnlySpan<char> to calculate its value as a binary number.
/// Assumes input has already been sanitized and only contains zeroes (0) or ones (1).
/// </summary>
/// <param name="digits">Span or string of binary digits. Assumes all digits are either 1 or 0.</param>
/// <param name="unsigned">
/// Whether to treat the number as unsigned. When false, respects established conventions
/// with sign bits for certain input string lengths.
/// </param>
/// <returns>Returns the value of the binary string as a BigInteger.</returns>
internal static BigInteger ParseBinary(ReadOnlySpan<char> digits, bool unsigned)
{
if (!unsigned)
{
if (digits[0] == '0')
{
unsigned = true;
}
else
{
switch (digits.Length)
{
// Only accept sign bits at these lengths:
case 8: // byte
case 16: // short
case 32: // int
case 64: // long
case 96: // decimal
case int n when n >= 128: // BigInteger
break;
default:
// If we do not flag these as unsigned, bigint assumes a sign bit for any (8 * n) string length
unsigned = true;
break;
}
}
}
// Only use heap allocation for very large numbers
const int MaxStackAllocation = 512;
// Calculate number of 8-bit bytes needed to hold the input, rounded up to next whole number.
int outputByteCount = (digits.Length + 7) / 8;
Span<byte> outputBytes = outputByteCount <= MaxStackAllocation ? stackalloc byte[outputByteCount] : new byte[outputByteCount];
int outputByteIndex = outputBytes.Length - 1;
// We need to be prepared for any partial leading bytes, (e.g., 010|00000011|00101100), or cases
// where we only have less than 8 bits to work with from the beginning.
//
// Walk bytes right to left, stepping one whole byte at a time (if there are any whole bytes).
int byteWalker;
for (byteWalker = digits.Length - 1; byteWalker >= 7; byteWalker -= 8)
{
// Use bit shifts and binary-or to sum the values in each byte. These calculations will
// create values higher than a single byte, but the higher bits will be stripped out when cast
// to byte.
//
// The low bits are added in separately to allow us to strip the higher 'noise' bits before we
// sum the values using binary-or.
//
// Simplified representation of logic: (byte)( (7)|(6)|(5)|(4) ) | ( ( (3)|(2)|(1)|(0) ) & 0b1111 )
//
// N.B.: This code has been tested against a straight for loop iterating through the byte, and in no
// circumstance was it faster or more effective than this unrolled version.
outputBytes[outputByteIndex--] =
(byte)(
((digits[byteWalker - 7] << 7)
| (digits[byteWalker - 6] << 6)
| (digits[byteWalker - 5] << 5)
| (digits[byteWalker - 4] << 4)
)
| (
((digits[byteWalker - 3] << 3)
| (digits[byteWalker - 2] << 2)
| (digits[byteWalker - 1] << 1)
| (digits[byteWalker])
) & 0b1111
)
);
}
// With complete bytes parsed, byteWalker is either at the partial byte start index, or at -1
if (byteWalker >= 0)
{
int currentByteValue = 0;
for (int i = 0; i <= byteWalker; i++)
{
currentByteValue = (currentByteValue << 1) | (digits[i] - '0');
}
outputBytes[outputByteIndex] = (byte)currentByteValue;
}
return new BigInteger(outputBytes, isUnsigned: unsigned, isBigEndian: true);
}
// From System.Web.Util.HashCodeCombiner
internal static int CombineHashCodes(int h1, int h2)
{
return unchecked(((h1 << 5) + h1) ^ h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8));
}
/// <summary>
/// Allowed PowerShell Editions.
/// </summary>
internal static readonly string[] AllowedEditionValues = { "Desktop", "Core" };
/// <summary>
/// Helper fn to check byte[] arg for null.
/// </summary>
///<param name="arg"> arg to check </param>
///<param name="argName"> name of the arg </param>
///<returns> Does not return a value.</returns>
internal static void CheckKeyArg(byte[] arg, string argName)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException(argName);
}
//
// we use AES algorithm which supports key
// lengths of 128, 192 and 256 bits.
// We throw ArgumentException if the key is
// of any other length
//
else if (!((arg.Length == 16) ||
(arg.Length == 24) ||
(arg.Length == 32)))
{
throw PSTraceSource.NewArgumentException(argName, Serialization.InvalidKeyLength, argName);
}
}
/// <summary>
/// Helper fn to check arg for empty or null.
/// Throws ArgumentNullException on either condition.
/// </summary>
///<param name="arg"> arg to check </param>
///<param name="argName"> name of the arg </param>
///<returns> Does not return a value.</returns>
internal static void CheckArgForNullOrEmpty(string arg, string argName)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException(argName);
}
else if (arg.Length == 0)
{
throw PSTraceSource.NewArgumentException(argName);
}
}
/// <summary>
/// Helper fn to check arg for null.
/// Throws ArgumentNullException on either condition.
/// </summary>
///<param name="arg"> arg to check </param>
///<param name="argName"> name of the arg </param>
///<returns> Does not return a value.</returns>
internal static void CheckArgForNull(object arg, string argName)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException(argName);
}
}
/// <summary>
/// Helper fn to check arg for null.
/// </summary>
///<param name="arg"> arg to check </param>
///<param name="argName"> name of the arg </param>
///<returns> Does not return a value.</returns>
internal static void CheckSecureStringArg(SecureString arg, string argName)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException(argName);
}
}
[ArchitectureSensitive]
internal static string GetStringFromSecureString(SecureString ss)
{
IntPtr p = IntPtr.Zero;
string s = null;
try
{
p = Marshal.SecureStringToCoTaskMemUnicode(ss);
s = Marshal.PtrToStringUni(p);
}
finally
{
if (p != IntPtr.Zero)
{
Marshal.ZeroFreeCoTaskMemUnicode(p);
}
}
return s;
}
/// <summary>
/// Gets TypeTable by querying the ExecutionContext stored in
/// Thread-Local-Storage. This will return null if ExecutionContext
/// is not available.
/// </summary>
/// <returns></returns>
internal static TypeTable GetTypeTableFromExecutionContextTLS()
{
ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS();
if (ecFromTLS == null)
{
return null;
}
return ecFromTLS.TypeTable;
}
#if !UNIX
private static string s_pshome = null;
/// <summary>
/// Get the application base path of the shell from registry.
/// </summary>
internal static string GetApplicationBaseFromRegistry(string shellId)
{
bool wantPsHome = (object)shellId == (object)DefaultPowerShellShellID;
if (wantPsHome && s_pshome != null)
return s_pshome;
string engineKeyPath = RegistryStrings.MonadRootKeyPath + "\\" +
PSVersionInfo.RegistryVersionKey + "\\" + RegistryStrings.MonadEngineKey;
using (RegistryKey engineKey = Registry.LocalMachine.OpenSubKey(engineKeyPath))
{
if (engineKey != null)
{
var result = engineKey.GetValue(RegistryStrings.MonadEngine_ApplicationBase) as string;
result = Environment.ExpandEnvironmentVariables(result);
if (wantPsHome)
Interlocked.CompareExchange(ref s_pshome, null, result);
return result;
}
}
return null;
}
private static string s_windowsPowerShellVersion = null;
/// <summary>
/// Get the Windows PowerShell version from registry.
/// </summary>
/// <returns>
/// String of Windows PowerShell version from registry.
/// </returns>
internal static string GetWindowsPowerShellVersionFromRegistry()
{
if (!string.IsNullOrEmpty(InternalTestHooks.TestWindowsPowerShellVersionString))
{
return InternalTestHooks.TestWindowsPowerShellVersionString;
}
if (s_windowsPowerShellVersion != null)
{
return s_windowsPowerShellVersion;
}
string engineKeyPath = RegistryStrings.MonadRootKeyPath + "\\" +
PSVersionInfo.RegistryVersionKey + "\\" + RegistryStrings.MonadEngineKey;
using (RegistryKey engineKey = Registry.LocalMachine.OpenSubKey(engineKeyPath))
{
if (engineKey != null)
{
s_windowsPowerShellVersion = engineKey.GetValue(RegistryStrings.MonadEngine_MonadVersion) as string;
return s_windowsPowerShellVersion;
}
}
return string.Empty;
}
#endif
internal static string DefaultPowerShellAppBase => GetApplicationBase(DefaultPowerShellShellID);
internal static string GetApplicationBase(string shellId)
{
// Use the location of SMA.dll as the application base.
Assembly assembly = typeof(PSObject).Assembly;
return Path.GetDirectoryName(assembly.Location);
}
private static string[] s_productFolderDirectories;
private static string[] GetProductFolderDirectories()
{
if (s_productFolderDirectories == null)
{
List<string> baseDirectories = new List<string>();
// Retrieve the application base from the registry
string appBase = Utils.DefaultPowerShellAppBase;
if (!string.IsNullOrEmpty(appBase))
{
baseDirectories.Add(appBase);
}
#if !UNIX
// Now add the two variations of System32
baseDirectories.Add(Environment.GetFolderPath(Environment.SpecialFolder.System));
string systemX86 = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86);
if (!string.IsNullOrEmpty(systemX86))
{
baseDirectories.Add(systemX86);
}
#endif
Interlocked.CompareExchange(ref s_productFolderDirectories, baseDirectories.ToArray(), null);
}
return s_productFolderDirectories;
}
/// <summary>
/// Checks if the filePath represents a file under product folder
/// ie., PowerShell ApplicationBase or $env:windir\system32 or
/// $env:windir\syswow64.
/// </summary>
/// <returns>
/// true: if the filePath is under product folder
/// false: otherwise
/// </returns>
internal static bool IsUnderProductFolder(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
string filename = fileInfo.FullName;
var productFolderDirectories = GetProductFolderDirectories();
for (int i = 0; i < productFolderDirectories.Length; i++)
{
string applicationBase = productFolderDirectories[i];
if (filename.StartsWith(applicationBase, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// Checks if the current process is using WOW.
/// </summary>
internal static bool IsRunningFromSysWOW64()
{
return DefaultPowerShellAppBase.Contains("SysWOW64");
}
/// <summary>
/// Checks if host machine is WinPE.
/// </summary>
internal static bool IsWinPEHost()
{
#if !UNIX
RegistryKey winPEKey = null;
try
{
// The existence of the following registry confirms that the host machine is a WinPE
// HKLM\System\CurrentControlSet\Control\MiniNT
winPEKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\MiniNT");
return winPEKey != null;
}
catch (ArgumentException) { }
catch (SecurityException) { }
catch (ObjectDisposedException) { }
finally
{
if (winPEKey != null)
{
winPEKey.Dispose();
}
}
#endif
return false;
}
#region Versioning related methods
/// <summary>
/// Returns current major version of monad ( that is running ) in a string
/// format.
/// </summary>
/// <returns>String.</returns>
/// <remarks>
/// Cannot return a Version object as minor number is a requirement for
/// version object.
/// </remarks>
internal static string GetCurrentMajorVersion()
{
return PSVersionInfo.PSVersion.Major.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Coverts a string to version format.
/// If the string is of the format x (ie., no dots), then ".0" is appended
/// to the string.
/// Version.TryParse will be used to convert the string to a Version
/// object.
/// </summary>
/// <param name="versionString">String representing version.</param>
/// <returns>A Version Object.</returns>
internal static Version StringToVersion(string versionString)
{
// max of 1 dot is allowed in version
if (string.IsNullOrEmpty(versionString))
{
return null;
}
int dotCount = 0;
foreach (char c in versionString)
{
if (c == '.')
{
dotCount++;
if (dotCount > 1)
{
break;
}
}
}
// Version.TryParse expects the string to be in format: major.minor[.build[.revision]]
if (dotCount == 0)
{
versionString += ".0";
}
Version result = null;
if (Version.TryParse(versionString, out result))
{
return result;
}
return null;
}
/// <summary>
/// Checks whether current monad session supports version specified
/// by ver.
/// </summary>
/// <param name="ver">Version to check.</param>
/// <returns>True if supported, false otherwise.</returns>
internal static bool IsPSVersionSupported(string ver)
{
// Convert version to supported format ie., x.x
Version inputVersion = StringToVersion(ver);
return IsPSVersionSupported(inputVersion);
}
/// <summary>
/// Checks whether current monad session supports version specified
/// by checkVersion.
/// </summary>
/// <param name="checkVersion">Version to check.</param>
/// <returns>True if supported, false otherwise.</returns>
internal static bool IsPSVersionSupported(Version checkVersion)
{
if (checkVersion == null)
{
return false;
}
foreach (Version compatibleVersion in PSVersionInfo.PSCompatibleVersions)
{
if (checkVersion.Major == compatibleVersion.Major && checkVersion.Minor <= compatibleVersion.Minor)
return true;
}
return false;
}
/// <summary>
/// Checks whether current PowerShell session supports edition specified
/// by checkEdition.
/// </summary>
/// <param name="checkEdition">Edition to check.</param>
/// <returns>True if supported, false otherwise.</returns>
internal static bool IsPSEditionSupported(string checkEdition)
{
return PSVersionInfo.PSEdition.Equals(checkEdition, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Check whether the current PowerShell session supports any of the specified editions.
/// </summary>
/// <param name="editions">The PowerShell editions to check compatibility with.</param>
/// <returns>True if the edition is supported by this runtime, false otherwise.</returns>
internal static bool IsPSEditionSupported(IEnumerable<string> editions)
{
string currentPSEdition = PSVersionInfo.PSEdition;
foreach (string edition in editions)
{
if (currentPSEdition.Equals(edition, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks whether the specified edition value is allowed.
/// </summary>
/// <param name="editionValue">Edition value to check.</param>
/// <returns>True if allowed, false otherwise.</returns>
internal static bool IsValidPSEditionValue(string editionValue)
{
return AllowedEditionValues.Contains(editionValue, StringComparer.OrdinalIgnoreCase);
}
#endregion
/// <summary>
/// String representing the Default shellID.
/// </summary>
internal const string DefaultPowerShellShellID = "Microsoft.PowerShell";
/// <summary>
/// This is used to construct the profile path.
/// </summary>
internal const string ProductNameForDirectory = "PowerShell";
/// <summary>
/// WSL introduces a new filesystem path to access the Linux filesystem from Windows, like '\\wsl$\ubuntu'.
/// </summary>
internal const string WslRootPath = @"\\wsl$";
/// <summary>
/// The subdirectory of module paths
/// e.g. ~\Documents\WindowsPowerShell\Modules and %ProgramFiles%\WindowsPowerShell\Modules.
/// </summary>
internal static readonly string ModuleDirectory = Path.Combine(ProductNameForDirectory, "Modules");
internal static readonly ConfigScope[] SystemWideOnlyConfig = new[] { ConfigScope.AllUsers };
internal static readonly ConfigScope[] CurrentUserOnlyConfig = new[] { ConfigScope.CurrentUser };
internal static readonly ConfigScope[] SystemWideThenCurrentUserConfig = new[] { ConfigScope.AllUsers, ConfigScope.CurrentUser };
internal static readonly ConfigScope[] CurrentUserThenSystemWideConfig = new[] { ConfigScope.CurrentUser, ConfigScope.AllUsers };
internal static T GetPolicySetting<T>(ConfigScope[] preferenceOrder) where T : PolicyBase, new()
{
T policy = null;
#if !UNIX
// On Windows, group policy settings from registry take precedence.
// If the requested policy is not defined in registry, we query the configuration file.
policy = GetPolicySettingFromGPO<T>(preferenceOrder);
if (policy != null) { return policy; }
#endif
policy = GetPolicySettingFromConfigFile<T>(preferenceOrder);
return policy;
}
private static readonly ConcurrentDictionary<ConfigScope, PowerShellPolicies> s_cachedPoliciesFromConfigFile =
new ConcurrentDictionary<ConfigScope, PowerShellPolicies>();
/// <summary>
/// Get a specific kind of policy setting from the configuration file.
/// </summary>
private static T GetPolicySettingFromConfigFile<T>(ConfigScope[] preferenceOrder) where T : PolicyBase, new()
{
foreach (ConfigScope scope in preferenceOrder)
{
PowerShellPolicies policies;
if (InternalTestHooks.BypassGroupPolicyCaching)
{
policies = PowerShellConfig.Instance.GetPowerShellPolicies(scope);
}
else if (!s_cachedPoliciesFromConfigFile.TryGetValue(scope, out policies))
{
// Use lock here to reduce the contention on accessing the configuration file
lock (s_cachedPoliciesFromConfigFile)
{
policies = s_cachedPoliciesFromConfigFile.GetOrAdd(scope, PowerShellConfig.Instance.GetPowerShellPolicies);
}
}
if (policies != null)
{
PolicyBase result = null;
switch (typeof(T).Name)
{
case nameof(ScriptExecution):
result = policies.ScriptExecution;
break;
case nameof(ScriptBlockLogging):
result = policies.ScriptBlockLogging;
break;
case nameof(ModuleLogging):
result = policies.ModuleLogging;
break;
case nameof(ProtectedEventLogging):
result = policies.ProtectedEventLogging;
break;
case nameof(Transcription):
result = policies.Transcription;
break;
case nameof(UpdatableHelp):
result = policies.UpdatableHelp;
break;
case nameof(ConsoleSessionConfiguration):
result = policies.ConsoleSessionConfiguration;
break;
default:
Diagnostics.Assert(false, "Should be unreachable code. Update this switch block when new PowerShell policy types are added.");
break;
}
if (result != null) { return (T)result; }
}
}
return null;
}
#if !UNIX
private static readonly Dictionary<string, string> GroupPolicyKeys = new Dictionary<string, string>
{
{nameof(ScriptExecution), @"Software\Policies\Microsoft\PowerShellCore"},
{nameof(ScriptBlockLogging), @"Software\Policies\Microsoft\PowerShellCore\ScriptBlockLogging"},
{nameof(ModuleLogging), @"Software\Policies\Microsoft\PowerShellCore\ModuleLogging"},
{nameof(ProtectedEventLogging), @"Software\Policies\Microsoft\Windows\EventLog\ProtectedEventLogging"},
{nameof(Transcription), @"Software\Policies\Microsoft\PowerShellCore\Transcription"},
{nameof(UpdatableHelp), @"Software\Policies\Microsoft\PowerShellCore\UpdatableHelp"},
{nameof(ConsoleSessionConfiguration), @"Software\Policies\Microsoft\PowerShellCore\ConsoleSessionConfiguration"}
};
private static readonly Dictionary<string, string> WindowsPowershellGroupPolicyKeys = new Dictionary<string, string>
{
{ nameof(ScriptExecution), @"Software\Policies\Microsoft\Windows\PowerShell" },
{ nameof(ScriptBlockLogging), @"Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" },
{ nameof(ModuleLogging), @"Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging" },
{ nameof(Transcription), @"Software\Policies\Microsoft\Windows\PowerShell\Transcription" },
{ nameof(UpdatableHelp), @"Software\Policies\Microsoft\Windows\PowerShell\UpdatableHelp" },
};
private const string PolicySettingFallbackKey = "UseWindowsPowerShellPolicySetting";
private static readonly ConcurrentDictionary<ConfigScope, ConcurrentDictionary<string, PolicyBase>> s_cachedPoliciesFromRegistry =
new ConcurrentDictionary<ConfigScope, ConcurrentDictionary<string, PolicyBase>>();
private static readonly Func<ConfigScope, ConcurrentDictionary<string, PolicyBase>> s_subCacheCreationDelegate =
key => new ConcurrentDictionary<string, PolicyBase>(StringComparer.Ordinal);
/// <summary>
/// Read policy settings from a registry key into a policy object.
/// </summary>
/// <param name="instance">Policy object that will be filled with values from registry.</param>
/// <param name="instanceType">Type of policy object used.</param>
/// <param name="gpoKey">Registry key that has policy settings.</param>
/// <returns>True if any property was successfully set on the policy object.</returns>
private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type instanceType, RegistryKey gpoKey)
{
var properties = instanceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
bool isAnyPropertySet = false;
string[] valueNames = gpoKey.GetValueNames();
string[] subKeyNames = gpoKey.GetSubKeyNames();
var valueNameSet = valueNames.Length > 0 ? new HashSet<string>(valueNames, StringComparer.OrdinalIgnoreCase) : null;
var subKeyNameSet = subKeyNames.Length > 0 ? new HashSet<string>(subKeyNames, StringComparer.OrdinalIgnoreCase) : null;
// If there are any values or subkeys in the registry key - read them into the policy instance object
if ((valueNameSet != null) || (subKeyNameSet != null))
{
foreach (var property in properties)
{
string settingName = property.Name;
object rawRegistryValue = null;
// Get the raw value from registry.
if (valueNameSet != null && valueNameSet.Contains(settingName))
{
rawRegistryValue = gpoKey.GetValue(settingName);
}
else if (subKeyNameSet != null && subKeyNameSet.Contains(settingName))
{
using (RegistryKey subKey = gpoKey.OpenSubKey(settingName))
{
if (subKey != null)
{
rawRegistryValue = subKey.GetValueNames();
}
}
}
// Get the actual property value based on the property type.
// If the final property value is not null, then set the property.
if (rawRegistryValue != null)
{
Type propertyType = property.PropertyType;
object propertyValue = null;
switch (propertyType)
{
case var _ when propertyType == typeof(bool?):
if (rawRegistryValue is int rawIntValue)
{
if (rawIntValue == 1)
{
propertyValue = true;
}
else if (rawIntValue == 0)
{
propertyValue = false;
}
}
break;
case var _ when propertyType == typeof(string):
if (rawRegistryValue is string rawStringValue)
{
propertyValue = rawStringValue;
}
break;
case var _ when propertyType == typeof(string[]):
if (rawRegistryValue is string[] rawStringArrayValue)
{
propertyValue = rawStringArrayValue;
}
else if (rawRegistryValue is string stringValue)
{
propertyValue = new string[] { stringValue };
}
break;
default:
throw System.Management.Automation.Interpreter.Assert.Unreachable;
}
// Set the property if the value is not null
if (propertyValue != null)
{
property.SetValue(instance, propertyValue);
isAnyPropertySet = true;
}
}
}
}
return isAnyPropertySet;
}
/// <summary>
/// The implementation of fetching a specific kind of policy setting from the given configuration scope.
/// </summary>
private static T GetPolicySettingFromGPOImpl<T>(ConfigScope scope) where T : PolicyBase, new()
{
Type tType = typeof(T);
// SystemWide scope means 'LocalMachine' root key when query from registry
RegistryKey rootKey = (scope == ConfigScope.AllUsers) ? Registry.LocalMachine : Registry.CurrentUser;
GroupPolicyKeys.TryGetValue(tType.Name, out string gpoKeyPath);
Diagnostics.Assert(gpoKeyPath != null, StringUtil.Format("The GPO registry key path should be pre-defined for {0}", tType.Name));
using (RegistryKey gpoKey = rootKey.OpenSubKey(gpoKeyPath))
{
// If the corresponding GPO key doesn't exist, return null
if (gpoKey == null) { return null; }
// The corresponding GPO key exists, then create an instance of T
// and populate its properties with the settings
object tInstance = Activator.CreateInstance(tType, nonPublic: true);
bool isAnyPropertySet = false;
// if PolicySettingFallbackKey is Not set - use PowerShell Core policy reg key
if ((int)gpoKey.GetValue(PolicySettingFallbackKey, 0) == 0)
{
isAnyPropertySet = TrySetPolicySettingsFromRegistryKey(tInstance, tType, gpoKey);
}
else
{
// when PolicySettingFallbackKey flag is set (REG_DWORD "1") use Windows PS policy reg key
WindowsPowershellGroupPolicyKeys.TryGetValue(tType.Name, out string winPowershellGpoKeyPath);
Diagnostics.Assert(winPowershellGpoKeyPath != null, StringUtil.Format("The Windows PS GPO registry key path should be pre-defined for {0}", tType.Name));
using (RegistryKey winPowershellGpoKey = rootKey.OpenSubKey(winPowershellGpoKeyPath))
{
// If the corresponding Windows PS GPO key doesn't exist, return null
if (winPowershellGpoKey == null) { return null; }
isAnyPropertySet = TrySetPolicySettingsFromRegistryKey(tInstance, tType, winPowershellGpoKey);
}
}
// If no property is set, then we consider this policy as undefined
return isAnyPropertySet ? (T)tInstance : null;
}
}
/// <summary>
/// Get a specific kind of policy setting from the group policy registry key.
/// </summary>
private static T GetPolicySettingFromGPO<T>(ConfigScope[] preferenceOrder) where T : PolicyBase, new()