Debian Codegraph @

lib/ansible/module_utils/powershell/Ansible.ModuleUtils.WebRequest.psm1

raw
1 # Copyright (c) 2019 Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 Function Get-AnsibleWebRequest {
5 <#
6 .SYNOPSIS
7 Creates a System.Net.WebRequest object based on common URL module options in Ansible.
8
9 .DESCRIPTION
10 Will create a WebRequest based on common input options within Ansible. This can be used manually or with
11 Invoke-WithWebRequest.
12
13 .PARAMETER Uri
14 The URI to create the web request for.
15
16 .PARAMETER Method
17 The protocol method to use, if omitted, will use the default value for the URI protocol specified.
18
19 .PARAMETER FollowRedirects
20 Whether to follow redirect responses. This is only valid when using a HTTP URI.
21 all - Will follow all redirects
22 none - Will follow no redirects
23 safe - Will only follow redirects when GET or HEAD is used as the Method
24
25 .PARAMETER Headers
26 A hashtable or dictionary of header values to set on the request. This is only valid for a HTTP URI.
27
28 .PARAMETER HttpAgent
29 A string to set for the 'User-Agent' header. This is only valid for a HTTP URI.
30
31 .PARAMETER MaximumRedirection
32 The maximum number of redirections that will be followed. This is only valid for a HTTP URI.
33
34 .PARAMETER Timeout
35 The timeout in seconds that defines how long to wait until the request times out.
36
37 .PARAMETER ValidateCerts
38 Whether to validate SSL certificates, default to True.
39
40 .PARAMETER ClientCert
41 The path to PFX file to use for X509 authentication. This is only valid for a HTTP URI. This path can either
42 be a filesystem path (C:\folder\cert.pfx) or a PSPath to a credential (Cert:\CurrentUser\My\<thumbprint>).
43
44 .PARAMETER ClientCertPassword
45 The password for the PFX certificate if required. This is only valid for a HTTP URI.
46
47 .PARAMETER ForceBasicAuth
48 Whether to set the Basic auth header on the first request instead of when required. This is only valid for a
49 HTTP URI.
50
51 .PARAMETER UrlUsername
52 The username to use for authenticating with the target.
53
54 .PARAMETER UrlPassword
55 The password to use for authenticating with the target.
56
57 .PARAMETER UseDefaultCredential
58 Whether to use the current user's credentials if available. This will only work when using Become, using SSH with
59 password auth, or WinRM with CredSSP or Kerberos with credential delegation.
60
61 .PARAMETER UseProxy
62 Whether to use the default proxy defined in IE (WinINet) for the user or set no proxy at all. This should not
63 be set to True when ProxyUrl is also defined.
64
65 .PARAMETER ProxyUrl
66 An explicit proxy server to use for the request instead of relying on the default proxy in IE. This is only
67 valid for a HTTP URI.
68
69 .PARAMETER ProxyUsername
70 An optional username to use for proxy authentication.
71
72 .PARAMETER ProxyPassword
73 The password for ProxyUsername.
74
75 .PARAMETER ProxyUseDefaultCredential
76 Whether to use the current user's credentials for proxy authentication if available. This will only work when
77 using Become, using SSH with password auth, or WinRM with CredSSP or Kerberos with credential delegation.
78
79 .PARAMETER Module
80 The AnsibleBasic module that can be used as a backup parameter source or a way to return warnings back to the
81 Ansible controller.
82
83 .EXAMPLE
84 $spec = @{
85 options = @{}
86 }
87 $module = Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-AnsibleWebRequestSpec))
88
89 $web_request = Get-AnsibleWebRequest -Module $module
90 #>
91 [CmdletBinding()]
92 [OutputType([System.Net.WebRequest])]
93 Param (
94 [Alias("url")]
95 [System.Uri]
96 $Uri,
97
98 [System.String]
99 $Method,
100
101 [Alias("follow_redirects")]
102 [ValidateSet("all", "none", "safe")]
103 [System.String]
104 $FollowRedirects = "safe",
105
106 [System.Collections.IDictionary]
107 $Headers,
108
109 [Alias("http_agent")]
110 [System.String]
111 $HttpAgent = "ansible-httpget",
112
113 [Alias("maximum_redirection")]
114 [System.Int32]
115 $MaximumRedirection = 50,
116
117 [System.Int32]
118 $Timeout = 30,
119
120 [Alias("validate_certs")]
121 [System.Boolean]
122 $ValidateCerts = $true,
123
124 # Credential params
125 [Alias("client_cert")]
126 [System.String]
127 $ClientCert,
128
129 [Alias("client_cert_password")]
130 [System.String]
131 $ClientCertPassword,
132
133 [Alias("force_basic_auth")]
134 [Switch]
135 $ForceBasicAuth,
136
137 [Alias("url_username")]
138 [System.String]
139 $UrlUsername,
140
141 [Alias("url_password")]
142 [System.String]
143 $UrlPassword,
144
145 [Alias("use_default_credential")]
146 [Switch]
147 $UseDefaultCredential,
148
149 # Proxy params
150 [Alias("use_proxy")]
151 [System.Boolean]
152 $UseProxy = $true,
153
154 [Alias("proxy_url")]
155 [System.String]
156 $ProxyUrl,
157
158 [Alias("proxy_username")]
159 [System.String]
160 $ProxyUsername,
161
162 [Alias("proxy_password")]
163 [System.String]
164 $ProxyPassword,
165
166 [Alias("proxy_use_default_credential")]
167 [Switch]
168 $ProxyUseDefaultCredential,
169
170 [ValidateScript({ $_.GetType().FullName -eq 'Ansible.Basic.AnsibleModule' })]
171 [System.Object]
172 $Module
173 )
174
175 # Set module options for parameters unless they were explicitly passed in.
176 if ($Module) {
177 foreach ($param in $PSCmdlet.MyInvocation.MyCommand.Parameters.GetEnumerator()) {
178 if ($PSBoundParameters.ContainsKey($param.Key)) {
179 # Was set explicitly we want to use that value
180 continue
181 }
182
183 foreach ($alias in @($Param.Key) + $param.Value.Aliases) {
184 if ($Module.Params.ContainsKey($alias)) {
185 $var_value = $Module.Params.$alias -as $param.Value.ParameterType
186 Set-Variable -Name $param.Key -Value $var_value
187 break
188 }
189 }
190 }
191 }
192
193 # Disable certificate validation if requested
194 # FUTURE: set this on ServerCertificateValidationCallback of the HttpWebRequest once .NET 4.5 is the minimum
195 if (-not $ValidateCerts) {
196 $callback = [System.Linq.Expressions.Expression]::Lambda(
197 [System.Net.Security.RemoteCertificateValidationCallback],
198 [System.Linq.Expressions.Expression]::Constant($true, [bool]),
199 [System.Linq.Expressions.Expression]::Parameter([object], "sender"),
200 [System.Linq.Expressions.Expression]::Parameter([System.Security.Cryptography.X509Certificates.X509Certificate], "certificate"),
201 [System.Linq.Expressions.Expression]::Parameter([System.Security.Cryptography.X509Certificates.X509Chain], "chain"),
202 [System.Linq.Expressions.Expression]::Parameter([System.Net.Security.SslPolicyErrors], "sslPolicyErrors")
203 ).Compile()
204
205 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $callback
206 }
207
208 # Enable TLS1.1/TLS1.2 if they're available but disabled (eg. .NET 4.5)
209 $security_protocols = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::SystemDefault
210 if ([System.Net.SecurityProtocolType].GetMember("Tls11").Count -gt 0) {
211 $security_protocols = $security_protocols -bor [System.Net.SecurityProtocolType]::Tls11
212 }
213 if ([System.Net.SecurityProtocolType].GetMember("Tls12").Count -gt 0) {
214 $security_protocols = $security_protocols -bor [System.Net.SecurityProtocolType]::Tls12
215 }
216 [System.Net.ServicePointManager]::SecurityProtocol = $security_protocols
217
218 $web_request = [System.Net.WebRequest]::Create($Uri)
219 if ($Method) {
220 $web_request.Method = $Method
221 }
222 $web_request.Timeout = $Timeout * 1000
223
224 if ($UseDefaultCredential -and $web_request -is [System.Net.HttpWebRequest]) {
225 $web_request.UseDefaultCredentials = $true
226 }
227 elseif ($UrlUsername) {
228 if ($ForceBasicAuth) {
229 $auth_value = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $UrlUsername, $UrlPassword)))
230 $web_request.Headers.Add("Authorization", "Basic $auth_value")
231 }
232 else {
233 $credential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $UrlUsername, $UrlPassword
234 $web_request.Credentials = $credential
235 }
236 }
237
238 if ($ClientCert) {
239 # Expecting either a filepath or PSPath (Cert:\CurrentUser\My\<thumbprint>)
240 $cert = Get-Item -LiteralPath $ClientCert -ErrorAction SilentlyContinue
241 if ($null -eq $cert) {
242 Write-Error -Message "Client certificate '$ClientCert' does not exist" -Category ObjectNotFound
243 return
244 }
245
246 $crypto_ns = 'System.Security.Cryptography.X509Certificates'
247 if ($cert.PSProvider.Name -ne 'Certificate') {
248 try {
249 $cert = New-Object -TypeName "$crypto_ns.X509Certificate2" -ArgumentList @(
250 $ClientCert, $ClientCertPassword
251 )
252 }
253 catch [System.Security.Cryptography.CryptographicException] {
254 Write-Error -Message "Failed to read client certificate at '$ClientCert'" -Exception $_.Exception -Category SecurityError
255 return
256 }
257 }
258 $web_request.ClientCertificates = New-Object -TypeName "$crypto_ns.X509Certificate2Collection" -ArgumentList @(
259 $cert
260 )
261 }
262
263 if (-not $UseProxy) {
264 $proxy = $null
265 }
266 elseif ($ProxyUrl) {
267 $proxy = New-Object -TypeName System.Net.WebProxy -ArgumentList $ProxyUrl, $true
268 }
269 else {
270 $proxy = $web_request.Proxy
271 }
272
273 # $web_request.Proxy may return $null for a FTP web request. We only set the credentials if we have an actual
274 # proxy to work with, otherwise just ignore the credentials property.
275 if ($null -ne $proxy) {
276 if ($ProxyUseDefaultCredential) {
277 # Weird hack, $web_request.Proxy returns an IWebProxy object which only guarantees the Credentials
278 # property. We cannot set UseDefaultCredentials so we just set the Credentials to the
279 # DefaultCredentials in the CredentialCache which does the same thing.
280 $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
281 }
282 elseif ($ProxyUsername) {
283 $proxy.Credentials = New-Object -TypeName System.Net.NetworkCredential -ArgumentList @(
284 $ProxyUsername, $ProxyPassword
285 )
286 }
287 else {
288 $proxy.Credentials = $null
289 }
290 }
291
292 $web_request.Proxy = $proxy
293
294 # Some parameters only apply when dealing with a HttpWebRequest
295 if ($web_request -is [System.Net.HttpWebRequest]) {
296 if ($Headers) {
297 foreach ($header in $Headers.GetEnumerator()) {
298 switch ($header.Key) {
299 Accept { $web_request.Accept = $header.Value }
300 Connection { $web_request.Connection = $header.Value }
301 Content-Length { $web_request.ContentLength = $header.Value }
302 Content-Type { $web_request.ContentType = $header.Value }
303 Expect { $web_request.Expect = $header.Value }
304 Date { $web_request.Date = $header.Value }
305 Host { $web_request.Host = $header.Value }
306 If-Modified-Since { $web_request.IfModifiedSince = $header.Value }
307 Range { $web_request.AddRange($header.Value) }
308 Referer { $web_request.Referer = $header.Value }
309 Transfer-Encoding {
310 $web_request.SendChunked = $true
311 $web_request.TransferEncoding = $header.Value
312 }
313 User-Agent { continue }
314 default { $web_request.Headers.Add($header.Key, $header.Value) }
315 }
316 }
317 }
318
319 # For backwards compatibility we need to support setting the User-Agent if the header was set in the task.
320 # We just need to make sure that if an explicit http_agent module was set then that takes priority.
321 if ($Headers -and $Headers.ContainsKey("User-Agent")) {
322 if ($HttpAgent -eq $ansible_web_request_options.http_agent.default) {
323 $HttpAgent = $Headers['User-Agent']
324 }
325 elseif ($null -ne $Module) {
326 $Module.Warn("The 'User-Agent' header and the 'http_agent' was set, using the 'http_agent' for web request")
327 }
328 }
329 $web_request.UserAgent = $HttpAgent
330
331 switch ($FollowRedirects) {
332 none { $web_request.AllowAutoRedirect = $false }
333 safe {
334 if ($web_request.Method -in @("GET", "HEAD")) {
335 $web_request.AllowAutoRedirect = $true
336 }
337 else {
338 $web_request.AllowAutoRedirect = $false
339 }
340 }
341 all { $web_request.AllowAutoRedirect = $true }
342 }
343
344 if ($MaximumRedirection -eq 0) {
345 $web_request.AllowAutoRedirect = $false
346 }
347 else {
348 $web_request.MaximumAutomaticRedirections = $MaximumRedirection
349 }
350 }
351
352 return $web_request
353 }
354
355 Function Invoke-WithWebRequest {
356 <#
357 .SYNOPSIS
358 Invokes a ScriptBlock with the WebRequest.
359
360 .DESCRIPTION
361 Invokes the ScriptBlock and handle extra information like accessing the response stream, closing those streams
362 safely as well as setting common module return values.
363
364 .PARAMETER Module
365 The Ansible.Basic module to set the return values for. This will set the following return values;
366 elapsed - The total time, in seconds, that it took to send the web request and process the response
367 msg - The human-readable description of the response status code
368 status_code - An int that is the response status code
369
370 .PARAMETER Request
371 The System.Net.WebRequest to call. This can either be manually crafted or created with Get-AnsibleWebRequest.
372
373 .PARAMETER Script
374 The ScriptBlock to invoke during the web request. This ScriptBlock should take in the params
375 Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream)
376
377 This scriptblock should manage the response based on what it need to do.
378
379 .PARAMETER Body
380 An optional Stream to send to the target during the request.
381
382 .PARAMETER IgnoreBadResponse
383 By default a WebException will be raised for a non 2xx status code and the Script will not be invoked. This
384 parameter can be set to process all responses regardless of the status code.
385
386 .EXAMPLE Basic module that downloads a file
387 $spec = @{
388 options = @{
389 path = @{ type = "path"; required = $true }
390 }
391 }
392 $module = Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-AnsibleWebRequestSpec))
393
394 $web_request = Get-AnsibleWebRequest -Module $module
395
396 Invoke-WithWebRequest -Module $module -Request $web_request -Script {
397 Param ([System.Net.WebResponse]$Response, [System.IO.Stream]$Stream)
398
399 $fs = [System.IO.File]::Create($module.Params.path)
400 try {
401 $Stream.CopyTo($fs)
402 $fs.Flush()
403 } finally {
404 $fs.Dispose()
405 }
406 }
407 #>
408 [CmdletBinding()]
409 param (
410 [Parameter(Mandatory = $true)]
411 [System.Object]
412 [ValidateScript({ $_.GetType().FullName -eq 'Ansible.Basic.AnsibleModule' })]
413 $Module,
414
415 [Parameter(Mandatory = $true)]
416 [System.Net.WebRequest]
417 $Request,
418
419 [Parameter(Mandatory = $true)]
420 [ScriptBlock]
421 $Script,
422
423 [AllowNull()]
424 [System.IO.Stream]
425 $Body,
426
427 [Switch]
428 $IgnoreBadResponse
429 )
430
431 $start = Get-Date
432 if ($null -ne $Body) {
433 $request_st = $Request.GetRequestStream()
434 try {
435 $Body.CopyTo($request_st)
436 $request_st.Flush()
437 }
438 finally {
439 $request_st.Close()
440 }
441 }
442
443 try {
444 try {
445 $web_response = $Request.GetResponse()
446 }
447 catch [System.Net.WebException] {
448 # A WebResponse with a status code not in the 200 range will raise a WebException. We check if the
449 # exception raised contains the actual response and continue on if IgnoreBadResponse is set. We also
450 # make sure we set the status_code return value on the Module object if possible
451
452 if ($_.Exception.PSObject.Properties.Name -match "Response") {
453 $web_response = $_.Exception.Response
454
455 if (-not $IgnoreBadResponse -or $null -eq $web_response) {
456 $Module.Result.msg = $_.Exception.StatusDescription
457 $Module.Result.status_code = $_.Exception.Response.StatusCode
458 throw $_
459 }
460 }
461 else {
462 throw $_
463 }
464 }
465
466 if ($Request.RequestUri.IsFile) {
467 # A FileWebResponse won't have these properties set
468 $Module.Result.msg = "OK"
469 $Module.Result.status_code = 200
470 }
471 else {
472 $Module.Result.msg = $web_response.StatusDescription
473 $Module.Result.status_code = $web_response.StatusCode
474 }
475
476 $response_stream = $web_response.GetResponseStream()
477 try {
478 # Invoke the ScriptBlock and pass in WebResponse and ResponseStream
479 &$Script -Response $web_response -Stream $response_stream
480 }
481 finally {
482 $response_stream.Dispose()
483 }
484 }
485 finally {
486 if ($web_response) {
487 $web_response.Close()
488 }
489 $Module.Result.elapsed = ((Get-date) - $start).TotalSeconds
490 }
491 }
492
493 Function Get-AnsibleWebRequestSpec {
494 <#
495 .SYNOPSIS
496 Used by modules to get the argument spec fragment for AnsibleModule.
497
498 .EXAMPLES
499 $spec = @{
500 options = @{}
501 }
502 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec, @(Get-AnsibleWebRequestSpec))
503 #>
504 @{ options = $ansible_web_request_options }
505 }
506
507 # See lib/ansible/plugins/doc_fragments/url_windows.py
508 # Kept here for backwards compat as this variable was added in Ansible 2.9. Ultimately this util should be removed
509 # once the deprecation period has been added.
510 $ansible_web_request_options = @{
511 method = @{ type = "str" }
512 follow_redirects = @{ type = "str"; choices = @("all", "none", "safe"); default = "safe" }
513 headers = @{ type = "dict" }
514 http_agent = @{ type = "str"; default = "ansible-httpget" }
515 maximum_redirection = @{ type = "int"; default = 50 }
516 timeout = @{ type = "int"; default = 30 } # Was defaulted to 10 in win_get_url but 30 in win_uri so we use 30
517 validate_certs = @{ type = "bool"; default = $true }
518
519 # Credential options
520 client_cert = @{ type = "str" }
521 client_cert_password = @{ type = "str"; no_log = $true }
522 force_basic_auth = @{ type = "bool"; default = $false }
523 url_username = @{ type = "str" }
524 url_password = @{ type = "str"; no_log = $true }
525 use_default_credential = @{ type = "bool"; default = $false }
526
527 # Proxy options
528 use_proxy = @{ type = "bool"; default = $true }
529 proxy_url = @{ type = "str" }
530 proxy_username = @{ type = "str" }
531 proxy_password = @{ type = "str"; no_log = $true }
532 proxy_use_default_credential = @{ type = "bool"; default = $false }
533 }
534
535 $export_members = @{
536 Function = "Get-AnsibleWebRequest", "Get-AnsibleWebRequestSpec", "Invoke-WithWebRequest"
537 Variable = "ansible_web_request_options"
538 }
539 Export-ModuleMember @export_members