-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathCommands.ps1
2567 lines (2125 loc) · 77.3 KB
/
Commands.ps1
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
if ($PSVersionTable.PSVersion.Major -eq 2)
{
$IgnoreError = 'SilentlyContinue'
}
else
{
$IgnoreError = 'Ignore'
}
$script:ValidTypes = @(
[string]
[System.Security.SecureString]
[System.Management.Automation.PSCredential]
[byte[]]
)
$script:PSCredentialHeader = [byte[]](5,12,19,75,80,20,19,11,11,6,11,13)
$script:EccAlgorithmOid = '1.2.840.10045.2.1'
#region Exported functions
function Protect-Data
{
<#
.Synopsis
Encrypts an object using one or more digital certificates and/or passwords.
.DESCRIPTION
Encrypts an object using a randomly-generated AES key. AES key information is encrypted using one or more certificate public keys and/or password-derived keys, allowing the data to be securely shared among multiple users and computers.
If certificates are used, they must be installed in either the local computer or local user's certificate stores, and the certificates' Key Usage extension must allow Key Encipherment (for RSA) or Key Agreement (for ECDH). The private keys are not required for Protect-Data.
.PARAMETER InputObject
The object that is to be encrypted. The object must be of one of the types returned by the Get-ProtectedDataSupportedTypes command.
.PARAMETER Certificate
Zero or more RSA or ECDH certificates that should be used to encrypt the data. The data can later be decrypted by using the same certificate (with its private key.) You can pass an X509Certificate2 object to this parameter, or you can pass in a string which contains either a path to a certificate file on the file system, a path to the certificate in the Certificate provider, or a certificate thumbprint (in which case the certificate provider will be searched to find the certificate.)
.PARAMETER UseLegacyPadding
Optional switch specifying that when performing certificate-based encryption, PKCS#1 v1.5 padding should be used instead of the newer, more secure OAEP padding scheme. Some certificates may not work properly with OAEP padding
.PARAMETER Password
Zero or more SecureString objects containing password that will be used to derive encryption keys. The data can later be decrypted by passing in a SecureString with the same value.
.PARAMETER SkipCertificateVerification
Deprecated parameter, which will be removed in a future release. Specifying this switch will generate a warning.
.PARAMETER PasswordIterationCount
Optional positive integer value specifying the number of iteration that should be used when deriving encryption keys from the specified password(s). Defaults to 50000.
Higher values make it more costly to crack the passwords by brute force.
.EXAMPLE
$encryptedObject = Protect-Data -InputObject $myString -CertificateThumbprint CB04E7C885BEAE441B39BC843C85855D97785D25 -Password (Read-Host -AsSecureString -Prompt 'Enter password to encrypt')
Encrypts a string using a single RSA or ECDH certificate, and a password. Either the certificate or the password can be used when decrypting the data.
.EXAMPLE
$credential | Protect-Data -CertificateThumbprint 'CB04E7C885BEAE441B39BC843C85855D97785D25', 'B5A04AB031C24BCEE220D6F9F99B6F5D376753FB'
Encrypts a PSCredential object using two RSA or ECDH certificates. Either private key can be used to later decrypt the data.
.INPUTS
Object
Object must be one of the types returned by the Get-ProtectedDataSupportedTypes command.
.OUTPUTS
PSObject
The output object contains the following properties:
CipherText : An array of bytes containing the encrypted data
Type : A string representation of the InputObject's original type (used when decrypting back to the original object later.)
KeyData : One or more structures which contain encrypted copies of the AES key used to protect the ciphertext, and other identifying information about the way this copy of the keys was protected, such as Certificate Thumbprint, Password Hash, Salt values, and Iteration count.
.LINK
Unprotect-Data
.LINK
Add-ProtectedDataCredential
.LINK
Remove-ProtectedDataCredential
.LINK
Get-ProtectedDataSupportedTypes
#>
[CmdletBinding()]
[OutputType([psobject])]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateScript({
if ($script:ValidTypes -notcontains $_.GetType() -and $null -eq ($_ -as [byte[]]))
{
throw "InputObject must be one of the following types: $($script:ValidTypes -join ', ')"
}
if ($_ -is [System.Security.SecureString] -and $_.Length -eq 0)
{
throw 'SecureString argument contained no data.'
}
return $true
})]
$InputObject,
[ValidateNotNullOrEmpty()]
[AllowEmptyCollection()]
[object[]]
$Certificate = @(),
[switch]
$UseLegacyPadding,
[ValidateNotNull()]
[AllowEmptyCollection()]
[ValidateScript({
if ($_.Length -eq 0)
{
throw 'You may not pass empty SecureStrings to the Password parameter'
}
return $true
})]
[System.Security.SecureString[]]
$Password = @(),
[ValidateRange(1,2147483647)]
[int]
$PasswordIterationCount = 50000,
[switch]
$SkipCertificateVerification
)
begin
{
if ($PSBoundParameters.ContainsKey('SkipCertificateVerification'))
{
Write-Warning 'The -SkipCertificateVerification switch has been deprecated, and the module now treats that as its default behavior. This switch will be removed in a future release.'
}
$certs = @(
foreach ($cert in $Certificate)
{
try
{
$x509Cert = ConvertTo-X509Certificate2 -InputObject $cert -ErrorAction Stop
ValidateKeyEncryptionCertificate -CertificateGroup $x509Cert -ErrorAction Stop
}
catch
{
Write-Error -ErrorRecord $_
}
}
)
if ($certs.Count -eq 0 -and $Password.Count -eq 0)
{
throw ('None of the specified certificates could be used for encryption, and no passwords were specified.' +
' Data protection cannot be performed.')
}
}
process
{
$plainText = $null
$payload = $null
try
{
$plainText = ConvertTo-PinnedByteArray -InputObject $InputObject
$payload = Protect-DataWithAes -PlainText $plainText
$protectedData = New-Object psobject -Property @{
CipherText = $payload.CipherText
HMAC = $payload.HMAC
Type = $InputObject.GetType().FullName
KeyData = @()
}
$params = @{
InputObject = $protectedData
Key = $payload.Key
InitializationVector = $payload.IV
Certificate = $certs
Password = $Password
PasswordIterationCount = $PasswordIterationCount
UseLegacyPadding = $UseLegacyPadding
}
Add-KeyData @params
if ($protectedData.KeyData.Count -eq 0)
{
Write-Error 'Failed to protect data with any of the supplied certificates or passwords.'
return
}
else
{
$protectedData
}
}
finally
{
if ($plainText -is [IDisposable]) { $plainText.Dispose() }
if ($null -ne $payload)
{
if ($payload.Key -is [IDisposable]) { $payload.Key.Dispose() }
if ($payload.IV -is [IDisposable]) { $payload.IV.Dispose() }
}
}
} # process
} # function Protect-Data
function Unprotect-Data
{
<#
.Synopsis
Decrypts an object that was produced by the Protect-Data command.
.DESCRIPTION
Decrypts an object that was produced by the Protect-Data command. If a Certificate is used to perform the decryption, it must be installed in either the local computer or current user's certificate stores (with its private key), and the current user must have permission to use that key.
.PARAMETER InputObject
The ProtectedData object that is to be decrypted.
.PARAMETER Certificate
An RSA or ECDH certificate that will be used to decrypt the data. You must have the certificate's private key, and it must be one of the certificates that was used to encrypt the data. You can pass an X509Certificate2 object to this parameter, or you can pass in a string which contains either a path to a certificate file on the file system, a path to the certificate in the Certificate provider, or a certificate thumbprint (in which case the certificate provider will be searched to find the certificate.)
.PARAMETER Password
A SecureString containing a password that will be used to derive an encryption key. One of the InputObject's KeyData objects must be protected with this password.
.PARAMETER SkipCertificateValidation
Deprecated parameter, which will be removed in a future release. Specifying this switch will generate a warning.
.EXAMPLE
$decryptedObject = $encryptedObject | Unprotect-Data -Password (Read-Host -AsSecureString -Prompt 'Enter password to decrypt the data')
Decrypts the contents of $encryptedObject and outputs an object of the same type as what was originally passed to Protect-Data. Uses a password to decrypt the object instead of a certificate.
.INPUTS
PSObject
The input object should be a copy of an object that was produced by Protect-Data.
.OUTPUTS
Object
Object may be any type returned by Get-ProtectedDataSupportedTypes. Specifically, it will be an object of the type specified in the InputObject's Type property.
.LINK
Protect-Data
.LINK
Add-ProtectedDataCredential
.LINK
Remove-ProtectedDataCredential
.LINK
Get-ProtectedDataSupportedTypes
#>
[CmdletBinding(DefaultParameterSetName = 'Certificate')]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateScript({
if (-not (Test-IsProtectedData -InputObject $_))
{
throw 'InputObject argument must be a ProtectedData object.'
}
if ($null -eq $_.CipherText -or $_.CipherText.Count -eq 0)
{
throw 'Protected data object contained no cipher text.'
}
$type = $_.Type -as [type]
if ($null -eq $type -or $script:ValidTypes -notcontains $type)
{
throw 'Protected data object specified an invalid type. Type must be one of: ' +
($script:ValidTypes -join ', ')
}
return $true
})]
$InputObject,
[Parameter(ParameterSetName = 'Certificate')]
[object]
$Certificate,
[Parameter(Mandatory = $true, ParameterSetName = 'Password')]
[System.Security.SecureString]
$Password,
[switch]
$SkipCertificateVerification
)
begin
{
if ($PSBoundParameters.ContainsKey('SkipCertificateVerification'))
{
Write-Warning 'The -SkipCertificateVerification switch has been deprecated, and the module now treats that as its default behavior. This switch will be removed in a future release.'
}
$cert = $null
if ($Certificate)
{
try
{
$cert = ConvertTo-X509Certificate2 -InputObject $Certificate -ErrorAction Stop
$params = @{
CertificateGroup = $cert
RequirePrivateKey = $true
}
$cert = ValidateKeyEncryptionCertificate @params -ErrorAction Stop
}
catch
{
throw
}
}
}
process
{
$plainText = $null
$aes = $null
$key = $null
$iv = $null
if ($null -ne $Password)
{
$params = @{ Password = $Password }
}
else
{
if ($null -eq $cert)
{
$paths = 'Cert:\CurrentUser\My', 'Cert:\LocalMachine\My'
$cert = :outer foreach ($path in $paths)
{
foreach ($keyData in $InputObject.KeyData)
{
if ($keyData.Thumbprint)
{
$certObject = $null
try
{
$certObject = Get-KeyEncryptionCertificate -Path $path -CertificateThumbprint $keyData.Thumbprint -RequirePrivateKey -ErrorAction $IgnoreError
} catch { }
if ($null -ne $certObject)
{
$certObject
break outer
}
}
}
}
}
if ($null -eq $cert)
{
Write-Error -Message 'No decryption certificate for the specified InputObject was found.' -TargetObject $InputObject
return
}
$params = @{
Certificate = $cert
}
}
try
{
$result = Unprotect-MatchingKeyData -InputObject $InputObject @params
$key = $result.Key
$iv = $result.IV
if ($null -eq $InputObject.HMAC)
{
throw 'Input Object contained no HMAC code.'
}
$hmac = $InputObject.HMAC
$plainText = (Unprotect-DataWithAes -CipherText $InputObject.CipherText -Key $key -InitializationVector $iv -HMAC $hmac).PlainText
ConvertFrom-ByteArray -ByteArray $plainText -Type $InputObject.Type -ByteCount $plainText.Count
}
catch
{
Write-Error -ErrorRecord $_
return
}
finally
{
if ($plainText -is [IDisposable]) { $plainText.Dispose() }
if ($key -is [IDisposable]) { $key.Dispose() }
if ($iv -is [IDisposable]) { $iv.Dispose() }
}
} # process
} # function Unprotect-Data
function Add-ProtectedDataHmac
{
<#
.Synopsis
Adds an HMAC authentication code to a ProtectedData object which was created with a previous version of the module.
.DESCRIPTION
Adds an HMAC authentication code to a ProtectedData object which was created with a previous version of the module. The parameters and requirements are the same as for the Unprotect-Data command, as the data must be partially decrypted in order to produce the HMAC code.
.PARAMETER InputObject
The ProtectedData object that is to have an HMAC generated.
.PARAMETER Certificate
An RSA or ECDH certificate that will be used to decrypt the data. You must have the certificate's private key, and it must be one of the certificates that was used to encrypt the data. You can pass an X509Certificate2 object to this parameter, or you can pass in a string which contains either a path to a certificate file on the file system, a path to the certificate in the Certificate provider, or a certificate thumbprint (in which case the certificate provider will be searched to find the certificate.)
.PARAMETER Password
A SecureString containing a password that will be used to derive an encryption key. One of the InputObject's KeyData objects must be protected with this password.
.PARAMETER SkipCertificateVerification
Deprecated parameter, which will be removed in a future release. Specifying this switch will generate a warning.
.PARAMETER PassThru
If specified, the command outputs the ProtectedData object after adding the HMAC.
.EXAMPLE
$encryptedObject | Add-ProtectedDataHmac -Password (Read-Host -AsSecureString -Prompt 'Enter password to decrypt the key data')
Adds an HMAC code to the $encryptedObject object.
.INPUTS
PSObject
The input object should be a copy of an object that was produced by Protect-Data.
.OUTPUTS
None, or ProtectedData object if the -PassThru switch is used.
.LINK
Protect-Data
.LINK
Unprotect-Data
.LINK
Add-ProtectedDataCredential
.LINK
Remove-ProtectedDataCredential
.LINK
Get-ProtectedDataSupportedTypes
#>
[CmdletBinding(DefaultParameterSetName = 'Certificate')]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateScript({
if (-not (Test-IsProtectedData -InputObject $_))
{
throw 'InputObject argument must be a ProtectedData object.'
}
if ($null -eq $_.CipherText -or $_.CipherText.Count -eq 0)
{
throw 'Protected data object contained no cipher text.'
}
$type = $_.Type -as [type]
if ($null -eq $type -or $script:ValidTypes -notcontains $type)
{
throw 'Protected data object specified an invalid type. Type must be one of: ' +
($script:ValidTypes -join ', ')
}
return $true
})]
$InputObject,
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[object]
$Certificate,
[Parameter(Mandatory = $true, ParameterSetName = 'Password')]
[System.Security.SecureString]
$Password,
[switch]
$SkipCertificateVerification,
[switch]
$PassThru
)
begin
{
if ($PSBoundParameters.ContainsKey('SkipCertificateVerification'))
{
Write-Warning 'The -SkipCertificateVerification switch has been deprecated, and the module now treats that as its default behavior. This switch will be removed in a future release.'
}
$cert = $null
if ($Certificate)
{
try
{
$cert = ConvertTo-X509Certificate2 -InputObject $Certificate -ErrorAction Stop
$params = @{
CertificateGroup = $cert
RequirePrivateKey = $true
}
$cert = ValidateKeyEncryptionCertificate @params -ErrorAction Stop
}
catch
{
throw
}
}
}
process
{
$key = $null
$iv = $null
if ($null -ne $cert)
{
$params = @{ Certificate = $cert }
}
else
{
$params = @{ Password = $Password }
}
try
{
$result = Unprotect-MatchingKeyData -InputObject $InputObject @params
$key = $result.Key
$iv = $result.IV
$hmac = Get-Hmac -Key $key -Bytes $InputObject.CipherText
if ($InputObject.PSObject.Properties['HMAC'])
{
$InputObject.HMAC = $hmac
}
else
{
Add-Member -InputObject $InputObject -Name HMAC -Value $hmac -MemberType NoteProperty
}
if ($PassThru)
{
$InputObject
}
}
catch
{
Write-Error -ErrorRecord $_
return
}
finally
{
if ($key -is [IDisposable]) { $key.Dispose() }
if ($iv -is [IDisposable]) { $iv.Dispose() }
}
} # process
} # function Unprotect-Data
function Add-ProtectedDataCredential
{
<#
.Synopsis
Adds one or more new copies of an encryption key to an object generated by Protect-Data.
.DESCRIPTION
This command can be used to add new certificates and/or passwords to an object that was previously encrypted by Protect-Data. The caller must provide one of the certificates or passwords that already exists in the ProtectedData object to perform this operation.
.PARAMETER InputObject
The ProtectedData object which was created by an earlier call to Protect-Data.
.PARAMETER Certificate
An RSA or ECDH certificate which was previously used to encrypt the ProtectedData structure's key.
.PARAMETER Password
A password which was previously used to encrypt the ProtectedData structure's key.
.PARAMETER NewCertificate
Zero or more RSA or ECDH certificates that should be used to encrypt the data. The data can later be decrypted by using the same certificate (with its private key.) You can pass an X509Certificate2 object to this parameter, or you can pass in a string which contains either a path to a certificate file on the file system, a path to the certificate in the Certificate provider, or a certificate thumbprint (in which case the certificate provider will be searched to find the certificate.)
.PARAMETER UseLegacyPadding
Optional switch specifying that when performing certificate-based encryption, PKCS#1 v1.5 padding should be used instead of the newer, more secure OAEP padding scheme. Some certificates may not work properly with OAEP padding
.PARAMETER NewPassword
Zero or more SecureString objects containing password that will be used to derive encryption keys. The data can later be decrypted by passing in a SecureString with the same value.
.PARAMETER SkipCertificateVerification
Deprecated parameter, which will be removed in a future release. Specifying this switch will generate a warning.
.PARAMETER PasswordIterationCount
Optional positive integer value specifying the number of iteration that should be used when deriving encryption keys from the specified password(s). Defaults to 50000.
Higher values make it more costly to crack the passwords by brute force.
.PARAMETER Passthru
If this switch is used, the ProtectedData object is output to the pipeline after it is modified.
.EXAMPLE
Add-ProtectedDataCredential -InputObject $protectedData -Certificate $oldThumbprint -NewCertificate $newThumbprints -NewPassword $newPasswords
Uses the certificate with thumbprint $oldThumbprint to add new key copies to the $protectedData object. $newThumbprints would be a string array containing thumbprints, and $newPasswords would be an array of SecureString objects.
.INPUTS
[PSObject]
The input object should be a copy of an object that was produced by Protect-Data.
.OUTPUTS
None, or
[PSObject]
.LINK
Unprotect-Data
.LINK
Add-ProtectedDataCredential
.LINK
Remove-ProtectedDataCredential
.LINK
Get-ProtectedDataSupportedTypes
#>
[CmdletBinding(DefaultParameterSetName = 'Certificate')]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateScript({
if (-not (Test-IsProtectedData -InputObject $_))
{
throw 'InputObject argument must be a ProtectedData object.'
}
return $true
})]
$InputObject,
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[object]
$Certificate,
[Parameter(ParameterSetName = 'Certificate')]
[switch]
$UseLegacyPaddingForDecryption,
[Parameter(Mandatory = $true, ParameterSetName = 'Password')]
[System.Security.SecureString]
$Password,
[ValidateNotNull()]
[AllowEmptyCollection()]
[object[]]
$NewCertificate = @(),
[switch]
$UseLegacyPadding,
[ValidateNotNull()]
[AllowEmptyCollection()]
[System.Security.SecureString[]]
$NewPassword = @(),
[ValidateRange(1,2147483647)]
[int]
$PasswordIterationCount = 50000,
[switch]
$SkipCertificateVerification,
[switch]
$Passthru
)
begin
{
if ($PSBoundParameters.ContainsKey('SkipCertificateVerification'))
{
Write-Warning 'The -SkipCertificateVerification switch has been deprecated, and the module now treats that as its default behavior. This switch will be removed in a future release.'
}
$decryptionCert = $null
if ($PSCmdlet.ParameterSetName -eq 'Certificate')
{
try
{
$decryptionCert = ConvertTo-X509Certificate2 -InputObject $Certificate -ErrorAction Stop
$params = @{
CertificateGroup = $decryptionCert
RequirePrivateKey = $true
}
$decryptionCert = ValidateKeyEncryptionCertificate @params -ErrorAction Stop
}
catch
{
throw
}
}
$certs = @(
foreach ($cert in $NewCertificate)
{
try
{
$x509Cert = ConvertTo-X509Certificate2 -InputObject $cert -ErrorAction Stop
ValidateKeyEncryptionCertificate -CertificateGroup $x509Cert -ErrorAction Stop
}
catch
{
Write-Error -ErrorRecord $_
}
}
)
if ($certs.Count -eq 0 -and $NewPassword.Count -eq 0)
{
throw 'None of the specified certificates could be used for encryption, and no passwords were ' +
'specified. Data protection cannot be performed.'
}
} # begin
process
{
if ($null -ne $decryptionCert)
{
$params = @{ Certificate = $decryptionCert }
}
else
{
$params = @{ Password = $Password }
}
$key = $null
$iv = $null
try
{
$result = Unprotect-MatchingKeyData -InputObject $InputObject @params
$key = $result.Key
$iv = $result.IV
Add-KeyData -InputObject $InputObject -Key $key -InitializationVector $iv -Certificate $certs -Password $NewPassword -PasswordIterationCount $PasswordIterationCount -UseLegacyPadding:$UseLegacyPadding
}
catch
{
Write-Error -ErrorRecord $_
return
}
finally
{
if ($key -is [IDisposable]) { $key.Dispose() }
if ($iv -is [IDisposable]) { $iv.Dispose() }
}
if ($Passthru)
{
$InputObject
}
} # process
} # function Add-ProtectedDataCredential
function Remove-ProtectedDataCredential
{
<#
.Synopsis
Removes copies of encryption keys from a ProtectedData object.
.DESCRIPTION
The KeyData copies in a ProtectedData object which are associated with the specified Certificates and/or Passwords are removed from the object, unless that removal would leave no KeyData copies behind.
.PARAMETER InputObject
The ProtectedData object which is to be modified.
.PARAMETER Certificate
RSA or ECDH certificates that you wish to remove from this ProtectedData object. You can pass an X509Certificate2 object to this parameter, or you can pass in a string which contains either a path to a certificate file on the file system, a path to the certificate in the Certificate provider, or a certificate thumbprint (in which case the certificate provider will be searched to find the certificate.)
.PARAMETER Password
Passwords in SecureString form which are to be removed from this ProtectedData object.
.PARAMETER Passthru
If this switch is used, the ProtectedData object will be written to the pipeline after processing is complete.
.EXAMPLE
$protectedData | Remove-ProtectedDataCredential -Certificate $thumbprints -Password $passwords
Removes certificates and passwords from an existing ProtectedData object.
.INPUTS
[PSObject]
The input object should be a copy of an object that was produced by Protect-Data.
.OUTPUTS
None, or
[PSObject]
.LINK
Protect-Data
.LINK
Unprotect-Data
.LINK
Add-ProtectedDataCredential
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateScript({
if (-not (Test-IsProtectedData -InputObject $_))
{
throw 'InputObject argument must be a ProtectedData object.'
}
return $true
})]
$InputObject,
[ValidateNotNull()]
[AllowEmptyCollection()]
[object[]]
$Certificate,
[ValidateNotNull()]
[AllowEmptyCollection()]
[System.Security.SecureString[]]
$Password,
[switch]
$Passthru
)
begin
{
$thumbprints = @(
$Certificate |
ConvertTo-X509Certificate2 |
Select-Object -ExpandProperty Thumbprint
)
$thumbprints = $thumbprints | Get-Unique
}
process
{
$matchingKeyData = @(
foreach ($keyData in $InputObject.KeyData)
{
if (Test-IsCertificateProtectedKeyData -InputObject $keyData)
{
if ($thumbprints -contains $keyData.Thumbprint) { $keyData }
}
elseif (Test-IsPasswordProtectedKeyData -InputObject $keyData)
{
foreach ($secureString in $Password)
{
$params = @{
Password = $secureString
Salt = $keyData.HashSalt
IterationCount = $keyData.IterationCount
}
if ($keyData.Hash -eq (Get-PasswordHash @params))
{
$keyData
}
}
}
}
)
if ($matchingKeyData.Count -eq $InputObject.KeyData.Count)
{
Write-Error 'You must leave at least one copy of the ProtectedData object''s keys.'
return
}
$InputObject.KeyData = $InputObject.KeyData | Where-Object { $matchingKeyData -notcontains $_ }
if ($Passthru)
{
$InputObject
}
}
} # function Remove-ProtectedDataCredential
function Get-ProtectedDataSupportedTypes
{
<#
.Synopsis
Returns a list of types that can be used as the InputObject in the Protect-Data command.
.EXAMPLE
$types = Get-ProtectedDataSupportedTypes
.INPUTS
None.
.OUTPUTS
Type[]
.NOTES
This function allows you to know which InputObject types are supported by the Protect-Data and Unprotect-Data commands in this version of the module. This list may expand over time, will always be backwards-compatible with previously-encrypted data.
.LINK
Protect-Data
.LINK
Unprotect-Data
#>
[CmdletBinding()]
[OutputType([Type[]])]
param ( )
$script:ValidTypes
}
function Get-KeyEncryptionCertificate
{
<#
.Synopsis
Finds certificates which can be used by Protect-Data and related commands.
.DESCRIPTION
Searches the given path, and all child paths, for certificates which can be used by Protect-Data. Such certificates must support Key Encipherment (for RSA) or Key Agreement (for ECDH) usage, and by default, must not be expired and must be issued by a trusted authority.
.PARAMETER Path
Path which should be searched for the certifictes. Defaults to the entire Cert: drive.
.PARAMETER CertificateThumbprint
Thumbprints which should be included in the search. Wildcards are allowed. Defaults to '*'.
.PARAMETER SkipCertificateVerification
Deprecated parameter, which will be removed in a future release. Specifying this switch will generate a warning.
.PARAMETER RequirePrivateKey
If this switch is used, the command will only output certificates which have a usable private key on this computer.
.EXAMPLE
Get-KeyEncryptionCertificate -Path Cert:\CurrentUser -RequirePrivateKey
Searches for certificates which support key encipherment (RSA) or key agreement (ECDH) and have a private key installed. All matching certificates are returned.
.EXAMPLE
Get-KeyEncryptionCertificate -Path Cert:\CurrentUser\TrustedPeople
Searches the current user's Trusted People store for certificates that can be used with Protect-Data. Certificates do not need to have a private key available to the current user.
.INPUTS
None.
.OUTPUTS
[System.Security.Cryptography.X509Certificates.X509Certificate2]
.LINK
Protect-Data
.LINK
Unprotect-Data
.LINK
Add-ProtectedDataCredential
.LINK
Remove-ProtectedDataCredential
#>
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param (
[ValidateNotNullOrEmpty()]
[string]
$Path = 'Cert:\',
[string]
$CertificateThumbprint = '*',
[switch]
$SkipCertificateVerification,
[switch]
$RequirePrivateKey
)
if ($PSBoundParameters.ContainsKey('SkipCertificateVerification'))
{
Write-Warning 'The -SkipCertificateVerification switch has been deprecated, and the module now treats that as its default behavior. This switch will be removed in a future release.'
}
# Suppress error output if we're doing a wildcard search (unless user specifically asks for it via -ErrorAction)
# This is a little ugly, may rework this later now that I've made Get-KeyEncryptionCertificate public. Originally
# it was only used to search for a single thumbprint, and threw errors back to the caller if no suitable cert could
# be found. Now I want it to also be used as a search tool for users to identify suitable certificates. Maybe just
# needs to be two separate functions, one internal and one public.
if (-not $PSBoundParameters.ContainsKey('ErrorAction') -and
$CertificateThumbprint -notmatch '^[A-F\d]+$')
{
$ErrorActionPreference = $IgnoreError
}
$certGroups = GetCertificateByThumbprint -Path $Path -Thumbprint $CertificateThumbprint -ErrorAction $IgnoreError |
Group-Object -Property Thumbprint
if ($null -eq $certGroups)
{
throw "Certificate '$CertificateThumbprint' was not found."
}
foreach ($group in $certGroups)
{
ValidateKeyEncryptionCertificate -CertificateGroup $group.Group -RequirePrivateKey:$RequirePrivateKey
}
} # function Get-KeyEncryptionCertificate
#endregion
#region Helper functions
function ConvertTo-X509Certificate2
{
[CmdletBinding()]
[OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
param (
[Parameter(ValueFromPipeline = $true)]
[object[]] $InputObject = @()
)
process
{
foreach ($object in $InputObject)
{
if ($null -eq $object) { continue }
$possibleCerts = @(
$object -as [System.Security.Cryptography.X509Certificates.X509Certificate2]
GetCertificateFromPSPath -Path $object
) -ne $null
if ($object -match '^[A-F\d]+$' -and $possibleCerts.Count -eq 0)
{
$possibleCerts = @(GetCertificateByThumbprint -Thumbprint $object)
}
$cert = $possibleCerts | Select-Object -First 1
if ($null -ne $cert)
{