Ansible - Issues with WinRM Listener Setup - powershell

In order to configure a Windows server as an Ansible host, I'm trying to setup WinRM by following the official documentation provided in https://docs.ansible.com/ansible/latest/user_guide/windows_setup.html.
I'm stuck at the "Setup WinRM Listener" step with the execution of the following comannd resulting in the error as described below:
PS C:\Users\Administrator> New-WSManInstance -ResourceURI "winrm/config/Listener" -SelectorSet $selector_set -ValueSet $value_set
New-WSManInstance : The WS-Management service cannot find the certificate that was requested.
At line:1 char:1
+ New-WSManInstance -ResourceURI "winrm/config/Listener" -SelectorSet $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-WSManInstance], InvalidOperationException
+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.NewWSManInstanceCommand
Following are the values of my "selector_set" and "value_set" which are also set in accordance with the document.
PS C:\Users\Administrator> $selector_set
Name Value
---- -----
Transport HTTPS
Address *
PS C:\Users\Administrator> $value_set
Name Value
---- -----
CertificateThumbprint E6CDAA82EEAF2ECE8546E05DB7F3E01AA47D76CE
OS: Windows Server 2012 R2

It might not be immediately obvious, but if you re-read the last part of the section immediately preceding the "Setup WinRM Listener" step (emphasis added):
If running over an HTTPS listener, this is the thumbprint of the certificate in the Windows Certificate Store that is used in the connection. To get the details of the certificate itself, run this command with the relevant certificate thumbprint in PowerShell:
$thumbprint = "E6CDAA82EEAF2ECE8546E05DB7F3E01AA47D76CE"
Get-ChildItem -Path cert:\LocalMachine\My -Recurse | Where-Object { $_.Thumbprint -eq $thumbprint } | Select-Object *
What this is telling us is that E6CDAA82EEAF2ECE8546E05DB7F3E01AA47D76CE is just an example - you need to provide the thumbprint of an actual certificate issued to the machine.
To list all the existing certificates installed in the machines certificate store with PowerShell, just remove the Where-Object clause from the example command:
Get-ChildItem -Path cert:\LocalMachine\My -Recurse
If there's no appropriate certificate installed you'll have to install one. You can either generate a self-signed certificate, acquire a certificate from a CA vendor, or enroll for one from your internal CA if Active Directory Certificate Services or similar PKI is configured in the environment.

Related

Error - Install-Package : Authenticode issuer 'System.Object[]' when running Update-Module on local package repository

We've set up a Nuget style package repository for our locally produced tools at work. This is done via a file share. However, the module that I am attempting to update is throwing an error about the authenticode signature of the old version not matching the publisher of the new version.
The signing certificate is from our AD PKI system and is trusted and it does not change/has not changed in any way.
Obviously using -SkipPublisherCheck is a viable workaround but that is not a long-term solution.
I receive no errors or warnings on the initial installation of the package. Only when performing the update.
On the signing machine there are only 3 certificates and all three are in the LocalMachine store. They do not have the same subject (this is mentioned as a possible cause on some sites I found via Google)
Code
$cert = get-ChildItem Cert:\LocalMachine\My\5B3B66061B02EBF0986CF7969F36C6FB58060046
Set-AuthenticodeSignature "C:\Jenkins\workspace\Scripts - Master\MyModule_Src\dist\MyModule\MyModule.psm1" -Certificate $cert
#... Pester tests
Publish-Module -Name MyModule -Repository ORGPSGet -Verbose -force
Error Message
PackageManagement\Install-Package : Authenticode issuer 'System.Object[]' of the new module 'MyModule' with version
'4.0.4' is not matching with the authenticode issuer 'System.Object[]' of the previously-installed module 'MyModule'
with version '4.0.3'. If you still want to install or update, use -SkipPublisherCheck parameter.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:2089 char:20
+ ... $sid = PackageManagement\Install-Package #PSBoundParameters
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exc
eption
+ FullyQualifiedErrorId : AuthenticodeIssuerMismatch,Validate-ModuleAuthenticodeSignature,Microsoft.PowerShell.Packag
eManagement.Cmdlets.InstallPackage
Based on the error message I assumed that there was something about the signature that PowerShell was either expecting multiple certificates and not finding it or that there were multiple certificates in the signature and PowerShell did not like that. I added -IncludeChain signer to the signing command and then after rerunning the build, I was able to use the Update-Module command as expected.
Set-AuthenticodeSignature "C:\Jenkins\workspace\Scripts - Master\MyModule_Src\dist\MyModule\MyModule.psm1" -Certificate $cert -IncludeChain signer
See the docs for more details.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-authenticodesignature?view=powershell-6

Unable to install AD-Domain-services on VM

I trying to build out a SharePoint 2016 Dev/test farm in Azure using PowerShell, starting with a DS server
Anyway, I have created my VM, created virtual network, public IP, NIC etc
DS VM is configured for RDP
I am getting stuck on installing the AD Domain Services
Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
False Maybe Failed {}
Install-WindowsFeature : The WinRM client cannot process the request because the server name cannot be resolved.
At line:1 char:1
+ Install-WindowsFeature -ComputerName adVm AD-Domain-Services -Include ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : DeviceError: (Microsoft.Manag...rDetailsHandle):CimException) [Install-WindowsFeature],
Exception
+ FullyQualifiedErrorId : UnSupportedTargetDevice,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureComman
d
I have installed Remote Server Administration Tools for Windows 10
Started WInRM
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value myVM
Q: Should I try to use the AD DS Deployment Commandlets directly from my win10 client

Install Windows certiciate inside Vagrant box via PowerShell

I want to install Windows certificate in Windows based Vagrant machine via PowerShell.
I tried to use this command
vagrant.exe powershell - c "Import-Certificate -Filepath C:\vagrant\Microcosm.cer"
But I revived an error
vagrant.exe : The machine with the name '-' was not found configured for
At line:1 char:1
+ vagrant.exe powershell - c "Import-Certificate -Filepath C:\vagrant\M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The machine wit... configured for:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
this Vagrant environment.
Isn't that a typo in your command? Shouldn't that be -cinstead of - c (mind the space) after the powershell verb.
I'm running Windows 2019 Core and having difficulty sharing a folder on my network; however, I am able to see, from the network, that I can reach a location shared through IIS on the VM's host machine. (running IIS with Access to a folder on the host machine) The network uses a domain issued certificate so the certificate should be accepted but it is not.
Workaround:
[Net.ServicePointManager]::ServerCertificateValidationCallback= {$true}
[Net.ServicePointManager]::SecurityProtocol = [Net.ServiceProtocolType]:: Tls -bor [Net.ServicePointManager]::SecurityProtocol = [Net.ServiceProtocolType]:: Tls11 -bor [Net.ServicePointManager]::SecurityProtocol = [Net.ServiceProtocolType]:: Tls12
$url=https://192.168.1.1/ChromeSetup.exe"
$WebClient=New-Object System.Net.WebClient
$WebCleint.DownloadFile($url,"C:\ChromeSetup.exe")

Getting error in installing executables (.msi/.exe) on remote servers using PowerShell

I have a list of executables(.msi and .exe) which I have to install on some remote servers (in same domain) silently using PowerShell script. For that first I am copying all programs from local server to remote servers. Next I am trying to install all these programs one by one to the remote servers. For that I am using below code:
Copy-Item -Path "C:\path\to\softwares\*" -Destination "C:\path\to\destination" # this is copying all softwares on destination path
$destItem = Get-ChildItem -Path "C:\path\to\destination"
foreach($software in $destItem)
{
$setup = Invoke-Command -ComputerName <computer> -ScriptBlock {$temp=Start-Process "C:\path\to\$software" -ArgumentList "/s" -Wait -PassThrough;$Temp}
}
Problem is: When I run this script I get the following error:
[172.xx.xx.xxx] Connecting to remote server 172.xx.xx.xxx failed with the following error message : The WinRM client
cannot process the request. Default authentication may be used with an IP address under the following conditions: the
transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use
winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more
information on how to set TrustedHosts run the following command: winrm help config. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (172.xx.xx.xxx:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotUseIPAddress,PSSessionStateBroken
I ran command winrm quickconfig on local machine and got this result:
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
and from remote servers got this output:
WinRm already is set up to recieve requests on this machine.
WinRm already is set up for remote management on this machine.
Windows version: Windows Server 2012R2
PS version: 4
Question is: How can I resolve this issue and can install executables on remote servers?
You might try to put the remote computer into the list of trusted hosts:
View the list of TrustedHosts
get-item wsman:\localhost\Client\TrustedHosts
Add all computers (be careful!) to the list of TrustedHosts
set-item wsman:\localhost\Client\TrustedHosts -value *
Add a computer with a specific IP address to the list of Trusted Hosts
set-item wsman:\localhost\Client\TrustedHosts -value 192.168.0.10
Check Matt Wrock's article about remotely installing software on windows:
http://www.hurryupandwait.io/blog/safely-running-windows-automation-operations-that-typically-fail-over-winrm-or-powershell-remoting
In his Boxstarter library he tackles this by wrapping the commands in a scheduled task using the Invoke-FromTask command:
Invoke-FromTask #"
Start-Process "$env:temp\net45.exe" -verb runas -wait `
-argumentList "/quiet /norestart /log $env:temp\net45.log"
"#

Enable PowerShell remoting on new Azure VM

I've created a new VM in Windows Azure to use to act as a host to learn a bit of Powershell Remoting. After the VM was created I RDP'd onto the box and enabled remoting via the following command:
Enable-PSRemoting
I confirmed both prompts with 'a' replies and it finished without errors. If I run
Get-PSSessionConfiguration
I can see that three endpoints (?) have been set up. In the Azure portal I can see that the Powershell port is open - both 5986 is open as a public and private port.
I've added the public IP address of the machine to my hosts file, but when I try the following:
Enter-PSSession -ComputerName AZURESERVERNAME
I get an error:
Enter-PSSession : Connecting to remote server AZURESERVERNAME failed
with the following error message : A specified logon session does not
exist. It may already have been terminated. For more information, see
the about_Remote_Troubleshooting Help topic. At line:1 char:1
+ Enter-PSSession -ComputerName AZURESERVERNAME
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (AZURESERVERNAME:String) [Enter-PSSession],
PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I've also tried setting all hosts as trused as follows:
cd wsman::localhost\client
Set-Item .\TrustedHosts *
Restart-Service WinRM
But that doesn't seemed to have helped either.
Is there anything else I need to do to get this working?
Thanks
OK, figured this out thanks to the awesome Secrets of Powershell Remoting ebook. Looks like you must add the machine directly to the TrustedHosts via IP address:
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value '11.22.33.44'
Then use that IP address and specify credentials in the Enter-PSSession:
Enter-PSSession -ComputerName 11.22.33.44 -Credential 11.22.33.44\username
You should then get a prompt for your password and voila! :)
I've successfully created a SharePoint farm in Azure using the scripts from Automated-Deployment-of-SharePoint-2013-with-Windows-Azure-PowerShell
On that page there are steps that configure PowerShell to work with Azure
Set-ExecutionPolicy ByPass
Enable-PSRemoting
Enable-WSManCredSSP -role client -delegatecomputer "*.cloudapp.net"
$regKey = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsDomain"
Set-ItemProperty $regKey -Name WSMan -Value "WSMAN/*.cloudapp.net"
Get-AzureSubscription -ExtendedDetails
You may also need to do this
Run GPEdit.msc You must also enable delegating of fresh credentials
using group policy editor on your client machine. Computer
Configuration -> Administrative Templates -> System -> Credentials
Delegation and then change the state of "Allow Delegating Fresh
Credentials with NTLM-only server authentication" to "Enabled." Its
default state will say, "Not configured."
In the Add Servers sections add the following.
WSMAN/*.cloudapp.net