CertificateValidation/Microsoft.AzureStack.PublicCertificateRequest.psm1

Import-Module $PSScriptRoot\Microsoft.AzureStack.PublicCertificateRequest.Internal.psm1 -Force

function New-AzsCertificateSigningRequest {
    <#
    .SYNOPSIS
        Wrapper function to build SANs and call internal certreq.exe function for multiSAN CSR or SingleSAN CSR
    .DESCRIPTION
        Imports the standard Azure Stack SANs and builds the SAN list, required/recommended certificate attributes and
        calls internal functions to generate multiple Certificate Signing Request files.
    .EXAMPLE
        $certificateRequestParams = @{
            'CertificateType' = 'Deployment'
            'IdentitySystem' = 'AAD'
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'requestType' = 'MultipleCSR'
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates multiple CSRs for deployment of Azure Stack Hub e.g. portal.azurestack.contoso.com, management.azurestack.contoso.com etc..
    .EXAMPLE
        $certificateRequestParams = @{
            'CertificateType' = 'Deployment'
            'IdentitySystem' = 'AAD'
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'KeyLength' = 4096
            'requestType' = 'MultipleCSR'
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates multiple CSRs for deployment of Azure Stack with Key Length of 4096 (rather than default 2048)
    .EXAMPLE
        $certificateRequestParams = @{
            'CertificateType' = 'Deployment'
            'IdentitySystem' = 'AAD'
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'HashAlgorithm' = 'SHA384'
            'requestType' = 'MultipleCSR'
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates multiple CSRs for deployment of Azure Stack with signature algorithm of SHA384 (rather than default SHA256)
    .EXAMPLE
        $certificateRequestParams = @{
            'CertificateType' = 'AppServices' # or DataboxEdge, DBAdapter, EventHubs, IoTHub.
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates multiple CSRs for AppServices of Azure Stack
    .EXAMPLE
        $certificateRequestParams = @{
            CertificateType = 'AzureStackEdgeDevice'
            DeviceName = 'DBG-KARB2NP5J'
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates multiple CSRs for Azure Stack Edge device certificates
    .EXAMPLE
        $certificateRequestParams = @{
            CertificateType = 'AzureStackEdgeVPN'
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates a CSR for a Azure Stack Edge VPN certificate
    .EXAMPLE
        $certificateRequestParams = @{
            CertificateType = 'AzureStackEdgeWifiClient'
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates a CSRs for a Azure Stack Edge Wifi Client certificate
    .EXAMPLE
        $certificateRequestParams = @{
            CertificateType = 'AzureStackEdgeWifiServer'
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            RadiusServerName = 'radiusserver01'
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates a CSRs for a Azure Stack Edge device certificate
    .EXAMPLE
        $certificateRequestParams = @{
            CertificateType = 'AzureStackEdgeWifiClient'
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            EnhancedKeyUsage = @('Server Authentication',@{'Custom Usage' = '1.3.6.1.5.7.8.2.1'})
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsCertificateSigningRequest @certificateRequestParams
        Generates a CSRs for a Azure Stack Edge wifi client certificate with custom OID for enhanced key usage.
        Note: You should include the required usage for the certificate and the custom usage as a hashtable where key = friendlyName; value = OID
    .OUTPUTS
        None - This is a wrapper function that calls an internal function to generate the encoded CSR
    .PARAMETER CertificateType
        Specifies the Azure Stack certificate type to generate a request for e.g. Deployment, AppServices, EventHubs, IoTHub etc.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name when deploymentdata.json is not used, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .PARAMETER DeviceName
        Specifies the serial number of an Azure Stack Edge device.
    .PARAMETER NodeSerialNumber
        Specifies the node name(s) of an Azure Stack Edge device.
    .PARAMETER RadiusServerName
        Specifies the Radius Server name for a wifi server with use on Azure Stack Edge.
    .PARAMETER DistinguishedName
        Specifies a DistinguishedName to be used on the certificate. Must be a valid System.Security.Cryptography.X509Certificates.X500DistinguishedName value.
        Common Name (CN) is not required, the appropriate value for the Azure Stack Service will be placed in the Common Name (CN).
        If a Common Name (CN) is given it will be honoured on every certificate request if supplied.
        Also aliased as subject.
    .PARAMETER DistinguishedNameFlag
        Specifies a string for the distinguished name flag to be used in the distinguished name. UseUTF8Encoding is selected by default. More information on x500DistinguishNameFlags
        can be found at https://aka.ms/dnflags
    .PARAMETER KeyLength
        Defines the length of the public and private key for the certificate request generation. Default is 2048. Valid values 2048, 4096, 8192
    .PARAMETER HashAlgorithm
        Hash Algorithm to be used for the certificate request generation. Default is SHA256. Valid values SHA256, SHA384, SHA512
    .PARAMETER EnhancedKeyUsage
        Extended (Enhanced) Key Usage to be included in the certificate request. Provide the required usage for the target certificate as well as the custom usage in hashtable format.
        e.g. @('Client Authentication','Server Authentication',@{'Custom Usage' = '1.3.6.1.5.7.8.2.1'}) will request Client and Server Auth key usage and the custom usage.
    .PARAMETER RequestType
        Specifies the SAN type of the certificate request. Valid values: MultipleCSR, SingleCSR.
        SingleCSR generates one certificate request for all services (not recommended for production). User will be prompted to confirm use.
        MultipleCSR generates multiple certificate requests, one for each service (strongly recommended in production environments).
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .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 OutputPath
        Specifies custom path to save Readiness JSON report and Verbose log file.
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
    #>

    [outputType([string])]
    [cmdletbinding()]
    [Alias("New-AzsCSR", "New-AzsCertificateRequest", "Write-AzsCertificateRequestFile")]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Specify the Azure Stack certificate type to generate a request")]
        [ArgumentCompleter({Get-AzsCertificateRequestTypes | Sort-Object})]
        [ValidateScript({$_ -in (Get-AzsCertificateRequestTypes)})]
        [string]
        $CertificateType,

        [Parameter(Mandatory = $false, ParameterSetName='AzureStackHub', HelpMessage = "Enter Azure Stack Hub Region Name")]
        [string]$RegionName,

        [Parameter(Mandatory = $true, HelpMessage = "Enter Azure Stack Fully Qualified Domain Name (without region name)")]
        [Alias("FQDN", "ExternalDomainName")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        [string]$ExternalFQDN,

        [Parameter(Mandatory = $false, HelpMessage = 'Provide subject name as a string, CN is not required and will be overwritten. E.g. "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"')]
        [Alias("Subject")]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedName]$DistinguishedName,

        [Parameter(Mandatory = $false, HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

        [Parameter(Mandatory = $false, HelpMessage = 'Provide Key Length: 2048, 4096 or 8192')]
        [ValidateSet(2048, 4096, 8192)]
        [int]$KeyLength = 2048,

        [Parameter(Mandatory = $false, HelpMessage = 'Provide Hash Algorithm: SHA256, SHA384 or SHA512')]
        [ValidateSet('SHA256', 'SHA384', 'SHA512')]
        [System.Security.Cryptography.HashAlgorithmName]$HashAlgorithm = 'SHA256',

        [Parameter(Mandatory = $false, HelpMessage = "Optionally provide Extended (Enhanced) Key Usage. By default, certificate config will be used. e.g. @('Client Authentication', 'Server Authentication', @{'Custom Usage' = '1.3.6.1.5.15.7.3.2'})")]
        $EnhancedKeyUsage,

        [Parameter(Mandatory = $false, HelpMessage = "Enter Certificate Request generation type ('Single' = Request individual wildcard certificates, 'Multiple' = Request single multi domain wildcard certificates")]
        [ValidateSet('MultipleCSR', 'SingleCSR')]
        [string]$requestType = 'MultipleCSR',

        [Parameter(Mandatory = $false, ParameterSetName='AzureStackHub', HelpMessage = "Enter Azure Stack Identity System (AAD or ADFS) when generating deployment certificates")]
        [ValidateSet('AAD', 'ADFS')]
        [string]$IdentitySystem,

        [Parameter(Mandatory = $true, HelpMessage = "Destination Path for Certificate Request(s)")]
        [ValidateScript( {Test-Path -Path $_ -PathType Container <# should be a valid directory path #>})]
        [string]$OutputRequestPath,

        [Parameter(Mandatory = $false, HelpMessage = "Directory path for log and report output")]
        [string]$OutputPath = "$ENV:TEMP\AzsReadinessChecker"
    )
    DynamicParam {
        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 AzureStackEdge
            $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary
                
            $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)
        }
        if ('AzureStackEdgeVPN' -in $CertificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $true
            $ParamAttrib.ParameterSetName = 'AzureStackEdgeVPN'

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

            # Create addition parameters for AzureStackEdge
            $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary

            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('NodeSerialNumber', [string[]],  $AttribColl)
            $RuntimeParamDic.Add('NodeSerialNumber', $RuntimeParam)
        }
        if ('AzureStackEdgeWifiClient' -in $CertificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $true
            $ParamAttrib.ParameterSetName = 'AzureStackEdgeWifiClient'

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

            # Create addition parameters for AzureStackEdge
            $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary

            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('NodeSerialNumber', [string[]],  $AttribColl)
            $RuntimeParamDic.Add('NodeSerialNumber', $RuntimeParam)
        }
        if ('AzureStackEdgeWifiServer' -in $CertificateType) {
            $ParamAttrib = New-Object  System.Management.Automation.ParameterAttribute
            $ParamAttrib.Mandatory = $true
            $ParamAttrib.ParameterSetName = 'AzureStackEdgeWifiServer'

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

            # Create addition parameters for AzureStackEdge
            $RuntimeParamDic = New-Object  System.Management.Automation.RuntimeDefinedParameterDictionary

            $RuntimeParam = New-Object  System.Management.Automation.RuntimeDefinedParameter('RadiusServerName', [string],  $AttribColl)
            $RuntimeParamDic.Add('RadiusServerName', $RuntimeParam)
        }
        if ($RuntimeParamDic) {
            return $RuntimeParamDic
        }
    }
    process
    {
        $thisFunction = $MyInvocation.MyCommand.Name
        $GLOBAL:OutputPath = $OutputPath

        Import-Module $PSScriptRoot\..\Microsoft.AzureStack.ReadinessChecker.Reporting.psm1 -Force
        Import-Module $PSScriptRoot\Microsoft.AzureStack.PublicCertificateRequest.Internal.psm1 -Force
        Write-Header -invocation $MyInvocation -params $PSBoundParameters

        $certificateConfigDataFile = Import-PowerShellDataFile -Path $PSScriptRoot\Microsoft.AzureStack.CertificateConfig.psd1

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

        try {
            # Check Extended Key Usage
            if ($EnhancedKeyUsage) {
                ConvertTo-EnhancedKeyUsage -EnhancedKeyUsages $EnhancedKeyUsage
            }

            foreach ($certificateType in $PSBoundParameters.CertificateType)
            {
                Write-AzsReadinessLog -Message ("Starting Certificate Request Process for {0}" -f $certificateType) -Type Info -Function $thisFunction -toScreen
                
                # Check the DistinguishedName is good to use.
                if ($DistinguishedName) {
                    $testDistinguishedName = Test-DistinguishedName -DistinguishedName $DistinguishedName -DistinguishedNameFlag $DistinguishedNameFlag
                    if (-not $testDistinguishedName) {
                        Write-AzsReadinessLog -Message ("Distinguished name '{0}' cannot be processed with x500DistinguishedName with flag '{1}', explicitly provide the right flag with -DistinguishedNameFlag. See https://aka.ms/azscsr for more information." -f $DistinguishedName,$DistinguishedNameFlag) -Type Error -Function $thisFunction -toScreen
                        break
                    }
                }

                # Check the user provided appropriate parameters
                # IdentitySystem if Deployment certificates are being generated (dynamic parameter do not allow this valdiate on the param block)
                if ($certificateType -eq 'Deployment' -AND $PSBoundParameters.keys -notcontains 'IdentitySystem') {                
                    throw "CertificateType is Deployment and IdentitySystem not provided. Please re-run providing -IdentitySystem valid values are AAD or ADFS."
                }
                # NodeSerialNumber is AzureStackEdgeDevice or AzureStackEdgeWifiClient
                if ($certificateType -in 'AzureStackEdgeDevice','AzureStackEdgeWifiClient' -and !$PSBoundParameters.NodeSerialNumber) {
                    throw "CertificateType is $certificateType and NodeSerialNumber not provided. Please re-run providing -NodeSerialNumber and the appropriate value for your system."
                }
                if ($certificateType -eq 'AzureStackEdgeWifiServer' -and !$PSBoundParameters.RadiusServerName) {
                    throw "CertificateType is $certificateType and RadiusServerName not provided. Please re-run providing -RadiusServerName and the appropriate value for your system."
                }

                $certificateConfig = $certificateConfigDataFile.CertificateTypes[$CertificateType]
                if ($certificateType -eq 'Deployment' -AND $IdentitySystem -eq 'AAD') {
                    Write-AzsReadinessLog -Message "CertificateType is Deployment and IdentitySystem is AAD, removing Graph and ADFS from config" -Type Info -Function $thisFunction
                    $certificateConfig.Remove('Graph')
                    $certificateConfig.Remove('ADFS')
                }
                
                # attributes should be user specified (globally), certificate specific or defaults
                $CertificateDefaults = $certificateConfigDataFile.CertificateDefaults
                foreach ($certificate in  $certificateConfig.Keys) {
                   Write-AzsReadinessLog -Message ("Starting attribute calculation for certificate {0}." -f $certificate) -Type Info -Function $thisFunction
                    foreach ($attribute in $certificateConfig.$Certificate.keys | where-Object {$PSITEM -notin 'DNSName', 'IncludeTests', 'ExcludeTests'}) {
                        Write-AzsReadinessLog -Message ("Starting attribute {0}." -f $attribute) -Type Info -Function $thisFunction
                        # user first
                        if ($attribute -in $PSBoundParameters.Keys) {
                            Write-AzsReadinessLog -Message ("Attribute {0} found on user parameters supplied. Replacing default value ({1}) with ({2})." -f $attribute,$CertificateDefaults[$attribute],$PSBoundParameters[$attribute]) -Type Info -Function $thisFunction
                            $certificateConfig.$Certificate.$attribute = $PSBoundParameters[$attribute]
                        }
                        else {
                            if ($certificateConfig.$Certificate.$attribute -eq 'default') {
                                Write-AzsReadinessLog -Message ("Attribute {0} should be default value ({1})." -f $attribute,$CertificateDefaults[$attribute]) -Type Info -Function $thisFunction
                                $certificateConfig.$Certificate.$attribute = $CertificateDefaults.$attribute
                            }
                            else {
                                Write-AzsReadinessLog -Message ("Attribute {0} is non default, keeping certificate config ({1})." -f $attribute,(($certificateConfig.$Certificate.$attribute) -join ',')) -Type Info -Function $thisFunction
                            }
                        }
                    }
                }

                if ($requestType -eq 'SingleCSR') {
                    # Handle SANs for AzureStackEdge certificates with DeviceName, NodeSerialNumbers, RadiusServerName
                    # Append region & fqdn to dnsname for the rest
                    if ($CertificateType -match 'AzureStackEdge') {
                        foreach ($key in $certificateConfig.Keys) {
                            $certificateConfig.$key.DNSName = $certificateConfig.$key.DNSName | Foreach-Object { `
                                $PSITEM.replace('[[DeviceName]]',$PSBoundParameters.DeviceName).replace('[[NodeSerialNumber]]',$PSBoundParameters.NodeSerialNumber).replace('[[RadiusServerName]]',$PSBoundParameters.RadiusServerName)
                            }
                        }                        
                    }

                    # If region name exists, append region & fqdn to dnsname, otherwise just use fqdn
                    $subjectAlternativeNames = $certificateConfig.Keys | ForEach-Object {$certificateConfig.$PSITEM.DNSName} | Foreach-Object { `
                        if ($PSITEM -ne '') {
                            "{0}.{1}" -f $PSITEM,$externalFQDN
                        }
                        else {
                            $externalFQDN
                        }
                    } | Sort-Object
                    $commonName = $subjectAlternativeNames | Sort-Object | Select-Object -First 1

                    # Set subject to first SAN or (if supplied) honour users common name
                    $certificateSubjectParams = @{
                        distinguishedName           = $DistinguishedName
                        DistinguishedNameFlag       = $DistinguishedNameFlag
                        commonName                  = $commonName
                    }
                    $certificateSubject = Set-CertificateSubject @certificateSubjectParams

                    # set request path to include regionname/devicename, externalfqdn and SingleCSR
                    if ($PSCmdlet.ParameterSetName -eq 'AzureStackEdgeDevice') {
                        $leaf = "{0}_{1}_{2}_SingleCSR" -f $CertificateType,$PSBoundParameters.DeviceName,$ExternalFQDN.replace('.','_')
                        $OutputRequestPathSeed = Join-Path -Path $OutputRequestPath -ChildPath $leaf
                    }
                    else {
                        $OutputRequestPathSeed = Join-Path -Path $OutputRequestPath -ChildPath ("{0}_{1}_SingleCSR" -f $CertificateType,$ExternalFQDN.replace('.','_'))
                    }

                    # TO DO remove this hardcoding of CN for AzureStackEdgeDevice
                    if ($key -in $certificateConfigDataFile.CertificateTypes.AzureStackEdgeDevice.Keys) {
                        $certificateSubject = [System.Security.Cryptography.X509Certificates.X500DistinguishedName]::new("CN=$commonName")
                    }

                    # Call CSR generation
                    $csrParams = @{
                        'subject'                   = $certificateSubject.decode($DistinguishedNameFlag)
                        'subjectAltNames'           = $SubjectAlternativeNames
                        'KeyLength'                 = $certificateConfig.keys | ForEach-Object {$certificateConfig.$PSITEM.KeyLength} | Sort-Object -Descending | Select-Object -first 1
                        'HashAlgorithm'             = $certificateConfig.keys | ForEach-Object {$certificateConfig.$PSITEM.HashAlgorithm} | Sort-Object -Descending | Select-Object -first 1
                        'KeyUsageEKUExtension'      = $certificateConfig.keys | ForEach-Object {$certificateConfig.$PSITEM.EnhancedKeyUsage.Keys} | Sort-Object | Get-Unique
                        'KeyUsage'                  = $certificateConfig.keys | ForEach-Object {$certificateConfig.$PSITEM.KeyUsage.Keys} | Sort-Object | Get-Unique
                        'DistinguishedNameFlag'     = $DistinguishedNameFlag
                        'OutputRequestPath'         = $OutputRequestPathSeed
                    }
                    Write-AzsCertificateRequestFileInternal @csrParams
                }
                else {
                    foreach ($key in $certificateConfig.Keys) {
                        # Handle SANs for AzureStackEdgeDevice appliance certificates with DeviceName and NodeSerialNumbers
                        # Append region & fqdn to dnsname for the rest
                        $AzureStackEdgeDeviceApplianceCertificates = $certificateConfigDataFile.CertificateTypes.AzureStackEdgeDevice.Keys + `
                                                                     $certificateConfigDataFile.CertificateTypes.AzureStackEdgeVPN.Keys + `
                                                                     $certificateConfigDataFile.CertificateTypes.AzureStackEdgeWifiClient.Keys + `
                                                                     $certificateConfigDataFile.CertificateTypes.AzureStackEdgeWifiServer.Keys
                        if ($key -in $AzureStackEdgeDeviceApplianceCertificates) {
                            $certificateConfig.$key.DNSName = $certificateConfig.$key.DNSName | Foreach-Object { `
                                $PSITEM.replace('[[DeviceName]]',$PSBoundParameters.DeviceName).replace('[[NodeSerialNumber]]',$PSBoundParameters.NodeSerialNumber).replace('[[RadiusServerName]]',$PSBoundParameters.RadiusServerName)
                            } | Sort-Object
                        }

                        # If region name exists, append region & fqdn to dnsname, otherwise just use fqdn
                        $subjectAlternativeNames = $certificateConfig.$key.DNSName | Foreach-Object { `
                            if ($PSITEM -ne '') {
                                "{0}.{1}" -f $PSITEM,$externalFQDN
                            }
                            else {
                                $externalFQDN
                            }
                        } | Sort-Object

                        # Set subject to first SAN or (if supplied) honour users common name
                        $commonName = $subjectAlternativeNames | Sort-Object -Descending | Select-Object -First 1
                        $certificateSubjectParams = @{
                            distinguishedName           = $DistinguishedName
                            DistinguishedNameFlag       = $DistinguishedNameFlag
                            commonName                  = $commonName
                        }
                        $certificateSubject = Set-CertificateSubject @certificateSubjectParams

                        # TO DO remove this hardcoding of CN for AzureStackEdgeDevice
                        if ($key -in $certificateConfigDataFile.CertificateTypes.AzureStackEdgeDevice.Keys) {
                            $certificateSubject = [System.Security.Cryptography.X509Certificates.X500DistinguishedName]::new("CN=$commonName")
                        }

                        # Check the object type of EKU
                        if ($certificateConfig.$key.EnhancedKeyUsage -is [HashTable]) {
                            $KeyUsageEKUExtension = $certificateConfig.$key.EnhancedKeyUsage.Keys
                        }
                        else {
                            $KeyUsageEKUExtension = $certificateConfig.$key.EnhancedKeyUsage
                        }

                        $OutputRequestPathSeed = Join-Path -Path $OutputRequestPath -ChildPath $commonName.Replace('.', '_').Replace('*', 'wildcard')
                        # Call CSR generation

                        $csrParams = @{
                            'subject'                   = $certificateSubject.decode($DistinguishedNameFlag)
                            'subjectAltNames'           = $SubjectAlternativeNames
                            'KeyLength'                 = $certificateConfig.$key.KeyLength
                            'HashAlgorithm'             = $certificateConfig.$key.HashAlgorithm
                            'KeyUsageEKUExtension'      = $KeyUsageEKUExtension
                            'KeyUsage'                  = $certificateConfig.$key.KeyUsage.Keys
                            'DistinguishedNameFlag'     = $DistinguishedNameFlag
                            'OutputRequestPath'         = $OutputRequestPathSeed
                        }
                        Write-AzsCertificateRequestFileInternal @csrParams
                    }
                }
            }
        }
        catch {
            Write-AzsReadinessLog -Message ("New-AzsCertificateSigningRequest failed with exception: {0}" -f $_.exception) -Type Error -Function $thisFunction -toScreen
        }
        finally {
            Write-Footer -invocation $MyInvocation
        }

    }
}

function Get-AzsCertificateRequestTypes {
    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 | Sort-Object
}

function Set-AzsCertificateCommonName {
    <#
    .SYNOPSIS
        Set's the CN of the subject to the first DNS name in the SAN
    .DESCRIPTION
        To avoid potential client problems the common name will be made consistent with
        the first DNS Name in the SubjectAlternativeNames
    .EXAMPLE
        Set-AzsCertificateCommonName -subjectAlternativeNames $SANs -SubjectToChange $subject
        This will set the common regardless of it's previous state or value.
    .INPUTS
        SubjectAlternativeNames - string - SANs to parse common from.
        SubjectToChange - OrderedDictionary - may or may not contain a common name.
    .OUTPUTS
        SubjectChanged - OrderedDictionary - with the new or replaced common name
    .NOTES
        General notes
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    [OutputType([System.Collections.Specialized.OrderedDictionary])]
    param ([string]$SubjectAlternativeNames,
        [System.Collections.Specialized.OrderedDictionary]$SubjectToChange
    )

    $thisFunction = $MyInvocation.MyCommand.Name

    # Write CN as first SAN, overwrite as needed.
    $commonName = $SubjectAlternativeNames.split('&')[0].Replace('dns=', '')
    if ($SubjectToChange.CN) {
        Write-AzsReadinessLog -Message ("Found CN = {0} and will remove it" -f $SubjectToChange.CN) -Type Info -Function $thisFunction
        $SubjectToChange.Remove('CN')
    }
    $SubjectToChange.Insert(0, 'CN', $commonName)
    Write-AzsReadinessLog -Message ("Inserted CN = {0}" -f $commonName) -Type Info -Function $thisFunction
    $SubjectChanged = $SubjectToChange
    $SubjectChanged
}

function New-SelfSignedHardwareCertificate {
    <#
    .SYNOPSIS
        Generates Self Signed Certificates for use with Hardware baseboard interfaces
    .DESCRIPTION
        Generates Self Signed Certificates for use with Hardware baseboard interfaces
        Overwrites existing pfx with the same name OutputPath\DNSName.pfx
    .EXAMPLE
        $outputPath = "$ENV:USERPROFILE\Documents\AzureStackCSR"
        $pfxPassword = Read-Host -Prompt "PFX Password" -AsSecureString
        New-SelfSignedHardwareCertificate -CertificateType BMC -DnsRecord node01-bmc -pfxPassword $pfxPassword -OutputPath $ENV:USERPROFILE\Documents\AzureStackCSR
        Creates a self-signed certificate for BMC with a dnsname of node01-bmc and places the pfx in $ENV:USERPROFILE\Documents\AzureStackCSR\node01-bmc.pfx
    .EXAMPLE
        $json = Get-Content "C:\Users\jerskine\OneDrive - Microsoft\DocumentsMSOneDrive\AzureStack\AzsReadinessChecker\TestAssets\DeploymentData.json" | Convertfrom-Json
        $outputPath = "$ENV:USERPROFILE\Documents\AzureStackCSR"
        $pfxPassword = Read-Host -Prompt "PFX Password" -AsSecureString
        $NodeDnsNames = $json.DeploymentData.PhysicalNodes.Name | Foreach-Object {"{0}.{1}.{2}" -f $PSITEM,$json.DeploymentData.RegionName, $json.DeploymentData.ExternalDomainFQDN}
        $NodeDnsNames | Foreach-Object {New-SelfSignedHardwareCertificate -CertificateType BMC -DnsRecord $PSITEM -pfxPassword $pfxPassword -OutputPath $outputPath}
        Creates a self-signed certificate for BMC for each node in a deploymentdata.json
    .OUTPUTS
        PFX File Path - String
    .NOTES
        Intended for deployment team usage at deployment site.
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param ( 
        [Parameter(Mandatory = $true, HelpMessage = "DNS Name for Certificate")]
        [string]
        $DnsRecord,
        [Parameter(Mandatory = $true, HelpMessage = "Password for Certificate")]
        [securestring]
        $pfxPassword,
        [Parameter(Mandatory = $true, HelpMessage = "Destination Path for Certificate")]
        [ValidateScript( {Test-Path -Path $_ -PathType Container <# should be a valid directory path #>})]
        [string]$OutputPath,
        [Parameter(Mandatory = $false, HelpMessage = "Leave certificate in store and pass System.Security.Cryptography.X509Certificates.X509Certificate2 object")]
        [switch]$passThru
    )
    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\Microsoft.AzureStack.CertificateConfig.psd1
        $certificateTypes = $certificateConfigDataFile.CertificateTypes.Hardware | 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 {
            Import-Module $PSScriptRoot\PublicCertHelper.psd1 -force
            $certPath = 'cert:/localmachine/my'
        
            # Get Certificate from config
            $certificateConfig = $certificateConfigDataFile.CertificateTypes.Hardware[$PSBoundParameters.CertificateType]

            # Get certificate default and replace with any values with user supplied values
            $CertificateDefaults = $certificateConfigDataFile.CertificateDefaults

            $certConfig = @{}
            foreach ($key in $certificateConfig.Keys) {
                if ($certificateConfig.$key -eq 'default') {
                    $certConfig.Add($key,$CertificateDefaults.$key)
                }
                else {
                    $certConfig.Add($key,$certificateConfig.$key)
                }
            }

            $NewCertParams = @{
                dnsname = $DnsRecord
                KeyUsage = @($certConfig.KeyUsage.Keys)
                HashAlgorithm = $certConfig.HashAlgorithm 
                KeyLength = $certConfig.KeyLength 
                NotAfter = [System.Datetime]::Now.AddYears(2)
                KeyUsageProperty = 'All'
                Provider = "Microsoft Enhanced RSA and AES Cryptographic Provider"
                KeyExportPolicy = 'Exportable'
                certstorelocation = $certPath
            }

            $certificate = New-SelfSignedCertificate @NewCertParams
            $filePath = Join-Path -Path $OutputPath -ChildPath "$DnsRecord.pfx"
            Export-AzsCertificate -filePath $filePath -certPath $certificate -pfxPassword $pfxPassword
        }
        catch {
            throw $_.exception
        }
        finally {
            if ($passThru) {
                $certificate
            }
            else {
                $certificate | Remove-Item -Force -ErrorAction Continue
                $filePath
            }
        }
    }
}

function ConvertTo-PEM {
    <#
    .SYNOPSIS
        Write the certificate in pem format.
    .DESCRIPTION
        Write the certificate in pem format.
    .EXAMPLE
        $cert = Get-Item Cert:\LocalMachine\my\04B781836CD350D78888FAC5612BCEBA9C2FA25F
        $path = "C:\scratch\{0}.key" -f $cert.Thumbprint
        ConvertTo-PEM -certificate $cert -path $path
        Convert the certificate to PEM format and generate key file.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    [CmdletBinding()]
    param (
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $certificate,
        [ValidateScript( { Test-Path $PSITEM -PathType Container } <#parent path must exist#>)]
        [string]$path
    )
    try {
        # build string
        $sb = [System.Text.StringBuilder]::new()
        [void]$sb.AppendLine('-----BEGIN CERTIFICATE-----')
        $base64 = [System.Convert]::ToBase64String($certificate.RawData, "InsertLineBreaks")
        [void]$sb.AppendLine($base64)
        [void]$sb.AppendLine('-----END CERTIFICATE-----')
        
        # write to file
        $filePath = "{0}\{1}.pem" -f $Path, $certificate.Thumbprint
        $stream = [System.IO.StreamWriter]::new($filePath)
        $stream.WriteLine($sb.ToString())
        $stream.close()
        Write-Verbose "Finished $filePath"

        $key = Write-PrivateKeyFile -path $path -certificate $certificate
        if (-not $key) {
            throw "Failed to create key file"
        }
        $path
    }
    catch {
        throw $_
    }
}

function Write-PrivateKeyFile {
    <#
    .SYNOPSIS
        Write the private key of a certificate in pem format.
    .DESCRIPTION
        Write the private key of a certificate in pem format.
    .EXAMPLE
        $cert = Get-Item Cert:\LocalMachine\my\04B781836CD350D78888FAC5612BCEBA9C2FA25F
        $path = "C:\scratch\{0}.key" -f $cert.Thumbprint
        Write-PrivateKeyFile -certificate $cert -path $path
        Write the private key of certificate to a file named after the certificate thumbprint.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    [CmdletBinding()]
    param (
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $certificate,
        [ValidateScript( { Test-Path $PSITEM -PathType Container } <#parent path must exist#>)]
        [string]$path
    )
    
    try {
        # Get key material
        $key = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
        $Pkcs8 = $key.key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
        $base64 = [Convert]::ToBase64String($Pkcs8, "InsertLineBreaks")

        # Build key string
        $sb = [System.Text.StringBuilder]::new()
        [void]$sb.AppendLine('-----BEGIN RSA PRIVATE KEY-----')
        [void]$sb.AppendLine($base64)
        [void]$sb.AppendLine("-----END RSA PRIVATE KEY-----")

        # write to file
        $filePath = "{0}\{1}.key" -f $Path, $certificate.Thumbprint
        $stream = [System.IO.StreamWriter]::new($filePath)
        $stream.WriteLine($sb.ToString())
        $stream.close()
        Write-Verbose "Finished $filePath"
        $path
    }
    catch {
        throw $_
    }
}
# SIG # Begin signature block
# MIIjhgYJKoZIhvcNAQcCoIIjdzCCI3MCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBz4BxR2HK+I5Ja
# LSQl1yKVAEc6Nz9yamlYpyaa3IabE6CCDYEwggX/MIID56ADAgECAhMzAAABUZ6N
# j0Bxow5BAAAAAAFRMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTkwNTAyMjEzNzQ2WhcNMjAwNTAyMjEzNzQ2WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
# AQ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