Guest User

Untitled

a guest
Apr 3rd, 2018
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.78 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 -EnableCredSSP to enable CredSSP as an authentication option.
  23. #
  24. # Use option -DisableBasicAuth to disable basic authentication.
  25. #
  26. # Use option -SkipNetworkProfileCheck to skip the network profile check.
  27. # Without specifying this the script will only run if the device's interfaces
  28. # are in DOMAIN or PRIVATE zones. Provide this switch if you want to enable
  29. # WinRM on a device with an interface in PUBLIC zone.
  30. #
  31. # Use option -SubjectName to specify the CN name of the certificate. This
  32. # defaults to the system's hostname and generally should not be specified.
  33.  
  34. # Written by Trond Hindenes <trond@hindenes.com>
  35. # Updated by Chris Church <cchurch@ansible.com>
  36. # Updated by Michael Crilly <mike@autologic.cm>
  37. # Updated by Anton Ouzounov <Anton.Ouzounov@careerbuilder.com>
  38. # Updated by Nicolas Simond <contact@nicolas-simond.com>
  39. # Updated by Dag Wieërs <dag@wieers.com>
  40. # Updated by Jordan Borean <jborean93@gmail.com>
  41. # Updated by Erwan Quélin <erwan.quelin@gmail.com>
  42. #
  43. # Version 1.0 - 2014-07-06
  44. # Version 1.1 - 2014-11-11
  45. # Version 1.2 - 2015-05-15
  46. # Version 1.3 - 2016-04-04
  47. # Version 1.4 - 2017-01-05
  48. # Version 1.5 - 2017-02-09
  49. # Version 1.6 - 2017-04-18
  50. # Version 1.7 - 2017-11-23
  51.  
  52. # Support -Verbose option
  53. [CmdletBinding()]
  54.  
  55. Param (
  56. [string]$SubjectName = $env:COMPUTERNAME,
  57. [int]$CertValidityDays = 1095,
  58. [switch]$SkipNetworkProfileCheck,
  59. $CreateSelfSignedCert = $true,
  60. [switch]$ForceNewSSLCert,
  61. [switch]$GlobalHttpFirewallAccess,
  62. [switch]$DisableBasicAuth = $false,
  63. [switch]$EnableCredSSP
  64. )
  65.  
  66. Function Write-Log
  67. {
  68. $Message = $args[0]
  69. Write-EventLog -LogName Application -Source $EventSource -EntryType Information -EventId 1 -Message $Message
  70. }
  71.  
  72. Function Write-VerboseLog
  73. {
  74. $Message = $args[0]
  75. Write-Verbose $Message
  76. Write-Log $Message
  77. }
  78.  
  79. Function Write-HostLog
  80. {
  81. $Message = $args[0]
  82. Write-Output $Message
  83. Write-Log $Message
  84. }
  85.  
  86. Function New-LegacySelfSignedCert
  87. {
  88. Param (
  89. [string]$SubjectName,
  90. [int]$ValidDays = 1095
  91. )
  92.  
  93. $name = New-Object -COM "X509Enrollment.CX500DistinguishedName.1"
  94. $name.Encode("CN=$SubjectName", 0)
  95.  
  96. $key = New-Object -COM "X509Enrollment.CX509PrivateKey.1"
  97. $key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
  98. $key.KeySpec = 1
  99. $key.Length = 4096
  100. $key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
  101. $key.MachineContext = 1
  102. $key.Create()
  103.  
  104. $serverauthoid = New-Object -COM "X509Enrollment.CObjectId.1"
  105. $serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1")
  106. $ekuoids = New-Object -COM "X509Enrollment.CObjectIds.1"
  107. $ekuoids.Add($serverauthoid)
  108. $ekuext = New-Object -COM "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
  109. $ekuext.InitializeEncode($ekuoids)
  110.  
  111. $cert = New-Object -COM "X509Enrollment.CX509CertificateRequestCertificate.1"
  112. $cert.InitializeFromPrivateKey(2, $key, "")
  113. $cert.Subject = $name
  114. $cert.Issuer = $cert.Subject
  115. $cert.NotBefore = (Get-Date).AddDays(-1)
  116. $cert.NotAfter = $cert.NotBefore.AddDays($ValidDays)
  117. $cert.X509Extensions.Add($ekuext)
  118. $cert.Encode()
  119.  
  120. $enrollment = New-Object -COM "X509Enrollment.CX509Enrollment.1"
  121. $enrollment.InitializeFromRequest($cert)
  122. $certdata = $enrollment.CreateRequest(0)
  123. $enrollment.InstallResponse(2, $certdata, 0, "")
  124.  
  125. # extract/return the thumbprint from the generated cert
  126. $parsed_cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
  127. $parsed_cert.Import([System.Text.Encoding]::UTF8.GetBytes($certdata))
  128.  
  129. return $parsed_cert.Thumbprint
  130. }
  131.  
  132. Function Enable-GlobalHttpFirewallAccess
  133. {
  134. Write-Verbose "Forcing global HTTP firewall access"
  135. # this is a fairly naive implementation; could be more sophisticated about rule matching/collapsing
  136. $fw = New-Object -ComObject HNetCfg.FWPolicy2
  137.  
  138. # try to find/enable the default rule first
  139. $add_rule = $false
  140. $matching_rules = $fw.Rules | ? { $_.Name -eq "Windows Remote Management (HTTP-In)" }
  141. $rule = $null
  142. If ($matching_rules) {
  143. If ($matching_rules -isnot [Array]) {
  144. Write-Verbose "Editing existing single HTTP firewall rule"
  145. $rule = $matching_rules
  146. }
  147. Else {
  148. # try to find one with the All or Public profile first
  149. Write-Verbose "Found multiple existing HTTP firewall rules..."
  150. $rule = $matching_rules | % { $_.Profiles -band 4 }[0]
  151.  
  152. If (-not $rule -or $rule -is [Array]) {
  153. Write-Verbose "Editing an arbitrary single HTTP firewall rule (multiple existed)"
  154. # oh well, just pick the first one
  155. $rule = $matching_rules[0]
  156. }
  157. }
  158. }
  159.  
  160. If (-not $rule) {
  161. Write-Verbose "Creating a new HTTP firewall rule"
  162. $rule = New-Object -ComObject HNetCfg.FWRule
  163. $rule.Name = "Windows Remote Management (HTTP-In)"
  164. $rule.Description = "Inbound rule for Windows Remote Management via WS-Management. [TCP 5985]"
  165. $add_rule = $true
  166. }
  167.  
  168. $rule.Profiles = 0x7FFFFFFF
  169. $rule.Protocol = 6
  170. $rule.LocalPorts = 5985
  171. $rule.RemotePorts = "*"
  172. $rule.LocalAddresses = "*"
  173. $rule.RemoteAddresses = "*"
  174. $rule.Enabled = $true
  175. $rule.Direction = 1
  176. $rule.Action = 1
  177. $rule.Grouping = "Windows Remote Management"
  178.  
  179. If ($add_rule) {
  180. $fw.Rules.Add($rule)
  181. }
  182.  
  183. Write-Verbose "HTTP firewall rule $($rule.Name) updated"
  184. }
  185.  
  186. # Setup error handling.
  187. Trap
  188. {
  189. $_
  190. Exit 1
  191. }
  192. $ErrorActionPreference = "Stop"
  193.  
  194. # Get the ID and security principal of the current user account
  195. $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
  196. $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  197.  
  198. # Get the security principal for the Administrator role
  199. $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
  200.  
  201. # Check to see if we are currently running "as Administrator"
  202. if (-Not $myWindowsPrincipal.IsInRole($adminRole))
  203. {
  204. Write-Output "ERROR: You need elevated Administrator privileges in order to run this script."
  205. Write-Output " Start Windows PowerShell by using the Run as Administrator option."
  206. Exit 2
  207. }
  208.  
  209. $EventSource = $MyInvocation.MyCommand.Name
  210. If (-Not $EventSource)
  211. {
  212. $EventSource = "Powershell CLI"
  213. }
  214.  
  215. If ([System.Diagnostics.EventLog]::Exists('Application') -eq $False -or [System.Diagnostics.EventLog]::SourceExists($EventSource) -eq $False)
  216. {
  217. New-EventLog -LogName Application -Source $EventSource
  218. }
  219.  
  220. # Detect PowerShell version.
  221. If ($PSVersionTable.PSVersion.Major -lt 3)
  222. {
  223. Write-Log "PowerShell version 3 or higher is required."
  224. Throw "PowerShell version 3 or higher is required."
  225. }
  226.  
  227. # Find and start the WinRM service.
  228. Write-Verbose "Verifying WinRM service."
  229. If (!(Get-Service "WinRM"))
  230. {
  231. Write-Log "Unable to find the WinRM service."
  232. Throw "Unable to find the WinRM service."
  233. }
  234. ElseIf ((Get-Service "WinRM").Status -ne "Running")
  235. {
  236. Write-Verbose "Setting WinRM service to start automatically on boot."
  237. Set-Service -Name "WinRM" -StartupType Automatic
  238. Write-Log "Set WinRM service to start automatically on boot."
  239. Write-Verbose "Starting WinRM service."
  240. Start-Service -Name "WinRM" -ErrorAction Stop
  241. Write-Log "Started WinRM service."
  242.  
  243. }
  244.  
  245. # WinRM should be running; check that we have a PS session config.
  246. If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener)))
  247. {
  248. If ($SkipNetworkProfileCheck) {
  249. Write-Verbose "Enabling PS Remoting without checking Network profile."
  250. Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop
  251. Write-Log "Enabled PS Remoting without checking Network profile."
  252. }
  253. Else {
  254. Write-Verbose "Enabling PS Remoting."
  255. Enable-PSRemoting -Force -ErrorAction Stop
  256. Write-Log "Enabled PS Remoting."
  257. }
  258. }
  259. Else
  260. {
  261. Write-Verbose "PS Remoting is already enabled."
  262. }
  263.  
  264. # Make sure there is a SSL listener.
  265. $listeners = Get-ChildItem WSMan:\localhost\Listener
  266. If (!($listeners | Where {$_.Keys -like "TRANSPORT=HTTPS"}))
  267. {
  268. # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
  269. $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
  270. Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
  271.  
  272. # Create the hashtables of settings to be used.
  273. $valueset = @{
  274. Hostname = $SubjectName
  275. CertificateThumbprint = $thumbprint
  276. }
  277.  
  278. $selectorset = @{
  279. Transport = "HTTPS"
  280. Address = "*"
  281. }
  282.  
  283. Write-Verbose "Enabling SSL listener."
  284. New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
  285. Write-Log "Enabled SSL listener."
  286. }
  287. Else
  288. {
  289. Write-Verbose "SSL listener is already active."
  290.  
  291. # Force a new SSL cert on Listener if the $ForceNewSSLCert
  292. If ($ForceNewSSLCert)
  293. {
  294.  
  295. # We cannot use New-SelfSignedCertificate on 2012R2 and earlier
  296. $thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
  297. Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
  298.  
  299. $valueset = @{
  300. CertificateThumbprint = $thumbprint
  301. Hostname = $SubjectName
  302. }
  303.  
  304. # Delete the listener for SSL
  305. $selectorset = @{
  306. Address = "*"
  307. Transport = "HTTPS"
  308. }
  309. Remove-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
  310.  
  311. # Add new Listener with new SSL cert
  312. New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
  313. }
  314. }
  315.  
  316. # Check for basic authentication.
  317. $basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object {$_.Name -eq "Basic"}
  318.  
  319. If ($DisableBasicAuth)
  320. {
  321. If (($basicAuthSetting.Value) -eq $true)
  322. {
  323. Write-Verbose "Disabling basic auth support."
  324. Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $false
  325. Write-Log "Disabled basic auth support."
  326. }
  327. Else
  328. {
  329. Write-Verbose "Basic auth is already disabled."
  330. }
  331. }
  332. Else
  333. {
  334. If (($basicAuthSetting.Value) -eq $false)
  335. {
  336. Write-Verbose "Enabling basic auth support."
  337. Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $true
  338. Write-Log "Enabled basic auth support."
  339. }
  340. Else
  341. {
  342. Write-Verbose "Basic auth is already enabled."
  343. }
  344. }
  345.  
  346. # If EnableCredSSP if set to true
  347. If ($EnableCredSSP)
  348. {
  349. # Check for CredSSP authentication
  350. $credsspAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where {$_.Name -eq "CredSSP"}
  351. If (($credsspAuthSetting.Value) -eq $false)
  352. {
  353. Write-Verbose "Enabling CredSSP auth support."
  354. Enable-WSManCredSSP -role server -Force
  355. Write-Log "Enabled CredSSP auth support."
  356. }
  357. }
  358.  
  359. If ($GlobalHttpFirewallAccess) {
  360. Enable-GlobalHttpFirewallAccess
  361. }
  362.  
  363. # Configure firewall to allow WinRM HTTPS connections.
  364. $fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS"
  365. $fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any
  366. If ($fwtest1.count -lt 5)
  367. {
  368. Write-Verbose "Adding firewall rule to allow WinRM HTTPS."
  369. netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow
  370. Write-Log "Added firewall rule to allow WinRM HTTPS."
  371. }
  372. ElseIf (($fwtest1.count -ge 5) -and ($fwtest2.count -lt 5))
  373. {
  374. Write-Verbose "Updating firewall rule to allow WinRM HTTPS for any profile."
  375. netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any
  376. Write-Log "Updated firewall rule to allow WinRM HTTPS for any profile."
  377. }
  378. Else
  379. {
  380. Write-Verbose "Firewall rule already exists to allow WinRM HTTPS."
  381. }
  382.  
  383. # Test a remoting connection to localhost, which should work.
  384. $httpResult = Invoke-Command -ComputerName "localhost" -ScriptBlock {$env:COMPUTERNAME} -ErrorVariable httpError -ErrorAction SilentlyContinue
  385. $httpsOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
  386.  
  387. $httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $httpsOptions -ErrorVariable httpsError -ErrorAction SilentlyContinue
  388.  
  389. If ($httpResult -and $httpsResult)
  390. {
  391. Write-Verbose "HTTP: Enabled | HTTPS: Enabled"
  392. }
  393. ElseIf ($httpsResult -and !$httpResult)
  394. {
  395. Write-Verbose "HTTP: Disabled | HTTPS: Enabled"
  396. }
  397. ElseIf ($httpResult -and !$httpsResult)
  398. {
  399. Write-Verbose "HTTP: Enabled | HTTPS: Disabled"
  400. }
  401. Else
  402. {
  403. Write-Log "Unable to establish an HTTP or HTTPS remoting session."
  404. Throw "Unable to establish an HTTP or HTTPS remoting session."
  405. }
  406. Write-VerboseLog "PS Remoting has been successfully configured for Ansible."
Add Comment
Please, Sign In to add comment