Guest User

Untitled

a guest
Oct 3rd, 2017
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.14 KB | None | 0 0
  1. #Requires -Version 3.0
  2.  
  3. # Configure a Windows host for remote management with Ansible
  4. # -----------------------------------------------------------
  5. #
  6. # This script checks the current WinRM (PS Remoting) configuration and makes
  7. # the necessary changes to allow Ansible to connect, authenticate and
  8. # execute PowerShell commands.
  9. #
  10. # All events are logged to the Windows EventLog, useful for unattended runs.
  11. #
  12. # Use option -Verbose in order to see the verbose output messages.
  13. #
  14. # Use option -CertValidityDays to specify how long this certificate is valid
  15. # starting from today. So you would specify -CertValidityDays 3650 to get
  16. # a 10-year valid certificate.
  17. #
  18. # Use option -ForceNewSSLCert if the system has been SysPreped and a new
  19. # SSL Certificate must be forced on the WinRM Listener when re-running this
  20. # script. This is necessary when a new SID and CN name is created.
  21. #
  22. # Use option -SkipNetworkProfileCheck to skip the network profile check.
  23. # Without specifying this the script will only run if the device's interfaces
  24. # are in DOMAIN or PRIVATE zones. Provide this switch if you want to enable
  25. # WinRM on a device with an interface in PUBLIC zone.
  26. #
  27. # Use option -SubjectName to specify the CN name of the certificate. This
  28. # defaults to the system's hostname and generally should not be specified.
  29.  
  30. # Written by Trond Hindenes <trond@hindenes.com>
  31. # Updated by Chris Church <cchurch@ansible.com>
  32. # Updated by Michael Crilly <mike@autologic.cm>
  33. # Updated by Anton Ouzounov <Anton.Ouzounov@careerbuilder.com>
  34. # Updated by Nicolas Simond <contact@nicolas-simond.com>
  35. # Updated by Dag Wieërs <dag@wieers.com>
  36. # Updated by Jordan Borean <jborean93@gmail.com>
  37. #
  38. # Version 1.0 - 2014-07-06
  39. # Version 1.1 - 2014-11-11
  40. # Version 1.2 - 2015-05-15
  41. # Version 1.3 - 2016-04-04
  42. # Version 1.4 - 2017-01-05
  43. # Version 1.5 - 2017-02-09
  44. # Version 1.6 - 2017-04-18
  45.  
  46. # Support -Verbose option
  47. [CmdletBinding()]
  48.  
  49. Param (
  50. [string]$SubjectName = $env:COMPUTERNAME,
  51. [int]$CertValidityDays = 1095,
  52. [switch]$SkipNetworkProfileCheck,
  53. $CreateSelfSignedCert = $true,
  54. [switch]$ForceNewSSLCert,
  55. [switch]$EnableCredSSP
  56. )
  57.  
  58. Function Write-Log
  59. {
  60. $Message = $args[0]
  61. Write-EventLog -LogName Application -Source $EventSource -EntryType Information -EventId 1 -Message $Message
  62. }
  63.  
  64. Function Write-VerboseLog
  65. {
  66. $Message = $args[0]
  67. Write-Verbose $Message
  68. Write-Log $Message
  69. }
  70.  
  71. Function Write-HostLog
  72. {
  73. $Message = $args[0]
  74. Write-Host $Message
  75. Write-Log $Message
  76. }
  77.  
  78. Function New-LegacySelfSignedCert
  79. {
  80. Param (
  81. [string]$SubjectName,
  82. [int]$ValidDays = 1095
  83. )
  84.  
  85. $name = New-Object -COM "X509Enrollment.CX500DistinguishedName.1"
  86. $name.Encode("CN=$SubjectName", 0)
  87.  
  88. $key = New-Object -COM "X509Enrollment.CX509PrivateKey.1"
  89. $key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
  90. $key.KeySpec = 1
  91. $key.Length = 4096
  92. $key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
  93. $key.MachineContext = 1
  94. $key.Create()
  95.  
  96. $serverauthoid = New-Object -COM "X509Enrollment.CObjectId.1"
  97. $serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1")
  98. $ekuoids = New-Object -COM "X509Enrollment.CObjectIds.1"
  99. $ekuoids.Add($serverauthoid)
  100. $ekuext = New-Object -COM "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
  101. $ekuext.InitializeEncode($ekuoids)
  102.  
  103. $cert = New-Object -COM "X509Enrollment.CX509CertificateRequestCertificate.1"
  104. $cert.InitializeFromPrivateKey(2, $key, "")
  105. $cert.Subject = $name
  106. $cert.Issuer = $cert.Subject
  107. $cert.NotBefore = (Get-Date).AddDays(-1)
  108. $cert.NotAfter = $cert.NotBefore.AddDays($ValidDays)
  109. $cert.X509Extensions.Add($ekuext)
  110. $cert.Encode()
  111.  
  112. $enrollment = New-Object -COM "X509Enrollment.CX509Enrollment.1"
  113. $enrollment.InitializeFromRequest($cert)
  114. $certdata = $enrollment.CreateRequest(0)
  115. $enrollment.InstallResponse(2, $certdata, 0, "")
  116.  
  117. # extract/return the thumbprint from the generated cert
  118. $parsed_cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
  119. $parsed_cert.Import([System.Text.Encoding]::UTF8.GetBytes($certdata))
  120.  
  121. return $parsed_cert.Thumbprint
  122. }
  123.  
  124. # Setup error handling.
  125. Trap
  126. {
  127. $_
  128. Exit 1
  129. }
  130. $ErrorActionPreference = "Stop"
  131.  
  132. # Get the ID and security principal of the current user account
  133. $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  134. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  135.  
  136. # Get the security principal for the Administrator role
  137. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  138.  
  139. # Check to see if we are currently running "as Administrator"
  140. if (-Not $myWindowsPrincipal.IsInRole($adminRole))
  141. {
  142. Write-Host "ERROR: You need elevated Administrator privileges in order to run this script."
  143. Write-Host " Start Windows PowerShell by using the Run as Administrator option."
  144. Exit 2
  145. }
  146.  
  147. $EventSource = $MyInvocation.MyCommand.Name
  148. If (-Not $EventSource)
  149. {
  150. $EventSource = "Powershell CLI"
  151. }
  152.  
  153. If ([System.Diagnostics.EventLog]::Exists('Application') -eq $False -or [System.Diagnostics.EventLog]::SourceExists($EventSource) -eq $False)
  154. {
  155. New-EventLog -LogName Application -Source $EventSource
  156. }
  157.  
  158. # Detect PowerShell version.
  159. If ($PSVersionTable.PSVersion.Major -lt 3)
  160. {
  161. Write-Log "PowerShell version 3 or higher is required."
  162. Throw "PowerShell version 3 or higher is required."
  163. }
  164.  
  165. # Find and start the WinRM service.
  166. Write-Verbose "Verifying WinRM service."
  167. If (!(Get-Service "WinRM"))
  168. {
  169. Write-Log "Unable to find the WinRM service."
  170. Throw "Unable to find the WinRM service."
  171. }
  172. ElseIf ((Get-Service "WinRM").Status -ne "Running")
  173. {
  174. Write-Verbose "Setting WinRM service to start automatically on boot."
  175. Set-Service -Name "WinRM" -StartupType Automatic
  176. Write-Log "Set WinRM service to start automatically on boot."
  177. Write-Verbose "Starting WinRM service."
  178. Start-Service -Name "WinRM" -ErrorAction Stop
  179. Write-Log "Started WinRM service."
  180.  
  181. }
  182.  
  183. # WinRM should be running; check that we have a PS session config.
  184. If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener)))
  185. {
  186. If ($SkipNetworkProfileCheck) {
  187. Write-Verbose "Enabling PS Remoting without checking Network profile."
  188. Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop
  189. Write-Log "Enabled PS Remoting without checking Network profile."
  190. }
  191. Else {
  192. Write-Verbose "Enabling PS Remoting."
  193. Enable-PSRemoting -Force -ErrorAction Stop
  194. Write-Log "Enabled PS Remoting."
  195. }
  196. }
  197. Else
  198. {
  199. Write-Verbose "PS Remoting is already enabled."
  200. }
  201.  
  202. # Make sure there is a SSL listener.
  203. $listeners = Get-ChildItem WSMan:\localhost\Listener
  204. If (!($listeners | Where {$_.Keys -like "TRANSPORT=HTTPS"}))
  205. {
  206. # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
  207. $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
  208. Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
  209.  
  210. # Create the hashtables of settings to be used.
  211. $valueset = @{
  212. Hostname = $SubjectName
  213. CertificateThumbprint = $thumbprint
  214. }
  215.  
  216. $selectorset = @{
  217. Transport = "HTTPS"
  218. Address = "*"
  219. }
  220.  
  221. Write-Verbose "Enabling SSL listener."
  222. New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
  223. Write-Log "Enabled SSL listener."
  224. }
  225. Else
  226. {
  227. Write-Verbose "SSL listener is already active."
  228.  
  229. # Force a new SSL cert on Listener if the $ForceNewSSLCert
  230. If ($ForceNewSSLCert)
  231. {
  232.  
  233. # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
  234. $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
  235. Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
  236.  
  237. $valueset = @{
  238. CertificateThumbprint = $thumbprint
  239. Hostname = $SubjectName
  240. }
  241.  
  242. # Delete the listener for SSL
  243. $selectorset = @{
  244. Address = "*"
  245. Transport = "HTTPS"
  246. }
  247. Remove-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
  248.  
  249. # Add new Listener with new SSL cert
  250. New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
  251. }
  252. }
  253.  
  254. # Check for basic authentication.
  255. $basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where {$_.Name -eq "Basic"}
  256. If (($basicAuthSetting.Value) -eq $false)
  257. {
  258. Write-Verbose "Enabling basic auth support."
  259. Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $true
  260. Write-Log "Enabled basic auth support."
  261. }
  262. Else
  263. {
  264. Write-Verbose "Basic auth is already enabled."
  265. }
  266.  
  267. # If EnableCredSSP if set to true
  268. If ($EnableCredSSP)
  269. {
  270. # Check for CredSSP authentication
  271. $credsspAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where {$_.Name -eq "CredSSP"}
  272. If (($credsspAuthSetting.Value) -eq $false)
  273. {
  274. Write-Verbose "Enabling CredSSP auth support."
  275. Enable-WSManCredSSP -role server -Force
  276. Write-Log "Enabled CredSSP auth support."
  277. }
  278. }
  279.  
  280. # Configure firewall to allow WinRM HTTPS connections.
  281. #$fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS"
  282. #$fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any
  283. #If ($fwtest1.count -lt 5)
  284. #{
  285. # Write-Verbose "Adding firewall rule to allow WinRM HTTPS."
  286. # netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 #protocol=TCP action=allow
  287. # Write-Log "Added firewall rule to allow WinRM HTTPS."
  288. #}
  289. #ElseIf (($fwtest1.count -ge 5) -and ($fwtest2.count -lt 5))
  290. #{
  291. # Write-Verbose "Updating firewall rule to allow WinRM HTTPS for any profile."
  292. # netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any
  293. # Write-Log "Updated firewall rule to allow WinRM HTTPS for any profile."
  294. #}
  295. #Else
  296. #{
  297. # Write-Verbose "Firewall rule already exists to allow WinRM HTTPS."
  298. #}
  299.  
  300. # Test a remoting connection to localhost, which should work.
  301. $httpResult = Invoke-Command -ComputerName "localhost" -ScriptBlock {$env:COMPUTERNAME} -ErrorVariable httpError -ErrorAction SilentlyContinue
  302. $httpsOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
  303.  
  304. $httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $httpsOptions -ErrorVariable httpsError -ErrorAction SilentlyContinue
  305.  
  306. If ($httpResult -and $httpsResult)
  307. {
  308. Write-Verbose "HTTP: Enabled | HTTPS: Enabled"
  309. }
  310. ElseIf ($httpsResult -and !$httpResult)
  311. {
  312. Write-Verbose "HTTP: Disabled | HTTPS: Enabled"
  313. }
  314. ElseIf ($httpResult -and !$httpsResult)
  315. {
  316. Write-Verbose "HTTP: Enabled | HTTPS: Disabled"
  317. }
  318. Else
  319. {
  320. Write-Log "Unable to establish an HTTP or HTTPS remoting session."
  321. Throw "Unable to establish an HTTP or HTTPS remoting session."
  322. }
  323. Write-VerboseLog "PS Remoting has been successfully configured for Ansible."
Add Comment
Please, Sign In to add comment