-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCmsCredentials.psm1
More file actions
1105 lines (912 loc) · 31.4 KB
/
CmsCredentials.psm1
File metadata and controls
1105 lines (912 loc) · 31.4 KB
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
# default certificate template
$CmsTemplate = @"
[Version]
Signature=`"`$Windows NT`$`"
[Strings]
szOID_ENHANCED_KEY_USAGE = "2.5.29.37"
szOID_DOCUMENT_ENCRYPTION = "1.3.6.1.4.1.311.80.1"
[NewRequest]
Subject = `"CN=<SUBJECT>`"
MachineKeySet = True
KeyLength = 4096
KeySpec = AT_KEYEXCHANGE
HashAlgorithm = SHA512
Exportable = False
RequestType = Cert
KeyUsage = "CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERT_DATA_ENCIPHERMENT_KEY_USAGE"
ValidityPeriod = "Years"
ValidityPeriodUnits = "100"
[Extensions]
%szOID_ENHANCED_KEY_USAGE% = "{text}%szOID_DOCUMENT_ENCRYPTION%"
"@
Function Get-ComputersFromParams {
<#
.SYNOPSIS
Creates a list of computers from inputs.
.DESCRIPTION
Creates a list of computers from inputs. Called by multiple functions in this module.
.PARAMETER ComputerName
Specifies one or more remote computers.
.PARAMETER ClusterName
Specifies one or more remote clusters.
.PARAMETER Cluster
Instructs the command to check if the local machine is a cluster and, if so, to execute on all members of the cluster.
.INPUTS
None.
.OUTPUTS
An array of computer hostnames.
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)][AllowEmptyCollection()]
[string[]]$ComputerName,
[Parameter(Position = 1)][AllowEmptyCollection()]
[string[]]$ClusterName,
[Parameter(Position = 2)]
[switch]$Cluster
)
# define empty array
$ComputersFromParams = @()
# retrieve local cluster name if requested
If ($Cluster) {
$ClusSvc = $null
$ClusSvc = Get-Service | Where-Object { $_.Name -eq 'ClusSvc' -and $_.StartType -ne 'Disabled' }
If ($null -ne $ClusSvc) {
Try { $ClusterName += (Get-Cluster).Name }
Catch { Write-Host 'ERROR: could not retrieve local cluster name' }
}
Else {
Write-Host 'ERROR: cluster service is not running on local host'
}
}
# add computers to array from ClusterName argument
If ($ClusterName.Count) {
ForEach ($cluster_name in $ClusterName) {
Try {
$cluster_nodes = $null
$cluster_nodes = Invoke-Command -ComputerName $cluster_name -ScriptBlock { (Get-ClusterNode).Name }
$cluster_nodes | ForEach-Object { $ComputersFromParams += $_ }
}
Catch {
Write-Host "ERROR: could not retrieve list of cluster nodes from '$cluster_name'"
}
}
}
# add computers to array from ComputerName argument
If ($ComputerName) {
$ComputerName | ForEach-Object { $ComputersFromParams += $_ }
}
# remove duplicate computers
$ComputersFromParams | Select-Object -Unique
}
Function Protect-CmsCredentialSecret {
<#
.SYNOPSIS
Internal function for protecting a credential with CMS.
.DESCRIPTION
Internal function for protecting a credential with CMS. This function is called by Protect-CmsCredentials.
.PARAMETER Target
Specifies the identity for the CMS credential.
.PARAMETER Cred
Specifies the PSCredential object to protect with CMS.
.PARAMETER Template
Specifies the certificate template for the CMS certificate.
.PARAMETER Reset
Specifies that a new CMS certificate is required.
.PARAMETER Prefix
Specifies the prefix for the CMS credential file. Set to 'cms' by default.
.PARAMETER Hostname
Specifies the hostname in the CMS credential. Set to the local hostname by default.
.PARAMETER ParentPath
Specifies the parent path of the CMS credential folder. Set to the ProgramData folder by default.
.INPUTS
None.
.OUTPUTS
None.
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0)]
[string]$Target,
[Parameter(Position = 1)]
[pscredential]$Cred,
[Parameter(Position = 2)]
[string]$Template,
[Parameter(Position = 3)]
[bool]$Reset,
[Parameter(Position = 4)]
[string]$Prefix = 'cms',
[Parameter(Position = 5)]
[string]$Hostname = [System.Environment]::MachineName.ToLowerInvariant(),
[Parameter(Position = 6)][ValidateScript({Test-Path -Path $_})]
[string]$ParentPath = [System.Environment]::GetFolderPath('CommonApplicationData')
)
# define required objects
$cms_cert = $null
$cms_make = $false
$cms_date = Get-Date -Format FileDateTimeUniversal
$cms_path = Join-Path -Path $ParentPath -ChildPath ($Prefix, $Hostname -join '_')
# verify cms folder
Write-Host "Checking CMS directory: $cms_path"
If (!(Test-Path -Path $cms_path)) { New-Item -ItemType Directory -Path $cms_path | Out-Null }
# check if a new certificate should be made regardless of current certs
If ($Reset) {
# set make flag to true
$cms_make = $true
# declare the certificate should be made
Write-Host 'CMS certificate reset requested, creating...'
}
Else {
# define required strings
$cms_cert_regex = ("CN=$Hostname", $Target, '\d{8}') -join '-'
# retrieve any certificates matching regex
$cms_cert = Get-ChildItem -Path 'Cert:\LocalMachine\My' -DocumentEncryptionCert | Where-Object { $_.Subject -match $cms_cert_regex } | Sort-Object 'Subject' | Select-Object -Last 1
# check certificates
If ($cms_cert) {
# retrieve certificate subject
$cms_subject = $cms_cert.Subject
# set make flag to false
$cms_make = $false
# declare certificate found
Write-Host "CMS certificate found, subject: '$cms_subject'"
}
Else {
# set make flag to true
$cms_make = $true
# declare the certificate should be made
Write-Host 'CMS certificate not found, creating...'
}
}
# create the certificate
If ($cms_make) {
# define certificate subject
$cms_subject = "CN=$($Hostname, $Target, $cms_date -join '-')"
# create temporary files
$cert_inf = New-TemporaryFile
$cert_cer = New-TemporaryFile
# create certificate template
$cert_txt = $Template.Replace('CN=<SUBJECT>', $cms_subject)
$cert_txt | Out-File -FilePath $cert_inf
# create certificate
Try {
certreq.exe -new -f -q $cert_inf $cert_cer | Out-Null
}
Catch {
# figure out what to put here!
}
# remove temporary files
Remove-Item -Path $cert_inf -Force
Remove-Item -Path $cert_cer -Force
# check local machine store for new certificate
$cms_cert = Get-ChildItem -Path 'Cert:\LocalMachine\My' -DocumentEncryptionCert | Where-Object { $_.Subject -eq $cms_subject } | Select-Object -Last 1
If ($cms_cert) {
# declare certificate subject
Write-Host "CMS certificate created, subject: '$($cms_subject)'"
}
Else {
# declare error and exit
Write-Host "ERROR: could not create CMS certificate: '$($cms_subject)'"
}
}
# if a CMS cert exists...
If ($cms_cert) {
# define required strings
$cms_name = ($Prefix, $Hostname, $Target, $cms_date) -join '_'
$cms_file = Join-Path -Path $cms_path -ChildPath "$cms_name.txt"
$cms_file_regex = ($Prefix, $Hostname, $Target, '\d{8}') -join '_'
# create custom object for export
$cms_cred = $null
$cms_cred = [pscustomobject]@{
Username = $Cred.Username
Password = $Cred.GetNetworkCredential().Password
}
# encrypt credentials to local certificate
Try {
$cms_cred | ConvertTo-Json | Protect-CmsMessage -To $cms_cert.Thumbprint -OutFile $cms_file
$cms_made = $true
Write-Host "CMS file created: '$($cms_file)'"
}
Catch {
$cms_made = $false
Write-Host 'ERROR: could not encrypt the CMS file'
}
# if CMS was made, clean up files and certificates
If ($cms_made) {
# retrieve old certificates files
Write-Host "Checking for old CMS certificates: 'Cert:\LocalMachine\My'"
$cms_cert_old = Get-ChildItem -Path 'Cert:\LocalMachine\My' -DocumentEncryptionCert | Where-Object { $_.Subject -match $cms_cert_regex } | Sort-Object -Property 'NotBefore' | Select-Object -SkipLast 1
# remove old certificates files
$cms_cert_old | ForEach-Object {
Write-Host "...removing old CMS certificate: '$($_.Subject)'"
$_ | Remove-Item -Force
}
# retrieve old credential files
Write-Host "Checking for old CMS credentials: $cms_path"
$cms_file_old = Get-ChildItem -Path $cms_path | Where-Object { $_.BaseName -match $cms_file_regex } | Sort-Object -Property 'BaseName' | Select-Object -SkipLast 1
# remove old credential files
$cms_file_old | ForEach-Object {
Write-Host "...removing old CMS credential: '$($_.FullName)'"
$_ | Remove-Item -Force
}
}
}
}
Function Remove-CmsCredentialSecret {
<#
.SYNOPSIS
Internal function for removing a CMS credential.
.DESCRIPTION
Internal function for removing a CMS credential. This function is called by Remove-CmsCredentials.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER Prefix
Specifies the prefix for the CMS credential file. Set to 'cms' by default.
.PARAMETER Hostname
Specifies the hostname in the CMS credential. Set to the local hostname by default.
.PARAMETER ParentPath
Specifies the parent path of the CMS credential folder. Set to the ProgramData folder by default.
.INPUTS
None.
.OUTPUTS
None.
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0)]
[string]$Target,
[Parameter(Position = 1)]
[string]$Prefix = 'cms',
[Parameter(Position = 2)]
[string]$Hostname = [System.Environment]::MachineName.ToLowerInvariant(),
[Parameter(Position = 3)][ValidateScript({Test-Path -Path $_})]
[string]$ParentPath = [System.Environment]::GetFolderPath('CommonApplicationData')
)
# define strings
$cms_path = Join-Path -Path $ParentPath -ChildPath ($Prefix, $Hostname -join '_')
$cms_cert_regex = ("CN=$Hostname", $Target, '\d{8}') -join '-'
$cms_file_regex = ($Prefix, $Hostname, $Target, '-\d{8}') -join '_'
# remove certificates
$cms_cert_old = Get-ChildItem -Path 'Cert:\LocalMachine\My' -DocumentEncryptionCert | Where-Object { $_.Subject -match $cms_cert_regex }
$cms_cert_old | ForEach-Object {
Write-Host "Removing CMS certificate: '$($_.Subject)'"
$_ | Remove-Item -Force
}
# remove credential files
$cms_file_old = Get-ChildItem -Path $cms_path | Where-Object { $_.BaseName -match $cms_file_regex }
$cms_file_old | ForEach-Object {
Write-Host "Removing CMS credential: '$($_.FullName)'"
$_ | Remove-Item -Force
}
}
Function Update-CmsCredentialAccess {
<#
.SYNOPSIS
Internal function for updating access to a CMS credential.
.DESCRIPTION
Internal function for updating access to a CMS credential. Utilized by Grant-CmsCredentialAccess, Revoke-CmsCredentialAccess, and Reset-CmsCredentialAccess.
.PARAMETER Mode
Specifies the mode for the function.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER Principals
Specifies one or more Active Directory principals.
.PARAMETER Hostname
Specifies the hostname in the CMS credential. Set to the local hostname by default.
.INPUTS
None.
.OUTPUTS
None.
#>
[CmdletBinding(SupportsShouldProcess)]
Param (
[Parameter(Position = 0)]
[string]$Mode,
[Parameter(Position = 1)]
[string]$Target,
[Parameter(Position = 2)]
[string[]]$Principals,
[Parameter(Position = 3)]
[string]$Hostname = [System.Environment]::MachineName.ToLowerInvariant()
)
# create regex to match expected CMS certificate name of machinename followed by the target name then either a simple date or a FileDateTimeUniversal
$cms_regx = "CN=$Hostname-$Target-\d{8}"
# retrieve SIDs for principals
$cms_sids = @()
If ($Mode -eq 'Reset') {
$cms_sids += [System.Security.Principal.SecurityIdentifier]('S-1-5-18') # add NT AUTHORITY\SYSTEM
$cms_sids += [System.Security.Principal.SecurityIdentifier]('S-1-5-32-544') # add BUILTIN\Administrators
}
Else {
ForEach ($cms_principal in $Principals) {
# verify the input
If ($cms_principal -isnot [System.String] -and $cms_principal -is [System.Security.Principal.SecurityIdentifier]) {
$cms_sids += $cms_principal
}
Else {
Try {
# check for specific well-known SIDs or translate the SID
switch ($cms_principal) {
# well-known built-in SID that only translates on a domain controller
{ ($_ -eq 'Windows Authorization Access Group') -or ($_ -eq "$([System.Environment]::UserDomainName)\Windows Authorization Access Group") } {
$cms_sids += [System.Security.Principal.SecurityIdentifier]('S-1-5-32-560')
}
# a SID in string format
{ ($_ -match 'S-1-\d{1,2}-\d+') } {
$cms_sids += [System.Security.Principal.SecurityIdentifier]($_)
}
# a principal with domain prefix or suffix
{ ($_ -match '^[\w\s\.-]+\\[\w\s\.-]+$') -or ($_ -match '^[\w\.-]+@[\w\.-]+$') } {
$cms_sids += ([System.Security.Principal.NTAccount]($_)).Translate([System.Security.Principal.SecurityIdentifier])
}
# any other username
Default {
$cms_sids += ([System.Security.Principal.NTAccount]("$([System.Environment]::UserDomainName)\$_")).Translate([System.Security.Principal.SecurityIdentifier])
}
}
}
Catch {
Write-Output "Could not translate principal to SID: '$cms_principal'"
Return
}
}
}
}
# check local machine store for existing certificate
$cms_cert = $null
$cms_cert = Get-ChildItem -Path 'Cert:\LocalMachine\My' -DocumentEncryptionCert | Where-Object { $_.Subject -match $cms_regx } | Sort-Object 'NotBefore' | Select-Object -Last 1
If ($cms_cert) {
# declare certificate subject
Write-Host "CMS certificate found, subject: '$($cms_cert.Subject)'"
# retrieve private key
$cms_key = Join-Path -Path 'C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys' -ChildPath $cms_cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
# retrieve private key permissions
$cms_acl = Get-Acl -Path $cms_key
# process SIDs
switch ($Mode) {
'Grant' {
# create ACE then add to ACL
ForEach ($cms_sid in $cms_sids) {
$cms_ace = New-Object System.Security.AccessControl.FileSystemAccessRule @($cms_sid, 'Read', 'Allow')
$cms_acl.AddAccessRule($cms_ace)
}
# declare actions
Write-Host "Granting read access to $($cms_sids.Count) principals..."
}
'Revoke' {
# find ACEs with provided SIDs then remove from ACL
ForEach ($cms_sid in $cms_sids) {
$cms_ace = $cms_acl.Access | Where-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -match $cms_sid }
$cms_ace | ForEach-Object { $cms_acl.RemoveAccessRule($_) } | Out-Null
}
# declare actions
Write-Host "Revoking read access for $($cms_sids.Count) principals..."
}
'Reset' {
# remove all ACEs from ACL
$cms_acl.Access | ForEach-Object { $cms_acl.RemoveAccessRule($_) } | Out-Null
# create ACEs then add to ACL
ForEach ($cms_sid in $cms_sids) {
$cms_ace = New-Object System.Security.AccessControl.FileSystemAccessRule @($cms_sid, 'FullControl', 'Allow')
$cms_acl.AddAccessRule($cms_ace)
}
# declare actions
Write-Host "Removing previous access and granting full control to: 'NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators'"
}
}
# update ACL on private key
Try {
If ($PSCmdlet.ShouldProcess($cms_cert.Subject, "$cms_mode access to CMS certificate")) {
# update ACL on private key
Set-Acl -Path $cms_key -AclObject $cms_acl
# declare actions
Write-Host "CMS certificate permissions updated: '$($cms_cert.Subject)'"
}
}
Catch {
Return $_
}
}
Else {
Write-Output "CMS certificate not found: '$($cms_cert.Subject)'"
Return
}
}
Function Protect-CmsCredentials {
<#
.SYNOPSIS
Protects a credential with CMS.
.DESCRIPTION
Creates a CMS certificate and encrypts the credential with the certificate using CMS. The calling user must have read access to the public key of the certificate that will protect the credential.
.PARAMETER Cred
Specifies a PSCredential object to be protected with CMS.
.PARAMETER Username
Specifies the username of a new credential to be protected with CMS.
.PARAMETER Password
Specifies the password of a new credential to be protected with CMS.
.PARAMETER TemplatePath
Specifies the path to the certificate template for the CMS certificate.
.PARAMETER Prefix
Specifies the prefix for the CMS credential file. Set to 'cms' by default.
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PS> Protect-CmsCredentials -Target "testcredential"
.EXAMPLE
PS> Protect-CmsCredentials -Target "testcredential" -Prefix "private"
.EXAMPLE
PS> Protect-CmsCredentials -Target "testcredential" PasswordOnly
.EXAMPLE
PS> Protect-CmsCredentials -Target "testcredential" -Prefix "private" -PasswordOnly
#>
[CmdletBinding(DefaultParameterSetName = 'Cred')]
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]$Target,
[Parameter(Position = 1, Mandatory = $True, ParameterSetName = 'Cred', ValueFromPipeline = $true)]
[pscredential]$Cred,
[Parameter(Position = 1, Mandatory = $True, ParameterSetName = 'Pass')]
[string]$Username,
[Parameter(Position = 2, Mandatory = $True, ParameterSetName = 'Pass')]
[securestring]$Password,
[ValidateScript({ Test-Path -Path $_ })]
[string]$TemplatePath,
[string]$Prefix = 'cms',
[string[]]$ComputerName,
[string[]]$ClusterName,
[switch]$Cluster,
[switch]$Reset
)
# check credentials
If ($null -eq $Cred) {
Try {
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $Password
}
Catch {
Write-Host 'ERROR: could not create credential from username and password'
Return
}
}
# import template if requested
If ([string]::IsNullOrEmpty($TemplatePath)) {
$Template = $CmsTemplate
}
Else {
$Template = Get-Content -Path $TemplatePath
}
# get computer names
$CmsComputers = @()
$CmsComputers += Get-ComputersFromParams -Cluster:$Cluster -ClusterName $ClusterName -ComputerName $ComputerName
# define parameter hashtable
$ProtectParameters = @{
Target = $Target
Cred = $Cred
Prefix = $Prefix
Template = $Template
Reset = $Reset
}
# encrypt credentials to certificate
If ($CmsComputers.Count -gt 0) {
$ProtectFunction = "function Protect-CmsCredentialSecret {${function:Protect-CmsCredentialSecret}}"
ForEach ($CmsComputer in $CmsComputers) {
Try {
Invoke-Command -ComputerName $CmsComputer -ScriptBlock {
. ([ScriptBlock]::Create($using:ProtectFunction))
Protect-CmsCredentialSecret @using:ProtectParameters
}
}
Catch {
Write-Host "ERROR: could not protect credentials on '$CmsComputer'"
}
}
}
Else {
Try {
Protect-CmsCredentialSecret @ProtectParameters
}
Catch {
Write-Host 'ERROR: could not protect credentials on local computer'
}
}
}
Function Remove-CmsCredentials {
<#
.SYNOPSIS
Removes a credential protected by CMS.
.DESCRIPTION
Removes the certificate and encrypted file for a credential protected by CMS.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER Prefix
Specifies the prefix for the CMS credential file. Set to 'cms' by default.
.PARAMETER ComputerName
Specifies one or more remote computers.
.PARAMETER ClusterName
Specifies the nodes of one or more remote clusters.
.PARAMETER Cluster
Specifies the nodes of the cluster which the local machine is a member of.
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential"
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential" -Prefix "private"
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential" -ComputerName "server1", "server2"
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential" -ClusterName "cluster1", "cluster2"
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential" -Cluster
.EXAMPLE
PS> Remove-CmsCredentials -Target "testcredential" -Prefix "private" -ComputerName "server1", "server2" -ClusterName "cluster1", "cluster2" -Cluster
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]$Target,
[Parameter(Position = 1)]
[string]$Prefix = 'cms',
[Parameter(Position = 2)]
[string[]]$ComputerName,
[Parameter(Position = 3)]
[string[]]$ClusterName,
[Parameter(Position = 4)]
[switch]$Cluster
)
# get computer names
$CmsComputers = @()
$CmsComputers += Get-ComputersFromParams -Cluster:$Cluster -ClusterName $ClusterName -ComputerName $ComputerName
# define parameter hashtable
$RemoveParameters = @{
Target = $Target
Prefix = $Prefix
}
# encrypt credentials to certificate
If ($CmsComputers.Count -gt 0) {
ForEach ($CmsComputer in $CmsComputers) {
$RemoveFunction = "function Remove-CmsCredentialSecret {${function:Remove-CmsCredentialSecret}}"
Try {
Invoke-Command -ComputerName $CmsComputer -ScriptBlock {
. ([ScriptBlock]::Create($using:RemoveFunction))
Remove-CmsCredentialSecret @using:RemoveParameters
}
}
Catch {
Write-Host "ERROR: could not remove credentials on '$CmsComputer'"
}
}
}
Else {
Try {
Remove-CmsCredentialSecret @RemoveParameters
}
Catch {
Write-Host 'ERROR: could not remove credentials on local computer'
}
}
}
Function Unprotect-CmsCredentials {
<#
.SYNOPSIS
Retrieves a credential protected by CMS.
.DESCRIPTION
Retrieves a credential encrypted by a CMS certificate. The calling user must have read access to the private key of the certificate that protects the credential.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER PasswordOnly
Specifies the credential should be returned as a plain-text password. This changes the output to a PSCustomObject with Username and Password properties.
.PARAMETER Prefix
Specifies the prefix for the CMS credential file. Set to 'cms' by default.
.PARAMETER Hostname
Specifies the hostname in the CMS credential. Set to the local hostname by default.
.PARAMETER ParentPath
Specifies the parent path of the CMS credential folder. Set to the ProgramData folder by default.
.INPUTS
None.
.OUTPUTS
System.Management.Automation.PSCredential or System.Management.Automation.PSCustomObject.
.EXAMPLE
PS> Unprotect-CmsCredentials -Target "testcredential"
.EXAMPLE
PS> Unprotect-CmsCredentials -Target "testcredential" -Prefix "private"
.EXAMPLE
PS> Unprotect-CmsCredentials -Target "testcredential" PasswordOnly
.EXAMPLE
PS> Unprotect-CmsCredentials -Target "testcredential" -Prefix "private" -PasswordOnly
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]$Target,
[Parameter(Position = 1)]
[switch]$PasswordOnly,
[Parameter(Position = 2)]
[string]$Prefix = 'cms',
[Parameter(Position = 3)]
[string]$Hostname = [System.Environment]::MachineName.ToLowerInvariant(),
[Parameter(Position = 4)][ValidateScript({Test-Path -Path $_})]
[string]$ParentPath = [System.Environment]::GetFolderPath('CommonApplicationData')
)
# define required strings
$cms_path = Join-Path -Path $ParentPath -ChildPath ($Prefix + '_' + $Hostname)
# verify cms folder
If (Test-Path -Path $cms_path) {
# get cms file matching the host and target
$cms_file = Get-ChildItem -Path $cms_path | Where-Object { $_.BaseName -match $Target -and $_.BaseName -match $Hostname } | Sort-Object BaseName | Select-Object -Last 1
If ($cms_file) {
# convert the encrypted file into an object
Try {
$cms_object = Get-Content -Path $cms_file.FullName | Unprotect-CmsMessage | ConvertFrom-Json
}
Catch {
Write-Output 'ERROR: could not decrypt the CMS file'
Return
}
# return the credentials based upon the params
If ($cms_object.Username -and $cms_object.Password) {
If ($PasswordOnly) {
# return a PSCustomObject with username and password
[PSCustomObject]@{Username = $cms_object.Username; Password = $cms_object.Password }
}
Else {
# return a PSCredential
New-Object 'System.Management.Automation.PSCredential' -ArgumentList $cms_object.Username, ($cms_object.Password | ConvertTo-SecureString -AsPlainText -Force)
}
}
Else {
Write-Output 'ERROR: could not find required objects in CMS file'
Return
}
}
Else {
Write-Output "ERROR: could not find a CMS file for target: $Target"
Return
}
}
Else {
Write-Output "ERROR: could not find the CMS folder: $cms_path"
Return
}
}
Function Grant-CmsCredentialAccess {
<#
.SYNOPSIS
Grants read access to the private key protecting a CMS credential
.DESCRIPTION
Grants read access to the private key protecting a CMS credential. This allows the permitted principal to decrypt the CMS credential.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER Principals
Specifies one or more Active Directory principals.
.PARAMETER ComputerName
Specifies one or more remote computers.
.PARAMETER ClusterName
Specifies the nodes of one or more remote clusters.
.PARAMETER Cluster
Specifies the nodes of the cluster which the local machine is a member of.
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PS> Grant-CmsCredentialAccess -Target "testcredential" -Principals "DOMAIN\TestUser"
.EXAMPLE
PS> Grant-CmsCredentialAccess -Target "testcredential" -Principals "DOMAIN\TestUser" -ComputerName "server1", "server2"
.EXAMPLE
PS> Grant-CmsCredentialAccess -Target "testcredential" -Principals "DOMAIN\TestUser" -ClusterName "cluster1", "cluster2"
.EXAMPLE
PS> Grant-CmsCredentialAccess -Target "testcredential" -Principals "DOMAIN\TestUser" -Cluster
.EXAMPLE
PS> Grant-CmsCredentialAccess -Target "testcredential" -Principals "DOMAIN\TestUser" -ComputerName "server1", "server2" -ClusterName "cluster1", "cluster2" -Cluster
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]$Target,
[Parameter(Position = 1, Mandatory = $True)]
[string[]]$Principals,
[Parameter(Position = 2)]
[string[]]$ComputerName,
[Parameter(Position = 3)]
[string[]]$ClusterName,
[Parameter(Position = 4)]
[switch]$Cluster
)
# get computer names
$CmsComputers = @()
$CmsComputers += Get-ComputersFromParams -Cluster:$Cluster -ClusterName $ClusterName -ComputerName $ComputerName
# define parameter hashtable
$UpdateParameters = @{
Mode = 'Grant'
Target = $Target
Principals = $Principals
}
# encrypt credentials to certificate
If ($CmsComputers.Count -gt 0) {
$UpdateFunction = "function Update-CmsCredentialAccess {${function:Update-CmsCredentialAccess}}"
ForEach ($CmsComputer in $CmsComputers) {
Invoke-Command -ComputerName $CmsComputer -ScriptBlock {
Try {
. ([ScriptBlock]::Create($using:UpdateFunction))
Update-CmsCredentialAccess @using:UpdateParameters
}
Catch {
Write-Host "ERROR: could not grant credential access on '$using:CmsComputer'"
}
}
}
}
Else {
Try {
Update-CmsCredentialAccess @UpdateParameters
}
Catch {
Write-Host 'ERROR: could not grant credential access on local computer'
}
}
}
Function Reset-CmsCredentialAccess {
<#
.SYNOPSIS
Resets read access to the private key protecting a CMS credential.
.DESCRIPTION
Resets read access to the private key protecting a CMS credential. Only the built-in Administrators and SYSTEM will have access to the private key after this command is run against a CMS credential.
.PARAMETER Target
Specifies the identity of a CMS credential.
.PARAMETER ComputerName
Specifies one or more remote computers.
.PARAMETER ClusterName
Specifies the nodes of one or more remote clusters.
.PARAMETER Cluster
Specifies the nodes of the cluster which the local machine is a member of.
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PS> Reset-CmsCredentialAccess -Target "testcredential"
.EXAMPLE
PS> Reset-CmsCredentialAccess -Target "testcredential" -ComputerName "server1", "server2"
.EXAMPLE
PS> Reset-CmsCredentialAccess -Target "testcredential" -ClusterName "cluster1", "cluster2"
.EXAMPLE
PS> Reset-CmsCredentialAccess -Target "testcredential" -Cluster
.EXAMPLE
PS> Reset-CmsCredentialAccess -Target "testcredential" -ComputerName "server1", "server2" -ClusterName "cluster1", "cluster2" -Cluster
#>
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]$Target,
[Parameter(Position = 1)]
[string[]]$ComputerName,
[Parameter(Position = 2)]
[string[]]$ClusterName,
[Parameter(Position = 3)]
[switch]$Cluster
)
# get computer names
$CmsComputers = @()
$CmsComputers += Get-ComputersFromParams -Cluster:$Cluster -ClusterName $ClusterName -ComputerName $ComputerName
# define parameter hashtable
$UpdateParameters = @{
Mode = 'Reset'
Target = $Target
}
# encrypt credentials to certificate
If ($CmsComputers.Count -gt 0) {
$UpdateFunction = "function Update-CmsCredentialAccess {${function:Update-CmsCredentialAccess}}"
ForEach ($CmsComputer in $CmsComputers) {
Invoke-Command -ComputerName $CmsComputer -ScriptBlock {
Try {
. ([ScriptBlock]::Create($using:UpdateFunction))
Update-CmsCredentialAccess @using:UpdateParameters
}
Catch {
Write-Host "ERROR: could not reset credential access on '$using:CmsComputer'"
}
}
}
}
Else {
Try {
Update-CmsCredentialAccess @UpdateParameters
}
Catch {
Write-Host 'ERROR: could not reset credential access on local computer'
}
}
}
Function Revoke-CmsCredentialAccess {
<#
.SYNOPSIS
Revokes read access to the private key protecting a CMS credential