CertificateValidation/Microsoft.AzureStack.PublicCertificatePackaging.psm1

Import-Module $PSScriptRoot\PublicCertHelper.psm1 -Force -DisableNameChecking
$certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1

class AzsCertificate {
    [string]$ExportFilePath
    [string]$RelativePath
    [string]$FilePath
    [string]$FileName
    [string]$FileExtension
    [secureString]$pfxPassword
    [string]$certificateStore
    [string]$CertificateStorePath
    [System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate
    [bool]$CertificateGroupComplete
    [string]$certificateGroup
    [string]$certificateGroupItem
    [string]$certificateType
    [string]$ErrorMessage
    [bool]$SingleCertificate
}

function ConvertTo-AzsPFX {
    <#
    .SYNOPSIS
        Converts certificates to Azure Stack certificates by packaging them with their private keys and chains into structured folders.
    .DESCRIPTION
        Reads directory for (configurable) file extensions suitable for certificate import (non recursive)
        Imports each file found in (configurable) cert store, defaults to localmachine/Trust, must be localmachine.
        Resolves certificates against Azure Stack config
        Exports certificates as PFX with chain into well structured path e.g. ExportPath\FQDN\CertificateType\Certificate
        ExportPath is user specified, FQDN is read from certificate, CertificateType is read from config, Certificate is read from config.
    .EXAMPLE
        $ExportPath = "$env:USERPROFILE\Documents\AzureStack"
        $pfxPassword = Read-Host -AsSecureString -Prompt "PFX Password"
        ConvertTo-AzsPFX -Path $env:USERPROFILE\Documents\AzureStackCSR -pfxPassword $pfxPassword -ExportPath $ExportPath
        Read certificate files from documents\AzureStack and output PFXs in a folder structure for Azs.
    .PARAMETER Path
        Path containing certificate files to be converted.
    .PARAMETER Filter
        The type of certificate files to convert, valid values: CER, CERT, SST, P7B, PFX.
    .PARAMETER PfxPassword
        Password for inbound and outbound PFX files. If inbound PFX does not have a password, this should be omitted and a prompt will appear during export.
    .PARAMETER ExternalFQDN
        ExternalFQDN of certificates, can be omitted, and will be detected, in the case of detection failure, use this parameter.
    .PARAMETER ExportPath
        Folder where certificate will be exported.
    .PARAMETER CertificateStore
        Certificate store used for packaging, must been a valid path in the local machine store.
    .PARAMETER DisableValidation
        Disables validation after the packaging is complete.
    .PARAMETER DisableChainCheck
        Do not check the chain as part of pre-packaging checks. Time consuming and not a true test of the Azure Stack PKI trust posture if ran externally.
    .PARAMETER OutputPath
        Directory path for log and report output.
    .PARAMETER CleanReport
        Remove all previous progress and create a clean report.
    .NOTES
        Ensure Certificates private key and chain is present in the local machine store when targetting public certificate files.
        Only target one ExternalFQDN at a time.
    #>

    [cmdletbinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param (
        [Parameter(Mandatory = $true, HelpMessage = 'Path containing certificate files to be converted.')]
        [ValidateScript( { Test-Path $PSITEM -PathType Container <# provide valid folder #> })]
        [string]
        $Path,

        [Parameter(Mandatory = $false, HelpMessage = 'The type of certificate files to convert, valid values: CER, CERT, SST, P7B, PFX.')]
        [ValidateSet('CER', 'CERT', 'SST', 'P7B', 'PFX')]
        [string]
        $Filter = 'CER',

        [Parameter(Mandatory = $false, HelpMessage = 'Password for inbound and outbound PFX files. If inbound PFX does not have a password, this should be omitted and a prompt will appear during export.')]
        [SecureString]
        $PfxPassword,

        [Parameter(Mandatory = $false, HelpMessage = 'ExternalFQDN of certificates, can be omitted, and will be detected, in the case of detection failure, use this parameter.')]
        [ValidateScript( { [System.Uri]::CheckHostName($PSITEM) -eq 'dns' <# provide valid fully qualified domain name #> })]
        [string]
        $ExternalFQDN,

        [Parameter(Mandatory = $true, HelpMessage = 'Folder where certificate will be exported.')]
        [ValidateScript( { Test-Path $PSITEM -PathType Container -IsValid <# provide valid path #> })]
        [string]
        $ExportPath,

        [Parameter(Mandatory = $false, HelpMessage = 'Certificate store used for packaging, must been a valid path in the local machine store.')]
        [ValidateScript( { Test-Path $PSITEM -PathType Container; $PSITEM -match "Cert:\LocalMachine\" <# provide valid localmachine certificate store #> })]
        [string]
        $certificateStore = "Cert:\LocalMachine\Trust",

        [Parameter(Mandatory = $false, HelpMessage = "Do not run validation after converting certificates.")]
        [switch]
        $DisableValidation,

        [Parameter(Mandatory = $false, HelpMessage = "Do not check the chain as part of pre-packaging checks.")]
        [switch]
        $DisableChainCheck,

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

        [Parameter(Mandatory = $false, HelpMessage = "Remove all previous progress and create a clean report.")]
        [switch]$CleanReport = $false
    )
    $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 ("`nStage 1: Scanning Certificates" -f $path, $filter) -Type Info -Function $thisFunction -toScreen
    $CertificateFiles = Get-ChildItem -Path $path -Filter ('*.{0}' -f $filter)

    if (-not $CertificateFiles) {
        Write-AzsReadinessLog -message "No certificate files detected in $path with filter: $filter. `nEnsure the path to the certificates is valid. `nExiting" -Type Error -Function $thisFunction -toScreen
        break
    }
    else {
        Write-AzsReadinessLog -message ("`tPath: {0} Filter: {1} Certificate count: {2}" -f $path, $filter, $CertificateFiles.count) -Type Info -Function $thisFunction -toScreen
    }

    # Create array for potential Azure Stack certificates
    $azsCertificates = @()
    $azsCertificates = $CertificateFiles | ForEach-Object { `
            $hash = @{
            FilePath         = $PSItem.FullName
            FileName         = $PSItem.Name
            FileExtension    = $PSItem.Extension
            PfxPassword      = $pfxPassword
            CertificateStore = $certificateStore
        }
        New-Object -TypeName AzsCertificate -Property $hash
    }

    $azsCertificates | Foreach-Object { Write-AzsReadinessLog -message ("`t{0}" -f $PSItem.FileName) -Type Info -Function $thisFunction -toScreen }

    # import/retrieve certificate
    $index = 0
    $azsCertificates | ForEach-Object { `
            # import cert as cert or pfx
            if ($PSItem.FileExtension -match 'pfx') {
            Write-AzsReadinessLog -message ("Inspecting PFX {0} using password supplied" -f $PSItem.FileName) -Type Info -Function $thisFunction
            try {
                $PSItem.Certificate = Import-AzsCertificate -pfxPath $PSItem.FilePath -pfxPassword $PSItem.pfxPassword -certificateStore $PSItem.certificateStore
            }
            catch {
                $azsCertificates[$index].ErrorMessage = "Importfailure: {0}" -f $_.Exception.Message
            }
        }
        else {
            # expect the pkey to be available locally for this path
            Write-AzsReadinessLog -message ("Importing {0}" -f $PSItem.FileName) -Type Info -Function $thisFunction
            try {
                $importResult = Import-Certificate -FilePath $PSItem.FilePath -CertStoreLocation $PSItem.certificateStore
                if ($importResult -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
                    $ImportedLeafCertificate = $importResult
                }
                else {
                    # in the case of p7b the full chain will be passed back, we only want to return the leaf.
                    $ImportedLeafCertificate = $importResult | Where-Object { $_.Subject -notin $importResult.issuer }
                    if ($ImportedLeafCertificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
                        throw "Unexpected import result. Check contents of $($PSItem.FileName)"
                    }
                }
                $PSItem.Certificate = $ImportedLeafCertificate
            }
            catch {
                $azsCertificates[$index].ErrorMessage = "ImportFailure: {0}" -f $_.Exception.Message
            }
        }
        $index++
    }

    if (-not $ExternalFQDN) {
        $ExternalFQDNDetection = @()
        $ExternalFQDNDetection += $azsCertificates.Certificate | ForEach-Object {Get-AzsExternalDomain -certificate $PSItem -dnsNamesFromConfig (Get-AzsCertificateDnsNamesFromConfig)} | Sort-Object | Get-Unique
        if ([System.Uri]::CheckHostName($ExternalFQDNDetection) -eq 'dns') {
            $ExternalFQDN = $ExternalFQDNDetection
            Write-AzsReadinessLog -message ("`nDetected ExternalFQDN: {0}" -f $ExternalFQDN) -Type Info -Function $thisFunction -toScreen
        }
        else {
            Write-AzsReadinessLog -message ("Detection of ExternalFQDN failed. Names detected: {0}" -f ($ExternalFQDNDetection -join ',')) -Type Error -Function $thisFunction -toScreen
            Write-AzsReadinessLog -message ("Please retry using -externalFQDN to target a single external namespace and continue.") -Type Error -Function $thisFunction -toScreen
            break
        }
    }

    # detect potential certificate usage
    # set a flag for single certificate, so we can avoid nested folders
    $matchedAzsCertificates = @()
    $matchedAzsCertificates += foreach ($azsCertificate in $azsCertificates) {
        [array] $relativePaths = Get-AzsCertificateRelativePath -certificate $azsCertificate.certificate -ExternalFQDN $ExternalFQDN -Verbose
        if ($relativePaths.count -eq 0) {
            Write-AzsReadinessLog -message ("`nCertificate {0} did not match any AzureStack namespace requirements with the specified an ExternalFQDN. Skipping certificate." -f $azsCertificate.FileName) -Type Warning -Function $thisFunction -toScreen
        }
        elseif ($relativePaths.count -eq 1) {
            $azsCertificate.RelativePath = $relativePaths.relativePath
            $azsCertificate.SingleCertificate = $relativePaths.SingleCertificate
            Write-AzsReadinessLog -message ("`nCertificate {0} matched {1}. Single Certifcate requirement: {2}" -f $azsCertificate.FileName, $azsCertificate.RelativePath, $azsCertificate.SingleCertificate) -Type Info -Function $thisFunction
            Write-Output $azsCertificate
        }
        elseif ($relativePaths.count -gt 1) {
            foreach ($relativePath in $relativePaths) {
                # create a new certificate for each matched certificate
                $NewAzsCertificate = New-Object -TypeName AzsCertificate
                foreach ($property in $azsCertificate.psobject.Properties.Name) {
                    $NewAzsCertificate.$property = $azsCertificate.$property
                }
                $NewAzsCertificate.RelativePath = $relativePath.RelativePath
                $NewAzsCertificate.SingleCertificate = $relativePath.SingleCertificate
                Write-AzsReadinessLog -message ("`nCertificate {0} matched {1}." -f $NewAzsCertificate.FileName, $NewAzsCertificate.RelativePath) -Type Info -Function $thisFunction
                Write-Output $NewAzsCertificate
            }
        }
        else {
            throw "unexpected error"
        }

    }

    Write-AzsReadinessLog -message ("`nStage 2: Exporting Certificates") -Type Info -Function $thisFunction -toScreen
    if (-not $pfxPassword) {
        $pfxPassword = Read-Host "Provide PFX Password for export" -AsSecureString
        $matchedAzsCertificates | ForEach-Object { if (-not $PSItem.pfxPassword) { $PSItem.pfxPassword = $pfxPassword }}
    }
    # keep track of what has been processed to avoid collisions
    $relativePathsProcessed = @()
    # export certificate if it doesn't collide with anything else (existing file or previous)
    $matchedAzsCertificates | ForEach-Object { `
        $PSItem.certificateGroupItem = Split-Path $PSItem.RelativePath -leaf
        $PSItem.CertificateStorePath = (Join-Path $PSItem.certificateStore $PSItem.Certificate.Thumbprint)
        # ExportFilePath should be nulled if export unsuccesful
        if ($PSItem.SingleCertificate) {
            $relativeFileName = ("{0}\{1}.pfx" -f (Split-Path -Path $PSItem.RelativePath -Parent), ($PSItem.certificateGroupItem.replace(' ', '')))
        }
        else {
            $relativeFileName = ("{0}\{1}.pfx" -f $PSItem.RelativePath, ($PSItem.certificateGroupItem.replace(' ', '')))
        }
        $ExportFilePath = Join-Path $ExportPath $relativeFileName
        Write-AzsReadinessLog -message ("Preparing to export {0} as {1}" -f $PSItem.FileName, $PSItem.RelativePath) -Type Info -Function $thisFunction

        # If path exists, move on
        # TO DO: AppServices DefaultDomain cert can overwrite
        $pathExists = Test-Path $ExportFilePath

        $CertCollision = $PSItem.RelativePath -in $relativePathsProcessed
        $relativePathsProcessed = $PSItem.RelativePath

        if ($pathExists -or $CertCollision) {
            $errorMsg = "Path exists detected: {0}. Certificate Collision detected: {1}. Cannot export to {2}" -f $pathExists, $CertCollision, $relativeFileName
            Write-AzsReadinessLog -message $ErrorMsg -Type Warning -Function $thisFunction
            $ExportFilePath = $null
        }
        else {
            try {
                $partialValidation = PartialValidation -certificate (Get-Item $PSItem.CertificateStorePath) -disableChainCheck:$disableChainCheck
                if (-not (Test-Path (Split-Path -Path $ExportFilePath -Parent))) {
                    New-Item (Split-Path -Path $ExportFilePath -Parent) -ItemType Directory -Force | Out-Null
                }
                Export-AzsCertificate -filePath $ExportFilePath -certPath $PSItem.CertificateStorePath -pfxPassword $PSItem.pfxPassword
                Write-AzsReadinessLog -message "`t$relativeFileName" -Type Info -Function $thisFunction -toScreen
            }
            catch {
                Write-AzsReadinessLog -Message ("Unable to export certificate {0}. Error: {1}" -f $PSItem.RelativePath, $_.exception.message) -Type Error -Function $thisFunction
                $errorMsg = $_.exception.message
                $ExportFilePath = $null
            }
        }
        $PSItem.ExportFilePath = $ExportFilePath
        $PSItem.ErrorMessage = $errorMsg
    }

    # Cleaning certificate array and reporting discards
    $discardedCertificates = $matchedAzsCertificates | Where-Object { -not $_.ExportFilePath }
    if ($discardedCertificates) {
        Write-AzsReadinessLog -Message "`nWARNING: Following certificates will be discarded:" -Type Warning -Function $thisFunction -toScreen
        $discardedCertificates | Format-Table FileName, ErrorMessage
    }

    $matchedAzsCertificates = $matchedAzsCertificates | Where-Object ExportFilePath

    # Write group and type information to work out what "sets" are complete.
    $matchedAzsCertificates | ForEach-Object {
        if ($PSItem.ExportFilePath) {
            $certificateTypeToMatch = Split-Path -Path (Split-Path -Path $PSItem.RelativePath -Parent) -Leaf
            $PSItem.certificateGroup = Set-CertificateGroup -certificateType $certificateTypeToMatch -ExternalFqdn $ExternalFQDN -certificates $matchedAzsCertificates
        }
    }

    $uniqueCertGroups = $matchedAzsCertificates | Where-Object CertificateGroup | Select-Object -expand CertificateGroup | Sort-Object | Get-Unique
    Write-AzsReadinessLog -Message ("Detected complete certificate group for {0}." -f ($uniqueCertGroups -join ',')) -Type Info -Function $thisFunction

    if (-not $DisableValidation -and $uniqueCertGroups) {
        Write-AzsReadinessLog -Message "`nStage 3: Validating Certificates" -Type Info -Function $thisFunction -toScreen
        foreach ($uniqueCertGroup in $uniqueCertGroups) {
            $validationSet = $matchedAzsCertificates | Where-Object CertificateGroup -eq $uniqueCertGroup
            if ($null -notin $validationSet.ExportFilePath) {
                # get unique certificate sets for validation e.g. deployment, iothub etc.
                $singleCertificateSet = $validationSet.SingleCertificate | Sort-Object | Get-Unique

                if ($singleCertificateSet) {
                    $certificatePath = $validationSet.ExportFilePath | ForEach-Object { Split-Path -Path $PSITEM -Parent } | Sort-Object | Get-Unique
                    $CertificateType = $validationSet.RelativePath | ForEach-Object { Split-Path -Path $PSITEM -Parent } | Sort-Object | Get-Unique
                }
                else {
                    $certificatePath = $validationSet.ExportFilePath | ForEach-Object { Split-Path -Parent -Path (Split-Path -Path $PSITEM -Parent) } | Sort-Object | Get-Unique
                    $CertificateType = $validationSet.RelativePath | ForEach-Object { Split-Path -Parent -Path (Split-Path -Path $PSITEM -Parent) } | Sort-Object | Get-Unique
                }

                # check there's only one group before proceding
                $CertificateGroup = $validationSet.CertificateGroup | Sort-Object | Get-Unique
                if ($certificatePath.count -ne 1 -and $CertificateGroup.count -ne 1 -and $certificateType.count -ne 1) {
                    Write-Warning $validationSet
                    throw ("Expected 1 certificate path, set and type. Detected {0} path, {1} sets and {2} types" -f $certificatePath.count, $CertificateGroup.count, $CertificateType.count)
                }

                $ValidationParams = @{
                    CertificateType = $certificatePath.split('\')[-1]
                    CertificatePath = $certificatePath
                    ExternalFQDN    = $CertificateType.split('\')[0]
                    pfxPassword     = $pfxPassword
                    OutputPath      = $OutputPath
                    CleanReport     = $CleanReport
                }

                if ($ValidationParams.CertificateType -eq 'Deployment') {
                    $ValidationParams.Add('IdentitySystem', $CertificateGroup.split('-')[-1])
                }
                Write-AzsReadinessLog -Message ("`nValidating {0} certificates in {1} " -f $uniqueCertGroup, $certificatePath) -Type Info -Function $thisFunction -toScreen
                Invoke-AzsCertificateValidation @ValidationParams
            }
            else {
                Write-AzsReadinessLog -Message ("Certificate validation was skipped due to incomplete certificate validation set {0}" -f $uniqueCertGroup, $_.exception.message) -Type Error -Function $thisFunction -toScreen
                Write-Output $validationSet
            }
        }
    }
    else {
        Write-AzsReadinessLog -Message ("Certificate validation was skipped.") -Type Info -Function $thisFunction -toScreen
    }
    Write-Footer -invocation $MyInvocation
}

function Get-AzsCertificateRelativePath {
    <#
    .SYNOPSIS
        Resolve Certificate Config from Certificate
    .DESCRIPTION
        Helper function to determine what type of Azure Stack certificate (if any) a certificate is.
        The resolution is determined by DNSName, other attributes are intended to be validated later (once packaged).
    .EXAMPLE
        Find-AzsCertificate -certificate $certificate -ExternalFQDN $ExternalFQDN
        Resolve Certificate Config from Certificate
    .INPUTS
        x509certificate
    .OUTPUTS
        Azure Stack CertificateConfig
    .NOTES
        General notes
    #>

    [cmdletbinding()]
    param ([System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate, $externalFQDN, $certificateTypeConfiguration)
    $thisFunction = $MyInvocation.MyCommand.Name
    #TO DO handle (no)externalFQDN

    # Make sure we've got cert config for all certs
    if (-not $certificateTypeConfiguration) {
        $certificateTypeConfiguration = Import-PowerShellDataFile $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
    }
    $certificateTypes = ($certificateTypeConfiguration).CertificateTypes

    # include only hub and RP certificates until support for ASE and Hardware certs is required by this cmdlet.
    foreach ($certificateTypeKey in ($certificateTypes.Keys | Where-Object {$PSITEM -notmatch 'Hardware|AzureStackEdge'})) {
        if ($certificateTypes.$certificateTypeKey.Keys.count -eq 1) {
            $singleCertConfig = $true
        }
        else {
            $singleCertConfig = $false
        }
        foreach ($key in $certificateTypes.$certificateTypeKey.keys) {
            $testDNSNames = Test-DNSNames -cert $Certificate -ExpectedDomain $ExternalFQDN -certConfig $certificateTypes.$certificateTypeKey.$key
            if ($testDNSNames.Result -eq 'OK') {
                $relativePath = "$ExternalFQDN\$certificateTypeKey\$key"
                @{relativePath = $relativePath; SingleCertificate = $singleCertConfig }
            }
        }
    }
}

function PartialValidation {
    <#
    .SYNOPSIS
        Packaging Validation
    .DESCRIPTION
        Packaging Validation to ensure the private key and chain is present
    #>

    param ($certificate, [switch]$DisableChainCheck)
    $thisFunction = $MyInvocation.MyCommand.Name
    if (-not $DisableChainCheck) {
        # Make sure chain is available for packaging
        Write-AzsReadinessLog -message ("Checking the certificate chain is available for packaging") -Type Info -Function $thisFunction
        $ChainCheck = Test-TrustedChain -cert $Certificate
        if ('PartialChain' -in $ChainCheck.outputObject.ChainStatus.Status) {
            Write-AzsReadinessLog -message ("Partial Chain detected") -Type Info -Function $thisFunction
            $missingChainElements = @()
            foreach ($issuer in $ChainCheck.outputObject.ChainElements.Certificate.Issuer) {
                if ($issuer -notin $ChainCheck.outputObject.ChainElements.Certificate.Subject) {
                    $missingChainElements += $issuer
                }
            }
            if ($missingChainElements) {
                Write-AzsReadinessLog -Message ("Missing chain elements {0}. Include certificates for all issuers in the chain in $path" -f ($missingChainElements -join '|')) -Type Error -Function $thisFunction
                throw "Missing Chain"
            }
        }
        if ('UntrustedRoot' -in $ChainCheck.outputObject.ChainStatus.Status) {
            Write-AzsReadinessLog -Message ("UntrustedRoot detected, if this is not on-stamp, this could be by design.") -Type Info -Function $thisFunction
        }
    }

    # Make sure Private Key is available
    $CheckPrivateKey = Test-PrivateKey -cert $Certificate
    if ($CheckPrivateKey.Result -ne 'OK') {
        Write-AzsReadinessLog -Message ("Certificate [{0}] has a problem with its private key. Error: {1}" -f $Certificate.Subject, ($CheckPrivateKey.FailureDetail -join ',')) -Type Error -Function $thisFunction
        throw "No Private Key"
    }
    return $true
}

function Get-AzsCertificateDnsNamesFromConfig {
    <#
    .SYNOPSIS
        Get All Dns Names from config
    .DESCRIPTION
        Get All Dns Name from config
    .EXAMPLE
        PS C:\> Get-AzsCertificateDnsNamesFromConfig
        Get All Dns Names from config
    #>

    # read config and return all DNSNames
    $thisFunction = $MyInvocation.MyCommand.Name
    $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
    $certificateTypes = $certificateConfigDataFile.CertificateTypes
    foreach ($certificateType in $certificateTypes.Keys) {
        $certificateTypes.$certificateType.keys | Foreach-Object { `
                $certificateTypes.$certificateType.$PSITEM.DNSName | Foreach-Object { `
                    $PSITEM
            }
        }
    }
}

function Get-AzsExternalDomain {
    <#
    .SYNOPSIS
        Determines External Domain for Azs Certificate
    .DESCRIPTION
        Read all dnsnames (sans domain) from config
        Iterate through every name on the certificate and every name from the config
        If there's a match return the domain sans the names the from the config.
        If the result is unique return the fqdn.
    .EXAMPLE
        Get-AzsExternalDomain -dnsNamesFromConfig (Get-AzsCertificateDnsNamesFromConfig) -certificate $Certificate
        Determines External Domain for Azs Certificate
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    param ([System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate, $dnsNamesFromConfig)
    $thisFunction = $MyInvocation.MyCommand.Name
    # Get DNSNames from Certificate
    $certDNSNames = $certificate.DnsNameList.Unicode

    $fqdns = @()
    # Go through each name on certificate and check each DNS name from config,
    # extract it and return if successful
    $fqdns += foreach ($certDNSName in $certDNSNames) {
        foreach ($dnsName in $certDNSNames) {
            foreach ($dnsConfig in $dnsNamesFromConfig) {
                $cfg = [regex]::Escape($dnsConfig)
                # attempt to remove the config dns name from the certificate dnsname and if successful return the resultant string
                if ($certDNSName -match ('^{0}.|^{1}.' -f $cfg, $cfg.replace($cfg.split('.')[0], '\*'))) {
                    $fqdn = [regex]::Replace($certDNSName, ('^{0}.' -f $cfg), '')
                    if ($fqdn -ne $certDNSName) {
                        $fqdn
                    }
                }
            }
        }
    }

    $uniqueFqdns = $fqdns | Sort-Object | Get-Unique
    if ($uniqueFqdns.count -eq 1) {
        Write-AzsReadinessLog -Message ("Detected an ExternalFQDN: $uniqueFqdns for Certificate {0}" -f $certificate.subject) -Type Info -Function $thisFunction
        $uniqueFqdns
    }
    else {
        Write-AzsReadinessLog -Message ("Cannot detect externalFQDN for Certificate {0}. Detected {1} fqdns: {2}" -f $certificate.subject,$uniqueFqdns.count,($uniqueFqdns -join ',')) -Type Warning -Function $thisFunction
    }
}

function Set-CertificateGroup {
    <#
    .SYNOPSIS
        Set Certificate Group information
    .DESCRIPTION
        Set Certificate Group information
    .EXAMPLE
        PS C:\> Set-CertificateGroup -certificateType Deployment -ExternalFqdn $ExternalFQDN -certificates $AzsCertificates
        Set Certificate Group information
    .NOTES
        General notes
    #>

    param ($certificateType = 'Deployment', $ExternalFqdn, $certificates)
    $thisFunction = $MyInvocation.MyCommand.Name
    # Get Certificate Configs for target certificateType
    $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1
    $certificateConfig = $certificateConfigDataFile.CertificateTypes[$certificateType]

    # Get certificates matching certificateType and ExternalFQDN
    $certificateSet = $certificates | Where-Object { $_.RelativePath -like "$ExternalFqdn\$CertificateType\*"}
    if (-not $certificateSet) {
        return $null
    }
    [array] $certificatesPresent = $certificateSet.RelativePath | Foreach-Object { $PSITEM.split('\')[2] }
    [array] $certificatesExpected = $certificateConfig.Keys

    # Compare certificates against config
    [array] $compareResult = Compare-Object $certificatesPresent $certificatesExpected -PassThru | Sort-Object

    # null = full set
    # ADFS and Graph missing only means AAD support
    # anything else is not a full set.
    if ($null -eq $compareResult) {
        # if deployment then ADFS is supported by this set
        Write-AzsReadinessLog -message ("Detected certificate group {0} for {1}" -f $certificateType, $externalFQDN) -Type Info -Function $thisFunction
        if ($certificateType -eq 'Deployment') {
            $certificateType = 'Deployment-ADFS'
        }
        $certificateSetValue = "$ExternalFqdn-$CertificateType"
    }
    elseif (($compareResult -join ',') -eq 'ADFS,Graph') {
        Write-AzsReadinessLog -message ("Detected certificate group {0} for {1}, but ADFS and Graph are missing, only support for Deployment AAD" -f $certificateType, $externalFQDN) -Type Info -Function $thisFunction
        $certificateType = 'Deployment-AAD'
        $certificateSetValue = "$ExternalFqdn-$CertificateType"

    }
    else {
        Write-AzsReadinessLog -message ("No match found: Compare output {0}" -f ($compareResult -join ',')) -Type Warning -Function $thisFunction
    }
    $certificateSetValue
}
# SIG # Begin signature block
# MIIjhgYJKoZIhvcNAQcCoIIjdzCCI3MCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAXkh8YdyNgMQ1I
# mxG37VeEh6W1Me4gtjQVUNMgVvJJqqCCDYEwggX/MIID56ADAgECAhMzAAAB32vw
# LpKnSrTQAAAAAAHfMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD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