Skip to main content

Assign an existing certificate to your IIS website with WiX - Part 2 (PowerShell version)

In my previous post I explained how to assign an existing certificate with a custom action. Because of all kind of IIS Manager related failures I had on my work with this solution I did some research and constructed a version based on the usage of a PowerShell step within the WiX installer.

PowerShellWixExtension

In this new scenario I use the PowerShellWixExtension written by David Gardiner which I found on GitHub. To use this extension you have to add a reference to the PowerShellWixExtension.dll in your WiX Setup project. I added this reference with the published NuGet package. Search for PowershellWixExtension in the store. The further steps to use this library are documented on the GitHub page.

PowerShell script

Add to your WiX setup project a PowerShell file name Add-ExistingCertificateToBinding.ps1 which will contain the steps to find and add the certificate to an existing IIS binding.

Add the below PowerShell code to this file.
param (
    [Parameter(Mandatory = $False, HelpMessage = "The name of the IIS site.")]
    [string] $siteName = "Default Web Site",

    [Parameter(Mandatory = $False, HelpMessage = "The IP address which the IIS binding uses.")]
    [string] $ip,

    [Parameter(Mandatory = $False, HelpMessage = "The port number which the IIS binding uses.")]
    [string] $port = 443,

    [Parameter(Mandatory = $False, HelpMessage = "The host name which the IIS binding uses.")]
    [string] $hostname,

    [Parameter(Mandatory = $True, HelpMessage = "The common name of the client certificate to use..")]
    [string] $certificateCommonName
)

function Execute-WithRetry([ScriptBlock] $command) {
    $attemptCount = 0
    $operationIncomplete = $true
    $maxFailures = 5
    $sleepBetweenFailures = 1

    while ($operationIncomplete -and $attemptCount -lt $maxFailures) {
        $attemptCount = ($attemptCount + 1)

        if ($attemptCount -ge 2) {
            Write-Host "Waiting for $sleepBetweenFailures seconds before retrying..."
            Start-Sleep -s $sleepBetweenFailures
            Write-Host "Retrying..."
        }

        try {
            # Call the script block
            & $command

            $operationIncomplete = $false
        }
        catch [System.Exception] {
            if ($attemptCount -lt ($maxFailures)) {
                Write-Host ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message)
            }
            else {
                throw
            }
        }
    }
}

function Ensure-IISAdministration {
    [CmdletBinding()]
    param ()

    $version = "1.1.0.0"

    if (-not (Get-Module IISAdministration -ListAvailable | Where-Object { $_.Version -eq $version })) {
        Install-Module IISAdministration -RequiredVersion $version -Scope AllUsers -Force
        Write-Host "IISAdministration version '$version' installed on machine."
    }
}

function Get-ClientCertificate {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True)]
        [string] $CommonName
    )

    $certificates = (Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject.StartsWith("CN=$CommonName") })

    $now = Get-Date
    $validCertificate = $null
    $notAfter = $now

    foreach ($certificate in $certificates) {
        if ($certificate.NotBefore -le $now -and $certificate.NotAfter -ge $notAfter) {
            $validCertificate = $certificate
        }
    }

    Write-Verbose ("Found valid certificate '{0}' with expiration date '{1}'." -f $validCertificate.Subject, $validCertificate.NotAfter)

    return $validCertificate
}

function Add-ExistingCertificateToBinding {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $False, HelpMessage = "The name of the IIS site.")]
        [string] $siteName = "Default Web Site",

        [Parameter(Mandatory = $False, HelpMessage = "The IP address which the IIS binding uses.")]
        [string] $ip,

        [Parameter(Mandatory = $False, HelpMessage = "The port number which the IIS binding uses.")]
        [string] $port = 443,

        [Parameter(Mandatory = $False, HelpMessage = "The host name which the IIS binding uses.")]
        [string] $hostname,

        [Parameter(Mandatory = $True, HelpMessage = "The common name of the client certificate to use..")]
        [string] $certificateCommonName
    )

    Ensure-IISAdministration

    if ($ip -eq "*") {
        $ip = $null
    }

    $bindingInformation = $ip + ":" + $port + ":" + $hostname

    $certificate = Get-ClientCertificate -CommonName $certificateCommonName

    if ($certificate -eq $null) {
        Throw "Certificate '$certificateCommonName' not found on server '$ENV:COMPUTERNAME'."
    }

    $binding = Get-IISSiteBinding -Name $siteName -BindingInformation $bindingInformation

    $sslFlag = "None"

    if ($Hostname) {
        $sslFlag = "Sni"
    }

    if ($binding -eq $null) {
        Execute-WithRetry {
            New-IISSiteBinding -Name $siteName -BindingInformation $bindingInformation -Protocol https -CertificateThumbPrint $certificate.Thumbprint -SslFlag $sslFlag -CertStoreLocation Cert:\LocalMachine\My
        }

        Write-Host ("Added web site binding '{0}' to IIS website '{1}'." -f $bindingInformation, $siteName)
    }
    else {
        Execute-WithRetry {
            Remove-IISSiteBinding -Name $siteName -BindingInformation $bindingInformation -Protocol https -RemoveConfigOnly -Confirm:$False
            New-IISSiteBinding -Name $siteName -BindingInformation $bindingInformation -Protocol https -CertificateThumbPrint $certificate.Thumbprint -SslFlag $sslFlag -CertStoreLocation Cert:\LocalMachine\My
        }

        Write-Host ("Modified existing web site binding '{0}' for IIS website '{1}'." -f $bindingInformation, $siteName)
    }
}

Add-ExistingCertificateToBinding -siteName $siteName -ip $ip -port $port -hostname $hostname -certificateCommonName $certificateCommonName

WiX configuration

In the WiX file we have to call this PowerShell function and pass the necessary parameters.
<!-- Add existing client certificate to HTTPS binding -->
<powershell:File Id="AddExistingCertificateToBindingAction"
                 File="[#AddExistingCertificateToBinding]"
                 Arguments="-siteName "[WEBSITE_DESCRIPTION]" -ip "[WEBSITE_BINDING_IP]" -port "[WEBSITE_BINDING_PORT]" -hostName "[WEBSITE_BINDING_URL]" -certificateCommonName "[CERTIFICATE_COMMON_NAME]"" />
We also have to instruct the WIX installer to execute this step after the install is finalized.
<InstallExecuteSequence>
  <Custom Action="PowerShellFilesDeferred" Before="InstallFinalize">NOT Installed</Custom>
</InstallExecuteSequence>

Comments