Guest User

Untitled

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