Search This Blog

Saturday, July 24, 2021

WINRM

step 1:

Verify if listener exist and server name matches. Run from command prompt:

winrm enumerate winrm/config/listener

step 2:

If there is an server name mismatch delete the listener

To delete Listeners manually:

--------------------------------------------------------------------------------------------------------------

delete 5985 port (HTTP)

Get-ChildItem -Path WSMan:\localhost\listener | Where-Object {$_.keys -contains "Transport=HTTP"} | Remove-Item -Recurse -Force

delete 5986 port (HTTPS)

Get-ChildItem -Path WSMan:\localhost\listener | Where-Object {$_.keys -contains "Transport=HTTPS"} | Remove-Item -Recurse -Force

--------------------------------------------------------------------------------------------------------------


step 3: 

use the PowerShell script listed at bottom of this page to recreate listeners 

(enable 5986 port)

Need to open port by submitting request to firewall team incase 5986 is not reachable from required server

===============================================================================================


Known issues:

out of memory - install kb to fix(KB2842230) ==> when powershell v3 is running and you get out of memory issue

===============================================================================================

Advanced commands to further troubleshoot the issue:

===============================================================================================

Example 1: 

Manual create listeners without powershell:

certificate thumbprint--(refer "sample screenshot to find the thumbprint of certificate")


create 5985 listener

new-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="HTTP"} -valueset @{Port="5985"}

create 5986 listener

new-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="HTTPS"} -valueset @{Port="5986";Hostname="Server1";CertificateThumbprint="‎d1d1213b1234fe2f8764da3755d8640c75c6eeb6"}

‎new-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="HTTPS"} -valueset @{Port="5986";Hostname="Server2";CertificateThumbprint="‎‎‎9070123471c394178d4266aef03ecbf7a9697405"}


Example 2:

winrm get wmicimv2/win32_Service?Name=spooler -remote:server1

OR

Connect-WSMan server1 -Credential $cred -Verbose

Not working server example

PS WSMan:\> Connect-WSMan server1.local.com -Credential $cred -Verbose

Connect-WSMan : An unknown security error occurred.

At line:1 char:1

+ Connect-WSMan server1.local.com  -Credential $cred -Verbose

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (server1.local.com m:String) [Connect-WSMan], InvalidOperationException

    + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.ConnectWSManCommand

 


Example 3:

to enable basic authentication

winrm set winrm/config/service/auth @{Basic="true"} 

winrm set winrm/config/service @{AllowUnencrypted="true"}


Example 4:

Set-item WSman:\localhost\service\enablecompatibilityhttplistener -value false


Example 5:

enable credssp authentication

winrm set winrm/config/service/Auth @{CredSSP="true"}

Enable-WSManCredSSP -Role Client -DelegateComputer * -Force


Example 6:

Manually create firewall rule on server for 5985 and 5986

netsh advfirewall firewall add rule name="WinRM-HTTP" dir=in localport=5985 protocol=TCP action=allow

netsh advfirewall firewall add rule name="Allow WinRM (Http)" dir=in localport=5985 protocol=tcp action=allow enable=yes

netsh advfirewall firewall add rule name="Allow WinRM (Https)" dir=in localport=5986 protocol=tcp action=allow enable=yes


Example 7:

when we face access issue we can try adding our account here with write permission.

winrm configSDDL default


Example 8:

when we run PowerShell remotely it failed because of low memory allocated to run PowerShell remotely. In latest versions like v5 value already changed

v3 - better to change value.


 cd WSMan:\localhost\Shell

 Set-Item .\MaxConcurrentUsers 2147483647

 Set-Item .\MaxProcessesPerShell 2147483647

 Set-Item .\MaxMemoryPerShellMB 2147483647

 Set-Item .\MaxShellsPerUser 2147483647

 

 

# makecert.exe is needed to create self-signed certificate Param ( [string]$Port="", [ValidateSet("HTTPS","HTTP")] [string]$Protocol="HTTPS") if (!($Port)) { switch ($Protocol) { "HTTP" {$Port = "5985"} "HTTPS" {$Port = "5986"} } } Function SelfCert ($validityyears=10) { $objIPProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() if ($objIPProperties.DomainName) {$fqhostname = "{0}.{1}" -f $objIPProperties.HostName, $objIPProperties.DomainName} else {$fqhostname = $objIPProperties.HostName} $osver=[environment]::osversion.version if ($osver.major -eq 6 -and $osver.minor -eq 0) { if (get-command $env:systemdrive\windows\system32\makecert.exe -ErrorAction SilentlyContinue) { $endDate=(get-date).addyears($validityyears).ToString("MM/dd/yyyy") & ${env:systemdrive}\windows\system32\makecert.exe -r -pe -len 2048 -n "CN=$fqhostname" -e $endDate -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -a sha1 -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 } else {LogMessage "Could not find makecert.exe";return} } else { $name = new-object -com "X509Enrollment.CX500DistinguishedName.1" $name.Encode("CN=$fqhostname", 0) $key = new-object -com "X509Enrollment.CX509PrivateKey.1" $key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider" $key.KeySpec = 1 $key.Length = 2048 $key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)" $key.MachineContext = 1 $key.Create() $serverauthoid = new-object -com "X509Enrollment.CObjectId.1" $serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1") $ekuoids = new-object -com "X509Enrollment.CObjectIds.1" $ekuoids.add($serverauthoid) $ekuext = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1" $ekuext.InitializeEncode($ekuoids) $cert = new-object -com "X509Enrollment.CX509CertificateRequestCertificate.1" $cert.InitializeFromPrivateKey(2, $key, "") $cert.Subject = $name $cert.Issuer = $cert.Subject $cert.NotBefore = [DateTime]::UtcNow $cert.NotAfter = $cert.NotBefore.AddYears($validityyears) $cert.X509Extensions.Add($ekuext) $cert.Encode() $enrollment = new-object -com "X509Enrollment.CX509Enrollment.1" $enrollment.InitializeFromRequest($cert) $certdata = $enrollment.CreateRequest(0) $enrollment.InstallResponse(2, $certdata, 0, "") } if ($?) {LogMessage "Created cert"} else {LogMessage "Could not create cert";} start-sleep 5 # Get the thumbprints of the SSL Server Auth certificates that match the hostname $certs=dir cert:\localmachine\my | ? {$_.Subject -eq "CN=$fqhostname"}| ? { $_.Extensions | % { $_.EnhancedKeyUsages | ? {$_.FriendlyName -eq "Server Authentication"}}} # PowerShell magic to retrieve the first matching thumbprint set-variable -name thumbprint @($certs)[0].Thumbprint -scope script } Function LogMessage ([string]$message) { $logpath="$($env:SYSTEMDRIVE)\winrmlog" if (-not ($logpath | Test-Path)) {mkdir $logpath} $logfile = "$($env:SYSTEMDRIVE)\winrmlog\winrm.log" if ($message) {$message = "$(get-date) " + $message} out-file $logfile -inputObject $message -encoding "ASCII" -Append } $objIPProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() if ($objIPProperties.DomainName) {$fqhostname = "{0}.{1}" -f $objIPProperties.HostName, $objIPProperties.DomainName} else {$fqhostname = $objIPProperties.HostName} LogMessage "Waiting 90 seconds to check sysprep status" while ((get-itemproperty "hklm:/SYSTEM/Setup").SystemSetupInProgress -ne 0) { LogMessage "Sysprep not yet complete" LogMessage "Stopping WinRM until sysprep is done" stop-service WinRM if ($?) {LogMessage "Stopped WinRM"} else {LogMessage "Could not stop WinRM"} set-service WinRM -startuptype "manual" start-sleep 30 } start-service WinRM if ($?) { LogMessage "Started WinRM" #Check WinRM listener on chosen protocol,port $noListener=$False try {$listener=get-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="$protocol"} } catch [system.exception] {$noListener=$True} if ($noListener) { #Create Listener for chosen protocol,port switch ($Protocol) { "HTTP" { #No cert needed, create listener $listener = new-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="$protocol"} -valueset @{Port="$Port"} if ($?) {LogMessage "Created $protocol protocol listener on port $port"} else {LogMessage "Could not create $protocol protocol listener on port $port"} } "HTTPS" { #Find suitable Server Authentication cert or create self-signed one $certs=dir cert:\localmachine\my | ? {$_.Subject -eq "CN=$fqhostname"}| ? { $_.Extensions | % { $_.EnhancedKeyUsages | ? {$_.FriendlyName -eq "Server Authentication"}}} if (@($certs)[0]) {$thumbprint = @($certs)[0].Thumbprint;LogMessage "Found server authentication cert with thumbprint $thumbprint"} else {SelfCert;if ($thumbprint) {LogMessage "Built self-signed cert with thumbprint $thumbprint"} } #Create Listener if ($thumbprint) {$listener = new-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="$protocol"} -valueset @{Port="$Port";Hostname="$fqhostname";CertificateThumbprint="$Thumbprint"} if ($?) {LogMessage "Created $protocol protocol listener on port $port with hostname $fqhostname and cert thumbprint $thumbprint"} else {LogMessage "Could not create $protocol protocol listener on port $port with hostname $fqhostname and cert thumbprint $thumbprint"} } } } } #Reset listener to Enabled $listener = set-wsmaninstance winrm/config/listener -SelectorSet @{Address="*";Transport="$protocol"} -ValueSet @{Port="$Port";Enabled="true"} if ($?) { $ips = $listener.ListeningOn -join "," LogMessage "$protocol listener on port $port is listening on addresses $ips" } } else {LogMessage "Could not start WinRM"} set-service WinRM -startuptype "Automatic" if ($?) {LogMessage "WinRM is set to autostart"} else {LogMessage "Could not set WinRM to autostart"} LogMessage "" try{ Enable-PSRemoting -Confirm:$false -Force -ErrorAction stop sleep 5 winrm set winrm/config/client '@{TrustedHosts="*"}' sleep 2 set-item wsman:\localhost\client\trustedhosts -value "*" sleep 2 winrm quickconfig sleep 5 LogMessage "" LogMessage "Enabled PSRemoting" LogMessage "" } catch{ LogMessage "" LogMessage "Failed to Enable PSRemoting" }


No comments:

Post a Comment