aggiornato script e inserito link a documentazione ufficiale

This commit is contained in:
dado
2025-09-11 21:20:39 +02:00
parent cc87fd75ba
commit 202e333eff
2 changed files with 81 additions and 99 deletions

View File

@@ -9,7 +9,7 @@ Per configurare correttamente WinRM, è necessario soddisfare i seguenti requisi
- Installare il pacchetto `pywinrm` sul node-manager Ansible, tramite il comando `pip install pywinrm` - Installare il pacchetto `pywinrm` sul node-manager Ansible, tramite il comando `pip install pywinrm`
- Windows 7, Windows Server 2008 o versioni successive sui nodi da gestire - Windows 7, Windows Server 2008 o versioni successive sui nodi da gestire
- PowerShell3.0 e .NET4.0 o versioni successive - PowerShell3.0 e .NET4.0 o versioni successive
- Per configurare WinRM, bisogna eseguire sui nodi lo script ufficiale di Ansible `ConfigureRemotingForAnsible.ps1`. Questo crea due listener, uno per HTTP e uno per HTTPS, sulla macchina Windows. Genera inoltre un certificato autofirmato e implementata un sistema di autenticazione di tipo BASIC, che richiede un nome utente e una password - Per configurare WinRM, bisogna eseguire sui nodi lo script ufficiale di Ansible [`ConfigureRemotingForAnsible.ps1`](https://github.com/ansible/ansible-documentation/blob/devel/examples/scripts/ConfigureRemotingForAnsible.ps1). Questo crea due listener, uno per HTTP e uno per HTTPS, sulla macchina Windows. Genera inoltre un certificato autofirmato e implementata un sistema di autenticazione di tipo BASIC, che richiede un nome utente e una password
## Configurazione del playbook ## Configurazione del playbook

View File

@@ -7,6 +7,21 @@
# the necessary changes to allow Ansible to connect, authenticate and # the necessary changes to allow Ansible to connect, authenticate and
# execute PowerShell commands. # execute PowerShell commands.
# #
# IMPORTANT: This script uses self-signed certificates and authentication mechanisms
# that are intended for development environments and evaluation purposes only.
# Production environments and deployments that are exposed on the network should
# use CA-signed certificates and secure authentication mechanisms such as Kerberos.
#
# To run this script in Powershell:
#
# [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# $url = "https://raw.githubusercontent.com/ansible/ansible-documentation/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
# $file = "$env:temp\ConfigureRemotingForAnsible.ps1"
#
# (New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)
#
# powershell.exe -ExecutionPolicy ByPass -File $file
#
# All events are logged to the Windows EventLog, useful for unattended runs. # All events are logged to the Windows EventLog, useful for unattended runs.
# #
# Use option -Verbose in order to see the verbose output messages. # Use option -Verbose in order to see the verbose output messages.
@@ -66,28 +81,24 @@ Param (
[switch]$EnableCredSSP [switch]$EnableCredSSP
) )
Function Write-Log Function Write-ProgressLog {
{
$Message = $args[0] $Message = $args[0]
Write-EventLog -LogName Application -Source $EventSource -EntryType Information -EventId 1 -Message $Message Write-EventLog -LogName Application -Source $EventSource -EntryType Information -EventId 1 -Message $Message
} }
Function Write-VerboseLog Function Write-VerboseLog {
{
$Message = $args[0] $Message = $args[0]
Write-Verbose $Message Write-Verbose $Message
Write-Log $Message Write-ProgressLog $Message
} }
Function Write-HostLog Function Write-HostLog {
{
$Message = $args[0] $Message = $args[0]
Write-Output $Message Write-Output $Message
Write-Log $Message Write-ProgressLog $Message
} }
Function New-LegacySelfSignedCert Function New-LegacySelfSignedCert {
{
Param ( Param (
[string]$SubjectName, [string]$SubjectName,
[int]$ValidDays = 1095 [int]$ValidDays = 1095
@@ -125,14 +136,13 @@ Function New-LegacySelfSignedCert
$SigOID = New-Object -ComObject X509Enrollment.CObjectId $SigOID = New-Object -ComObject X509Enrollment.CObjectId
$SigOID.InitializeFromValue(([Security.Cryptography.Oid]$SignatureAlgorithm).Value) $SigOID.InitializeFromValue(([Security.Cryptography.Oid]$SignatureAlgorithm).Value)
[string[]] $AlternativeName += $hostnonFQDN [string[]] $AlternativeName += $hostnonFQDN
$AlternativeName += $hostFQDN $AlternativeName += $hostFQDN
$IAlternativeNames = New-Object -ComObject X509Enrollment.CAlternativeNames $IAlternativeNames = New-Object -ComObject X509Enrollment.CAlternativeNames
foreach ($AN in $AlternativeName) foreach ($AN in $AlternativeName) {
{
$AltName = New-Object -ComObject X509Enrollment.CAlternativeName $AltName = New-Object -ComObject X509Enrollment.CAlternativeName
$AltName.InitializeFromString(0x3,$AN) $AltName.InitializeFromString(0x3, $AN)
$IAlternativeNames.Add($AltName) $IAlternativeNames.Add($AltName)
} }
@@ -162,15 +172,14 @@ Function New-LegacySelfSignedCert
return $parsed_cert.Thumbprint return $parsed_cert.Thumbprint
} }
Function Enable-GlobalHttpFirewallAccess Function Enable-GlobalHttpFirewallAccess {
{
Write-Verbose "Forcing global HTTP firewall access" Write-Verbose "Forcing global HTTP firewall access"
# this is a fairly naive implementation; could be more sophisticated about rule matching/collapsing # this is a fairly naive implementation; could be more sophisticated about rule matching/collapsing
$fw = New-Object -ComObject HNetCfg.FWPolicy2 $fw = New-Object -ComObject HNetCfg.FWPolicy2
# try to find/enable the default rule first # try to find/enable the default rule first
$add_rule = $false $add_rule = $false
$matching_rules = $fw.Rules | Where-Object { $_.Name -eq "Windows Remote Management (HTTP-In)" } $matching_rules = $fw.Rules | Where-Object { $_.Name -eq "Windows Remote Management (HTTP-In)" }
$rule = $null $rule = $null
If ($matching_rules) { If ($matching_rules) {
If ($matching_rules -isnot [Array]) { If ($matching_rules -isnot [Array]) {
@@ -217,80 +226,71 @@ Function Enable-GlobalHttpFirewallAccess
} }
# Setup error handling. # Setup error handling.
Trap Trap {
{
$_ $_
Exit 1 Exit 1
} }
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
# Get the ID and security principal of the current user account # Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent() $myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID) $myWindowsPrincipal = new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role # Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator" # Check to see if we are currently running "as Administrator"
if (-Not $myWindowsPrincipal.IsInRole($adminRole)) if (-Not $myWindowsPrincipal.IsInRole($adminRole)) {
{
Write-Output "ERROR: You need elevated Administrator privileges in order to run this script." Write-Output "ERROR: You need elevated Administrator privileges in order to run this script."
Write-Output " Start Windows PowerShell by using the Run as Administrator option." Write-Output " Start Windows PowerShell by using the Run as Administrator option."
Exit 2 Exit 2
} }
$EventSource = $MyInvocation.MyCommand.Name $EventSource = $MyInvocation.MyCommand.Name
If (-Not $EventSource) If (-Not $EventSource) {
{
$EventSource = "Powershell CLI" $EventSource = "Powershell CLI"
} }
If ([System.Diagnostics.EventLog]::Exists('Application') -eq $False -or [System.Diagnostics.EventLog]::SourceExists($EventSource) -eq $False) If ([System.Diagnostics.EventLog]::Exists('Application') -eq $False -or [System.Diagnostics.EventLog]::SourceExists($EventSource) -eq $False) {
{
New-EventLog -LogName Application -Source $EventSource New-EventLog -LogName Application -Source $EventSource
} }
# Detect PowerShell version. # Detect PowerShell version.
If ($PSVersionTable.PSVersion.Major -lt 3) If ($PSVersionTable.PSVersion.Major -lt 3) {
{ Write-ProgressLog "PowerShell version 3 or higher is required."
Write-Log "PowerShell version 3 or higher is required."
Throw "PowerShell version 3 or higher is required." Throw "PowerShell version 3 or higher is required."
} }
# Find and start the WinRM service. # Find and start the WinRM service.
Write-Verbose "Verifying WinRM service." Write-Verbose "Verifying WinRM service."
If (!(Get-Service "WinRM")) If (!(Get-Service "WinRM")) {
{ Write-ProgressLog "Unable to find the WinRM service."
Write-Log "Unable to find the WinRM service."
Throw "Unable to find the WinRM service." Throw "Unable to find the WinRM service."
} }
ElseIf ((Get-Service "WinRM").Status -ne "Running") ElseIf ((Get-Service "WinRM").Status -ne "Running") {
{
Write-Verbose "Setting WinRM service to start automatically on boot." Write-Verbose "Setting WinRM service to start automatically on boot."
Set-Service -Name "WinRM" -StartupType Automatic Set-Service -Name "WinRM" -StartupType Automatic
Write-Log "Set WinRM service to start automatically on boot." Write-ProgressLog "Set WinRM service to start automatically on boot."
Write-Verbose "Starting WinRM service." Write-Verbose "Starting WinRM service."
Start-Service -Name "WinRM" -ErrorAction Stop Start-Service -Name "WinRM" -ErrorAction Stop
Write-Log "Started WinRM service." Write-ProgressLog "Started WinRM service."
} }
# WinRM should be running; check that we have a PS session config. # WinRM should be running; check that we have a PS session config.
If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener))) If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener))) {
{ If ($SkipNetworkProfileCheck) {
If ($SkipNetworkProfileCheck) { Write-Verbose "Enabling PS Remoting without checking Network profile."
Write-Verbose "Enabling PS Remoting without checking Network profile." Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop
Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop Write-ProgressLog "Enabled PS Remoting without checking Network profile."
Write-Log "Enabled PS Remoting without checking Network profile." }
} Else {
Else { Write-Verbose "Enabling PS Remoting."
Write-Verbose "Enabling PS Remoting." Enable-PSRemoting -Force -ErrorAction Stop
Enable-PSRemoting -Force -ErrorAction Stop Write-ProgressLog "Enabled PS Remoting."
Write-Log "Enabled PS Remoting." }
}
} }
Else Else {
{
Write-Verbose "PS Remoting is already enabled." Write-Verbose "PS Remoting is already enabled."
} }
@@ -310,8 +310,7 @@ if ($token_value -ne 1) {
# Make sure there is a SSL listener. # Make sure there is a SSL listener.
$listeners = Get-ChildItem WSMan:\localhost\Listener $listeners = Get-ChildItem WSMan:\localhost\Listener
If (!($listeners | Where-Object {$_.Keys -like "TRANSPORT=HTTPS"})) If (!($listeners | Where-Object { $_.Keys -like "TRANSPORT=HTTPS" })) {
{
# We cannot use New-SelfSignedCertificate on 2012R2 and earlier # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
$thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint" Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
@@ -329,15 +328,13 @@ If (!($listeners | Where-Object {$_.Keys -like "TRANSPORT=HTTPS"}))
Write-Verbose "Enabling SSL listener." Write-Verbose "Enabling SSL listener."
New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
Write-Log "Enabled SSL listener." Write-ProgressLog "Enabled SSL listener."
} }
Else Else {
{
Write-Verbose "SSL listener is already active." Write-Verbose "SSL listener is already active."
# Force a new SSL cert on Listener if the $ForceNewSSLCert # Force a new SSL cert on Listener if the $ForceNewSSLCert
If ($ForceNewSSLCert) If ($ForceNewSSLCert) {
{
# We cannot use New-SelfSignedCertificate on 2012R2 and earlier # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
$thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
@@ -361,45 +358,37 @@ Else
} }
# Check for basic authentication. # Check for basic authentication.
$basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object {$_.Name -eq "Basic"} $basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object { $_.Name -eq "Basic" }
If ($DisableBasicAuth) If ($DisableBasicAuth) {
{ If (($basicAuthSetting.Value) -eq $true) {
If (($basicAuthSetting.Value) -eq $true)
{
Write-Verbose "Disabling basic auth support." Write-Verbose "Disabling basic auth support."
Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $false Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $false
Write-Log "Disabled basic auth support." Write-ProgressLog "Disabled basic auth support."
} }
Else Else {
{
Write-Verbose "Basic auth is already disabled." Write-Verbose "Basic auth is already disabled."
} }
} }
Else Else {
{ If (($basicAuthSetting.Value) -eq $false) {
If (($basicAuthSetting.Value) -eq $false)
{
Write-Verbose "Enabling basic auth support." Write-Verbose "Enabling basic auth support."
Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $true Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $true
Write-Log "Enabled basic auth support." Write-ProgressLog "Enabled basic auth support."
} }
Else Else {
{
Write-Verbose "Basic auth is already enabled." Write-Verbose "Basic auth is already enabled."
} }
} }
# If EnableCredSSP if set to true # If EnableCredSSP if set to true
If ($EnableCredSSP) If ($EnableCredSSP) {
{
# Check for CredSSP authentication # Check for CredSSP authentication
$credsspAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object {$_.Name -eq "CredSSP"} $credsspAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object { $_.Name -eq "CredSSP" }
If (($credsspAuthSetting.Value) -eq $false) If (($credsspAuthSetting.Value) -eq $false) {
{
Write-Verbose "Enabling CredSSP auth support." Write-Verbose "Enabling CredSSP auth support."
Enable-WSManCredSSP -role server -Force Enable-WSManCredSSP -role server -Force
Write-Log "Enabled CredSSP auth support." Write-ProgressLog "Enabled CredSSP auth support."
} }
} }
@@ -410,44 +399,37 @@ If ($GlobalHttpFirewallAccess) {
# Configure firewall to allow WinRM HTTPS connections. # Configure firewall to allow WinRM HTTPS connections.
$fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" $fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS"
$fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any $fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any
If ($fwtest1.count -lt 5) If ($fwtest1.count -lt 5) {
{
Write-Verbose "Adding firewall rule to allow WinRM HTTPS." Write-Verbose "Adding firewall rule to allow WinRM HTTPS."
netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow
Write-Log "Added firewall rule to allow WinRM HTTPS." Write-ProgressLog "Added firewall rule to allow WinRM HTTPS."
} }
ElseIf (($fwtest1.count -ge 5) -and ($fwtest2.count -lt 5)) ElseIf (($fwtest1.count -ge 5) -and ($fwtest2.count -lt 5)) {
{
Write-Verbose "Updating firewall rule to allow WinRM HTTPS for any profile." Write-Verbose "Updating firewall rule to allow WinRM HTTPS for any profile."
netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any
Write-Log "Updated firewall rule to allow WinRM HTTPS for any profile." Write-ProgressLog "Updated firewall rule to allow WinRM HTTPS for any profile."
} }
Else Else {
{
Write-Verbose "Firewall rule already exists to allow WinRM HTTPS." Write-Verbose "Firewall rule already exists to allow WinRM HTTPS."
} }
# Test a remoting connection to localhost, which should work. # Test a remoting connection to localhost, which should work.
$httpResult = Invoke-Command -ComputerName "localhost" -ScriptBlock {$env:COMPUTERNAME} -ErrorVariable httpError -ErrorAction SilentlyContinue $httpResult = Invoke-Command -ComputerName "localhost" -ScriptBlock { $using:env:COMPUTERNAME } -ErrorVariable httpError -ErrorAction SilentlyContinue
$httpsOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck $httpsOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $httpsOptions -ErrorVariable httpsError -ErrorAction SilentlyContinue $httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $httpsOptions -ErrorVariable httpsError -ErrorAction SilentlyContinue
If ($httpResult -and $httpsResult) If ($httpResult -and $httpsResult) {
{
Write-Verbose "HTTP: Enabled | HTTPS: Enabled" Write-Verbose "HTTP: Enabled | HTTPS: Enabled"
} }
ElseIf ($httpsResult -and !$httpResult) ElseIf ($httpsResult -and !$httpResult) {
{
Write-Verbose "HTTP: Disabled | HTTPS: Enabled" Write-Verbose "HTTP: Disabled | HTTPS: Enabled"
} }
ElseIf ($httpResult -and !$httpsResult) ElseIf ($httpResult -and !$httpsResult) {
{
Write-Verbose "HTTP: Enabled | HTTPS: Disabled" Write-Verbose "HTTP: Enabled | HTTPS: Disabled"
} }
Else Else {
{ Write-ProgressLog "Unable to establish an HTTP or HTTPS remoting session."
Write-Log "Unable to establish an HTTP or HTTPS remoting session."
Throw "Unable to establish an HTTP or HTTPS remoting session." Throw "Unable to establish an HTTP or HTTPS remoting session."
} }
Write-VerboseLog "PS Remoting has been successfully configured for Ansible." Write-VerboseLog "PS Remoting has been successfully configured for Ansible."