Renewing (or enabling) Windows Remote Management (WinRM) over HTTPS

This post became possible due to the work done by these 2 persons:
Laurie Rhodes and of course Vadims Podans
So don’t thank me for the “hard work” thank me only for the little adjustments that needed to be done to make this working…

So, the problem: Set up WinRM over HTTPs, so that you can securely remote manage a window server with WinRM and Powershell. Since we are sometimes cheap, we like to use a self signed certificate and work with firewalled servers so that not every1 can connect to the WinRM if they like to.
We once have set up WinRM on our remote server with a self signed certificate, but that worked for only 1 year and a few weeks/months. I say AND a few weeks/month because of the Spooky Certificate issue.
So today we ran into the issue that when trying to connect to our remote server we get this error:
WinRM testing failed with the following error:

Connecting to remote server XXX.XXX.XXX.XXX failed with the following error message: The server certificate on the destination computer (XXX.XXX.XXX.XXX:5986) has the following errors: The SSL certificate is expired.

Trying to renew this certificate is not easy, to I search together with my friend Google for a #HowToFixThis 🙂

Firstly, you need to remove the WinRM listener using the expired certificate :

  • Open an elevated command prompt or PowerShell prompt.
  • View the currently existing listener with the following command:
    winrm get winrm/config/listener?Address=*+Transport=HTTPS 
    
  • The CertificateThumbprint will match what is seen on the certificate.
  • To remove the listener use the following command:
    winrm delete winrm/config/Listener?Address=*+Transport=HTTPS

    Secondly: Remove the expired certificate with MMC

  • Click Run, then type MMC.
  • Go to File > Add/Remote Snap-in.
  • Select Certificates then click Add.
  • Select the Computer Account option.
  • In the left-hand pane, expand Certificates > Personal > Certificates.
  • Right-click the certificate and click Delete.

Now, creating the certificate: I need to use the Enhanced version of the, due to limitations in the Windows 2012 New-SelfSignedCertificate Powershell Module.
Download New-SelfSignedCertificateEx.zip
Extract in to a folder somewhere (eg: D:\Tools)
Open and run in an Admin PS console:

Import-Module D:\Tools\New-SelfSignedCertificateEx.ps1

Create a 2nd file D:\Tools\CreateWinRMCert.ps1 with the following content:
Note: change 2 things in this script if wanted:
* On line that start with: New-SelfSignedCertificateEx
-NotAfter (Get-Date).AddMonths(60)
to a value that you like. By default, not adding this variable, yournew certificate wil be valid for 12 months only.
* At the end of the script, change your export password
-ExportPassword "S3cr3tP4ssw0rd"

 
<##############################################################################
 #  Create-WinRMCert (-FriendlyName "WinRMCert" -ExportPassword "MyPassword")
 #
 #          Creates a self-signed cerificate for use with WinRM
 ##############################################################################>
function Create-WinRMCert(){
	param (
        # Create a Unique Friendly Name tag
		[Parameter(Mandatory = $false)]
		[string]$FriendlyName,
		[Parameter(Mandatory = $true)]
		[string]$ExportPassword
)
 
$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$Hostname = "{0}.{1}" -f $ipProperties.Hostname,$ipProperties.DomainName
$Hostname = $Hostname.ToLower() 
 
# The File location for the exported Certificate
$ExportCertFile    = "$($env:TEMP)\$($Hostname).pfx"
 
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Script must be run with Admin Privileges"
    Break
}
 
 
New-SelfSignedCertificateEx -Subject "CN=$($Hostname)" -StoreLocation LocalMachine -FriendlyName $FriendlyName -EnhancedKeyUsage @("1.3.6.1.5.5.7.3.1") -Exportable -SignatureAlgorithm SHA256  -NotAfter (Get-Date).AddMonths(60)
  
# Create a handle to the certificate
# Note that multiple certificates with the same friendly name could be returned
# We will assume the desired certificate is the first in the returned array
$foundCertArray = get-childitem cert:\LocalMachine\My | where-object {$_.FriendlyName -eq  $FriendlyName }
 
 
#Export the Certificate - can't rely upon 'Export-Certificate' being available
"Exporting Certificate $($foundCertArray[0].Thumbprint)"
 
If (Test-Path $ExportCertFile){ Remove-Item $ExportCertFile }
 
 
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::pfx
 
[byte[]]$Bytes  = $foundCertArray[0].Export($type, $ExportPassword)
 
[io.file]::WriteAllBytes($ExportCertFile,$Bytes)
 

  Write-Debug "Thumbprint = $foundCertArray[0].Thumbprint)"
 

  Start-Process -FilePath "C:\Windows\Explorer.exe" -ArgumentList "$($env:TEMP)"
}
 
 
 
#### Call the example script
cls
 
Create-WinRMCert -FriendlyName "WinRMCert" -ExportPassword "S3cr3tP4ssw0rd"

Run the script in Powershell:

PS D:\Tools\> ./CreateWinRMCert.ps1

So that your Certificate will be created.
Powershell output should be something like:

Thumbprint                                Subject
----------                                -------
8DCA1E0253ADDE2A3AZEE85BF751481A8B8228AB  CN=hostname.local
Exporting Certificate 8DCA1E0253ADDE2A3AZEE85BF751481A8B8228AB

Use the PFX generated in C:\Users\Administrator\AppData\Local\Temp\2 to import in your Client Server, using the Password provided above.
After Generating this Certificate, you need to configure the WinRM to use this certificate:

PS D:\> New-Item WSMan:\localhost\Listener -Address * -Transport HTTPS -HostName  "hostname.local" -CertificateThumbPrint "8DAA1E0023ADDE2A3BAEE85BF751481A8B8788AB"

Creates a new Listener item.
This command creates a new Listener item.

Do you want to continue?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Listener

Type            Keys                                Name
----            ----                                ----
Container       {Transport=HTTPS, Address=*}        Listener_1305953032


PS D:\> winrm enumerate winrm/config/listener
Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = x.x.x.x, 127.0.0.1, ::1
Listener
    Address = *
    Transport = HTTPS
    Port = 5986
    Hostname = hostname.local
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint = 8DAA1E0023ADDE2A3BAEE85BF751481A8B8788AB
    ListeningOn = x.x.x.x, 127.0.0.1, ::1

PS D:\>

Test and enjoy WinRM again 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *