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
    .EXAMPLE
        New-AzsCertificateSigningRequest -certificateType Deployment -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .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, 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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .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, HelpMessage = "Enter Azure Stack Hub Region Name")]
        [string]$RegionName,

        [Parameter(Mandatory = $false, 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, HelpMessage = "Enter Azure Stack Identity System (AAD or ADFS) when generating deployment certificates")]
        [ValidateSet('AAD', 'ADFS')]
        [string]$IdentitySystem,

        [Parameter(Mandatory = $false, HelpMessage = "Optionally provide an existing stamp endpoint (region.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 ('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

        # gather attributes from an existing certificate
        if ($StampEndpoint) {
            # Get intended certificate config
            $StampEndpointExpectedConfig = $certificateConfigDataFile.CertificateTypes[$PSBoundParameters.CertificateType]
            $FixedEndpoint = Get-FixedEndPoints -certificateConfig $StampEndpointExpectedConfig -stampEndpoint $stampEndpoint

            # check each endpoint for the certificate and break at the first match
            foreach ($Endpoint in $FixedEndpoint) {
                $csrParams = Get-AzsCSRParameters -StampEndpoint $Endpoint
                if ($csrParams) {
                    break
                }
            }

            if (-not $csrParams){
                $csrParamError = ("Failed to query {0} for existing certificate. Please create certificate signing request as a new request." -f ($FixedEndpoint -join ','))
                Write-AzsReadinessLog -Message $csrParamError -Type Error
                throw $csrParamError
            }

            foreach ($key in $csrParams.Keys) {
                Set-Variable -Name $key -Value $csrParams.$key
            }
        }

        # 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 -not $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')
                }

                # Adding support for multiple node certs, adding and setting DNSName (template) in one go.
                if ($CertificateType -in @('AzureStackEdgeDevice','AzureStackEdgeWifiClient')) {
                    if ($PSBoundParameters.nodeSerialNumber.count -gt 1) {
                        $num = 0
                        $PSBoundParameters.nodeSerialNumber | ForEach-Object {
                            $newNode = $certificateConfig.node.Clone()
                            $nodeKey = "Node{0:d2}" -f $num
                            $certificateConfig.Add($nodeKey,$newNode)
                            $certificateConfig[$nodeKey].DnsName = $PSITEM
                            $num++
                        }
                        $certificateConfig.remove('Node')
                    }
                }

                # 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 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.
#>

    [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"

        if ($certificate.HasPrivateKey) {
            $key = Write-PrivateKeyFile -path $path -certificate $certificate
        }
        else {
            Write-Verbose "Certificate does not contain private key, key file cannot be written"
        }

        if (-not $key) {
            Write-Verbose "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.
#>

    [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 {
        Write-Verbose "Unable to create private key file err: $($_.exception.message)"
    }
}

function New-AzsEdgeDeviceCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Edge Device Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Edge Device certificates
    .EXAMPLE
        $certificateRequestParams = @{
            DeviceName = 'DBG-KARB2NP5J'
            NodeSerialNumber = 'WIN-KARB2NP5J3O'
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsEdgeDeviceCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Edge Device Certificates
    .EXAMPLE
        $certificateRequestParams = @{
            DeviceName = 'DBG-KARB2NP5J'
            NodeSerialNumber = 'WIN-KARB2NP5J3O','WIN-GBWB7ML4K9O'
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsEdgeDeviceCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for multi-node Azure Stack Edge Device Certificates
    .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 externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
#>

    [CmdletBinding()]
    param (
        [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 = $true, HelpMessage = "Enter the Device Name of an Azure Stack Edge device.")]
        [string]$DeviceName,

        [Parameter(Mandatory = $true, HelpMessage = "Enter the Node Serial Number of an Azure Stack Edge device.")]
        [string[]]$NodeSerialNumber,

        [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 = $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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType AzureStackEdgeDevice
}

function New-AzsEdgeVPNCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Edge VPN Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Edge VPN certificates
    .EXAMPLE
        $certificateRequestParams = @{
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            externalFQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsEdgeVPNCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Edge VPN Certificates
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 OutputPath
        Specifies custom path to save verbose log file.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, 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 = $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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType AzureStackEdgeVPN
}

function New-AzsEdgeWifiClientCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Edge Wifi Client Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Edge Wifi Client certificates
    .EXAMPLE
        $certificateRequestParams = @{
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            externalFQDN = 'azurestackedge.contoso.com'
            NodeSerialNumber = "WIN-KARB2NP5J3O"
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsEdgeWifiClientCertificateSigningRequest @certificateRequestParams
        Explanation of what the example does
    .PARAMETER NodeSerialNumber
        Specifies the node name(s) of an Azure Stack Edge device.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, 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 = $true, HelpMessage = "Enter the Node Serial Number of an Azure Stack Edge device.")]
        [string[]]$NodeSerialNumber,

        [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 = $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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType AzureStackEdgeWifiClient
}

function New-AzsEdgeWifiServerCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Edge Wifi Server Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Edge Wifi Server certificates
    .EXAMPLE
        $certificateRequestParams = @{
            Subject = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack Edge"
            RadiusServerName = "radiusserver01"
            FQDN = 'azurestackedge.contoso.com'
            OutputRequestPath = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsEdgeWifiServerCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Edge Wifi Server Certificates
    .PARAMETER RadiusServerName
        Specifies the fully qualifed Radius Server Name of an Azure Stack Edge wifi server.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
#>

    [CmdletBinding()]
    param (
        [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=$true, HelpMessage="Enter the Radius Server Name of an Azure Stack Edge wifi server.")]
        [string]$RadiusServerName,

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

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType AzureStackEdgeWifiServer
}

function New-AzsHubDeploymentCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub Deployment Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub Deployment certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'IdentitySystem' = 'AAD'
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubDeploymentCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub Deployment Certificates
    .EXAMPLE
        New-AzsHubDeploymentCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

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

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType Deployment
}

function New-AzsHubAppServicesCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub AppServices Resource Provider Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub AppServices Resource Provider certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubAppServicesCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub AppServices Resource Provider Certificates
    .EXAMPLE
        New-AzsHubAppServicesCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .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.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType AppServices
}

function New-AzsHubEventHubsCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub Event Hubs Resource Provider Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub Event Hubs Resource Provider certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubEventHubsCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub EventHubs Resource Provider Certificates
    .EXAMPLE
        New-AzsHubEventHubsCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType EventHubs
}

function New-AzsHubIoTHubCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub IoTHub Resource Provider Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub IoTHub Resource Provider certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubIoTHubCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub IoTHub Resource Provider Certificates
    .EXAMPLE
        New-AzsHubIoTHubCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType IoTHub
}

function New-AzsHubDBAdapterCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub DBAdapter Resource Provider Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub DBAdapter Resource Provider certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubDBAdapterCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub DBAdapter Resource Provider Certificates
    .EXAMPLE
        New-AzsHubDBAdapterCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType DBAdapter
}

function New-AzsHubDataBoxEdgeCertificateSigningRequest {
    <#
    .SYNOPSIS
        Generates Certificate Signing Requests for Azure Stack Hub Databox Edge Resource Provider Certificates
    .DESCRIPTION
        Calls New-AzsCertificateSigningRequest with neccessary parameters to generate CSR for Azure Stack Hub DBAdapter Resource Provider certificates
    .EXAMPLE
        $certificateRequestParams = @{
            'regionName' = 'azurestack'
            'externalFQDN' = 'contoso.com'
            'subject' = "C=US,ST=Washington,L=Redmond,O=Microsoft,OU=Azure Stack"
            'OutputRequestPath' = "$ENV:USERPROFILE\Documents\AzsCertRequests"
        }
        New-AzsHubDataBoxEdgeCertificateSigningRequest @certificateRequestParams
        Generates Certificate Signing Requests for Azure Stack Hub Databox Edge Resource Provider Certificates
    .EXAMPLE
        New-AzsHubDataBoxEdgeCertificateSigningRequest -StampEndpoint portal.azurestack.contoso.com -OutputRequestPath "$ENV:USERPROFILE\Documents\AzsCertRequests"
        Connects to existing endpoint https://portal.azurestack.contoso.com read the current SSL certificate, clones the attributes and creates Certificate Signing Requests with those attributes.
        For use with renewal of soon-to-be expired certs.
    .PARAMETER RegionName
        Specifies the Azure Stack deployment's region name, must be alphanumeric.
    .PARAMETER externalFQDN
        Specifies the Azure Stack deployment's External FQDN, also aliased as ExternalFQDN and FQDN, must be valid DNSHostName
    .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 StampEndpoint
        Provide a dns hostname of an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.
    .PARAMETER OutputRequestPath
        Specifies the destination path for certificate request files, directory must already exist.
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .LINK
        Generate Azure Stack Certificate Requests - https://aka.ms/AzsCSR
        Azure Stack Readiness Checker Tool - https://aka.ms/AzsReadinessChecker
    .NOTES
        General notes
    #>

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

        [Parameter(Mandatory = $true, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'Manual', 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, ParameterSetName = 'Manual', HelpMessage = 'Provide X500DistinguishedNameFlags if The distinguished name has special characteristics. Default UseUTF8Encoding.')]
        [System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]$DistinguishedNameFlag = 'UseUTF8Encoding',

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

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

        [Parameter(Mandatory = $false, ParameterSetName = 'Manual', 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 = $true, ParameterSetName = 'ExistingEndpoint', HelpMessage = "Optionally provide an existing stamp endpoint (region.external.fqdn) to clone the certificate attributes to be used to generate the certificate signing request.")]
        [ValidateScript( {[System.Uri]::CheckHostName($_) -eq 'dns' <#FQDN must be valid DNSHostName#>})]
        $StampEndpoint,

        [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 = $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"

    )
    New-AzsCertificateSigningRequest @PSBoundParameters -CertificateType DataBoxEdge
}

function Get-AzsCSRParameters {
    <#
    .SYNOPSIS
        Get CSR parameters from existing endpoint.
    .DESCRIPTION
        Get CSR parameters from existing endpoint.
    .EXAMPLE
        PS C:\> Get-AzsCSRParameters -StampEndpoint management.east.azurestack.contoso.com
        Explanation of what the example does
    .INPUTS
        Uri - System.Uri
    .OUTPUTS
        Hashtable
    .NOTES
        General notes
    #>

    param ([System.Uri]$StampEndpoint,$OutputRequestPath,$OutputPath)

    Write-AzsReadinessLog -Message ("Querying StampEndpoint {0} for existing certificate" -f $StampEndpoint) -Type Info -ToScreen
    if (Resolve-DnsName -Name $StampEndpoint -ErrorAction SilentlyContinue -QuickTimeout) {
        #try and retrieve certificate inventory from SSL endpoint
        try {
            foreach ($port in 443,44300) {
                try {
                    $Timeout = 1000
                    $tcpClient = New-Object System.Net.Sockets.TcpClient
                    $portOpened = $tcpClient.ConnectAsync($StampEndpoint.OriginalString, $port).Wait($Timeout)
                    if ($portOpened) {            
                        #create service connection point to the target SSL endpoint
                        $SSLEndPoint = "https://{0}:{1}" -f $StampEndpoint, $port
                        Write-AzsReadinessLog -Message ("Testing StampEndpoint {0}." -f $SSLEndPoint) -Type Info -ToScreen
                        try {
                            $null = Invoke-WebRequest $SSLEndPoint -TimeoutSec 3 -ErrorAction SilentlyContinue
                        }
                        catch { <# ignore webrequest errors for now #> }

                        # read certificate
                        $servicePoint = [System.Net.ServicePointManager]::FindServicePoint($SSLEndPoint)
                        [System.Security.Cryptography.X509Certificates.X509Certificate2]$certificate = $servicePoint.Certificate
                
                        # if we were succesfully, break so we dont waste time checking other ports.
                        if ($certificate) { break }
                        else {
                            throw "Unable to read certificate from $SSLEndPoint" 
                        }
                    }
                }
                catch {
                    throw $_.exception.message # allow errors, we only want the certificate from the handshake and will catch a null certificate instead.
                }
                
            }

            Import-Module $PSScriptRoot\Microsoft.AzureStack.PublicCertificatePackaging.psm1 -force
            $externalFqdn = Get-AzsExternalDomain -dnsNamesFromConfig (Get-AzsCertificateDnsNamesFromConfig) -certificate $Certificate

            # If subject contains a DNSName, remove it to let the tool populate it normally,
            # We don't want to take a single distinguished name throughout all certificates e.g. cn=adminportal on portal certificate etc.
            # If subject does not contain a DNSName, the previous certificate had a custom subject that must be honoured. e.g. CN=Contoso Cloud.
            foreach ($name in $certificate.DnsNameList.Unicode) {
                if ($certificate.SubjectName.Name -like "*CN=$Name*") {
                    $subject = $certificate.SubjectName.Format($true) -split "`n" | Where-Object { $PSITEM -inotmatch 'cn=' -and $PSITEM -ne ""}
                }
                break
            }
            if (-not $subject) {
                $subject = $certificate.SubjectName.Name
                Write-AzsReadinessLog -Message ("Custom subject detected {0}." -f $subject) -Type Info
            }
            else {
                $subject = $subject.replace("`r","") -join ', '
                Write-AzsReadinessLog -Message ("Tool generated subject detected {0}. Removing common name and continuing." -f $subject) -Type Info
            }

            # convert Oid to HashAlgorithm Name
            try {
                [System.Security.Cryptography.HashAlgorithmName]$algorithm = ($certificate.SignatureAlgorithm.FriendlyName | select-string -Pattern 'SHA[0-9]{3}').Matches[0].value
                if (-not $algorithm) {
                    throw $_
                }
            }
            catch {
                $errmsg = ("Unable to convert {0} to type System.Security.Cryptography.HashAlgorithmName Error:{1}" -f $certificate.SignatureAlgorithm.FriendlyName, $_.exception.message)
                Write-AzsReadinessLog -Message $errmsg -Type Error -toScreen
                throw $_.exception.Message
            }

            # construct params needed to request new certificate.
            $params = @{
                DistinguishedName = $subject.ToString()
                ExternalFQDN      = $externalFqdn
                KeyLength         = $certificate.PublicKey.Key.KeySize
                HashAlgorithm     = $algorithm
            }

            # If this is Azure Stack Hub Deployment certificates, get IdentitySystem and add to parameters
            if ((Get-PSCallStack).arguments -match 'CertificateType=Deployment') {
                try {
                    $ADFSRequest = Invoke-WebRequest "https://adfs.$externalFqdn/FederationMetadata/2007-06/FederationMetadata.xml" -UseBasicParsing -ErrorAction SilentlyContinue
                    if ($ADFSRequest.StatusCode -ne 200) {
                        $params.Add('IdentitySystem','ADFS')
                        Write-AzsReadinessLog -Message ("Checking for ADFS endpoint. Found") -Type Info
                    }
                    else {
                        throw ("ADFS Request failed with: {0} - {1}" -f $ADFSRequest.StatusCode, $ADFSRequest.StatusDescription)
                    }
                }
                catch {
                    Write-AzsReadinessLog -Message ("Checking for ADFS endpoint failed with {0}. Setting identity system to AAD." -f $_.exception.message) -Type Info
                    $params.Add('IdentitySystem','AAD')
                }
            }

            $paramToString = ($params.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join ';'
            Write-AzsReadinessLog -Message ("Found CSR params {0}" -f ($paramToString)) -Type Info
            $params
        }
        catch {
            $ConnectionError = $_.exception.message
            Write-AzsReadinessLog -Message ("Failed to query {0} for existing certificate. Error: {1}" -f $SSLEndPoint,$ConnectionError) -Type Error -ToScreen
            break
        }
    }
    else {
        Write-AzsReadinessLog -Message ("Unable to resolve StampEndpoint {0}. Ensure StampEndpoint can be resolved." -f $StampEndpoint) -Type Error -ToScreen
        break
    }
}

function Get-FixedEndPoints {
    <#
    .SYNOPSIS
        Resolve fixed endpoints to check existing certificates against.
    .DESCRIPTION
        Resolve fixed endpoints to check existing certificates against, first by using FixedEndPoint property of
        certificate configuration, and fall back to dnsname and remove any wildcards.
    #>

    [cmdletbinding()]
    param (
        [ValidateNotNullOrEmpty()]
        $certificateConfig,
        [ValidateNotNullOrEmpty()]
        $stampEndpoint)

    $fixedEndPoints = @()
    $fixedEndPoints = $certificateConfig.Keys | ForEach-Object {`
        if ($certificateConfig[$_].FixedEndPoint) {
            $certificateConfig[$_].FixedEndPoint
        } 
        else {
            $certificateConfig[$_].DnsName
        }
    }
    $output = $fixedEndPoints | where-object {$PSITEM -notmatch '\*.'} | Sort-Object -Descending | Foreach-Object {"{0}.{1}" -f $PSITEM, $stampEndpoint}
    Write-AzsReadinessLog -Message ("Resolved fixed endpoints {0}" -f $fixedEndPoints -join ',')
    return $output
}
# SIG # Begin signature block
# MIIjigYJKoZIhvcNAQcCoIIjezCCI3cCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDKsJDwMeEvv3IG
# tuEQyM5xxDEGgI5pUS83QTy4IeGcVaCCDYUwggYDMIID66ADAgECAhMzAAABiK9S
# 1rmSbej5AAAAAAGIMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjAwMzA0MTgzOTQ4WhcNMjEwMzAzMTgzOTQ4WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqG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