forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCertificateProvider.cs
3453 lines (3033 loc) · 123 KB
/
CertificateProvider.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.
#if !UNIX
using System;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using Runspaces = System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation;
using Security = System.Management.Automation.Security;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections;
using System.Runtime.InteropServices;
using System.Management.Automation.Provider;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Xml;
using System.Xml.XPath;
using System.Security;
using DWORD = System.UInt32;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the Certificate Provider dynamic parameters.
///
/// We only support one dynamic parameter for Win 7 and earlier:
/// CodeSigningCert
/// If provided, we only return certificates valid for signing code or
/// scripts.
/// </summary>
internal sealed class CertificateProviderCodeSigningDynamicParameters
{
/// <summary>
/// switch that controls whether we only return
/// code signing certs.
/// </summary>
[Parameter()]
public SwitchParameter CodeSigningCert
{
get { return _codeSigningCert; }
set { _codeSigningCert = value; }
}
private SwitchParameter _codeSigningCert = new SwitchParameter();
}
/// <summary>
/// Defines the type of DNS string
/// The structure contains punycode name and unicode name
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
public struct DnsNameRepresentation
{
/// <summary>
/// punycode version of DNS name
/// </summary>
private string _punycodeName;
/// <summary>
/// Unicode version of DNS name
/// </summary>
private string _unicodeName;
/// <summary>
/// ambiguous constructor of a DnsNameRepresentation
/// </summary>
public DnsNameRepresentation(string inputDnsName)
{
_punycodeName = inputDnsName;
_unicodeName = inputDnsName;
}
/// <summary>
/// specific constructor of a DnsNameRepresentation
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")]
public DnsNameRepresentation(
string inputPunycodeName,
string inputUnicodeName)
{
_punycodeName = inputPunycodeName;
_unicodeName = inputUnicodeName;
}
/// <summary>
/// value comparison
/// </summary>
public bool Equals(DnsNameRepresentation dnsName)
{
bool match = false;
if (_unicodeName != null && dnsName._unicodeName != null)
{
if (String.Equals(
_unicodeName,
dnsName._unicodeName,
StringComparison.OrdinalIgnoreCase))
{
match = true;
}
}
else if (_unicodeName == null && dnsName._unicodeName == null)
{
match = true;
}
return match;
}
/// <summary>
/// get property of Punycode
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Punycode")]
public string Punycode
{
get
{
return _punycodeName;
}
}
/// <summary>
/// get property of Unicode
/// </summary>
public string Unicode
{
get
{
return _unicodeName;
}
}
/// <summary>
/// get display string
/// </summary>
public override string ToString()
{
// Use case sensitive comparison here.
// We don't ever expect to see the punycode and unicode strings
// to differ only by upper/lower case. If they do, that's really
// a code bug, and the effect is to just display both strings.
return String.Equals(_punycodeName, _unicodeName) ?
_punycodeName :
_unicodeName + " (" + _punycodeName + ")";
}
}
/// <summary>
/// Defines the Certificate Provider remove-item dynamic parameters.
///
/// Currently, we only support one dynamic parameter: DeleteKey
/// If provided, we will delete the private key when we remove a certificate
/// </summary>
internal sealed class ProviderRemoveItemDynamicParameters
{
/// <summary>
/// switch that controls whether we should delete private key
/// when remove a certificate
/// </summary>
[Parameter()]
public SwitchParameter DeleteKey
{
get
{
{
return _deleteKey;
}
}
set
{
{
_deleteKey = value;
}
}
}
private SwitchParameter _deleteKey = new SwitchParameter();
}
/// <summary>
/// Defines the safe handle class for native cert store handles,
/// HCERTSTORE.
/// </summary>
internal sealed class CertificateStoreHandle : SafeHandle
{
public CertificateStoreHandle() : base(IntPtr.Zero, true)
{
return;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle()
{
bool fResult = false;
if (IntPtr.Zero != handle)
{
fResult = Security.NativeMethods.CertCloseStore(handle, 0);
handle = IntPtr.Zero;
}
return fResult;
}
public IntPtr Handle
{
get { return handle; }
set { handle = value; }
}
}
/// <summary>
/// Defines the Certificate Provider store handle class
/// </summary>
internal sealed class X509NativeStore
{
//#region tracer
/// <summary>
/// Initializes a new instance of the X509NativeStore class.
/// </summary>
public X509NativeStore(X509StoreLocation StoreLocation, string StoreName)
{
_storeLocation = StoreLocation;
_storeName = StoreName;
}
public void Open(bool includeArchivedCerts)
{
if (_storeHandle != null && _archivedCerts != includeArchivedCerts)
{
_storeHandle = null; // release the old handle
}
if (_storeHandle == null)
{
_valid = false;
_open = false;
Security.NativeMethods.CertOpenStoreFlags StoreFlags =
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_STORE_FLAG |
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_CONTEXT_FLAG |
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG |
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG;
if (includeArchivedCerts)
{
StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG;
}
switch (_storeLocation.Location)
{
case StoreLocation.LocalMachine:
StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;
break;
case StoreLocation.CurrentUser:
StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER;
break;
default:
//ThrowItemNotFound(storeLocation.ToString(), CertificateProviderItem.StoreLocation);
break;
}
IntPtr hCertStore = Security.NativeMethods.CertOpenStore(
Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM,
Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
IntPtr.Zero, // hCryptProv
StoreFlags,
_storeName);
if (IntPtr.Zero == hCertStore)
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
_storeHandle = new CertificateStoreHandle();
_storeHandle.Handle = hCertStore;
//we only do CertControlStore for stores other than UserDS
if (!String.Equals(
_storeName,
"UserDS",
StringComparison.OrdinalIgnoreCase))
{
if (!Security.NativeMethods.CertControlStore(
_storeHandle.Handle,
0,
Security.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC,
IntPtr.Zero))
{
_storeHandle = null;
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
}
_valid = true;
_open = true;
_archivedCerts = includeArchivedCerts;
}
}
public IntPtr GetFirstCert()
{
return GetNextCert(IntPtr.Zero);
}
public IntPtr GetNextCert(IntPtr certContext)
{
if (!_open)
{
throw Marshal.GetExceptionForHR(
Security.NativeMethods.CRYPT_E_NOT_FOUND);
}
if (Valid)
{
certContext = Security.NativeMethods.CertEnumCertificatesInStore(
_storeHandle.Handle,
certContext);
}
else
{
certContext = IntPtr.Zero;
}
return certContext;
}
public IntPtr GetCertByName(string Name)
{
IntPtr certContext = IntPtr.Zero;
if (!_open)
{
throw Marshal.GetExceptionForHR(
Security.NativeMethods.CRYPT_E_NOT_FOUND);
}
if (Valid)
{
if (DownLevelHelper.HashLookupSupported())
{
certContext = Security.NativeMethods.CertFindCertificateInStore(
_storeHandle.Handle,
Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
0, // dwFindFlags
Security.NativeMethods.CertFindType.CERT_FIND_HASH_STR,
Name,
IntPtr.Zero); // pPrevCertContext
}
else
{
//
// the pre-Win8 CAPI2 code does not provide an easy way
// to directly access a specific certificate.
// We have to iterate through all certs to find
// what we want.
//
while (true)
{
certContext = GetNextCert(certContext);
if (IntPtr.Zero == certContext)
{
break;
}
X509Certificate2 cert = new X509Certificate2(certContext);
if (String.Equals(
cert.Thumbprint,
Name,
StringComparison.OrdinalIgnoreCase))
{
break;
}
}
}
}
return certContext;
}
public void FreeCert(IntPtr certContext)
{
Security.NativeMethods.CertFreeCertificateContext(certContext);
}
/// <summary>
/// native IntPtr store handle
/// </summary>
public IntPtr StoreHandle
{
get
{
return _storeHandle.Handle;
}
}
/// <summary>
/// X509StoreLocation store location
/// </summary>
public X509StoreLocation Location
{
get
{
return _storeLocation;
}
}
/// <summary>
/// string store name
/// </summary>
public string StoreName
{
get
{
return _storeName;
}
}
/// <summary>
/// true if a real store is open
/// </summary>
public bool Valid
{
get
{
return _valid;
}
}
private bool _archivedCerts = false;
private X509StoreLocation _storeLocation = null;
private string _storeName = null;
private CertificateStoreHandle _storeHandle = null;
private bool _valid = false;
private bool _open = false;
}
/// <summary>
/// Defines the types of items
/// supported by the certificate provider.
/// </summary>
internal enum CertificateProviderItem
{
/// <summary>
/// An unknown item.
/// </summary>
Unknown,
/// <summary>
/// An X509 Certificate.
/// </summary>
Certificate,
/// <summary>
/// A certificate store location.
/// For example, cert:\CurrentUser
/// </summary>
Store,
/// <summary>
/// A certificate store.
/// For example, cert:\CurrentUser\My
/// </summary>
StoreLocation
}
/// <summary>
/// Defines the implementation of a Certificate Store Provider. This provider
/// allows for stateless namespace navigation of the computer's certificate
/// store.
/// </summary>
[CmdletProvider("Certificate", ProviderCapabilities.ShouldProcess)]
[OutputType(typeof(String), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)]
[OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)]
[OutputType(typeof(Microsoft.PowerShell.Commands.X509StoreLocation), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(X509Store), typeof(X509Certificate2), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp
{
#region tracer
/// <summary>
/// tracer for certificate provider
/// </summary>
[TraceSource("CertificateProvider",
"The core command provider for certificates")]
private readonly static PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider",
"The core command provider for certificates");
#endregion tracer
/// <summary>
/// Indicate if we already have attempted to load the PKI module
/// </summary>
private bool _hasAttemptedToLoadPkiModule = false;
/// <summary>
/// lock that guards access to the following static members
/// -- storeLocations
/// -- pathCache
/// </summary>
private static object s_staticLock = new object();
/// <summary>
/// list of store locations. They do not change once initialized.
///
/// Synchronized on staticLock
/// </summary>
private static List<X509StoreLocation> s_storeLocations = null;
/// <summary>
/// cache that stores paths and their associated objects.
///
/// key is full path to store-location/store/certificate
/// value is X509StoreLocation/X509NativeStore/X509Certificate2 object
///
/// Synchronized on staticLock
/// </summary>
private static Hashtable s_pathCache = null;
/// <summary>
/// we allow either / or \ to be the path separator
/// </summary>
private static readonly char[] s_pathSeparators = new char[] { '/', '\\' };
/// <summary>
/// regex pattern that defines a valid cert path
/// </summary>
private const string certPathPattern = @"^\\((?<StoreLocation>CurrentUser|LocalMachine)(\\(?<StoreName>[a-zA-Z]+)(\\(?<Thumbprint>[0-9a-f]{40}))?)?)?$";
/// <summary>
/// Cache the store handle to avoid repeated CertOpenStore calls.
/// </summary>
private static X509NativeStore s_storeCache = null;
/// <summary>
/// On demand create the Regex to avoid a hit to startup perf.
/// </summary>
/// <remarks>
/// Note, its OK that staticLock is being used here because only
/// IsValidPath is calling this static property so we shouldn't
/// have any deadlocks due to other locked static members calling
/// this property.
/// </remarks>
private static Regex s_certPathRegex = null;
private static Regex CertPathRegex
{
get
{
lock (s_staticLock)
{
if (s_certPathRegex == null)
{
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
s_certPathRegex = new Regex(certPathPattern, options);
}
}
return s_certPathRegex;
}
}
/// <summary>
/// Initializes a new instance of the CertificateProvider class.
/// This initializes the default certificate store locations.
/// </summary>
public CertificateProvider()
{
//
// initialize storeLocations list and also update the cache
//
lock (s_staticLock)
{
if (s_storeLocations == null)
{
s_pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase);
s_storeLocations =
new List<X509StoreLocation>();
//
// create and cache CurrentUser store-location
//
X509StoreLocation user =
new X509StoreLocation(StoreLocation.CurrentUser);
s_storeLocations.Add(user);
AddItemToCache(StoreLocation.CurrentUser.ToString(),
user);
//
// create and cache LocalMachine store-location
//
X509StoreLocation machine =
new X509StoreLocation(StoreLocation.LocalMachine);
s_storeLocations.Add(machine);
AddItemToCache(StoreLocation.LocalMachine.ToString(),
machine);
AddItemToCache(string.Empty, s_storeLocations);
}
}
}
/// <summary>
/// Removes an item at the specified path
/// </summary>
/// <param name="path">
/// The path of the item to remove.
/// </param>
/// <param name="recurse">
/// Recursively remove.
/// </param>
/// <returns>
/// Nothing.
/// </returns>
/// <exception cref="System.ArgumentException">
/// path is null or empty.
/// destination is null or empty.
/// </exception>
protected override void RemoveItem(
string path,
bool recurse)
{
path = NormalizePath(path);
bool isContainer = false;
bool fDeleteKey = false;
object outObj = GetItemAtPath(path, false, out isContainer);
string[] pathElements = GetPathElements(path);
bool fUserContext = String.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);
// isContainer = true means not a valid certificate
// if source store is user root store and UI is not allowed
// we raise invalid operation
if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero && fUserContext &&
String.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))
{
string message = CertificateProviderStrings.UINotAllowed;
string errorId = "UINotAllowed";
ThrowInvalidOperation(errorId, message);
}
if (DynamicParameters != null)
{
ProviderRemoveItemDynamicParameters dp =
DynamicParameters as ProviderRemoveItemDynamicParameters;
if (dp != null)
{
if (dp.DeleteKey)
{
fDeleteKey = true;
}
}
}
if (isContainer)
{
if (pathElements.Length == 2) //is a store
{
//not support user context
if (fUserContext)
{
string message = CertificateProviderStrings.CannotDeleteUserStore;
string errorId = "CannotDeleteUserStore";
ThrowInvalidOperation(errorId, message);
}
RemoveCertStore(pathElements[1], fDeleteKey, path);
return;
}
else //other container than a store
{
string message = CertificateProviderStrings.CannotRemoveContainer;
string errorId = "CannotRemoveContainer";
ThrowInvalidOperation(errorId, message);
}
}
else //certificate
{
//do remove
X509Certificate2 certificate = outObj as X509Certificate2;
RemoveCertItem(certificate, fDeleteKey, !fUserContext, path);
return;
}
}
/// <summary>
/// Gets the dynamic parameters for remove-item on the Certificate
/// Provider. We currently only support one dynamic parameter,
/// "DeleteKey," that delete private key when we delete a certificate.
/// </summary>
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item for which to get the dynamic parameters.
/// </param>
/// <param name="recurse">
/// Ignored.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
protected override object RemoveItemDynamicParameters(string path, bool recurse)
{
return new ProviderRemoveItemDynamicParameters();
}
/// <summary>
/// Moves an item at the specified path to the given destination.
/// </summary>
/// <param name="path">
/// The path of the item to move.
/// </param>
/// <param name="destination">
/// The path of the destination.
/// </param>
/// <returns>
/// Nothing. Moved items are written to the context's pipeline.
/// </returns>
/// <exception cref="System.ArgumentException">
/// path is null or empty.
/// destination is null or empty.
/// </exception>
protected override void MoveItem(
string path,
string destination)
{
//normalize path
path = NormalizePath(path);
destination = NormalizePath(destination);
//get elements from the path
string[] pathElements = GetPathElements(path);
string[] destElements = GetPathElements(destination);
bool isContainer = false;
object cert = GetItemAtPath(path, false, out isContainer);
//
// isContainer = true; means an invalid path
//
if (isContainer)
{
string message = CertificateProviderStrings.CannotMoveContainer;
string errorId = "CannotMoveContainer";
ThrowInvalidOperation(errorId, message);
}
if (destElements.Length != 2) //not a store
{
//if the destination leads to the same thumbprint
if (destElements.Length == 3 &&
(String.Equals(pathElements[2], destElements[2], StringComparison.OrdinalIgnoreCase)))
{
//in this case we think of destination path as valid
//and strip the thumbprint part
destination = Path.GetDirectoryName(destination);
}
else
{
string message = CertificateProviderStrings.InvalidDestStore;
string errorId = "InvalidDestStore";
ThrowInvalidOperation(errorId, message);
}
}
//the second element is store location
//we do not allow cross context move
//we do not allow the destination store is the same as source
if (!String.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase))
{
string message = CertificateProviderStrings.CannotMoveCrossContext;
string errorId = "CannotMoveCrossContext";
ThrowInvalidOperation(errorId, message);
}
if (String.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase))
{
string message = CertificateProviderStrings.CannotMoveToSameStore;
string errorId = "CannotMoveToSameStore";
ThrowInvalidOperation(errorId, message);
}
// if source or destination store is user root store and UI is not allowed
// we raise invalid operation
if (DetectUIHelper.GetOwnerWindow(Host) == IntPtr.Zero)
{
if ((String.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) &&
String.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) ||
(String.Equals(destElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase) &&
String.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)))
{
string message = CertificateProviderStrings.UINotAllowed;
string errorId = "UINotAllowed";
ThrowInvalidOperation(errorId, message);
}
}
if (cert != null) //we get cert
{
//get destination store
bool isDestContainer = false;
object store = GetItemAtPath(destination, false, out isDestContainer);
X509Certificate2 certificate = cert as X509Certificate2;
X509NativeStore certstore = store as X509NativeStore;
if (certstore != null)
{
certstore.Open(true);
string action = CertificateProviderStrings.Action_Move;
string resource = String.Format(
CultureInfo.CurrentCulture,
CertificateProviderStrings.MoveItemTemplate,
path,
destination);
if (ShouldProcess(resource, action))
{
DoMove(destination, certificate, certstore, path);
}
}
}
else
{
ThrowItemNotFound(path, CertificateProviderItem.Certificate);
}
}
/// <summary>
/// Creates a certificate store with the given path.
/// </summary>
/// <remarks>
/// New-Item doesn't go through the method "ItemExists". But for the
/// CertificateProvider, New-Item can create an X509Store and return
/// it, and the user can access the certificates within the store via its
/// property "Certificates". We want the extra new properties of the
/// X509Certificate2 objects to be shown to the user, so we also need
/// to import the PKI module in this method, if we haven't tried it yet.
/// </remarks>
/// <param name="path">
/// The path of the certificate store to create.
/// </param>
///<param name="type">
/// Ignored.
/// Only support store.
/// </param>
/// <param name="value">
/// Ignored
/// </param>
/// <returns>
/// Nothing. The new certificate store object is
/// written to the context's pipeline.
/// </returns>
/// <exception cref="System.ArgumentException">
/// path is null or empty.
/// </exception>
protected override void NewItem(
string path,
string type,
object value)
{
if (!_hasAttemptedToLoadPkiModule)
{
// Attempt to load the PKI module if we haven't tried yet
AttemptToImportPkiModule();
}
path = NormalizePath(path);
//get the elements from the path
string[] pathElements = GetPathElements(path);
//only support creating store
if (pathElements.Length != 2)
{
string message = CertificateProviderStrings.CannotCreateItem;
string errorId = "CannotCreateItem";
ThrowInvalidOperation(errorId, message);
}
bool fUserContext = String.Equals(pathElements[0], "CurrentUser", StringComparison.OrdinalIgnoreCase);
//not support user context
if (fUserContext)
{
string message = CertificateProviderStrings.CannotCreateUserStore;
string errorId = "CannotCreateUserStore";
ThrowInvalidOperation(errorId, message);
}
Security.NativeMethods.CertOpenStoreFlags StoreFlags =
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG |
Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG |
Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;
//Create new store
IntPtr hCertStore = Security.NativeMethods.CertOpenStore(
Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM,
Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING,
IntPtr.Zero, // hCryptProv
StoreFlags,
pathElements[1]);
if (IntPtr.Zero == hCertStore)
{
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
}
else //free native store handle
{
bool fResult = false;
fResult = Security.NativeMethods.CertCloseStore(hCertStore, 0);
}
X509Store outStore = new X509Store(
pathElements[1],
StoreLocation.LocalMachine);
WriteItemObject(outStore, path, true);
}
#region DriveCmdletProvider overrides
/// <summary>
/// Initializes the cert: drive.
/// </summary>
/// <returns>
/// A collection that contains the PSDriveInfo object
/// that represents the cert: drive.
/// </returns>
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
string providerDescription = CertificateProviderStrings.CertProvidername;
PSDriveInfo drive =
new PSDriveInfo(
"Cert", // drive name
ProviderInfo,// provider name
@"\", // root path
providerDescription,
null);
Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>();
drives.Add(drive);
return drives;
}
/// <summary>
/// Determines if the item at the given path is a store-location
/// or store with items in it.
/// </summary>
/// <param name="path">
/// The full path to the item.
/// </param>
/// <returns>
/// True if the path refers to a store location, or store that contains
/// certificates. False otherwise.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// Path is null
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">
/// This exception can be thrown if any cryptographic error occurs.
/// It is not possible to know exactly what went wrong.
/// This is because of the way CryptographicException is designed.
/// Some example reasons include:
/// -- certificate is invalid
/// -- certificate has no private key
/// -- certificate password mismatch
/// </exception>
protected override bool HasChildItems(string path)
{
bool result = false;
Utils.CheckArgForNull(path, "path");