CertificateValidation/Microsoft.AzureStack.CertificateValidation.psm1

#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 = 'AzureStackEdgeDevice'
            DeviceName = 'DBG-KARB2NP5J'
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            certificatepath = "$ENV:USERPROFILE\Documents\AzureStack\Certificates\AzureStackEdgeDevice"
            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='AzureStackEdgeDevice', 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 ('AzureStackEdgeDevice' -in $certificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $true
            $ParamAttrib.ParameterSetName = 'AzureStackEdgeDevice'

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

            # Create addition parameters for AzureStackEdgeDevice
            $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 'AzureStackEdgeDevice') {
                $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
            }
            $AzureStackEdgeDeviceInternalCertificates = $certificateConfigDataFile.CertificateTypes.AzureStackEdgeDevice.Keys
            if ($key -in $AzureStackEdgeDeviceInternalCertificates) {
                $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 AzureStackEdgeDevice -OutputPath C:\SecureStore\AzureStack
        Create Azure Stack Edge Folders in C:\SecureStore\AzureStack\AzureStackEdgeDevice
    .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
# MIIjhAYJKoZIhvcNAQcCoIIjdTCCI3ECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCApJjuIs9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