#Fix-RDPCertificate # # Search for the optimal certificate for RDP-Connections and update bindnug, if approved param ( [switch]$updatecertificatebinding # enable to change Binding ) Write-host "FixPRDCertificate: Start" Write-host "Determine local CN name" [string]$dnsname="$([System.Net.Dns]::GetHostByName(($env:computerName)).hostname)" write-host "DNSName: $($dnsname)" write-host "Loading local certificates" [Array]$candidates =@() foreach ($cert in get-childitem cert:\localmachine\my ) { write-host "---------- Processing Cert " write-host " Hash :$($cert.Thumbprint)" write-host " Subject:$($cert.Subject)" if (!$cert.HasPrivateKey) { write-host " Skip: Missing private key" -ForegroundColor Yellow } elseif (!($cert.EnhancedKeyUsageList.objectid.Contains("1.3.6.1.5.5.7.3.1") ` -or $cert.EnhancedKeyUsageList.objectid.Contains("1.3.6.1.4.1.311.54.1.2"))) { write-host " Skip: ExtendedUsage not ServerAuthentication/Remote Desktop Authentication" -ForegroundColor Yellow } elseif ($cert.NotAfter -lt (get-date)) { write-host " Skip: NotAfter is expired" -ForegroundColor Yellow } elseif ($cert.NotBefore -gt (get-date)) { write-host " Skip:validdate in the future. Check local time settings" -ForegroundColor Yellow } elseif ($cert.issuer -eq $cert.subject) { write-host " Skip:because is self signed" -ForegroundColor Yellow } elseif ($cert.DnsNameList.unicode.tolower() -notcontains ($dnsname.tolower()) ` -or ($cert.subject.tolower() -ne "CN=$($dnsname)".tolower() )) { write-host " Skip:DNSName not in Subject or SAN" -ForegroundColor Yellow } else { write-host " Found a candidate. Add to list" -ForegroundColor green $candidates += $cert } } if ($candidates) { Write-host "Sorting Candidates" $candidates = $candidates | sort-object NotAfter Write-host "Preferred certificate: $($candidates[0].thumbprint)" $wmirdpbinding = Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName=""RDP-tcp""" $currenthash= $wmirdpbinding.SSLCertificateSHA1Hash write-host "Existing Certificate hash: $($currenthash)" if ($currenthash -eq $candidates[0].thumbprint) { write-host " Preferred certificate already active" -ForegroundColor green } else { if ($updatecertificatebinding) { write-host "Update binding" Set-WmiInstance ` -Path $wmirdpbinding.__path ` -argument @{SSLCertificateSHA1Hash=”ThumbprintWithoutSpaces”} } else { Write-host "Certifiate not updated" -ForegroundColor yellow } } }