Repository navigation
Expand file tree
/
Copy pathexport-federationconfiguration.ps1
More file actions
1691 lines (1490 loc) · 143 KB
/
Copy pathexport-federationconfiguration.ps1
File metadata and controls
1691 lines (1490 loc) · 143 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
<#############################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
############################################################>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium", DefaultParameterSetName="Default")]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelinebyPropertyName=$true)]
[string] $Path,
[Parameter(Mandatory=$false)]
[string] $ComputerName,
[Parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential] $Credential,
[Parameter(Mandatory=$false)]
[switch] $Force,
[Parameter(Mandatory=$false)]
[System.Security.SecureString] $CertificatePassword,
[Parameter(Mandatory=$false, ParameterSetName="Id")]
[string[]] $RelyingPartyTrustIdentifier,
[Parameter(Mandatory=$false, ParameterSetName="Id")]
[string[]] $ClaimsProviderTrustIdentifier,
[Parameter(Mandatory=$false, ParameterSetName="Name")]
[string[]] $RelyingPartyTrustName,
[Parameter(Mandatory=$false, ParameterSetName="Name")]
[string[]] $ClaimsProviderTrustName
)
<#################################################################
# Localizable strings.
################################################################>
Data _system_translations
{
ConvertFrom-StringData @'
# Fallback text
# Copy all the strings in the psd1 file here
InvalidPathError = '{0}' is not a valid path.
PathNotFoundError = The path '{0}' does not exist.
RegistryPathNotFoundError = The AD FS installation registry key '{0}' does not exist.
InvalidRegistryPathError = The AD FS installation registry key '{0}' does not point to a valid registry key.
RegistryKeyReadError = Failed to read the AD FS installation registry key '{0}'.
RegistryValueReadError = Failed to read value '{0}' from AD FS installation registry key '{1}'.
InvalidInstallationPathError = The path to the Federation Service '{0}' is not valid.
ConfigFileNotFoundError = The AD FS service configuration file '{0}' does not exist.
ConfigFileReadError = Failed to read the AD FS configuration file '{0}'.
ConnectionStringReadError = Failed to read the policy store connection string from the AD FS service configuration file '{0}'.
ServiceSettingsReadError = Failed to read service setting data from the AD FS configuration database '{0}'.
ServiceSettingsReadException = Failed to read service setting data from the AD FS configuration database '{0}'. Exception: {1}
ServiceSettingsDataError = The service settings data is not a valid XML document.
ServiceSettingsWriteError = The service settings data in the AD FS configuration database '{0}' could not be updated. Error code: '{1}'.
ServiceSettingsWriteException = The service settings data in the AD FS configuration database '{0}' could not be updated. Exception: {1}
CertificatePasswordError = The password to import/export certificates is not specified or empty.
ExportCertificatePasswordPrompt = Enter a password to export certificates
ImportCertificatePasswordPrompt = Enter a password to import certificates
ExportCertificateWarning = The '{0}' certificate '{1}' in '{2}/{3}' could not be exported.
ImportCertificateError = The certificate with thumbprint '{0}' could not be imported. Make sure the password is correct. You can also import this certificate to '{1}/{2}' and run this tool again. Exception: {3}
SaveCertificateError = The certificate with thumbprint '{0}' could not be saved to '{1}/{2}'. You can import this certificate to '{1}/{2}' and run this tool again. Exception: {3}
OpenCertStoreError = The certificate store '{0}/{1}' could not be opened. Exception: {2}
MissingCertWarning = The certificate '{0}' is not in store '{1}/{2}'. The exported files do not have its content. Make sure to import it into '{1}/{2}'. Otherwise, your STS service may not function properly.
InvalidCertPfxError = The certificate '{0}' contains invalid exported Personal Information Exchange (pfx) data.
ExportConfirmMessageCaption = Export Federation Configurations.
ImportConfirmMessageCaption = Import Federation Configurations.
ExportConfirmMessage = The folder '{0}' is not empty. If you choose to export configurations to this folder, all files and directories in it will be deleted. Do you want to continue?
ImportConfirmMessage = If you choose to import federation configurations, existing claims provider and relying party trusts on the target server will be overwritten. Do you want to continue?
ImportConfirmMessageDeleteAll = If you choose to import federation configurations, all existing claims provider and relying party trusts on the target server will be deleted. Do you want to continue?
SummaryInvalidElement = {0}: Invalid element '{1}'.
SummaryRequiredElementNotFound = {0}: The required element '{2}' cannot be found under element '{1}'.
SummaryRequiredAttributeNotFound = {0}: The required attribute '{2}' cannot be found in element '{1}'.
ExportStsVersionNotSupported = This version of the Federation service is not supported. Exiting...
ImportStsVersionNotSupported = The files are exported from Federation Services version {0}. This tool does not support importing files from that version.
ImportToolVersionNotSupported = The files are exported by Federation Services Migration Tool version {0}. This tool does not support importing files exported by that version.
ExportConfigurations = Exporting federation services configurations from server '{0}'...
ExportSavingFiles = Saving configuration files...
ExportFinished = The following AD FS configuration has been exported to '{0}':
EncryptionToken = Token-decrypting certificate
SigningToken = Token-signing certificate
CertNotExportedWarning = Warning: Ensure that you have the following certificates and private keys available in a Personal Information Exchange (.pfx) file or on each server in the new farm. The same certificates must be used on the destination farm, otherwise each trust partner must be updated with the new certificate:
AttrStoreWarning = Warning: The following custom attribute stores were not exported and must be migrated manually:
ImportConfigInfo = Use '{0}' to import this configuration to another AD FS farm.
TargetFarmRequirement = Ensure that the destination farm has the farm name '{0}' and uses service account '{1}'.
ServiceSettingsImported = The federation service settings data were successfully imported.
ImportReadingFiles = Reading configurations from folder '{0}'...
ImportConfigurations = Importing federation services configurations to server '{0}'...
ImportFinished = The configuration was successfully imported.
AddRelyingPartyTrust = Creating relying party trust '{0}'...
AddClaimsProviderTrust = Creating claims provider trust '{0}'...
SkipClaimDescription = The claim description '{0}' already exists. Skipping...
ImportClaimDescription = Creating claim description '{0}'...
MoreHelpMessage = For help with AD FS migration, see {0}.
ErrorLog = Error: {0}
WarningLog = Warning: {0}
# In the following group of strings, parameter {0} is always empty. It is used to mark the start of the string.
TrustExported = {0} Claims provider and relying party trust relationships
CertExported = {0} {1} with thumbprint '{2}'
CertTypeInfo = {0} Certificate: {1}
ThumbprintInfo = {0} Thumbprint: {1}
CertStoreInfo = {0} Certificate store: {1}/{2}
AttrStoreName = {0} {1}
SetCertificatePermissionsError = Failed to grant the AD FS service account read permissions to the private key of certificate with thumbprint '{0}' in store '{1}/{2}'. You can grant read permissions to the AD FS service account and run this tool again. Exception: {3}
SetCertificatePermissionsSuccess = The AD FS service account was granted read permissions to the private key of certificate with thumbprint '{0}'.
CertificateImported = The certificate with thumbprint '{0}' was successfully imported to '{1}/{2}'.
ComfirmExportCertificatePasswordPrompt = Re-enter password
MismatchedExportCertificatePasswordPrompt = The repeat password you typed does not match. {0}
TestImportError = The exported object of type ‘{0}’ with name ‘{1}’ could not be imported. Check the file ‘{2}’ for details about the object. Exception: {3}
TestExportError = The object of type ‘{0}’ with name ‘{1}’ could not be exported. Check the file ‘{2}’ for details about the object. Exception: {3}
'@
}
<#################################################################
# Non-localizable strings.
################################################################>
$ToolVersion = '1.0'
$HelpFwLink = 'http://go.microsoft.com/fwlink/?LinkId=294108'
Function Main
{
Begin
{
## this is to support localization
Import-LocalizedData -BindingVariable _system_translations -fileName Migrate-FederationConfiguration.psd1
$activity = $_system_translations.ExportConfirmMessageCaption
$ErrorActionPreference = 'Stop'
}
Process
{
if (Prepare-Folder -eq $true)
{
$summary = Create-Summary
if ($ComputerName)
{
$status = $_system_translations.ExportConfigurations -f $ComputerName
}
else
{
$status = $_system_translations.ExportConfigurations -f $env:ComputerName
}
Write-Progress -Activity $activity -Status $status -CurrentOperation $status -PercentComplete 0
Write-Host $status | Out-Null
$arguments = @($RelyingPartyTrustIdentifier, $ClaimsProviderTrustIdentifier, $RelyingPartyTrustName, $ClaimsProviderTrustName, $CertificatePassword, $Force, $_system_translations, $Credential, $VerbosePreference)
if ($ComputerName)
{
if ($Credential)
{
$configData = Invoke-Command -ScriptBlock $GetConfig -ArgumentList $arguments -ComputerName $ComputerName -Credential $Credential
}
else
{
$configData = Invoke-Command -ScriptBlock $GetConfig -ArgumentList $arguments -ComputerName $ComputerName
}
}
else
{
$configData = Invoke-Command -ScriptBlock $GetConfig -ArgumentList $arguments
}
$rpTrusts = $configData.rpTrusts
$cpTrusts = $configData.cpTrusts
$claims = $configData.claimDescriptions
$certificates = $configData.certificates
$adfsProperties = $configData.adfsProperties
$attributeStores = $configData.attrStores
$serviceAccount = $configData.svcAcct
# If the $GetConfig script block is invoked on a remote computer, the relying party objects will be deserailized.
# It is possible that the content of the claim descriptions are not restored during deserialization.
# Only the type of the claim descriptions are stored, e.g., the value of $rpTrusts[0].ClaimsAccepted[0] would be
# "Microsoft.IdentityServer.PowerShell.Resources.ClaimDescription".
#
# If the script block is invoked locally, we won't have this problem. The value of $rpTrusts[0].ClaimsAccepted[0]
# would be of type ClaimDescription.
#
# SamlEndpoints are similar.
# We need to restore claim descriptions and saml endpoints here.
# We can check if the objects are deserialized by check the type of any value in ClaimsAccepted or SamlEndpoints.
# If the type is ClaimDescription, then it is not deserialized.
# If the type is String, then it is deserialized.
$deserialized = $false
$checked = $false
foreach ($rp in $rpTrusts)
{
if ($rp -ne $null)
{
foreach ($c in $rp.ClaimsAccepted)
{
if ($c -ne $null)
{
if ($c -is [System.String])
{
$deserialized = $true
}
$checked = $true
break
}
}
if ($checked)
{
# checking one claim description object is good enough
break
}
foreach ($se in $rp.SamlEndpoints)
{
if ($se -ne $null)
{
if ($se -is [System.String])
{
$deserialized = $true
}
$checked = $true
break
}
}
}
if ($checked)
{
break
}
}
if ($deserialized)
{
# Restore claim descriptions and saml endpoints using the hash tables returned
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Deserialized.ClaimDescription' -PercentComplete 65
$totalNum = 0
$currentNum = 0
$base = 65
$totalWeight = 5
if ($rpTrusts -ne $null)
{
$totalNum += $rpTrusts.Count
}
if ($cpTrusts -ne $null)
{
$totalNum += $cpTrusts.Count
}
if ($totalNum -eq 0)
{
$totalNum = 1
}
$rpClaimsHash = $configData.rpClaimsHash
$rpSamlEnpointsHash = $configData.rpSamlEnpointsHash
foreach ($rp in $rpTrusts)
{
if ($rp -ne $null)
{
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Deserialized.ClaimDescription' -PercentComplete ($currentNum / $totalNum * $totalWeight + $base)
$currentNum += 1
$rp.ClaimsAccepted = $rpClaimsHash[$rp.Name]
$rp.SamlEndpoints = $rpSamlEnpointsHash[$rp.Name]
}
}
$cpClaimsHash = $configData.cpClaimsHash
$cpSamlEnpointsHash = $configData.cpSamlEnpointsHash
foreach ($cp in $cpTrusts)
{
if ($cp -ne $null)
{
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Deserialized.ClaimDescription' -PercentComplete ($currentNum / $totalNum * $totalWeight + $base)
$currentNum += 1
$cp.ClaimsOffered = $cpClaimsHash[$cp.Name]
$cp.SamlEndpoints = $cpSamlEnpointsHash[$cp.Name]
}
}
}
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Test-CliXml' -PercentComplete 70
$totalNum = 0
$currentNum = 0
$base = 70
$totalWeight = 20
if ($rpTrusts -ne $null)
{
$totalNum += $rpTrusts.Count
}
if ($cpTrusts -ne $null)
{
$totalNum += $cpTrusts.Count
}
if ($claims -ne $null)
{
$totalNum += $claims.Count
}
if ($totalNum -eq 0)
{
$totalNum = 1
}
[System.IO.DirectoryInfo]$folder = (Get-Item -Path $Path)
$testPath = $folder.FullName + '\object.xml'
# Test RPs to make sure their exports can be imported
foreach ($obj in $rpTrusts)
{
if ($obj -ne $null)
{
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Test-CliXml RelyingPartyTrust' -PercentComplete ($currentNum / $totalNum * $totalWeight + $base)
$currentNum += 1
Test-CliXml $obj 'RelyingPartyTrust' $testPath
}
}
# Test CPs to make sure their exports can be imported
foreach ($obj in $cpTrusts)
{
if ($obj -ne $null)
{
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Test-CliXml ClaimsProviderTrust' -PercentComplete ($currentNum / $totalNum * $totalWeight + $base)
$currentNum += 1
Test-CliXml $obj 'ClaimsProviderTrust' $testPath
}
}
# Test claim descriptions to make sure their exports can be imported
foreach ($obj in $claims)
{
if ($obj -ne $null)
{
Write-Progress -Activity $activity -Status $status -CurrentOperation 'Test-CliXml ClaimDescription' -PercentComplete ($currentNum / $totalNum * $totalWeight + $base)
$currentNum += 1
Test-CliXml $obj 'ClaimDescription' $testPath
}
}
Write-Progress -Activity $activity -Status $status -CurrentOperation ($_system_translations.ExportSavingFiles) -PercentComplete 90
Write-Host ($_system_translations.ExportSavingFiles) | Out-Null
$rpPath = $folder.FullName + '\rp.xml'
Export-Clixml -Path $rpPath -InputObject $rpTrusts -Force | Out-Null
$cpPath = $folder.FullName + '\cp.xml'
Export-Clixml -Path $cpPath -InputObject $cpTrusts -Force | Out-Null
$claimPath = $folder.FullName + '\claim.xml'
Export-Clixml -Path $claimPath -InputObject $claims -Force | Out-Null
$certPath = $folder.FullName + '\cert.xml'
Export-Clixml -Path $certPath -InputObject $certificates -Force | Out-Null
$propertiesPath = $folder.FullName + '\properties.xml'
Export-Clixml -Path $propertiesPath -InputObject $adfsProperties -Force | Out-Null
$summaryPath = $folder.FullName + '\summary.xml'
$summary.Save($summaryPath) | Out-Null
Write-Host
Write-Host ($_system_translations.ExportFinished -f $folder.FullName) | Out-Null
Write-Host ($_system_translations.TrustExported -f '') | Out-Null
$missingEncryptionTokens = @()
if (($certificates -ne $null) -and ($certificates.EncryptionToken -ne $null) -and ($certificates.EncryptionToken.AdditionalEncryptionTokens -ne $null))
{
foreach ($c in $certificates.EncryptionToken.AdditionalEncryptionTokens)
{
if ($c -ne $null)
{
if ((($c.EncryptedPfx -ne $null) -and ($c.EncryptedPfx.Length -gt 0)) -or (($c.ExportedPfx -ne $null) -and ($c.ExportedPfx.Length -gt 0)))
{
Write-Host ($_system_translations.CertExported -f '', $_system_translations.EncryptionToken, $c.FindValue) | Out-Null
}
else
{
$missingEncryptionTokens += $c
}
}
}
}
$missingSigningTokens = @()
if (($certificates -ne $null) -and ($certificates.SigningToken -ne $null) -and ($certificates.SigningToken.AdditionalSigningTokens -ne $null))
{
foreach ($c in $certificates.SigningToken.AdditionalSigningTokens)
{
if ($c -ne $null)
{
if ((($c.EncryptedPfx -ne $null) -and ($c.EncryptedPfx.Length -gt 0)) -or (($c.ExportedPfx -ne $null) -and ($c.ExportedPfx.Length -gt 0)))
{
Write-Host ($_system_translations.CertExported -f '', $_system_translations.SigningToken, $c.FindValue) | Out-Null
}
else
{
$missingSigningTokens += $c
}
}
}
}
Write-Host
Write-Host ($_system_translations.ImportConfigInfo -f 'Import-FederationConfiguration') | Out-Null
Write-Host ($_system_translations.TargetFarmRequirement -f $adfsProperties.HostName, $serviceAccount) | Out-Null
Write-Host
if (($missingEncryptionTokens.Count -gt 0) -or ($missingSigningTokens.Count -gt 0))
{
Write-Host $_system_translations.CertNotExportedWarning
Write-Host
foreach ($c in $missingEncryptionTokens)
{
if ($c -ne $null)
{
Write-Host ($_system_translations.CertTypeInfo -f '', $_system_translations.EncryptionToken)
Write-Host ($_system_translations.ThumbprintInfo -f '', $c.FindValue)
Write-Host ($_system_translations.CertStoreInfo -f '', $c.StoreLocationValue, $c.StoreNameValue)
Write-Host
}
}
foreach ($c in $missingSigningTokens)
{
if ($c -ne $null)
{
Write-Host ($_system_translations.CertTypeInfo -f '', $_system_translations.SigningToken)
Write-Host ($_system_translations.ThumbprintInfo -f '', $c.FindValue)
Write-Host ($_system_translations.CertStoreInfo -f '', $c.StoreLocationValue, $c.StoreNameValue)
Write-Host
}
}
}
if ($attributeStores -ne $null)
{
$storeWarningShown = $false
foreach ($store in $attributeStores)
{
if (($store -ne $null) -and ($store.StoreClassification -ne 'ActiveDirectory'))
{
if ($storeWarningShown -eq $false)
{
Write-Host ($_system_translations.AttrStoreWarning)
$storeWarningShown = $true
}
Write-Host ($_system_translations.AttrStoreName -f '', $store.Name)
}
}
if ($storeWarningShown -eq $true)
{
Write-Host
}
}
Write-Host ($_system_translations.MoreHelpMessage -f $HelpFwLink)
Write-Host
Write-Progress -Activity $activity -Status ($_system_translations.ExportFinished) -PercentComplete 100 -Completed
Write-Output $folder.FullName
}
}
}
<#################################################################
# Output exception information
################################################################>
Function Get-ExceptionString
{
Param($ErrorRecord)
Process
{
$exceptionStr = ''
if (($ErrorRecord -ne $null) -and ($ErrorRecord.Exception -ne $null))
{
$exceptionStr = $ErrorRecord.Exception.Message
}
Write-Output $exceptionStr
}
}
<#################################################################
# Test an object using Export-CliXml and Import-CliXml
################################################################>
Function Test-CliXml
{
Param(
$obj,
[string] $type,
[string] $path
)
Process
{
try
{
Export-Clixml -Path $path -InputObject $obj -Force | Out-Null
}
catch
{
throw ($_system_translations.TestExportError -f $type, $obj.Name, $path, (Get-ExceptionString $_))
}
try
{
Import-Clixml -Path $path | Out-Null
}
catch
{
throw ($_system_translations.TestImportError -f $type, $obj.Name, $path, (Get-ExceptionString $_))
}
}
}
$GetConfig = {
Param (
[string[]] $rpId,
[string[]] $cpId,
[string[]] $rpName,
[string[]] $cpName,
[System.Security.SecureString] $certPassword,
[bool] $forced,
$_system_translations,
[System.Management.Automation.PSCredential] $credential,
$verbose
)
$ErrorActionPreference = 'Stop'
$VerbosePreference = $verbose
$ImpersonationContext = [System.Security.Principal.WindowsImpersonationContext]$null
$activity = $_system_translations.ExportConfirmMessageCaption
$status = $_system_translations.ExportConfigurations -f $env:ComputerName
<#################################################################
# Load native functions
################################################################>
Function Add-MigrationUtilites
{
Param()
Process
{
$signature = @'
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool LogonUser(
string username,
string domain,
IntPtr password,
int logonType,
int logonProvider,
out IntPtr token
);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_PROVIDER_WINNT40 = 2;
public const int LOGON32_PROVIDER_WINNT50 = 3;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_NETWORK = 3;
public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
'@
Add-Type -MemberDefinition $signature -Name ExportUtilities -Namespace Microsoft.IdentityServer.Migration -UsingNamespace Microsoft.Win32.SafeHandles -PassThru
}
}
<#################################################################
# Split the combined username string into user and domain
################################################################>
Function SplitUserDomain
{
Param(
[string] $combined,
[ref] $domain,
[ref] $user
)
Process
{
if ($combined -eq $null)
{
$user.Value = $null
$domain.Value = $null
}
else
{
$i = $combined.IndexOf('\')
if ($i -ge 0)
{
$user.Value = $combined.Substring($i + 1)
$domain.Value = $combined.Substring(0, $i)
}
else
{
$user.Value = $combined
$domain.Value = ''
}
}
}
}
<#################################################################
# Do a LogonUser then an impersonation
################################################################>
Function ImpersonateUser
{
Param(
[System.Management.Automation.PSCredential] $cred
)
Process
{
$token = [System.IntPtr]::Zero
$password = [System.IntPtr]::Zero
$ret = $flase
$identity = $null
$user = $null
$domain = $null
SplitUserDomain $cred.UserName ([ref] $domain) ([ref] $user)
try
{
$password = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($cred.Password)
$ret = [Microsoft.IdentityServer.Migration.ExportUtilities]::LogonUser($user, $domain, $password, [Microsoft.IdentityServer.Migration.ExportUtilities]::LOGON32_LOGON_NETWORK_CLEARTEXT, [Microsoft.IdentityServer.Migration.ExportUtilities]::LOGON32_PROVIDER_DEFAULT, [ref] $token)
}
finally
{
# erase password
[System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($password)
$password = $null
}
if ($ret -eq $false)
{
$errCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
$ex = New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList $errCode
$msg = ("{0}`n{1}" -f ($_system_translations.ErrorLog -f 'LogonUser'), $ex.Message)
throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList $errCode, $msg)
}
try
{
$identity = New-Object Security.Principal.WindowsIdentity $token
$identity.Impersonate()
}
catch
{
if ($identity)
{
$identity.Dispose()
$identity = $null
}
if ($token -ne [System.IntPtr]::Zero)
{
[Microsoft.IdentityServer.Migration.ExportUtilities]::CloseHandle($token) | Out-Null
}
throw
}
}
}
<#################################################################
# Get the path to the ADFS config file
################################################################>
Function Get-AdfsInstallationConfigFromRegistry
{
Param()
Process
{
$FederationServiceConfigFilePath = "Microsoft.IdentityServer.Servicehost.exe.config"
$MSISInstallRegistryPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\adfssrv'
$MSISInstallRegistryValue = 'ImagePath'
$ServiceAccountRegistryValue = 'ObjectName'
if ((Test-Path -Path $MSISInstallRegistryPath -PathType Container) -eq $false)
{
throw ($_system_translations.RegistryPathNotFoundError -f $MSISInstallRegistryPath)
}
else
{
$key = Get-Item -Path $MSISInstallRegistryPath
if (!($key -is [Microsoft.Win32.RegistryKey]))
{
throw ($_system_translations.RegistryKeyReadError -f $MSISInstallRegistryPath)
}
else
{
$configFilePath = $null
$imagePath = $key.GetValue($MSISInstallRegistryValue)
if ($imagePath -eq $null)
{
throw ($_system_translations.RegistryValueReadError -f $MSISInstallRegistryValue,$MSISInstallRegistryPath)
}
else
{
$index = $imagePath.LastIndexOf('\')
if ($index -eq -1)
{
throw ($_system_translations.InvalidInstallationPathError -f $imagePath)
}
else
{
if ($imagePath.StartsWith('"', [System.StringComparison]::OrdinalIgnoreCase))
{
#start at index 1 if this image path is surrounded in quotes
$installPath = $imagePath.Substring(1, $index)
}
else
{
$installPath = $imagePath.Substring(0, $index)
}
$configFilePath = ($installPath + '\' + $FederationServiceConfigFilePath)
}
}
$svcAcct = $key.GetValue($ServiceAccountRegistryValue)
if ($svcAcct -eq $null)
{
throw ($_system_translations.RegistryValueReadError -f $MSISInstallRegistryValue, $ServiceAccountRegistryValue)
}
$result = New-Object PSObject -Property @{ 'ConfigFilePath' = $configFilePath; 'ServiceAccount' = $svcAcct }
Write-Output $result
}
}
}
}
<#################################################################
# Get SQL policy database connection string
################################################################>
Function Get-PolicyConnectionString
{
Param([string] $configFilePath)
Process
{
if ((Test-Path -Path $configFilePath -PathType Leaf) -eq $false)
{
throw ($_system_translations.ConfigFileNotFoundError -f $configFilePath)
}
else
{
$configFile = [xml] (Get-Content -Path $configFilePath)
if ($configFile -eq $null)
{
throw ($_system_translations.ConfigFileReadError -f $configFilePath)
}
else
{
$policyStore = $configFile.SelectSingleNode('//policyStore')
if ($policyStore -ne $null)
{
$connectionString = $policyStore.connectionString
}
if ($connectionString -eq $null)
{
throw ($_system_translations.ConnectionStringReadError -f $configFilePath)
}
else
{
Write-Output $connectionString
}
}
}
}
}
<#################################################################
# Output exception information
################################################################>
Function Get-ExceptionString
{
Param($ErrorRecord)
Process
{
$exceptionStr = ''
if (($ErrorRecord -ne $null) -and ($ErrorRecord.Exception -ne $null))
{
$exceptionStr = $ErrorRecord.Exception.Message
}
Write-Output $exceptionStr
}
}
<#################################################################
# Compare two secure strings
################################################################>
Function Compare-SecureString
{
Param(
[System.Security.SecureString] $left,
[System.Security.SecureString] $right
)
Process
{
$result = $false
if (($left.Length -eq 0) -and ($right.Length -eq 0))
{
$result = $true
}
elseif ($left.Length -eq $right.Length)
{
$bstr1 = $null
$bstr2 = $null
try
{
$bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($left)
$bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($right)
$tmp1 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr1)
$tmp2 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr2)
$result = ($tmp1 -ceq $tmp2)
}
finally
{
if ($bstr1 -ne $null)
{
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr1)
}
if ($bstr2 -ne $null)
{
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr2)
}
}
}
Write-Output $result
}
}
<#################################################################
# Parse a Certificate Refrence from SeviceSettingsData
################################################################>
Function Get-CertificateFromServiceSettingsXml
{
Param(
[System.Xml.XmlElement] $cert,
$svcCerts,
[bool] $exportPfx,
[ref] $certPasswordRef,
[bool] $forced
)
Process
{
if ($cert -ne $null)
{
$properties = @{'StoreNameValue' = $cert.StoreName; 'StoreLocationValue' = $cert.StoreLocation; 'X509FindTypeValue' = $cert.X509FindType; 'FindValue' = $cert.FindValue; 'RawCertificate' = $cert.RawCertificate; 'EncryptedPfx' = $cert.EncryptedPfx }
if (($exportPfx -eq $true) -and ($cert.EncryptedPfx -eq $null))
{
# The certificate is in local store. Try exporting it into pfx.
$svcCert = $svcCerts |? {$_.Thumbprint -eq $cert.FindValue}
if ($svcCert -ne $null)
{
if (($certPasswordRef.Value -eq $null) -or ($certPasswordRef.Value.Length -eq 0))
{
# The password is not specified or empty
if ($forced -eq $true)
{
# Output is suppressed
throw ($_system_translations.CertificatePasswordError)
}
else
{
$firstTime = $true
while (($certPasswordRef.Value -eq $null) -or ($certPasswordRef.Value.Length -eq 0))
{
# Prompting the user to enter a non-empty password
$p1 = $null
if ($firstTime)
{
$prompt = ($_system_translations.ExportCertificatePasswordPrompt)
}
else
{
$prompt = ($_system_translations.MismatchedExportCertificatePasswordPrompt -f ($_system_translations.ExportCertificatePasswordPrompt))
}
while (($p1 -eq $null) -or ($p1.Length -eq 0))
{
$p1 = Read-Host -Prompt $prompt -AsSecureString
}
# Prompting the user to confirm the password
$p2 = $null
while (($p2 -eq $null) -or ($p2.Length -eq 0))
{
$p2 = Read-Host -Prompt ($_system_translations.ComfirmExportCertificatePasswordPrompt) -AsSecureString
}
# Compare user inputs
$matched = (Compare-SecureString $p1 $p2)
if ($matched -eq $true)
{
$certPasswordRef.Value = $p1
}
$firstTime = $flase
}
}
}
if (($certPasswordRef.Value -ne $null) -and ($certPasswordRef.Value.Length -gt 0))
{
$exportedPfx = $null
try
{
$exportedPfx = $svcCert.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx, $certPasswordRef.Value)
}
catch
{
Write-Warning ($_system_translations.ExportCertificateWarning -f $svcCert.CertificateType, $svcCert.Thumbprint, $svcCert.StoreLocation, $svcCert.StoreName)
Write-Verbose $_
}
if ($exportedPfx -ne $null)
{
$encodedPfx = [System.Convert]::ToBase64String($exportedPfx)
$properties.Add('ExportedPfx', $encodedPfx)
}
}
}
}
$certRef = New-Object PSObject -Property $properties
Write-Output $certRef
}
}
}
<#################################################################
# Parse ADFS certificates refrences from SeviceSettingsData using CertificateType
################################################################>
Function Get-AdfsCertificatesFromServiceSettingsXml
{
Param(
[xml] $serviceSettingsXml,
[string] $certificateType,
[ref] $certPasswordRef,
[bool] $forced
)
Process
{
$svcCerts = $null
$primaryTag = $null
$additionalTag = $null
$svcCerts = Get-AdfsCertificate -CertificateType $certificateType