Debian Codegraph @

lib/ansible/plugins/connection/winrm.py

raw
1 # (c) 2014, Chris Church <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 DOCUMENTATION = """
8 author: Ansible Core Team
9 name: winrm
10 short_description: Run tasks over Microsoft's WinRM
11 description:
12 - Run commands or put/fetch on a target via WinRM
13 - This plugin allows extra arguments to be passed that are supported by the protocol but not explicitly defined here.
14 They should take the form of variables declared with the following pattern C(ansible_winrm_<option>).
15 version_added: "2.0"
16 extends_documentation_fragment:
17 - connection_pipelining
18 requirements:
19 - pywinrm (python library)
20 options:
21 # figure out more elegant 'delegation'
22 remote_addr:
23 description:
24 - Address of the windows machine
25 default: inventory_hostname
26 vars:
27 - name: inventory_hostname
28 - name: ansible_host
29 - name: ansible_winrm_host
30 type: str
31 remote_user:
32 description:
33 - The user to log in as to the Windows machine
34 - If O(transport) is not defined, the authentication used will be V(kerberos) if the user is in the UPN format V(user@domain),
35 otherwise it will be V(basic)
36 vars:
37 - name: ansible_user
38 - name: ansible_winrm_user
39 keyword:
40 - name: remote_user
41 type: str
42 remote_password:
43 description: Authentication password for the O(remote_user). Can be supplied as CLI option.
44 vars:
45 - name: ansible_password
46 - name: ansible_winrm_pass
47 - name: ansible_winrm_password
48 type: str
49 secret: true
50 aliases:
51 - password # Needed for --ask-pass to come through on delegation
52 port:
53 description:
54 - port for winrm to connect on remote target
55 - The default is the https (5986) port, if using http it should be 5985
56 vars:
57 - name: ansible_port
58 - name: ansible_winrm_port
59 default: 5986
60 keyword:
61 - name: port
62 type: integer
63 scheme:
64 description:
65 - URI scheme to use
66 - If not set, then will default to V(https) or V(http) if O(port) is
67 V(5985).
68 choices: [http, https]
69 vars:
70 - name: ansible_winrm_scheme
71 type: str
72 path:
73 description: URI path to connect to
74 default: '/wsman'
75 vars:
76 - name: ansible_winrm_path
77 type: str
78 transport:
79 description:
80 - List of winrm transports to attempt to use (ssl, plaintext, kerberos, etc)
81 - If None (the default) the plugin will try to automatically guess the correct list. It will use
82 V(kerberos) if the username looks like a UPN V(user@domain), otherwise it will use V(basic).
83 - The choices available depend on your version of pywinrm
84 type: list
85 elements: string
86 vars:
87 - name: ansible_winrm_transport
88 kerberos_command:
89 description: kerberos command to use to request a authentication ticket
90 default: kinit
91 vars:
92 - name: ansible_winrm_kinit_cmd
93 type: str
94 kinit_args:
95 description:
96 - Extra arguments to pass to C(kinit) when getting the Kerberos authentication ticket.
97 - By default no extra arguments are passed into C(kinit) unless I(ansible_winrm_kerberos_delegation) is also
98 set. In that case C(-f) is added to the C(kinit) args so a forwardable ticket is retrieved.
99 - If set, the args will overwrite any existing defaults for C(kinit), including C(-f) for a delegated ticket.
100 type: str
101 vars:
102 - name: ansible_winrm_kinit_args
103 version_added: '2.11'
104 kinit_env_vars:
105 description:
106 - A list of environment variables to pass through to C(kinit) when getting the Kerberos authentication ticket.
107 - By default no environment variables are passed through and C(kinit) is run with a blank slate.
108 - The environment variable C(KRB5CCNAME) cannot be specified here as it's used to store the temp Kerberos
109 ticket used by WinRM.
110 type: list
111 elements: str
112 default: []
113 ini:
114 - section: winrm
115 key: kinit_env_vars
116 vars:
117 - name: ansible_winrm_kinit_env_vars
118 version_added: '2.12'
119 kerberos_mode:
120 description:
121 - kerberos usage mode.
122 - The managed option means Ansible will obtain kerberos ticket.
123 - While the manual one means a ticket must already have been obtained by the user.
124 choices: [managed, manual]
125 vars:
126 - name: ansible_winrm_kinit_mode
127 type: str
128 connection_timeout:
129 description:
130 - Despite its name, sets both the 'operation' and 'read' timeout settings for the WinRM
131 connection.
132 - The operation timeout belongs to the WS-Man layer and runs on the winRM-service on the
133 managed windows host.
134 - The read timeout belongs to the underlying python Request call (http-layer) and runs
135 on the ansible controller.
136 - The operation timeout sets the WS-Man 'Operation timeout' that runs on the managed
137 windows host. The operation timeout specifies how long a command will run on the
138 winRM-service before it sends the message 'WinRMOperationTimeoutError' back to the
139 client. The client (silently) ignores this message and starts a new instance of the
140 operation timeout, waiting for the command to finish (long running commands).
141 - The read timeout sets the client HTTP-request timeout and specifies how long the
142 client (ansible controller) will wait for data from the server to come back over
143 the HTTP-connection (timeout for waiting for in-between messages from the server).
144 When this timer expires, an exception will be thrown and the ansible connection
145 will be terminated with the error message 'Read timed out'
146 - To avoid the above exception to be thrown, the read timeout will be set to 10
147 seconds higher than the WS-Man operation timeout, thus make the connection more
148 robust on networks with long latency and/or many hops between server and client
149 network wise.
150 - Setting the difference between the operation and the read timeout to 10 seconds
151 aligns it to the defaults used in the winrm-module and the PSRP-module which also
152 uses 10 seconds (30 seconds for read timeout and 20 seconds for operation timeout)
153 - Corresponds to the C(operation_timeout_sec) and
154 C(read_timeout_sec) args in pywinrm so avoid setting these vars
155 with this one.
156 - The default value is whatever is set in the installed version of
157 pywinrm.
158 vars:
159 - name: ansible_winrm_connection_timeout
160 type: int
161 """
162
163 import base64
164 import logging
165 import os
166 import re
167 import traceback
168 import json
169 import tempfile
170 import shlex
171 import subprocess
172 import time
173 import typing as t
174 import xml.etree.ElementTree as ET
175
176 from inspect import getfullargspec
177 from urllib.parse import urlunsplit
178
179 HAVE_KERBEROS = False
180 try:
181 import kerberos # pylint: disable=unused-import
182 HAVE_KERBEROS = True
183 except ImportError:
184 pass
185
186 from ansible import constants as C
187 from ansible._internal._powershell import _clixml, _script
188 from ansible.errors import AnsibleError, AnsibleConnectionFailure
189 from ansible.errors import AnsibleFileNotFound
190 from ansible.executor.powershell.module_manifest import _bootstrap_powershell_script
191 from ansible.module_utils.json_utils import _filter_non_json_lines
192 from ansible.module_utils.parsing.convert_bool import boolean
193 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
194 from ansible.plugins.connection import ConnectionBase
195 from ansible.plugins.shell import ShellBase
196 from ansible.plugins.shell.cmd import ShellModule as CmdShellModule
197 from ansible.utils.hashing import secure_hash
198 from ansible.utils.display import Display
199
200
201 try:
202 import winrm
203 from winrm.exceptions import WinRMError, WinRMOperationTimeoutError, WinRMTransportError
204 from winrm.protocol import Protocol
205 import requests.exceptions
206 HAS_WINRM = True
207 WINRM_IMPORT_ERR = None
208 except ImportError as e:
209 HAS_WINRM = False
210 WINRM_IMPORT_ERR = e
211
212 try:
213 from winrm.exceptions import WSManFaultError
214 except ImportError:
215 # This was added in pywinrm 0.5.0, we just use our no-op exception for
216 # older versions which won't be able to handle this scenario.
217 class WSManFaultError(Exception): # type: ignore[no-redef]
218 pass
219
220 try:
221 import xmltodict
222 HAS_XMLTODICT = True
223 XMLTODICT_IMPORT_ERR = None
224 except ImportError as e:
225 HAS_XMLTODICT = False
226 XMLTODICT_IMPORT_ERR = e
227
228 # used to try and parse the hostname and detect if IPv6 is being used
229 try:
230 import ipaddress
231 HAS_IPADDRESS = True
232 except ImportError:
233 HAS_IPADDRESS = False
234
235 display = Display()
236
237
238 class Connection(ConnectionBase):
239 """WinRM connections over HTTP/HTTPS."""
240
241 transport = 'winrm'
242 module_implementation_preferences = ('.ps1', '.exe', '')
243 allow_executable = False
244 has_pipelining = True
245 allow_extras = True
246
247 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
248
249 self.protocol: winrm.Protocol | None = None
250 self.shell_id: str | None = None
251 self.delegate = None
252 self._shell: ShellBase
253 self._shell_type = 'cmd' # Default shell for the WinRS protocol is always cmd
254
255 super(Connection, self).__init__(*args, **kwargs)
256 if not isinstance(self._shell, CmdShellModule):
257 # This only happens if ansible_shell_type=powershell is set.
258 # It probably will work but edge cases like spaces in executables
259 # will most likely fail.
260 display.warning(
261 msg=(
262 "The winrm connection plugin should have the shell type of cmd and not powershell. "
263 "This may result in an error when attempting to run more complex commands."
264 ),
265 help_text="Unset ansible_shell_type or set to cmd to use the required cmd shell.",
266 )
267
268 if not C.DEFAULT_DEBUG:
269 logging.getLogger('requests_credssp').setLevel(logging.INFO)
270 logging.getLogger('requests_kerberos').setLevel(logging.INFO)
271 logging.getLogger('urllib3').setLevel(logging.INFO)
272
273 def _build_winrm_kwargs(self) -> None:
274 # this used to be in set_options, as win_reboot needs to be able to
275 # override the conn timeout, we need to be able to build the args
276 # after setting individual options. This is called by _connect before
277 # starting the WinRM connection
278 self._winrm_host = self.get_option('remote_addr')
279 self._winrm_user = self.get_option('remote_user')
280 self._winrm_pass = self.get_option('remote_password')
281
282 self._winrm_port = self.get_option('port')
283
284 self._winrm_scheme = self.get_option('scheme')
285 # old behaviour, scheme should default to http if not set and the port
286 # is 5985 otherwise https
287 if self._winrm_scheme is None:
288 self._winrm_scheme = 'http' if self._winrm_port == 5985 else 'https'
289
290 self._winrm_path = self.get_option('path')
291 self._kinit_cmd = self.get_option('kerberos_command')
292 self._winrm_transport = self.get_option('transport')
293 self._winrm_connection_timeout = self.get_option('connection_timeout')
294
295 if hasattr(winrm, 'FEATURE_SUPPORTED_AUTHTYPES'):
296 self._winrm_supported_authtypes = set(winrm.FEATURE_SUPPORTED_AUTHTYPES)
297 else:
298 # for legacy versions of pywinrm, use the values we know are supported
299 self._winrm_supported_authtypes = set(['plaintext', 'ssl', 'kerberos'])
300
301 # calculate transport if needed
302 if self._winrm_transport is None or self._winrm_transport[0] is None:
303 # TODO: figure out what we want to do with auto-transport selection in the face of NTLM/Kerb/CredSSP/Cert/Basic
304 if self._winrm_user and '@' in self._winrm_user:
305 # A UPN must be a domain account and we always default to Kerberos for this.
306 self._winrm_transport = ['kerberos']
307 else:
308 self._winrm_transport = ['ssl'] if self._winrm_scheme == 'https' else ['plaintext']
309
310 unsupported_transports = set(self._winrm_transport).difference(self._winrm_supported_authtypes)
311
312 if unsupported_transports:
313 raise AnsibleError('The installed version of WinRM does not support transport(s) %s' %
314 to_native(list(unsupported_transports), nonstring='simplerepr'))
315
316 # if kerberos is among our transports and there's a password specified, we're managing the tickets
317 kinit_mode = self.get_option('kerberos_mode')
318 if kinit_mode is None:
319 # HACK: ideally, remove multi-transport stuff
320 self._kerb_managed = "kerberos" in self._winrm_transport and (self._winrm_pass is not None and self._winrm_pass != "")
321 elif kinit_mode == "managed":
322 self._kerb_managed = True
323 elif kinit_mode == "manual":
324 self._kerb_managed = False
325
326 # arg names we're going passing directly
327 internal_kwarg_mask = {'self', 'endpoint', 'transport', 'username', 'password', 'scheme', 'path', 'kinit_mode', 'kinit_cmd'}
328
329 self._winrm_kwargs = dict(username=self._winrm_user, password=self._winrm_pass)
330 argspec = getfullargspec(Protocol.__init__)
331 supported_winrm_args = set(argspec.args)
332 supported_winrm_args.update(internal_kwarg_mask)
333 passed_winrm_args = {v.replace('ansible_winrm_', '') for v in self.get_option('_extras')}
334 unsupported_args = passed_winrm_args.difference(supported_winrm_args)
335
336 # warn for kwargs unsupported by the installed version of pywinrm
337 for arg in unsupported_args:
338 display.warning("ansible_winrm_{0} unsupported by pywinrm (is an up-to-date version of pywinrm installed?)".format(arg))
339
340 # pass through matching extras, excluding the list we want to treat specially
341 for arg in passed_winrm_args.difference(internal_kwarg_mask).intersection(supported_winrm_args):
342 self._winrm_kwargs[arg] = self.get_option('_extras')['ansible_winrm_%s' % arg]
343
344 # Until pykerberos has enough goodies to implement a rudimentary kinit/klist, simplest way is to let each connection
345 # auth itself with a private CCACHE.
346 def _kerb_auth(self, principal: str, password: str) -> None:
347 if password is None:
348 password = ""
349 b_password = to_bytes(password, encoding='utf-8', errors='surrogate_or_strict')
350
351 self._kerb_ccache = tempfile.NamedTemporaryFile()
352 display.vvvvv("creating Kerberos CC at %s" % self._kerb_ccache.name)
353 krb5ccname = "FILE:%s" % self._kerb_ccache.name
354 os.environ["KRB5CCNAME"] = krb5ccname
355 krb5env = dict(PATH=os.environ["PATH"], KRB5CCNAME=krb5ccname)
356
357 # Add any explicit environment vars into the krb5env block
358 kinit_env_vars = self.get_option('kinit_env_vars')
359 for var in kinit_env_vars:
360 if var not in krb5env and var in os.environ:
361 krb5env[var] = os.environ[var]
362
363 # Stores various flags to call with kinit, these could be explicit args set by 'ansible_winrm_kinit_args' OR
364 # '-f' if kerberos delegation is requested (ansible_winrm_kerberos_delegation).
365 kinit_cmdline = [self._kinit_cmd]
366 kinit_args = self.get_option('kinit_args')
367 if kinit_args:
368 kinit_args = [to_text(a) for a in shlex.split(kinit_args) if a.strip()]
369 kinit_cmdline.extend(kinit_args)
370
371 elif boolean(self.get_option('_extras').get('ansible_winrm_kerberos_delegation', False)):
372 kinit_cmdline.append('-f')
373
374 kinit_cmdline.append(principal)
375
376 display.vvvv(f"calling kinit for principal {principal}")
377
378 # It is important to use start_new_session which spawns the process
379 # with setsid() to avoid it inheriting the current tty. On macOS it
380 # will force it to read from stdin rather than the tty.
381 try:
382 p = subprocess.Popen(
383 kinit_cmdline,
384 start_new_session=True,
385 stdin=subprocess.PIPE,
386 stdout=subprocess.PIPE,
387 stderr=subprocess.PIPE,
388 env=krb5env,
389 )
390
391 except OSError as err:
392 err_msg = "Kerberos auth failure when calling kinit cmd " \
393 "'%s': %s" % (self._kinit_cmd, to_native(err))
394 raise AnsibleConnectionFailure(err_msg)
395
396 stdout, stderr = p.communicate(b_password + b'\n')
397 rc = p.returncode
398
399 if rc != 0:
400 # one last attempt at making sure the password does not exist
401 # in the output
402 exp_msg = to_native(stderr.strip())
403 exp_msg = exp_msg.replace(to_native(password), "<redacted>")
404
405 err_msg = f"Kerberos auth failure for principal {principal}: {exp_msg}"
406 raise AnsibleConnectionFailure(err_msg)
407
408 display.vvvvv("kinit succeeded for principal %s" % principal)
409
410 def _winrm_connect(self) -> winrm.Protocol:
411 """
412 Establish a WinRM connection over HTTP/HTTPS.
413 """
414 display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" %
415 (self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host)
416
417 winrm_host = self._winrm_host
418 if HAS_IPADDRESS:
419 display.debug("checking if winrm_host %s is an IPv6 address" % winrm_host)
420 try:
421 ipaddress.IPv6Address(winrm_host)
422 except ipaddress.AddressValueError:
423 pass
424 else:
425 winrm_host = "[%s]" % winrm_host
426
427 netloc = '%s:%d' % (winrm_host, self._winrm_port)
428 endpoint = urlunsplit((self._winrm_scheme, netloc, self._winrm_path, '', ''))
429 errors = []
430 for transport in self._winrm_transport:
431 if transport == 'kerberos':
432 if not HAVE_KERBEROS:
433 kerb_msg = (
434 'WinRM Kerberos authentication requested but the python kerberos library is not installed. '
435 'Please install the pykerberos library, set a different authentication method with ansible_winrm_transport, '
436 'or use a local user account to connect using basic authentication.'
437 )
438 errors.append(kerb_msg)
439 continue
440 if self._kerb_managed:
441 self._kerb_auth(self._winrm_user, self._winrm_pass)
442 display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._winrm_host)
443 try:
444 winrm_kwargs = self._winrm_kwargs.copy()
445 if self._winrm_connection_timeout:
446 winrm_kwargs['operation_timeout_sec'] = self._winrm_connection_timeout
447 winrm_kwargs['read_timeout_sec'] = self._winrm_connection_timeout + 10
448 protocol = Protocol(endpoint, transport=transport, **winrm_kwargs)
449
450 # open the shell from connect so we know we're able to talk to the server
451 if not self.shell_id:
452 self.shell_id = protocol.open_shell(codepage=65001) # UTF-8
453 display.vvvvv('WINRM OPEN SHELL: %s' % self.shell_id, host=self._winrm_host)
454
455 return protocol
456 except Exception as e:
457 err_msg = to_text(e).strip()
458 if re.search(to_text(r'Operation\s+?timed\s+?out'), err_msg, re.I):
459 raise AnsibleError('the connection attempt timed out')
460 m = re.search(to_text(r'Code\s+?(\d{3})'), err_msg)
461 if m:
462 code = int(m.groups()[0])
463 if code == 401:
464 err_msg = 'the specified credentials were rejected by the server'
465 elif code == 411:
466 return protocol
467 errors.append(u'%s: %s' % (transport, err_msg))
468 display.vvvvv(u'WINRM CONNECTION ERROR: %s\n%s' % (err_msg, to_text(traceback.format_exc())), host=self._winrm_host)
469 if errors:
470 raise AnsibleConnectionFailure(', '.join(map(to_native, errors)))
471 else:
472 raise AnsibleError('No transport found for WinRM connection')
473
474 def _winrm_write_stdin(self, command_id: str, stdin_iterator: t.Iterable[tuple[bytes, bool]]) -> None:
475 for (data, is_last) in stdin_iterator:
476 for attempt in range(1, 4):
477 try:
478 self._winrm_send_input(self.protocol, self.shell_id, command_id, data, eof=is_last)
479
480 except WinRMOperationTimeoutError:
481 # A WSMan OperationTimeout can be received for a Send
482 # operation when the server is under severe load. On manual
483 # testing the input is still processed and it's safe to
484 # continue. As the calling method still tries to wait for
485 # the proc to end if this failed it shouldn't hurt to just
486 # treat this as a warning.
487 display.warning(
488 "WSMan OperationTimeout during send input, attempting to continue. "
489 "If this continues to occur, try increasing the connection_timeout "
490 "value for this host."
491 )
492 if not is_last:
493 time.sleep(5)
494
495 except WinRMError as e:
496 # Error 170 == ERROR_BUSY. This could be the result of a
497 # timed out Send from above still being processed on the
498 # server. Add a 5 second delay and try up to 3 times before
499 # fully giving up.
500 # pywinrm does not expose the internal WSMan fault details
501 # through an actual object but embeds it as a repr.
502 if attempt == 3 or "'wsmanfault_code': '170'" not in str(e):
503 raise
504
505 display.warning(f"WSMan send failed on attempt {attempt} as the command is busy, trying to send data again")
506 time.sleep(5)
507 continue
508
509 break
510
511 def _winrm_send_input(self, protocol: winrm.Protocol, shell_id: str, command_id: str, stdin: bytes, eof: bool = False) -> None:
512 rq = {'env:Envelope': protocol._get_soap_header(
513 resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd',
514 action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send',
515 shell_id=shell_id)}
516 stream = rq['env:Envelope'].setdefault('env:Body', {}).setdefault('rsp:Send', {})\
517 .setdefault('rsp:Stream', {})
518 stream['@Name'] = 'stdin'
519 stream['@CommandId'] = command_id
520 stream['#text'] = base64.b64encode(to_bytes(stdin))
521 if eof:
522 stream['@End'] = 'true'
523 protocol.send_message(xmltodict.unparse(rq))
524
525 def _winrm_get_raw_command_output(
526 self,
527 protocol: winrm.Protocol,
528 shell_id: str,
529 command_id: str,
530 ) -> tuple[bytes, bytes, int, bool]:
531 rq = {'env:Envelope': protocol._get_soap_header(
532 resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd',
533 action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive',
534 shell_id=shell_id)}
535
536 stream = rq['env:Envelope'].setdefault('env:Body', {}).setdefault('rsp:Receive', {})\
537 .setdefault('rsp:DesiredStream', {})
538 stream['@CommandId'] = command_id
539 stream['#text'] = 'stdout stderr'
540
541 res = protocol.send_message(xmltodict.unparse(rq))
542 root = ET.fromstring(res)
543 stream_nodes = [
544 node for node in root.findall('.//*')
545 if node.tag.endswith('Stream')]
546 stdout = []
547 stderr = []
548 return_code = -1
549 for stream_node in stream_nodes:
550 if not stream_node.text:
551 continue
552 if stream_node.attrib['Name'] == 'stdout':
553 stdout.append(base64.b64decode(stream_node.text.encode('ascii')))
554 elif stream_node.attrib['Name'] == 'stderr':
555 stderr.append(base64.b64decode(stream_node.text.encode('ascii')))
556
557 command_done = len([
558 node for node in root.findall('.//*')
559 if node.get('State', '').endswith('CommandState/Done')]) == 1
560 if command_done:
561 return_code = int(
562 next(node for node in root.findall('.//*')
563 if node.tag.endswith('ExitCode')).text)
564
565 return b"".join(stdout), b"".join(stderr), return_code, command_done
566
567 def _winrm_get_command_output(
568 self,
569 protocol: winrm.Protocol,
570 shell_id: str,
571 command_id: str,
572 try_once: bool = False,
573 ) -> tuple[bytes, bytes, int]:
574 stdout_buffer, stderr_buffer = [], []
575 command_done = False
576 return_code = -1
577
578 while not command_done:
579 try:
580 stdout, stderr, return_code, command_done = \
581 self._winrm_get_raw_command_output(protocol, shell_id, command_id)
582 stdout_buffer.append(stdout)
583 stderr_buffer.append(stderr)
584
585 # If we were able to get output at least once then we should be
586 # able to get the rest.
587 try_once = False
588 except WinRMOperationTimeoutError:
589 # This is an expected error when waiting for a long-running process,
590 # just silently retry if we haven't been set to do one attempt.
591 if try_once:
592 break
593 continue
594 return b''.join(stdout_buffer), b''.join(stderr_buffer), return_code
595
596 def _winrm_exec(
597 self,
598 command: str,
599 args: t.Iterable[bytes | str] = (),
600 from_exec: bool = False,
601 stdin_iterator: t.Iterable[tuple[bytes, bool]] = None,
602 ) -> tuple[int, bytes, bytes]:
603 if not self.protocol:
604 self.protocol = self._winrm_connect()
605 self._connected = True
606 if from_exec:
607 display.vvvvv("WINRM EXEC %r %r" % (command, args), host=self._winrm_host)
608 else:
609 display.vvvvvv("WINRM EXEC %r %r" % (command, args), host=self._winrm_host)
610 command_id = None
611 try:
612 stdin_push_failed = False
613 command_id = self._winrm_run_command(
614 to_bytes(command),
615 tuple(map(to_bytes, args)),
616 console_mode_stdin=(stdin_iterator is None),
617 )
618
619 try:
620 if stdin_iterator:
621 self._winrm_write_stdin(command_id, stdin_iterator)
622
623 except Exception as ex:
624 display.error_as_warning(f"ERROR DURING WINRM SEND INPUT TO {self._winrm_host}. Attempting to recover.", ex)
625 stdin_push_failed = True
626
627 # Even on a failure above we try at least once to get the output
628 # in case the stdin was actually written and it an normally.
629 b_stdout, b_stderr, rc = self._winrm_get_command_output(
630 self.protocol,
631 self.shell_id,
632 command_id,
633 try_once=stdin_push_failed,
634 )
635 stdout = to_text(b_stdout)
636 stderr = to_text(b_stderr)
637
638 log_stdout = stdout
639 log_stderr = stderr
640 if self._play_context.no_log:
641 log_stdout = log_stderr = '<censored due to no log>'
642
643 if from_exec:
644 display.vvvvv(f'WINRM RESULT <Response code {rc}>', host=self._winrm_host)
645 display.vvvvvv('WINRM RC %d' % rc, host=self._winrm_host)
646 # The raw output is only shown under ANSIBLE_DEBUG. Module output may contain secrets which are not
647 # registered with the secret masker until the result has been parsed by the action plugin, so displaying
648 # the raw output here at a normal verbosity level could leak them.
649 display.debug(f'WINRM STDOUT {log_stdout}')
650 display.debug(f'WINRM STDERR {log_stderr}')
651
652 # This is done after logging so we can still see the raw stderr for
653 # debugging purposes.
654 b_stderr = _clixml.replace_stderr_clixml(b_stderr)
655 stderr = to_text(stderr)
656
657 if stdin_push_failed:
658 # There are cases where the stdin input failed but the WinRM service still processed it. We attempt to
659 # see if stdout contains a valid json return value so we can ignore this error
660 try:
661 filtered_output, dummy = _filter_non_json_lines(stdout)
662 json.loads(filtered_output)
663 except ValueError:
664 # stdout does not contain a return response, stdin input was a fatal error
665 raise AnsibleError(f'winrm send_input failed; \nstdout: {stdout}\nstderr {stderr}')
666
667 return rc, b_stdout, b_stderr
668 except requests.exceptions.Timeout as exc:
669 raise AnsibleConnectionFailure('winrm connection error: %s' % to_native(exc))
670 finally:
671 if command_id:
672 # Due to a bug in how pywinrm works with message encryption we
673 # ignore a 400 error which can occur when a task timeout is
674 # set and the code tries to clean up the command. This happens
675 # as the cleanup msg is sent over a new socket but still uses
676 # the already encrypted payload bound to the other socket
677 # causing the server to reply with 400 Bad Request.
678 try:
679 self.protocol.cleanup_command(self.shell_id, command_id)
680 except WinRMTransportError as e:
681 if e.code != 400:
682 raise
683
684 display.warning("Failed to cleanup running WinRM command, resources might still be in use on the target server")
685
686 def _winrm_run_command(
687 self,
688 command: bytes,
689 args: tuple[bytes, ...],
690 console_mode_stdin: bool = False,
691 ) -> str:
692 """Starts a command with handling when the WSMan quota is exceeded."""
693 try:
694 return self.protocol.run_command(
695 self.shell_id,
696 command,
697 args,
698 console_mode_stdin=console_mode_stdin,
699 )
700 except WSManFaultError as fault_error:
701 if fault_error.wmierror_code != 0x803381A6:
702 raise
703
704 # 0x803381A6 == ERROR_WSMAN_QUOTA_MAX_OPERATIONS
705 # WinRS does not decrement the operation count for commands,
706 # only way to avoid this is to re-create the shell. This is
707 # important for action plugins that might be running multiple
708 # processes in the same connection.
709 display.vvvvv("Shell operation quota exceeded, re-creating shell", host=self._winrm_host)
710 self.close()
711 self._connect()
712 return self.protocol.run_command(
713 self.shell_id,
714 command,
715 args,
716 console_mode_stdin=console_mode_stdin,
717 )
718
719 def _connect(self) -> Connection:
720
721 if not HAS_WINRM:
722 raise AnsibleError("winrm or requests is not installed: %s" % to_native(WINRM_IMPORT_ERR))
723 elif not HAS_XMLTODICT:
724 raise AnsibleError("xmltodict is not installed: %s" % to_native(XMLTODICT_IMPORT_ERR))
725
726 super(Connection, self)._connect()
727 if not self.protocol:
728 self._build_winrm_kwargs() # build the kwargs from the options set
729 self.protocol = self._winrm_connect()
730 self._connected = True
731 return self
732
733 def reset(self) -> None:
734 if not self._connected:
735 return
736 self.protocol = None
737 self.shell_id = None
738 self._connect()
739
740 def _wrapper_payload_stream(self, payload: bytes, buffer_size: int = 200000) -> t.Iterable[tuple[bytes, bool]]:
741 payload_bytes = to_bytes(payload)
742 byte_count = len(payload_bytes)
743 for i in range(0, byte_count, buffer_size):
744 yield payload_bytes[i:i + buffer_size], i + buffer_size >= byte_count
745
746 def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
747 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
748
749 if cmd.find(" -EncodedCommand ") != -1:
750 # Avoid double encoding the script if we can help it. This is a
751 # rudimentary check but seeing -EncodedCommand as an argument most
752 # likely means we are running PowerShell or at least any executable
753 # with an argument rather than a shell command. While WinRM accepts
754 # a command and args separately it is just joined together with a
755 # space on the remote side and we expect cmd to already be safely
756 # escaped.
757 cmd_parts = [cmd]
758 else:
759 # For backwards compatibility winrm always wrapped every command
760 # within PowerShell. This makes raw not very raw but we can't
761 # change that now.
762 cmd_parts = _script.get_pwsh_encoded_cmdline(cmd, override_execution_policy=True)
763
764 # TODO: display something meaningful here
765 display.vvv("EXEC (via pipeline wrapper)")
766
767 stdin_iterator = None
768
769 if in_data:
770 stdin_iterator = self._wrapper_payload_stream(in_data)
771
772 return self._winrm_exec(cmd_parts[0], cmd_parts[1:], from_exec=True, stdin_iterator=stdin_iterator)
773
774 # FUTURE: determine buffer size at runtime via remote winrm config?
775 def _put_file_stdin_iterator(
776 self,
777 initial_stdin: bytes,
778 in_path: str,
779 out_path: str,
780 buffer_size: int = 250000,
781 ) -> t.Iterable[tuple[bytes, bool]]:
782 yield initial_stdin, False
783
784 in_size = os.path.getsize(to_bytes(in_path, errors='surrogate_or_strict'))
785 offset = 0
786 with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file:
787 for out_data in iter((lambda: in_file.read(buffer_size)), b''):
788 offset += len(out_data)
789 self._display.vvvvv('WINRM PUT "%s" to "%s" (offset=%d size=%d)' % (in_path, out_path, offset, len(out_data)), host=self._winrm_host)
790 # yes, we're double-encoding over the wire in this case- we want to ensure that the data shipped to the end PS pipeline is still b64-encoded
791 b64_data = base64.b64encode(out_data) + b'\r\n'
792 # cough up the data, as well as an indicator if this is the last chunk so winrm_send knows to set the End signal
793 yield b64_data, (in_file.tell() == in_size)
794
795 if offset == 0: # empty file, return an empty buffer + eof to close it
796 yield b"", True
797
798 def put_file(self, in_path: str, out_path: str) -> None:
799 super(Connection, self).put_file(in_path, out_path)
800 display.vvv('PUT "%s" TO "%s"' % (in_path, out_path), host=self._winrm_host)
801 if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
802 raise AnsibleFileNotFound('file or module does not exist: "%s"' % to_native(in_path))
803
804 copy_script, copy_script_stdin = _bootstrap_powershell_script('winrm_put_file.ps1', {
805 'Path': out_path,
806 }, has_input=True)
807 cmd_parts = _script.get_pwsh_encoded_cmdline(copy_script, override_execution_policy=True)
808
809 status_code, b_stdout, b_stderr = self._winrm_exec(
810 cmd_parts[0],
811 cmd_parts[1:],
812 stdin_iterator=self._put_file_stdin_iterator(copy_script_stdin, in_path, out_path),
813 )
814 stdout = to_text(b_stdout)
815 stderr = to_text(b_stderr)
816
817 if status_code != 0:
818 raise AnsibleError(stderr)
819
820 try:
821 put_output = json.loads(stdout)
822 except ValueError:
823 # stdout does not contain a valid response
824 raise AnsibleError('winrm put_file failed; \nstdout: %s\nstderr %s' % (stdout, stderr))
825
826 remote_sha1 = put_output.get("sha1")
827 if not remote_sha1:
828 raise AnsibleError("Remote sha1 was not returned")
829
830 local_sha1 = secure_hash(in_path)
831
832 if not remote_sha1 == local_sha1:
833 raise AnsibleError("Remote sha1 hash {0} does not match local hash {1}".format(to_native(remote_sha1), to_native(local_sha1)))
834
835 def fetch_file(self, in_path: str, out_path: str) -> None:
836 super(Connection, self).fetch_file(in_path, out_path)
837 out_path = out_path.replace('\\', '/')
838 # consistent with other connection plugins, we assume the caller has created the target dir
839 display.vvv('FETCH "%s" TO "%s"' % (in_path, out_path), host=self._winrm_host)
840 buffer_size = 2**19 # 0.5MB chunks
841 out_file = None
842 try:
843 offset = 0
844 while True:
845 try:
846 script, in_data = _bootstrap_powershell_script('winrm_fetch_file.ps1', {
847 'Path': in_path,
848 'BufferSize': buffer_size,
849 'Offset': offset,
850 })
851 display.vvvvv('WINRM FETCH "%s" to "%s" (offset=%d)' % (in_path, out_path, offset), host=self._winrm_host)
852 cmd_parts = _script.get_pwsh_encoded_cmdline(script, override_execution_policy=True)
853 status_code, b_stdout, b_stderr = self._winrm_exec(cmd_parts[0], cmd_parts[1:], stdin_iterator=self._wrapper_payload_stream(in_data))
854 stdout = to_text(b_stdout)
855 stderr = to_text(b_stderr)
856
857 if status_code != 0:
858 raise OSError(stderr)
859 if stdout.strip() == '[DIR]':
860 data = None
861 else:
862 data = base64.b64decode(stdout.strip())
863 if data is None:
864 break
865 else:
866 if not out_file:
867 # If out_path is a directory and we're expecting a file, bail out now.
868 if os.path.isdir(to_bytes(out_path, errors='surrogate_or_strict')):
869 break
870 out_file = open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb')
871 out_file.write(data)
872 if len(data) < buffer_size:
873 break
874 offset += len(data)
875 except Exception:
876 raise AnsibleError('failed to transfer file to "%s"' % to_native(out_path))
877 finally:
878 if out_file:
879 out_file.close()
880
881 def close(self) -> None:
882 if self.protocol and self.shell_id:
883 display.vvvvv('WINRM CLOSE SHELL: %s' % self.shell_id, host=self._winrm_host)
884 self.protocol.close_shell(self.shell_id)
885 self.shell_id = None
886 self.protocol = None
887 self._connected = False
888
889 def is_pipelining_enabled(self, wrap_async: bool = False) -> bool:
890 return True