WinRM cannot process the request - powershell

"Connecting to remote server failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090304 occurred while using Negotiate authentication: An unknown security error occurred."
I'm attempting to run scripts remotely to non-domain servers and the clients are also not part of a domain since our environment is based on MicroFocus eDirectory.
I've configured/tried the following on both client AND server:
winrm quickconfig
WinRM set winrm/config/client #{TrustedHosts="*"}
Set-item wsman:localhost\client\trustedhosts -value *
And again, none of the machines are part of a domain but I assumed it would work with trustedhosts.
Code attempting to authenticate looks like this:
[xml]$windows=(Get-Content P:\script\windows.xml)
$windows.servers.host | ForEach-Object {
$password = ConvertTo-SecureString $_.pass -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$_.name+$_.user",$password
Invoke-Command -ComputerName $_.name -Credential $credential -ScriptBlock {Get-Culture}
}

Your problem is in the formatting of the username. "$.name+$.user" will evaluate to a string with a + in the middle of it since the quotes are wrapped around both elements. correct way to write it would be "$($_.name)$($_.user)" or more likely if the source file does not place a trailing '\' on the name field
"$($_.name)\$($_.user)"

Related

How to avoid this error when trying to copy a specific folder from my local system to remote VM using winrm in Jenkins configuration?

Am using Powershell script to copy a folder from local system to remote VM.
The below script works fine when am running from my local system.
New-SelfSignedCertificate -DnsName dummy.southcentralus.cloudapp.azure.com -CertStoreLocation Cert:\LocalMachine\My
winrm create winrm/config/Listener?Address=*+Transport=HTTPS #{Hostname="dummy.southcentralus.cloudapp.azure.com"; CertificateThumbprint="9C207E7D249D385FDE9D4BBFE7AF7EB008RDGD"}
$pw = convertto-securestring -AsPlainText -Force -String <Password>
$cred = new-object -typename System.Management.Automation.PSCredential - argumentlist <username>,$pw
$session = new-pssession -computername dummy.southcentralus.cloudapp.azure.com -credential $cred
Copy-Item -Path C:\Jenkins\workspace\deploy-service\bin.zip -Destination F:\destpath\bin1.zip -ToSession $session
But when I use the same script in Jenkins at the build step. It throws me an error as given below.
"WinRM cannot process the request. The following error with errorcode 0x8009030d occurred while using Negotiate authentication: A specified logon session does not exist. It may already have been terminated."
What I tried So Far to resolve this error:
I have ensured that winrm is setup on both the host machines involved. Infact with 'Unrestricted' access via set-ExecutionPolicy.
I have Ensured remote machine running as a non-domain user, because local machine is running as a non-domain user.
Used Invoke-Command.
Change in this line, fixed my issue.
$cred = new-object -typename System.Management.Automation.PSCredential - argumentlist <username>,$pw
as
$cred = new-object -typename System.Management.Automation.PSCredential - argumentlist <domainname>\<username>,$pw
PSCredential, would expect the credential to be with domainname\username rather than passing username alone.

Using Powershell to remotely invoke commands in Azure

I'm writing a series of automation scripts that will allow our developers to stand up a simple development environment in Azure. This environment has 3 primary properties:
There is a client machine (Windows 10) where dev tools like their IDE and code will live.
There is a server machine (Windows Server 2016) where that their scripts will target.
Both of these machines live in the same domain, and 1 Domain Admin user is available for use.
I have steps 1 and 2 scripted out, but 3 is currently a mess. Since the script is designed to work from the Developer's local workstation, I need to have the script remote in to the Windows Server and run a few commands to set up the Domain Controller.
Here is my code currently:
Invoke-Command -ComputerName "$RGName-$VMPurpose" -ScriptBlock
{
$ADFeature = Install-WindowsFeature AD-Domain-Services
If ($ADFeature.Success -eq $true)
{
Import-Module ADDSDeployment
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath
"C:\Windows\NTDS" -DomainMode "Win2016R2" -DomainName "$project.com" -
DomainNetbiosName "$project" -ForestMode "Win2016R2" -InstallDns:$true -
LogPath "C:\Windows\NTDS" -NoRebootOnCompletion $false -sysvolpath
"C:\Windows\SYSVOL" -force $true
$domUserPassword = ConvertTo-SecureString "Th1s is a bad password" -
AsPlainText -Force
New-ADUser -Name "$VMPurpose-DomAdm" -AccountPassword
$domUserPassword
Add-ADGroupMember -Name "Administrators" -Member {Get-ADUser
"$VMPurpose-DomAdm"}
}
} -Credential $Cred
When I attempt to run this I get an error showing that WinRM cannot connect, specifically this error:
[Foo] Connecting to remote server Foo failed with the following error
message : WinRM cannot process the request. The following error with
errorcode 0x80090311
occurred while using Kerberos authentication: There are currently no logon
servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are
specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port
does not exist.
-The client and remote computers are in different domains and there is no
trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the
WinRM TrustedHosts configuration setting or use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following
command: winrm help config. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionStateBroken
I added the target machine (Foo) to the TrustedHosts configuration setting in WinRM (I actually added the IP address to make sure that there wasn't any DNS problem happening), and then I get this error:
[Foo's IP] Connecting to remote server <Foo's IP> failed with the following
error message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the
computer is accessible over the network, and that a firewall exception for
the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public
profiles limits access to remote computers within the same local subnet. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (Foo's Ip[:String) [],
PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
Any thoughts here? Am what I trying simply not ever going to work via Powershell?
According to your error message, we can use this PowerShell script to invoke command to Azure:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}
PowerShell result like this:
More information about invoke command, please refer to this answer.

Access is Denied when Reset-ComputerMachinePassword is run through Invoke-command

I'm using the following command to reset a remote machine'
s password.
$user="Domain\domainadmin";
$pass="dapassword" | ConvertTo-SecureString -AsPlainText -Force;
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $pass;
Invoke-Command -Credential $creds -ComputerName "DomainControllerMachine" -ScriptBlock{
$ComputerName = #"
SomeRemoteHost
"#
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server ${ComputerName};
}
I keep getting 'Access is denied' error.
This command cannot be executed on target computer('DomainControllerMachine') due to following error: Access is
denied.
+ CategoryInfo : InvalidOperation: (DomainControllerMachine:String) [Reset-ComputerMachinePasswor
d], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.ResetCompute
rMachinePasswordCommand
The account I use has all levels of access to the ActiveDirectory. So there won't be a issue with the credentials used for authentication.
If I run the same command on the 'DomainControllerMachine' (logged in as same user) it works fine.
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server "SomeRemoteHost";
Even the whole invoke-command block above just works without complaining on the DomainControllerMachine.
But when I do it remotely through Invoke-Command, or Enter-PSSession I get that dreaded access denied error..
I've also tried using CredSSP after setting up the WSManCredSSP (Client, delegation and Server) on the machines with no luck.
I may have missed something, or is there a better way to handle such a case?
It looks to me like you are running the Reset-computermachinepassword command on the domaincontroller. As far as I know it should be run on the computer that needs to be reset with the DC name in the -server field.
To do this you would need to run the command on the computer that needs it's credentials reset:
Reset-Computermachinepassword -server "DomainControllerMachine" -credential $PScredential
You can try to do it remotely with a PSsession if the computer has powershell remoting enabled. You will need to specify a different authentication method to reach a computer that has lost it's trust with the domain.
You can use Credssp but this will only work if your GPO allows delegating your credentials to the target computer.
Or you can use Basic authentication. But for that to work the Target must accept unencrypted traffic.
The command to do it remotely would probably look something like this:
$session = new-PSSession "targetcomputer" -Authentication Basic -Credential "Domain\domainadmin"
Invoke-Command -Session $session -scriptblock {Reset-Computermachinepassword -server "Domain\domainadmin"}

Powershell remoting - Policy does not allow the delegation of user credentials

I'm new to powershell and I'm having troubles using credentials delegation. I have the following script:
$session = New-PSSession myserver -Authentication CredSSP -Credential DOMAIN\Administrator
Invoke-Command -Session $session -ScriptBlock { <Some PowerShell Command> }
Before running it, I did the following:
Run Enable-PSRemoting on myserver.
Run Enable-WSManCredSSP Server on myserver.
Run Restart-Service WinRM on myserver.
Run Enable-WSManCredSSP Client –DelegateComputer myserver on the client.
Rebooted both the server and the client.
But once I run the script, I get the following error message:
[myserver] Connecting to remote server failed with the following error message : The WinRM client cannot process the request. A computer policy does not allow the delegation of
the user credentials to the target computer. Use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delega
tion -> Allow Delegating Fresh Credentials. Verify that it is enabled and configured with an SPN appropriate for the target computer. For example, for a target computer name "m
yserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailed
I checked the policies as mentioned in the error message but everything seems to be fine. What else could be blocking me?
Do the following on the server:
Enable-WSManCredSSP -Role Server
Do the following on the client:
set-item wsman:localhost\client\trustedhosts -value *
Enable-WSManCredSSP -Role Client –DelegateComputer *
Use gpedit.msc on the client to enable Delegating Fresh Credentials to WSMAN/*:
Expand Local Computer Policy, expand Computer Configuration, expand
Administrative Templates, expand System, and then click Credential Delegation.
In the Settings pane, double-click Allow Delegating Fresh Credentials with NTLM-only Server Authentication.
In the Allow Delegating Fresh Credentials with NTLM-only Server Authentication dialog box, do the following:
Click Enabled.
In the Options area, click Show.
In Value, type WSMAN/*, and then click OK. Make sure that
Concatenate OS defaults with input above is selected, and then
click OK.
The following command now works (after a password prompt):
Invoke-Command { dir \\fileserver\devtools } -computer appserver01 -authentication credssp -credential domain\user
See MSDN forums.
See TechNet
I finally got it to work thanks to this page. It provides a script that sets the required credential delegation policies by setting the appropriate registry keys directly. Once I ran that script with admin privileges, I was able to successfully establish a CredSSP connection to myserver:
Enable-WSManCredSSP -Role client -DelegateComputer *.mydomain.com
$allowed = #('WSMAN/*.mydomain.com')
$key = 'hklm:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation'
if (!(Test-Path $key)) {
md $key
}
New-ItemProperty -Path $key -Name AllowFreshCredentials -Value 1 -PropertyType Dword -Force
$key = Join-Path $key 'AllowFreshCredentials'
if (!(Test-Path $key)) {
md $key
}
$i = 1
$allowed |% {
# Script does not take into account existing entries in this key
New-ItemProperty -Path $key -Name $i -Value $_ -PropertyType String -Force
$i++
}
I had to the need to fully automate my solution, particularly the part section in the solution that has you go into the GPO editor.
1) Enable Remote PS
Enable-PSRemoting -force
2) Enable CredSSP
Enable-WSManCredSSP -Role Server -Force
Enable-WSManCredSSP -Role Client -DelegateComputer locahost -Force
Enable-WSManCredSSP -Role Client -DelegateComputer $env:COMPUTERNAME -Force
Enable-WSManCredSSP -Role Client -DelegateComputer $domain -Force
Enable-WSManCredSSP -Role Client -DelegateComputer "*.$domain" -Force
Set-Item -Path "wsman:\localhost\service\auth\credSSP" -Value $True -Force
3) Enable NTLM Fresh Credentials through the Registery:
New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name AllowFreshCredentialsWhenNTLMOnly -Force
New-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name 1 -Value * -PropertyType String
Only after this was I able to launch powershell script as the local admin that was able to run in a PSSession and preform AD actions.
$secpasswd = ConvertTo-SecureString $adPassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ("$domain\Admin", $secpasswd)
$adminSession = New-PSSession -Credential $credential -Authentication Credssp;
$sb = {
param($p1, $p2)
whoami
New-ADUser ....
}
Invoke-Command -Session $adminSession -Script $sb -ArgumentList $domain,$userPassword
Expanding upon Akira's answer above, in gpedit.msc I had to set "Allow Delegating Fresh Credentials with NTLM-only Server Authentication" rather than "Allow Delegating Fresh Credentials".

powershell v2 remoting - How do you enable unencrypted traffic

I'm writing a powershell v2 script that I'd like to run against a remote server. When I run it, I get the error :
Connecting to remote server failed
with the following error message : The
WinRM client cannot process the
request. Unencrypted traffic is
currently disabled in the client
configuration. Change the client
configurati on and try the request
again. For more information, see the
about_ Remote_Troubleshooting Help
topic.
I looked at the online help for about _ Remote_Troubleshooting, but it didn't point me towards how to enable unecrypted traffic. Below is the script that I'm using that is causing me problems.
Note: I have already run Enable-PSRemoting on the remote machine to allow it to accept incoming requests.
I have tried to use a session option variable, but it doesn't seem to make any difference.
$key = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds"
Set-ItemProperty $key ConsolePrompting True
$tvar = "password"
$password = ConvertTo-SecureString -string $tvar -asPlainText –force
$username="domain\username"
$mySessionOption = New-PSSessionOption -NoEncryption
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
invoke-command -filepath C:\scripts\RemoteScript.ps1 -sessionoption $mySessionOption -authentication digest -credential $credential -computername RemoteServer
How do I enable unencrypted traffic?
AllowEncrypted is defined on the client end, via the WSMAN: drive. You must be running powershell.exe (or powershell_ise.exe) as an elevated process.
ps> cd WSMan:\localhost\Client
ps> dir
Name Value
---- -----
NetworkDelayms 5000
URLPrefix wsman
AllowUnencrypted false
Auth
DefaultPorts
TrustedHosts
You would change it like so (after changing to the directory above):
Set-Item .\allowunencrypted $true
Hope this helps,
Oisin
You probably will need to set the AllowUnencrypted config setting in both the Client and the Service. The Service setting has to be changed in the remote server using the following:
set-item -force WSMan:\localhost\Service\AllowUnencrypted $true
And don't forget to also enable Digest Authorization:
set-item -force WSMan:\localhost\Service\Auth\Digest $true
You can allow unencrypted traffic on the client with the following command (execute it on the client):
winrm set winrm/config/client '#{AllowUnencrypted="true"}'
To verify, you can get the whole config (client and service) with this command:
winrm get winrm/config
Be aware that each machine has two configs (one for being a client, one for beeing a server). To allow unencrypted traffic on the server, execute the following command on the server:
winrm set winrm/config/service '#{AllowUnencrypted="true"}'
This worked for me:
enable-wsmancredssp –role server
If the parameter AllowUnencryptedTraffic is under GPO, you can set it through registrar:
$RegPath = 'HKLM:\Software\Policies\Microsoft\Windows\WinRM\Client'
$RegUnencryptedTraffic = 'AllowUnencryptedTraffic'
$RegValue = '1'
Set-ItemProperty -Path $RegPath -Name $RegUnencryptedTraffic -Value $RegValue