forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSecuritySupport.cs
1804 lines (1572 loc) · 67.5 KB
/
SecuritySupport.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. All rights reserved.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
#pragma warning disable 56523
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.Security;
using System.Management.Automation.Configuration;
using System.Management.Automation.Internal;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using DWORD = System.UInt32;
namespace Microsoft.PowerShell
{
/// <summary>
/// Defines the different Execution Policies supported by the
/// PSAuthorizationManager class.
/// </summary>
public enum ExecutionPolicy
{
/// Unrestricted - No files must be signed. If a file originates from the
/// internet, Monad provides a warning prompt to alert the user. To
/// suppress this warning message, right-click on the file in File Explorer,
/// select "Properties," and then "Unblock."
Unrestricted = 0,
/// RemoteSigned - Only .msh and .mshxml files originating from the internet
/// must be digitally signed. If remote, signed, and executed, Monad
/// prompts to determine if files from the signing publisher should be
/// run or not. This is the default setting.
RemoteSigned = 1,
/// AllSigned - All .msh and .mshxml files must be digitally signed. If
/// signed and executed, Monad prompts to determine if files from the
/// signing publisher should be run or not.
AllSigned = 2,
/// Restricted - All .msh files are blocked. Mshxml files must be digitally
/// signed, and by a trusted publisher. If you haven't made a trust decision
/// on the publisher yet, prompting is done as in AllSigned mode.
Restricted = 3,
/// Bypass - No files must be signed, and internet origin is not verified
Bypass = 4,
/// Undefined - Not specified at this scope
Undefined = 5,
/// <summary>
/// Default - The most restrictive policy available.
/// </summary>
Default = Restricted
};
/// <summary>
/// Defines the available configuration scopes for an execution
/// policy. They are in the following priority, with successive
/// elements overriding the items that precede them:
/// LocalMachine -> CurrentUser -> Runspace
/// </summary>
public enum ExecutionPolicyScope
{
/// Execution policy is retrieved from the
/// PSExecutionPolicyPreference environment variable.
Process = 0,
/// Execution policy is retrieved from the HKEY_CURRENT_USER
/// registry hive for the current ShellId.
CurrentUser = 1,
/// Execution policy is retrieved from the HKEY_LOCAL_MACHINE
/// registry hive for the current ShellId.
LocalMachine = 2,
/// Execution policy is retrieved from the current user's
/// group policy setting.
UserPolicy = 3,
/// Execution policy is retrieved from the machine-wide
/// group policy setting.
MachinePolicy = 4
}
}
namespace System.Management.Automation.Internal
{
/// <summary>
/// The SAFER policy associated with this file
/// </summary>
internal enum SaferPolicy
{
/// Explicitly allowed through an Allow rule
ExplicitlyAllowed = 0,
/// Allowed because it has not been explicitly disallowed
Allowed = 1,
/// Disallowed by a rule or policy.
Disallowed = 2
}
/// <summary>
/// Security Support APIs
/// </summary>
public static class SecuritySupport
{
#region execution policy
internal static ExecutionPolicyScope[] ExecutionPolicyScopePreferences
{
get
{
return new ExecutionPolicyScope[] {
ExecutionPolicyScope.MachinePolicy,
ExecutionPolicyScope.UserPolicy,
ExecutionPolicyScope.Process,
ExecutionPolicyScope.CurrentUser,
ExecutionPolicyScope.LocalMachine
};
}
}
internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId)
{
#if UNIX
throw new PlatformNotSupportedException();
#else
string executionPolicy = "Restricted";
switch (policy)
{
case ExecutionPolicy.Restricted:
executionPolicy = "Restricted"; break;
case ExecutionPolicy.AllSigned:
executionPolicy = "AllSigned"; break;
case ExecutionPolicy.RemoteSigned:
executionPolicy = "RemoteSigned"; break;
case ExecutionPolicy.Unrestricted:
executionPolicy = "Unrestricted"; break;
case ExecutionPolicy.Bypass:
executionPolicy = "Bypass"; break;
}
// Set the execution policy
switch (scope)
{
case ExecutionPolicyScope.Process:
{
if (policy == ExecutionPolicy.Undefined)
executionPolicy = null;
Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy);
break;
}
case ExecutionPolicyScope.CurrentUser:
{
// They want to remove it
if (policy == ExecutionPolicy.Undefined)
{
PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId);
}
else
{
PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy);
}
break;
}
case ExecutionPolicyScope.LocalMachine:
{
// They want to remove it
if (policy == ExecutionPolicy.Undefined)
{
PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId);
}
else
{
PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy);
}
break;
}
}
#endif
}
internal static ExecutionPolicy GetExecutionPolicy(string shellId)
{
foreach (ExecutionPolicyScope scope in ExecutionPolicyScopePreferences)
{
ExecutionPolicy policy = GetExecutionPolicy(shellId, scope);
if (policy != ExecutionPolicy.Undefined)
return policy;
}
return ExecutionPolicy.Restricted;
}
private static bool? _hasGpScriptParent;
/// <summary>
/// A value indicating that the current process was launched by GPScript.exe
/// Used to determine execution policy when group policies are in effect
/// </summary>
/// <remarks>
/// This is somewhat expensive to determine and does not change within the lifetime of the current process
/// </remarks>
private static bool HasGpScriptParent
{
get
{
if (!_hasGpScriptParent.HasValue)
{
_hasGpScriptParent = IsCurrentProcessLaunchedByGpScript();
}
return _hasGpScriptParent.Value;
}
}
private static bool IsCurrentProcessLaunchedByGpScript()
{
Process currentProcess = Process.GetCurrentProcess();
string gpScriptPath = IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
"gpscript.exe");
bool foundGpScriptParent = false;
try
{
while (currentProcess != null)
{
if (String.Equals(gpScriptPath,
PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase))
{
foundGpScriptParent = true;
break;
}
else
{
currentProcess = PsUtils.GetParentProcess(currentProcess);
}
}
}
catch (System.ComponentModel.Win32Exception)
{
// If you attempt to retrieve the MainModule of a 64-bit process
// from a WOW64 (32-bit) process, the Win32 API has a fatal
// flaw that causes this to return the error:
// "Only part of a ReadProcessMemory or WriteProcessMemory
// request was completed."
// In this case, we just catch the exception and eat it.
// The implication is that logon / logoff scripts that somehow
// launch the Wow64 version of PowerShell will be subject
// to the execution policy deployed by Group Policy (where
// our goal here is to not have the Group Policy execution policy
// affect logon / logoff scripts.
}
return foundGpScriptParent;
}
internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPolicyScope scope)
{
#if UNIX
return ExecutionPolicy.Unrestricted;
#else
switch (scope)
{
case ExecutionPolicyScope.Process:
{
string policy = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference");
if (!String.IsNullOrEmpty(policy))
return ParseExecutionPolicy(policy);
else
return ExecutionPolicy.Undefined;
}
case ExecutionPolicyScope.CurrentUser:
case ExecutionPolicyScope.LocalMachine:
{
string policy = GetLocalPreferenceValue(shellId, scope);
if (!String.IsNullOrEmpty(policy))
return ParseExecutionPolicy(policy);
else
return ExecutionPolicy.Undefined;
}
// TODO: Group Policy is only supported on Full systems, but !LINUX && CORECLR
// will run there as well, so I don't think we should remove it.
case ExecutionPolicyScope.UserPolicy:
case ExecutionPolicyScope.MachinePolicy:
{
string groupPolicyPreference = GetGroupPolicyValue(shellId, scope);
// Be sure we aren't being called by Group Policy
// itself. A group policy should never block a logon /
// logoff script.
if (String.IsNullOrEmpty(groupPolicyPreference) || HasGpScriptParent)
{
return ExecutionPolicy.Undefined;
}
return ParseExecutionPolicy(groupPolicyPreference);
}
}
return ExecutionPolicy.Restricted;
#endif
}
internal static ExecutionPolicy ParseExecutionPolicy(string policy)
{
if (String.Equals(policy, "Bypass",
StringComparison.OrdinalIgnoreCase))
{
return ExecutionPolicy.Bypass;
}
else if (String.Equals(policy, "Unrestricted",
StringComparison.OrdinalIgnoreCase))
{
return ExecutionPolicy.Unrestricted;
}
else if (String.Equals(policy, "RemoteSigned",
StringComparison.OrdinalIgnoreCase))
{
return ExecutionPolicy.RemoteSigned;
}
else if (String.Equals(policy, "AllSigned",
StringComparison.OrdinalIgnoreCase))
{
return ExecutionPolicy.AllSigned;
}
else if (String.Equals(policy, "Restricted",
StringComparison.OrdinalIgnoreCase))
{
return ExecutionPolicy.Restricted;
}
else
{
return ExecutionPolicy.Default;
}
}
internal static string GetExecutionPolicy(ExecutionPolicy policy)
{
switch (policy)
{
case ExecutionPolicy.Bypass: return "Bypass";
case ExecutionPolicy.Unrestricted: return "Unrestricted";
case ExecutionPolicy.RemoteSigned: return "RemoteSigned";
case ExecutionPolicy.AllSigned: return "AllSigned";
case ExecutionPolicy.Restricted: return "Restricted";
default: return "Restricted";
}
}
/// <summary>
/// Returns true if file has product binary signature
/// </summary>
/// <param name="file">Name of file to check</param>
/// <returns>True when file has product binary signature.</returns>
public static bool IsProductBinary(string file)
{
if (String.IsNullOrEmpty(file) || (!IO.File.Exists(file)))
{
return false;
}
// Check if it is in the product folder, if not, skip checking the catalog
// and any other checks.
var isUnderProductFolder = Utils.IsUnderProductFolder(file);
if (!isUnderProductFolder)
{
return false;
}
#if UNIX
// There is no signature support on non-Windows platforms (yet), when
// execution reaches here, we are sure the file is under product folder
return true;
#else
// Check the file signature
Signature fileSignature = SignatureHelper.GetSignature(file, null);
if ((fileSignature != null) && (fileSignature.IsOSBinary))
{
return true;
}
// WTGetSignatureInfo is used to verify catalog signature.
// On Win7, catalog API is not available.
// On OneCore SKUs like NanoServer/IoT, the API has a bug that makes it not able to find the
// corresponding catalog file for a given product file, so it doesn't work properly.
// In these cases, we just trust the 'isUnderProductFolder' check.
if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value)
{
// When execution reaches here, we are sure the file is under product folder
return true;
}
return false;
#endif
}
/// <summary>
/// Returns the value of the Execution Policy as retrieved
/// from group policy.
/// </summary>
/// <returns>NULL if it is not defined at this level.</returns>
private static string GetGroupPolicyValue(string shellId, ExecutionPolicyScope scope)
{
ConfigScope[] scopeKey = null;
switch (scope)
{
case ExecutionPolicyScope.MachinePolicy:
scopeKey = Utils.SystemWideOnlyConfig;
break;
case ExecutionPolicyScope.UserPolicy:
scopeKey = Utils.CurrentUserOnlyConfig;
break;
}
var scriptExecutionSetting = Utils.GetPolicySetting<ScriptExecution>(scopeKey);
if (scriptExecutionSetting != null)
{
if (scriptExecutionSetting.EnableScripts == false)
{
// Script execution is explicitly disabled
return "Restricted";
}
else if (scriptExecutionSetting.EnableScripts == true)
{
// Script execution is explicitly enabled
return scriptExecutionSetting.ExecutionPolicy;
}
}
return null;
}
/// <summary>
/// Returns the value of the Execution Policy as retrieved
/// from the local preference.
/// </summary>
/// <returns>NULL if it is not defined at this level.</returns>
private static string GetLocalPreferenceValue(string shellId, ExecutionPolicyScope scope)
{
switch (scope)
{
// 1: Look up the current-user preference
case ExecutionPolicyScope.CurrentUser:
return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.CurrentUser, shellId);
// 2: Look up the system-wide preference
case ExecutionPolicyScope.LocalMachine:
return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.AllUsers, shellId);
}
return null;
}
#endregion execution policy
private static bool _saferIdentifyLevelApiSupported = true;
/// <summary>
/// Get the pass / fail result of calling the SAFER API
/// </summary>
/// <param name="path">The path to the file in question</param>
/// <param name="handle">A file handle to the file in question, if available.</param>
[ArchitectureSensitive]
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle)
{
SaferPolicy status = SaferPolicy.Allowed;
if (!_saferIdentifyLevelApiSupported)
{
return status;
}
SAFER_CODE_PROPERTIES codeProperties = new SAFER_CODE_PROPERTIES();
IntPtr hAuthzLevel;
// Prepare the code properties struct.
codeProperties.cbSize = (uint)Marshal.SizeOf(typeof(SAFER_CODE_PROPERTIES));
codeProperties.dwCheckFlags = (
NativeConstants.SAFER_CRITERIA_IMAGEPATH |
NativeConstants.SAFER_CRITERIA_IMAGEHASH |
NativeConstants.SAFER_CRITERIA_AUTHENTICODE);
codeProperties.ImagePath = path;
if (handle != null)
{
codeProperties.hImageFileHandle = handle.DangerousGetHandle();
}
// turn off WinVerifyTrust UI
codeProperties.dwWVTUIChoice = NativeConstants.WTD_UI_NONE;
// Identify the level associated with the code
if (NativeMethods.SaferIdentifyLevel(1, ref codeProperties, out hAuthzLevel, NativeConstants.SRP_POLICY_SCRIPT))
{
// We found an Authorization Level applicable to this application.
IntPtr hRestrictedToken = IntPtr.Zero;
try
{
if (!NativeMethods.SaferComputeTokenFromLevel(
hAuthzLevel, // Safer Level
IntPtr.Zero, // Test current process' token
ref hRestrictedToken, // target token
NativeConstants.SAFER_TOKEN_NULL_IF_EQUAL,
IntPtr.Zero))
{
int lastError = Marshal.GetLastWin32Error();
if ((lastError == NativeConstants.ERROR_ACCESS_DISABLED_BY_POLICY) ||
(lastError == NativeConstants.ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY))
{
status = SaferPolicy.Disallowed;
}
else
{
throw new System.ComponentModel.Win32Exception();
}
}
else
{
if (hRestrictedToken == IntPtr.Zero)
{
// This is not necessarily the "fully trusted" level,
// it means that the thread token is complies with the requested level
status = SaferPolicy.Allowed;
}
else
{
status = SaferPolicy.Disallowed;
NativeMethods.CloseHandle(hRestrictedToken);
}
}
}
finally
{
NativeMethods.SaferCloseLevel(hAuthzLevel);
}
}
else
{
int lastError = Marshal.GetLastWin32Error();
if (lastError == NativeConstants.FUNCTION_NOT_SUPPORTED)
{
_saferIdentifyLevelApiSupported = false;
}
else
{
throw new System.ComponentModel.Win32Exception(lastError);
}
}
return status;
}
/// <summary>
/// throw if file does not exist
/// </summary>
/// <param name="filePath"> path to file </param>
/// <returns>Does not return a value.</returns>
internal static void CheckIfFileExists(string filePath)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
}
/// <summary>
/// check to see if the specified cert is suitable to be
/// used as a code signing cert
/// </summary>
/// <param name="c"> certificate object </param>
/// <returns>True on success, false otherwise.</returns>
internal static bool CertIsGoodForSigning(X509Certificate2 c)
{
if (!CertHasPrivatekey(c))
{
return false;
}
return CertHasOid(c, CertificateFilterInfo.CodeSigningOid);
}
/// <summary>
/// check to see if the specified cert is suitable to be
/// used as an encryption cert for PKI encryption. Note
/// that this cert doesn't require the private key.
/// </summary>
/// <param name="c"> certificate object </param>
/// <returns>True on success, false otherwise.</returns>
internal static bool CertIsGoodForEncryption(X509Certificate2 c)
{
return (
CertHasOid(c, CertificateFilterInfo.DocumentEncryptionOid) &&
(CertHasKeyUsage(c, X509KeyUsageFlags.DataEncipherment) ||
CertHasKeyUsage(c, X509KeyUsageFlags.KeyEncipherment)));
}
private static bool CertHasOid(X509Certificate2 c, string oid)
{
Collection<string> ekus = GetCertEKU(c);
foreach (string testOid in ekus)
{
if (testOid == oid)
{
return true;
}
}
return false;
}
private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsage)
{
foreach (X509Extension extension in c.Extensions)
{
X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension;
if (keyUsageExtension != null)
{
if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage)
{
return true;
}
break;
}
}
return false;
}
/// <summary>
/// check if the specified cert has a private key in it
/// </summary>
/// <param name="cert"> certificate object </param>
/// <returns>True on success, false otherwise.</returns>
internal static bool CertHasPrivatekey(X509Certificate2 cert)
{
return cert.HasPrivateKey;
}
/// <summary>
/// Get the EKUs of a cert
/// </summary>
/// <param name="cert"> certificate object </param>
/// <returns>A collection of cert eku strings.</returns>
[ArchitectureSensitive]
internal static Collection<string> GetCertEKU(X509Certificate2 cert)
{
Collection<string> ekus = new Collection<string>();
IntPtr pCert = cert.Handle;
int structSize = 0;
IntPtr dummy = IntPtr.Zero;
if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0, dummy,
out structSize))
{
if (structSize > 0)
{
IntPtr ekuBuffer = Marshal.AllocHGlobal(structSize);
try
{
if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0,
ekuBuffer,
out structSize))
{
Security.NativeMethods.CERT_ENHKEY_USAGE ekuStruct =
(Security.NativeMethods.CERT_ENHKEY_USAGE)
Marshal.PtrToStructure<Security.NativeMethods.CERT_ENHKEY_USAGE>(ekuBuffer);
IntPtr ep = ekuStruct.rgpszUsageIdentifier;
IntPtr ekuptr;
for (int i = 0; i < ekuStruct.cUsageIdentifier; i++)
{
ekuptr = Marshal.ReadIntPtr(ep, i * Marshal.SizeOf(ep));
string eku = Marshal.PtrToStringAnsi(ekuptr);
ekus.Add(eku);
}
}
else
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
Marshal.FreeHGlobal(ekuBuffer);
}
}
}
else
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
return ekus;
}
/// <summary>
/// convert an int to a DWORD
/// </summary>
/// <param name="n"> signed int number </param>
/// <returns>DWORD.</returns>
internal static DWORD GetDWORDFromInt(int n)
{
UInt32 result = BitConverter.ToUInt32(BitConverter.GetBytes(n), 0);
return (DWORD)result;
}
/// <summary>
/// convert a DWORD to int
/// </summary>
/// <param name="n"> number </param>
/// <returns>Int.</returns>
internal static int GetIntFromDWORD(DWORD n)
{
Int64 n64 = n - 0x100000000L;
return (int)n64;
}
}
/// <summary>
/// information used for filtering a set of certs
/// </summary>
internal sealed class CertificateFilterInfo
{
internal CertificateFilterInfo()
{
}
/// <summary>
/// purpose of a certificate
/// </summary>
internal CertificatePurpose Purpose
{
get { return _purpose; }
set { _purpose = value; }
}
/// <summary>
/// SSL Server Authentication
/// </summary>
internal bool SSLServerAuthentication
{
get { return _sslServerAuthentication; }
set { _sslServerAuthentication = value; }
}
/// <summary>
/// DNS name of a certificate
/// </summary>
internal string DnsName
{
set { _dnsName = value; }
}
/// <summary>
/// EKU OID list of a certificate
/// </summary>
internal string[] Eku
{
set { _eku = value; }
}
/// <summary>
/// remaining validity period in days for a certificate
/// </summary>
internal int ExpiringInDays
{
set { _expiringInDays = value; }
}
/// <summary>
/// combine properties into a filter string
/// </summary>
internal string FilterString
{
get
{
string filterString = string.Empty;
if (_dnsName != null)
{
filterString = AppendFilter(filterString, "dns", _dnsName);
}
string ekuT = string.Empty;
if (_eku != null)
{
for (int i = 0; i < _eku.Length; i++)
{
if (ekuT.Length != 0)
{
ekuT = ekuT + ",";
}
ekuT = ekuT + _eku[i];
}
}
if (_purpose == CertificatePurpose.CodeSigning)
{
if (ekuT.Length != 0)
{
ekuT = ekuT + ",";
}
ekuT = ekuT + CodeSigningOid;
}
if (_purpose == CertificatePurpose.DocumentEncryption)
{
if (ekuT.Length != 0)
{
ekuT = ekuT + ",";
}
ekuT = ekuT + DocumentEncryptionOid;
}
if (_sslServerAuthentication)
{
if (ekuT.Length != 0)
{
ekuT = ekuT + ",";
}
ekuT = ekuT + szOID_PKIX_KP_SERVER_AUTH;
}
if (ekuT.Length != 0)
{
filterString = AppendFilter(filterString, "eku", ekuT);
if (_purpose == CertificatePurpose.CodeSigning ||
_sslServerAuthentication)
{
filterString = AppendFilter(filterString, "key", "*");
}
}
if (_expiringInDays >= 0)
{
filterString = AppendFilter(
filterString,
"ExpiringInDays",
_expiringInDays.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
if (filterString.Length == 0)
{
filterString = null;
}
return filterString;
}
}
private string AppendFilter(
string filterString,
string name,
string value)
{
string newfilter = value;
// append a "name=value" filter to the existing filter string.
// insert a separating "&" if existing filter string is not empty.
// if the value is empty, do nothing.
if (newfilter.Length != 0)
{
// if the value contains an equal sign or an ampersand, throw
// an exception to avoid compromising the native code parser.
if (newfilter.Contains("=") || newfilter.Contains("&"))
{
throw Marshal.GetExceptionForHR(
Security.NativeMethods.E_INVALID_DATA);
}
newfilter = name + "=" + newfilter;
if (filterString.Length != 0)
{
newfilter = "&" + newfilter;
}
}
return filterString + newfilter;
}
private CertificatePurpose _purpose = 0;
private bool _sslServerAuthentication = false;
private string _dnsName = null;
private string[] _eku = null;
private int _expiringInDays = -1;
internal const string CodeSigningOid = "1.3.6.1.5.5.7.3.3";
internal const string szOID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1";
// The OID arc 1.3.6.1.4.1.311.80 is assigned to PowerShell. If we need
// new OIDs, we can assign them under this branch.
internal const string DocumentEncryptionOid = "1.3.6.1.4.1.311.80.1";
}
}
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the valid purposes by which
/// we can filter certificates.
/// </summary>
internal enum CertificatePurpose
{
/// <summary>
/// Certificates where a purpose has not been specified.
/// </summary>
NotSpecified = 0,
/// <summary>
/// Certificates that can be used to sign
/// code and scripts.
/// </summary>
CodeSigning = 0x1,
/// <summary>
/// Certificates that can be used to encrypt
/// data.
/// </summary>
DocumentEncryption = 0x2,
/// <summary>
/// Certificates that can be used for any
/// purpose.
/// </summary>
All = 0xffff
}
}
namespace System.Management.Automation
{
using System.Security.Cryptography.Pkcs;
/// <summary>
/// Utility class for CMS (Cryptographic Message Syntax) related operations
/// </summary>
internal static class CmsUtils
{
internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipients, SessionState sessionState, out ErrorRecord error)
{
error = null;
if ((contentBytes == null) || (contentBytes.Length == 0))
{
return String.Empty;
}
// After review with the crypto board, NIST_AES256_CBC is more appropriate
// than .NET's default 3DES. Also, when specified, uses szOID_RSAES_OAEP for key
// encryption to prevent padding attacks.
const string szOID_NIST_AES256_CBC = "2.16.840.1.101.3.4.1.42";
ContentInfo content = new ContentInfo(contentBytes);
EnvelopedCms cms = new EnvelopedCms(content,
new AlgorithmIdentifier(
Oid.FromOidValue(szOID_NIST_AES256_CBC, OidGroup.EncryptionAlgorithm)));
CmsRecipientCollection recipientCollection = new CmsRecipientCollection();
foreach (CmsMessageRecipient recipient in recipients)
{
// Resolve the recipient, if it hasn't been done yet.
if ((recipient.Certificates != null) && (recipient.Certificates.Count == 0))