CertificateValidation/Microsoft.AzureStack.CertificateValidation.psm1

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
#Requires -RunAsAdministrator
#Requires -Version 5.0

<#############################################################
 # #
 # Copyright (C) Microsoft Corporation. All rights reserved. #
 # #
 #############################################################>


<#
 
.SYNOPSIS
This module is intended to be given to the customer along with their deploymentdata.json
in order to validate the certificates are suitable before Azure Stack deployment.
 
.DESCRIPTION
The validation checks the following:
    Read PFX. Checks for valid PFX file, correct password and warns if public information is not protected by the password.
    Signature Algorithm. Checks the Signature Algorithm is not SHA1
    Private Key. Checks the private key is present and is exported with the Local Machine attribute.
    Cert Chain. Checks certificate chain is in tact including for self-signed certificates.
    DNS Names. Checks the SAN contains relevant DNS names for each endpoint or if a supporting wildcard is present.
    Key Usage. Checks Key Usage contains Digital Signature and Key Encipherment and Enhanced Key Usage contains Server Authentication and Client Authentication.
    Key Size. Checks Key Size is 2048 or larger
    Chain Order. Checks the order of the other certificates making the chain is correct.
    Other Certificates. Ensure no other certificates have been packaged in PFX other than the relevant leaf certificate and its chain.
    No Profile. Checks a new user can load the PFX data without a user profile loaded, mimicking the behavior of gMSA accounts during certificate servicing.
 
 
.EXAMPLE
To Check certificates are ready for install run the following:
Import-Module .\Microsoft.AzureStack.CertificateValidation.psm1
$password = Read-Host -Prompt "Enter PFX Password" -AsSecureString
Start-CertChecker -CertificatePath .\Certificates\ -pfxPassword $password -deploymentDataJSONPath .\DeploymentData.json
 
To import/export certificates as indicated by the output of the above command
Import-Module .\Microsoft.AzureStack.CertificateValidation.psm1
$password = Read-Host -Prompt "Enter PFX Password" -AsSecureString
Start-CertChecker -pfxPassword $password -pfxPath \certificates\acsblob\old_sslblob.pfx -ExportToPath \certificates\acsblob\new_sslblob.pfx [<CommonParameters>]
 
.NOTES
The script expects the certificates in the same directory structure as the install: i.e.
\Certificates\
    \ACSblob
        \ssl.pfx
    \ADFS
        \ssl.pfx
The script requires the deploymentdata.json that will be used for deployment.
 
.LINK
 
#>


$mod = Import-Module $PSScriptRoot\PublicCertHelper.psd1 -Force -PassThru
Import-Module $PSScriptRoot\..\Microsoft.AzureStack.ReadinessChecker.Utilities.psm1 -Force
#setting global variable to true
$GLOBAL:standalone = $true
$ErrorActionPreference = 'Stop'

function Test-AzsCertificatePlacement {
    param ($certificatePath, $certConfig, $UseADFS)
    $thisFunction = $MyInvocation.MyCommand.Name
    # set expected folder names
    $validContainers = $certConfig.Keys | Foreach-Object {$PSITEM}
    if ($validContainers.count -eq 1) {
        if ($validContainers -eq (Split-Path $certificatePath -leaf)) {
            Write-AzsReadinessLog -message ("Single container expected: {0}" -f ($validContainers)) -Type Info -Function $thisFunction
            $folders = (Get-Item -Path $certificatePath)
            $actualContainers = (Get-Item -Path $certificatePath).Name
        }
        else {
            Write-AzsReadinessLog -Message ("Invalid folder name used {0}, expecting {1}. Please correct the folder name and retry. Exiting." -f (Split-Path -Path $certificatePath -leaf),$validContainers) -Type Error -Function $thisFunction -toScreen    
            break
        }
    }
    elseif ($validContainers.count -gt 1) {
        Write-AzsReadinessLog -message ("Multiple containers found. Checking for folders: {0}" -f ($validContainers -join ',')) -Type Info -Function $thisFunction
        # Check directory structure is valid
        $actualContainers = (Get-ChildItem -Path $certificatePath -Directory).Name
        $folders = (Get-ChildItem -Path $certificatePath -Directory)
        if (-not $actualContainers) {
            Write-AzsReadinessLog -message ("Invalid folder structure found in certificate folder {0}, ensure only required folders are present. `nRequired folders: {1}" -f `
                $CertificatePath, `
                ($validContainers -join ', ')`
            ) -Type Error -Function $thisFunction -toScreen
            break
        }
    }
    else {
        Write-AzsReadinessLog -Message "Unable to determine expected certificate placement. Exiting." -Type Error -Function $thisFunction
        break
    }
    
    $compareContainers = Compare-Object -ReferenceObject $validContainers -DifferenceObject $actualContainers
    if ($compareContainers) {
        $invalidContainers = $compareContainers | Where-Object SideIndicator -eq '=>' | Select-Object -ExpandProperty InputObject
        $missingContainers = $compareContainers | Where-Object SideIndicator -eq '<=' | Select-Object -ExpandProperty InputObject
        if (-not $invalidContainers) {$invalidContainers = '[none]'}
        if (-not $missingContainers) {$missingContainers = '[none]'}
        Write-AzsReadinessLog -Message ("Invalid folder structure found in certificate folder {0}, ensure only required folders are present. `nRequired folders: {1} `nInvalid folders: {2} `nMissing folders: {3}" -f `
                $CertificatePath, `
            ($validContainers -join ', '), `
            ($invalidContainers -join ', '), `
            ($missingContainers -join ', ')
        ) -Type Error -Function $thisFunction -toScreen
        Write-AzsReadinessLog -Message 'Expected folder structure is as follows:' -Type Info -Function $thisFunction -toScreen
        Write-AzsReadinessLog -Message "`t$certificatePath" -Type Info -Function $thisFunction -toScreen
        $i = 0
        foreach ($key in $certConfig.keys) {
            $i++
            Write-AzsReadinessLog -Message "`t +--$key" -Type Info -Function $thisFunction -toScreen
            if ($i -lt $certConfig.Keys.count) {
                Write-AzsReadinessLog -Message "`t | \-<customFileName>.pfx" -Type Info -Function $thisFunction -toScreen
            }
            else {
                Write-AzsReadinessLog -Message "`t \-<customFileName>.pfx" -Type Info -Function $thisFunction -toScreen
            }
        }
        Write-AzsReadinessLog -Message "`nCorrect the folder structure and rerun validation." -Type Info -Function $thisFunction -toScreen
        break
    }
    else {
        Write-AzsReadinessLog -Message "Folder structure verified." -Type Info -Function $thisFunction
    }

    # Check there is only a single cert in each folder
    foreach ($folder in $folders) {
        Set-PFXPlacement -path $folder.fullname -certConfig $certConfig
    }
}

function Invoke-AzsCertificateValidation {
    <#
    .SYNOPSIS
        Invoke-Microsoft.AzureStack.CertificateValidation is a standalone wrapper for "certchecker"
    .DESCRIPTION
        Either invokes certificate validation for Azure Stack public certificates or
        import/export routine to correct Azure Stack public certificates
    .EXAMPLE
        $pfxPassword = ConvertTo-SecureString -String '<pfxPassword>' -AsPlainText -Force
        $certificateValidationParams = @{
            CertificateType = 'Deployment'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\Deployment"
            pfxPassword = $pfxPassword
            RegionName = 'east'
            ExternalFQDN = 'azurestack.contoso.com'
            IdentitySystem = 'AAD'
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates multiple certificates are ready for Azure Stack Deployment and Secret Rotation.
    .EXAMPLE
        $pfxPassword = ConvertTo-SecureString -String '<pfxPassword>' -AsPlainText -Force
        $certificateValidationParams = @{
            CertificateType = 'Deployment'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\Deployment"
            pfxPassword = $pfxPassword
            DeploymentDataJSONPath = "$ENV:USERPROFILE\Documents\AzureStack\DeploymentData.json"
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates multiple certificates are ready for Azure Stack Deployment and Secret Rotation using the DeploymentData.json.
    .EXAMPLE
        $pfxPassword = ConvertTo-SecureString -String '<pfxPassword>' -AsPlainText -Force
        $certificateValidationParams = @{
            CertificateType = 'AppServices'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\AppServices"
            pfxPassword = $pfxPassword
            RegionName = 'east'
            ExternalFQDN = 'azurestack.contoso.com'
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates multiple Certificates are ready for AppServices and Azure Stack. Requires certificates in folders DefaultDomain, API, Publishing, Identity respectively.
    .EXAMPLE
        $pfxPassword = ConvertTo-SecureString -String '<pfxPassword>' -AsPlainText -Force
        $certificateValidationParams = @{
            CertificateType = 'IoTHub'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\IoTHub"
            pfxPassword = $pfxPassword
            RegionName = 'east'
            ExternalFQDN = 'azurestack.contoso.com'
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates single Certificates are ready for IoTHub and Azure Stack. Also applicable to EventHubs, DBAdapter and DataboxEdge certificate types.
    .EXAMPLE
        $customCertConfig = @{
            'NWTradersRP' = @{
                DNSName = @('*.nwtraders','admin.nwtraders')
                KeyLength = 4096
            }
            'TailSpinRP' = @{
                DNSName = @('*.tailspin')
                HashAlgorithm = 'SHA386'
            }
        }
 
        $certificateValidationParams = @{
            CustomCertConfig = $customCertConfig
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\CustomRPs"
            pfxPassword = $pfxPassword
            RegionName = 'east'
            ExternalFQDN = 'azurestack.contoso.com'
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates multiple Certificates. Each single certificates should be placed in a subfolder (of CertificatePath) named the same as the key in the custom hashtable e.g. NWTraderRP and TailSpinRP as in the example.
    .EXAMPLE
        $pfxPassword = ConvertTo-SecureString -String '<pfxPassword>' -AsPlainText -Force
        $certificateValidationParams = @{
            CertificateType = 'AzureStackEdge'
            DeviceName = 'DBG-KARB2NP5J'
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\AzureStackEdge"
            pfxPassword = $pfxPassword
            ExternalFQDN = 'azurestack.contoso.com'
        }
        Invoke-AzsCertificateValidation @certificateValidationParams
        Validates multiple certificates are ready for Azure Stack Edge device certificates.
    .PARAMETER CertificateType
        Specifies the Azure Stack certificate type to generate a request for e.g. Deployment, AppServices, EventHubs, IoTHub etc.
    .PARAMETER CertificatePath
        Path to directory structure for Azure Stack Public Certificates.
        The path given for this parameter is expected to contain one of the following sets of sub-directories, each with a single pfx certificate:
        Identity System AAD:
            ACSBlob, ACSQueue, ACSTable, Admin Portal, ARM Admin, ARM Public, KeyVault, KeyVaultInternal, Public Portal
        Identity System ADFS:
            ADFS, Graph, ACSBlob, ACSQueue, ACSTable, Admin Portal, ARM Admin, ARM Public, KeyVault, KeyVaultInternal, Public Portal
    .PARAMETER pfxPassword
        A securestring containing a single password that is common across all certificates
    .PARAMETER deploymentDataJSONPath
        Specifies the Azure Stack deployment deployment data JSON configuration file. Generally only available to the deployment team.
    .PARAMETER ExternalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and ExternalDomainName, must be valid DNSHostName
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name when deploymentdata.json is not used, must be alphanumeric.
    .PARAMETER DeviceName
        Specifies the Device Name of an Azure Stack Edge device.
    .PARAMETER NodeSerialNumber
        Specifies the node serial number(s) of an Azure Stack Edge device.
    .PARAMETER IdentitySystem
        Specifies the Azure Stack deployment's Identity System valid values, AAD or ADFS, for Azure Active Directory and Active Directory Federated Services respectively
    .PARAMETER CustomCertConfig
        Specifies a custom hashtable for custom validation. Minimum required info: @{'CertificateName' = @{DNSName= @('*.rpnamespace')}} where DNSName declared everything left of region.domain.com.
    .PARAMETER CleanReport
        Specifies whether to purge the existing report and start again with a clean report. Execution history and validation data is lost for all Readiness Checker validations.
    .PARAMETER OutputPath
        Specifies custom path to save Readiness JSON report and Verbose log file.
    .LINK
        Deployment Certificate Validation - https://aka.ms/AzsValidateCerts
        PaaS Certificate Validation - https://aka.ms/AzsValidatePaaSCerts
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
 
    #>

    [CmdletBinding()]
    [Alias("Start-CertChecker", "Start-AzsCertChecker", "Start-AzureStackCertChecker", "CertChecker", "Invoke-AzureStackCertificateValidation")]
    Param(
        [Parameter(Mandatory = $true, HelpMessage = "Specify the Azure Stack certificate type to generate a request")]
        [ArgumentCompleter({Get-AzsCertificateTypes | Sort-Object})]
        [ValidateScript({$_ -in (Get-AzsCertificateTypes)})]
        [string]
        $CertificateType,    
    
        [Parameter(Mandatory=$true,HelpMessage="Enter Path to Certificates Directory")]
        [ValidateScript( {Test-Path $_ -PathType Container})]
        [string]
        $CertificatePath,

        [Parameter(Mandatory=$true,ParameterSetName='ConfigValidation',HelpMessage="Enter Azure Stack Region Name")]
        [Parameter(Mandatory=$false,ParameterSetName='CustomValidation',HelpMessage="Enter Azure Stack Region Name")]
        [ValidatePattern('(?# Region must be alphanumeric)^[a-zA-Z0-9]+$')]
        [string]
        $RegionName,

        [Parameter(Mandatory=$true, ParameterSetName='ConfigValidation', HelpMessage="Enter Azure Stack External FQDN")]
        [Parameter(Mandatory=$true, ParameterSetName='CustomValidation', HelpMessage="Enter Azure Stack External FQDN")]
        [Parameter(Mandatory=$true, ParameterSetName='AzureStackEdge', HelpMessage="Enter Azure Stack External FQDN")]
        [Alias("ExternalDomainName", "FQDN")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        [string]
        $ExternalFQDN,

        [Parameter(Mandatory = $true, HelpMessage = "Enter Password for PFX Certificates as a secure string" )]
        [ValidateScript({`
            Test-PasswordLength -MinimumCharactersInPassword 8 -Password $PSITEM -CredentialDescription 'pfxPassword'
            Test-PasswordComplexity -Password $PSITEM -CredentialDescription 'pfxPassword'
        })]
        [securestring]
        $pfxPassword,

        [Parameter(Mandatory = $true, ParameterSetName = "JSON", HelpMessage = "Enter Path to DeploymentData.json")]
        [ValidateScript( {Test-Path $_ -Include *.json})]
        [string]
        $deploymentDataJSONPath,

        [Parameter(Mandatory = $true, ParameterSetName = "CustomValidation", HelpMessage = "Custom Hashtable for custom validation. Minimum required info: @{'CertificateName' = @{DNSName= @('*.rpnamespace')}} where DNSName declared everything left of externalfqdn.com.")]
        [hashtable]
        $customCertConfig,

        [Parameter(HelpMessage = "Directory path for log and report output")]
        [string]$OutputPath = "$ENV:TEMP\AzsReadinessChecker",

        [Parameter(HelpMessage = "Remove all previous progress and create a clean report")]
        [switch]$CleanReport = $false
    )
    
    DynamicParam {
        $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
        $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary
        if ('AzureStackEdge' -in $certificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $true
            $ParamAttrib.ParameterSetName = 'AzureStackEdge'

            $AttribColl = New-Object  System.Collections.ObjectModel.Collection[System.Attribute]
            $AttribColl.Add($ParamAttrib)

            # Create addition parameters for AzureStackEdge
            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('DeviceName', [string],  $AttribColl)
            $RuntimeParamDic.Add('DeviceName', $RuntimeParam)

            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('NodeSerialNumber', [string[]],  $AttribColl)
            $RuntimeParamDic.Add('NodeSerialNumber', $RuntimeParam)
        }
        elseif ('Deployment' -in $certificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $false
            $ParamAttrib.ParameterSetName = 'ConfigValidation'
            $ParamAttrib.HelpMessage = "Specify the target identity system (only required for deployment/infrastructure certificates)"

            $AttribColl = New-Object  System.Collections.ObjectModel.Collection[System.Attribute]
            $AttribColl.Add($ParamAttrib)

            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute(@('AAD','ADFS'))
            # Add the ValidateSet to the attributes collection
            $AttribColl.Add($ValidateSetAttribute)
            $PSBoundParameters["IdentitySystem"] = "AAD"
            # Create addition parameters for AzureStackHub deployment certificates
            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('IdentitySystem', [string],  $AttribColl)
            $RuntimeParamDic.Add('IdentitySystem', $RuntimeParam)
        }
        return $RuntimeParamDic
    }
    process {

        $thisFunction = $MyInvocation.MyCommand.Name
        $GLOBAL:OutputPath = $OutputPath
        Import-Module $PSScriptRoot\..\Microsoft.AzureStack.ReadinessChecker.Reporting.psm1 -Force
        Write-Header -invocation $MyInvocation -params $PSBoundParameters

        # Get/Clean Existing Report
        $readinessReport = Get-AzsReadinessProgress -clean:$CleanReport
        $readinessReport = Add-AzsReadinessCheckerJob -report $readinessReport

        if ($PSCmdlet.ParameterSetName -eq 'JSON') {
            if ($deploymentDataJSONPath) {
                # detect deployment type, get region name and fqdn, and set useADFS flag and directory name
                $deploymentDataJSON = ConvertTo-DeploymentData -path $deploymentDataJSONPath
                $RegionName = $deploymentDataJSON.DeploymentData.RegionName
                $externalFQDN = $deploymentDataJSON.DeploymentData.ExternalDomainFQDN
                if ($deploymentDataJSON.DeploymentData.UseAdfs) {
                    $UseADFS = $true
                    $dirName = 'ADFS'
                }
                elseif ($deploymentDataJSON.DeploymentData.InfraAzureEnvironment) {
                    $UseADFS = $false
                    $dirName = 'AAD'
                }
                else {
                    Write-Error -message "Failed to parse identity store in DeploymentJSON"
                }
            }
        }
        else {
            switch ($PSBoundParameters.IdentitySystem) {
                'ADFS' { $UseADFS = $true; $dirName = 'ADFS' }
                'AAD' { $UseADFS = $false; $dirName = 'AAD' }
            }
        }

        # Join RegionName and ExternalFQDN
        if ($regionName -and $CertificateType -ne 'AzureStackEdge') {
                $ExternalFQDN = "{0}" -f (($regionName,$ExternalFQDN) -join '.')
        }

        # Get certificate Config
        if ($customCertConfig) {
            # Test custom cert structure
            $customCertConfig = Test-CustomCertConfig -customCertConfig $customCertConfig
            if (-not $customCertConfig) {
                Write-AzsReadinessLog -Message "Please correct the custom certificate configuration and retry." -Type Error -Function $thisFunction -toScreen
                break
            }
            $certConfig = $customCertConfig
        }
        else {
            # Get declared configs
            $CertificateType = $PSBoundParameters.CertificateType
            $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
            $certConfig = $certificateConfigDataFile.CertificateTypes[$certificateType]
            if (-not $UseADFS) {
                $certConfig.Remove('Graph')
                $certConfig.Remove('ADFS')
            }
        }
        # Validate certificate placement (single cert in one folder for single certs, multiple correctly named folders for multiple certs (e.g. infra/AppServices))
        Test-AzsCertificatePlacement -UseADFS:$UseADFS -certificatePath $CertificatePath -certConfig $certConfig

        #Validate any certificates
        Write-Log -Message ("Starting Azure Stack {0} Certificate Validation {1} " -f $certificateType[0],$mod.Version) -Type Info -Function $thisfunction -toScreen
        $TestAzsCertificatesResults = foreach ($key in $certConfig.keys) {
            # Handle SANs for Azure Stack Edge certificates with DeviceName and Node serial numbers instead of regionname and fqdn
            # Append region & fqdn to dnsname for the rest
            Write-AzsReadinessLog -Message ("Getting pfx content {0}" -f $certConfig.$key.pfxPath) -Type Info -Function $thisFunction
            $pfxBinary = Get-Content -Path $certConfig.$key.pfxPath -Encoding Byte
            if (-not $pfxBinary) {
                Write-AzsReadinessLog -Message ("Invalid PFX {0}" -f $certConfig.$key.pfxPath) -Type Error -Function $thisFunction
            }
            $azureStackEdgeInternalCertificates = $certificateConfigDataFile.CertificateTypes.AzureStackEdge.Keys
            if ($key -in $azureStackEdgeInternalCertificates) {
                $certConfig.$key.DNSName = $certConfig.$key.DNSName | Foreach-Object {$PSITEM.replace('[[DeviceName]]',$PSBoundParameters.DeviceName).replace('[[NodeSerialNumber]]',$PSBoundParameters.NodeSerialNumber)} | Sort-Object
                $TestAzsRPCertificatesResult = Test-AzSCertificate -CertificateBinary $pfxBinary -CertificatePassword $pfxPassword -ExpectedDomainFQDN $externalFQDN -certConfig $certConfig.$key
            }
            else {                        
                $TestAzsRPCertificatesResult = Test-AzSCertificate -CertificateBinary $pfxBinary -CertificatePassword $pfxPassword -ExpectedDomainFQDN $externalFQDN -certConfig $certConfig.$key
            }
            $TestAzsRPCertificatesResult
        }

        # Copy the log certchecker log for now, until migration can occur.
        Copy-AzsReadinessLogging -ComponentLogFile CertChecker

        # Write results to readiness report
        $readinessReport.CertificateValidation.$certificateType = $TestAzsCertificatesResults
        $readinessReport = Close-AzsReadinessCheckerJob -report $readinessReport
        $readinessReport.CertificateValidation.$certificateType = Test-CertificateReuse -validationResult $readinessReport.CertificateValidation.$certificateType

        Write-AzsReadinessProgress -report $readinessReport
        Write-AzsReadinessReport -report $readinessReport
        Write-Footer -invocation $MyInvocation
    }


}

function Repair-AzsPfxCertificate {
    <#
    .SYNOPSIS
        Re-package PFX files to remediate common packaging problems
    .DESCRIPTION
        Import PFX into local machine store, export the package ensuring chain export, encryption usage etc
    .EXAMPLE
        PS C:\> Repair-AzsPfxCertificate -PfxPassword $pfxPassword -PfxPath .\certificates\ACSBlob\ACSBlob.pfx -ExportPFXPath .\certificates\ACSBlob\ACSBlob_new.pfx
        Import ACSBlob PFX and re-exports it to the same folder with a new name.
    .PARAMETER PfxPassword
        Specifies the password associated with PFX certificate files.
    .PARAMETER PfxPath
        Specifies the path to a problematic certificate that requires import/export routine to fix, as indicated by certificate validation in this tool
    .PARAMETER ExportPFXPath
        Specifies the destination path for the resultant PFX file from import/export routine.
    .PARAMETER OutputPath
        Specifies custom path to save Readiness JSON report and Verbose log file.
    .LINK
        Remediate common issues for Azure Stack PKI certificates - https://aka.ms/AzsRemediateCerts
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false, HelpMessage = "Enter Password for PFX Certificates as a secure string")]
        [ValidateScript({`
            Test-PasswordLength -MinimumCharactersInPassword 8 -Password $PSITEM -CredentialDescription 'pfxPassword'
            Test-PasswordComplexity -Password $PSITEM -CredentialDescription 'pfxPassword'
        })]
        [securestring]
        $pfxPassword,

        [Parameter(Mandatory = $true, HelpMessage = "Path to PFX on disk", ParameterSetName = "ImportExport")]
        [ValidateScript( {Test-Path $_ -Include *.pfx -PathType Leaf})]
        [string]
        $pfxPath,

        [Parameter(Mandatory = $true, HelpMessage = "Destination Path for PFX export", ParameterSetName = "ImportExport")]
        [ValidateScript( {Test-Path -Path (split-path -Path $_ -Parent)})]
        [string]
        $ExportPFXPath,

        [Parameter(HelpMessage = "Directory path for log")]
        [string]$OutputPath = "$ENV:TEMP\AzsReadinessChecker"
    )

    $thisFunction = $MyInvocation.MyCommand.Name
    $GLOBAL:OutputPath = $OutputPath
    Import-Module $PSScriptRoot\..\Microsoft.AzureStack.ReadinessChecker.Reporting.psm1 -Force
    Write-Header -invocation $MyInvocation -params $PSBoundParameters

    Write-AzsReadinessLog -Message ("Starting Azure Stack Certificate Import/Export") -Type Info -Function $thisfunction -toScreen
    Write-AzsReadinessLog -Message "Importing PFX $pfxPath into Local Machine Store" -Type Info -Function $thisfunction -toScreen
    $certificate = Import-AzsCertificate -pfxPath $pfxPath -pfxPassword $pfxPassword
    if (-not $certificate) {
        Write-AzsReadinessLog -Message "Import Failed. Please review log." -Type Error -Function $thisfunction -toScreen
    }
    else {
        Write-AzsReadinessLog -Message "Exporting certificate to $exportPFXPath" -Type Info -Function $thisfunction -toScreen
        Export-AzsCertificate -filePath $ExportPFXPath -certPath $certificate -pfxPassword $pfxPassword
        Write-AzsReadinessLog -Message "Export complete. Removing certificate from the local machine store." -Type Info -Function $thisfunction -toScreen
        Remove-Item $certificate.pspath -Force
        if (-not (Test-Path $certificate.pspath)) {
            Write-AzsReadinessLog -Message "Removal complete." -Type Info -Function $thisfunction -toScreen
        }
        else {
            Write-AzsReadinessLog -Message ("Removal incomplete. Please manually remove {0}." -f $certificate.pspath) -Type Warning -Function $thisfunction -toScreen
        }
    }
    Copy-AzsReadinessLogging -ComponentLogFile CertChecker
    Write-Footer -invocation $MyInvocation
}

function Set-PFXPlacement {
    # checks for a single certificate and sets pfxPath in the certConfig
    param ($path,$certConfig)
    $thisFunction = $MyInvocation.MyCommand.Name
    $pfxfiles = Get-ChildItem $path -Filter *.pfx -ErrorAction SilentlyContinue
    if ($pfxfiles.count -ne 1) {
        Write-AzsReadinessLog -Message ("The certificate path '{0}' should only contain 1 PFX certificate. {1} PFX files found. `nEnsure all certificate folders only contain a single certificate." -f $path, $pfxfiles.count) -Type Error -Function $thisFunction -toScreen
        break
    }
    else {
        Write-AzsReadinessLog -Message ("Single PFX found with name '{0}'. Setting pfxPath in certConfig." -f $pfxfiles.FullName) -Type Info -Function $thisFunction
        $certConfig.$($pfxfiles.Directory.Name).pfxPath = $pfxfiles.FullName
        Write-AzsReadinessLog -Message ("After") -Type Info -Function $thisFunction
    }
}

function Test-CustomCertConfig {
    param ([hashtable]$customCertConfig)
    if ($customCertConfig -isnot [HashTable]) {
        Write-AzsReadinessLog -Message ("Custom Cert Config is not a valid hashtable. `nExpecting at least: `n@{'CertificateName' = @{DNSName= @('*.certificate.domain')}}.") -Type Error -Function $thisfunction -toScreen
        return $false
    }

    foreach ($customCertName in $customCertConfig.Keys) {
        $customCertHash = $customCertConfig.$customCertName
        # Check its a hashtable
        if ($customCertHash -isnot [HashTable]) {
            Write-AzsReadinessLog -Message ("Custom Cert {0} is not a valid hashtable. `nExpecting at least: `n@{'CertificateName' = @{DNSName= @('*.certificate.domain')}}." -f $customCertName) -Type Error -Function $thisfunction -toScreen
            return $false
        }
        else {
            $hashToString = ($customCertHash.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join '; '
            Write-AzsReadinessLog -Message ("Custom Cert is a valid hashtable @{{{0} = @{{{1}}}}}" -f $customCertName,$hashToString) -Type Info -Function $thisfunction
        }

        # Check it has at least a DNSName
        if (-not $customCertHash.DNSName){
            Write-AzsReadinessLog -Message ("Custom cert {0} must contain at least DNSName key. Exiting." -f $customCertName)  -Type Error -Function $thisfunction -toScreen
            return $false
        }
        else {
            Write-AzsReadinessLog -Message ("Custom Config {0} contains DNSName to check" -f $customCertName) -Type Info -Function $thisfunction
        }

        # Add include and exclude test if they're not present
        if (-not $customCertHash.IncludeTests) {
            Write-AzsReadinessLog -Message ("Custom Config {0}. Adding IncludeTests as 'All'" -f $customCertName) -Type Info -Function $thisfunction
            $customCertConfig.$customCertName.IncludeTests = 'All'
        }
        else {
            Write-AzsReadinessLog -Message ("Custom Config {0}. IncludeTests contains {1}" -f $customCertName, $customCertHash.IncludeTests) -Type Info -Function $thisfunction
        }
        if (-not $customCertHash.ExcludeTests) {
            Write-AzsReadinessLog -Message ("Custom Config {0}. Adding ExcludeTests as 'CNG Key'" -f $customCertName) -Type Info -Function $thisfunction
            $customCertConfig.$customCertName.ExcludeTests = 'CNG Key'
        }
        else {
            Write-AzsReadinessLog -Message ("Custom Config {0}. ExcludeTests contains {1}" -f $customCertName, $customCertHash.ExcludeTests) -Type Info -Function $thisfunction
        }
    }
    $customCertConfig
}

function New-AzsCertificateFolder {
    <#
    .SYNOPSIS
        Create folder structure Azure Stack Certificates
    .DESCRIPTION
        Create folder structure Azure Stack Certificates
    .EXAMPLE
        New-AzsCertificateFolder -certificateType Deployment -IdentitySystem AAD -OutputPath C:\SecureStore\AzureStack
        Create Deployment Folders in C:\SecureStore\AzureStack\Deployment
    .EXAMPLE
        New-AzsCertificateFolder -certificateType AppServices -OutputPath C:\SecureStore\AzureStack
        Create AppServices Folders in C:\SecureStore\AzureStack\AppServices
    .EXAMPLE
        New-AzsCertificateFolder -certificateType EventHubs -OutputPath C:\SecureStore\AzureStack
        Create EventHubs Folders in C:\SecureStore\AzureStack\EventHubs
    .EXAMPLE
        New-AzsCertificateFolder -certificateType IoTHub -OutputPath C:\SecureStore\AzureStack
        Create IoTHub Folders in C:\SecureStore\AzureStack\IoTHub
    .EXAMPLE
        New-AzsCertificateFolder -certificateType DataboxEdge -OutputPath C:\SecureStore\AzureStack
        Create DataboxEdge Folders in C:\SecureStore\AzureStack\DataboxEdge
    .EXAMPLE
        New-AzsCertificateFolder -certificateType AzureStackEdge -OutputPath C:\SecureStore\AzureStack
        Create Azure Stack Edge Folders in C:\SecureStore\AzureStack\AzureStackEdge
    .EXAMPLE
        New-AzsCertificateFolder -certificateType DBAdapter -OutputPath C:\SecureStore\AzureStack
        Create DBAdapter Folders in C:\SecureStore\AzureStack\DBAdapter
    .NOTES
        General notes
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param ( 
        [Parameter(Mandatory = $true, HelpMessage = "Destination Path for Certificate")]
        [string]$OutputPath,
        [Parameter(Mandatory = $false, HelpMessage = "Enter Azure Stack Identity System (AAD or ADFS) when generating deployment certificates")]
        [ValidateSet('AAD', 'ADFS')]
        [string]$IdentitySystem
    )
    DynamicParam {
        #Certificate Type Param
        $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
        $ParamAttrib.Mandatory = $true
        $ParamAttrib.ParameterSetName = '__AllParameterSets'

        $AttribColl = New-Object  System.Collections.ObjectModel.Collection[System.Attribute]
        $AttribColl.Add($ParamAttrib)

        $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\..\CertificateValidation\Microsoft.AzureStack.CertificateConfig.psd1
        $certificateTypes = $certificateConfigDataFile.CertificateTypes | Select-Object -ExpandProperty Keys
        $AttribColl.Add((New-Object  System.Management.Automation.ValidateSetAttribute($certificateTypes)))

        $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('CertificateType', [string],  $AttribColl)

        $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary
        $RuntimeParamDic.Add('CertificateType', $RuntimeParam)

        return $RuntimeParamDic
    }
    process
    {
        try {
            # Get Certificate Config
            $CertificateType = $PSBoundParameters.CertificateType
            $certificateConfig = $certificateConfigDataFile.CertificateTypes[$CertificateType]
            if ($certificateType -eq 'Deployment' -AND $IdentitySystem -ne 'ADFS') {
                        $certificateConfig.Remove('Graph')
                        $certificateConfig.Remove('ADFS')
            }

            # Create Folder Structure
            if ($certificateConfig.Keys.count -eq 1) {
                $destination = $OutputPath
            }
            else{
                $destination = Join-Path -Path $OutputPath -ChildPath $CertificateType
            }
            Foreach ($key in $certificateConfig.keys) {
                $newFolder = Join-Path -Path $destination -ChildPath $key
                New-Item -Path $newFolder -ItemType Directory -Force
            }
        }
        catch {
            throw $_.exception
        }
    }
}

function Get-AzsCertificateTypes {
    param ([string[]]$certificateTypeExclusions = @('Hardware'))
    $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
    $certificateTypes = $certificateConfigDataFile.CertificateTypes | Select-Object -ExpandProperty Keys | Where-Object {$PSITEM -notin $certificateTypeExclusions}
    $certificateTypes + 'Custom' | Sort-Object
}
# SIG # Begin signature block
# MIIjigYJKoZIhvcNAQcCoIIjezCCI3cCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDM8U0fzvcaZfmF
# cjZeouXeiLT7LH3h6fkUOjj1/y80rKCCDYUwggYDMIID66ADAgECAhMzAAABUptA
# n1BWmXWIAAAAAAFSMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTkwNTAyMjEzNzQ2WhcNMjAwNTAyMjEzNzQ2WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ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