Debian Codegraph @

lib/ansible/plugins/connection/ssh.py

raw
1 # Copyright (c) 2012, Michael DeHaan <[email protected]>
2 # Copyright 2015 Abhijit Menon-Sen <[email protected]>
3 # Copyright 2017 Toshio Kuratomi <[email protected]>
4 # Copyright (c) 2017 Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 name: ssh
11 short_description: connect via SSH client binary
12 description:
13 - This connection plugin allows Ansible to communicate to the target machines through normal SSH command line.
14 - Ansible does not expose a channel to allow communication between the user and the SSH process to accept
15 a password manually to decrypt an SSH key when using this connection plugin (which is the default). The
16 use of C(ssh-agent) is highly recommended.
17 author: ansible (@core)
18 extends_documentation_fragment:
19 - connection_pipelining
20 version_added: historical
21 notes:
22 - This plugin is mostly a wrapper to the C(ssh) CLI utility and the exact behavior of the options depends on this tool.
23 - The documentation provided here is subject to be overridden by configurations of C(ssh) itself.
24 - External configurations of the C(ssh) client CLI can lead to insecure configurations.
25 - Many options default to V(None) here but that only means we do not override the SSH tool's defaults and/or configuration.
26 For example, if you specify the port in this plugin it will override any C(Port) entry in your C(.ssh/config).
27 - The ssh CLI tool uses return code 255 as a 'connection error', this can conflict with commands/tools that
28 also return 255 as an error code and will look like an 'unreachable' condition or 'connection error' to this plugin.
29 options:
30 host:
31 description: Hostname/IP to connect to.
32 default: inventory_hostname
33 type: string
34 vars:
35 - name: inventory_hostname
36 - name: ansible_host
37 - name: ansible_ssh_host
38 host_key_checking:
39 description: Determines if SSH should reject or not a connection after checking host keys.
40 default: True
41 type: boolean
42 ini:
43 - section: defaults
44 key: 'host_key_checking'
45 - section: ssh_connection
46 key: 'host_key_checking'
47 version_added: '2.5'
48 env:
49 - name: ANSIBLE_HOST_KEY_CHECKING
50 - name: ANSIBLE_SSH_HOST_KEY_CHECKING
51 version_added: '2.5'
52 vars:
53 - name: ansible_host_key_checking
54 version_added: '2.5'
55 - name: ansible_ssh_host_key_checking
56 version_added: '2.5'
57 password:
58 description: Authentication password for the O(remote_user). Can be supplied as CLI option.
59 type: string
60 secret: true
61 vars:
62 - name: ansible_password
63 - name: ansible_ssh_pass
64 - name: ansible_ssh_password
65 password_mechanism:
66 description: Mechanism to use for handling ssh password prompt
67 type: string
68 default: ssh_askpass
69 choices:
70 - ssh_askpass
71 - sshpass
72 - disable
73 version_added: '2.19'
74 env:
75 - name: ANSIBLE_SSH_PASSWORD_MECHANISM
76 ini:
77 - {key: password_mechanism, section: ssh_connection}
78 vars:
79 - name: ansible_ssh_password_mechanism
80 sshpass_prompt:
81 description:
82 - Password prompt that C(sshpass)/C(SSH_ASKPASS) should search for.
83 - Supported by sshpass 1.06 and up when O(password_mechanism) set to V(sshpass).
84 - Defaults to C(Enter PIN for) when pkcs11_provider is set.
85 - Defaults to C(assword) when O(password_mechanism) set to V(ssh_askpass).
86 default: ''
87 type: string
88 ini:
89 - section: 'ssh_connection'
90 key: 'sshpass_prompt'
91 env:
92 - name: ANSIBLE_SSHPASS_PROMPT
93 vars:
94 - name: ansible_sshpass_prompt
95 version_added: '2.10'
96 ssh_args:
97 description: Arguments to pass to all SSH CLI tools. The use of C(LocalForward)/C(-L)
98 along with the default C(-C) can lead to an insecure configuration. Ensure
99 these options are not used in combination.
100 default: '-C -o ControlMaster=auto -o ControlPersist=60s'
101 type: string
102 ini:
103 - section: 'ssh_connection'
104 key: 'ssh_args'
105 env:
106 - name: ANSIBLE_SSH_ARGS
107 vars:
108 - name: ansible_ssh_args
109 version_added: '2.7'
110 ssh_common_args:
111 description: Common extra args for all SSH CLI tools.
112 type: string
113 ini:
114 - section: 'ssh_connection'
115 key: 'ssh_common_args'
116 version_added: '2.7'
117 env:
118 - name: ANSIBLE_SSH_COMMON_ARGS
119 version_added: '2.7'
120 vars:
121 - name: ansible_ssh_common_args
122 cli:
123 - name: ssh_common_args
124 default: ''
125 ssh_executable:
126 default: ssh
127 description:
128 - This defines the location of the SSH binary. It defaults to V(ssh) which will use the first SSH binary available in $PATH.
129 - This option is usually not required, it might be useful when access to system SSH is restricted,
130 or when using SSH wrappers to connect to remote hosts.
131 type: string
132 env: [{name: ANSIBLE_SSH_EXECUTABLE}]
133 ini:
134 - {key: ssh_executable, section: ssh_connection}
135 #const: ANSIBLE_SSH_EXECUTABLE
136 version_added: "2.2"
137 vars:
138 - name: ansible_ssh_executable
139 version_added: '2.7'
140 sftp_executable:
141 default: sftp
142 description:
143 - This defines the location of the sftp binary. It defaults to V(sftp) which will use the first binary available in $PATH.
144 type: string
145 env: [{name: ANSIBLE_SFTP_EXECUTABLE}]
146 ini:
147 - {key: sftp_executable, section: ssh_connection}
148 version_added: "2.6"
149 vars:
150 - name: ansible_sftp_executable
151 version_added: '2.7'
152 scp_executable:
153 default: scp
154 description:
155 - This defines the location of the scp binary. It defaults to V(scp) which will use the first binary available in $PATH.
156 type: string
157 env: [{name: ANSIBLE_SCP_EXECUTABLE}]
158 ini:
159 - {key: scp_executable, section: ssh_connection}
160 version_added: "2.6"
161 vars:
162 - name: ansible_scp_executable
163 version_added: '2.7'
164 scp_extra_args:
165 description: Extra exclusive to the C(scp) CLI
166 type: string
167 vars:
168 - name: ansible_scp_extra_args
169 env:
170 - name: ANSIBLE_SCP_EXTRA_ARGS
171 version_added: '2.7'
172 ini:
173 - key: scp_extra_args
174 section: ssh_connection
175 version_added: '2.7'
176 cli:
177 - name: scp_extra_args
178 default: ''
179 sftp_extra_args:
180 description: Extra exclusive to the C(sftp) CLI
181 type: string
182 vars:
183 - name: ansible_sftp_extra_args
184 env:
185 - name: ANSIBLE_SFTP_EXTRA_ARGS
186 version_added: '2.7'
187 ini:
188 - key: sftp_extra_args
189 section: ssh_connection
190 version_added: '2.7'
191 cli:
192 - name: sftp_extra_args
193 default: ''
194 ssh_extra_args:
195 description: Extra exclusive to the SSH CLI.
196 type: string
197 vars:
198 - name: ansible_ssh_extra_args
199 env:
200 - name: ANSIBLE_SSH_EXTRA_ARGS
201 version_added: '2.7'
202 ini:
203 - key: ssh_extra_args
204 section: ssh_connection
205 version_added: '2.7'
206 cli:
207 - name: ssh_extra_args
208 default: ''
209 reconnection_retries:
210 description:
211 - Number of attempts to connect.
212 - Ansible retries connections only if it gets an SSH error with a return code of 255.
213 - Any errors with return codes other than 255 indicate an issue with program execution.
214 default: 0
215 type: integer
216 env:
217 - name: ANSIBLE_SSH_RETRIES
218 ini:
219 - section: connection
220 key: retries
221 - section: ssh_connection
222 key: retries
223 vars:
224 - name: ansible_ssh_retries
225 version_added: '2.7'
226 port:
227 description: Remote port to connect to.
228 type: int
229 ini:
230 - section: defaults
231 key: remote_port
232 env:
233 - name: ANSIBLE_REMOTE_PORT
234 vars:
235 - name: ansible_port
236 - name: ansible_ssh_port
237 keyword:
238 - name: port
239 remote_user:
240 description:
241 - User name with which to login to the remote server, normally set by the remote_user keyword.
242 - If no user is supplied, Ansible will let the SSH client binary choose the user as it normally.
243 type: string
244 ini:
245 - section: defaults
246 key: remote_user
247 env:
248 - name: ANSIBLE_REMOTE_USER
249 vars:
250 - name: ansible_user
251 - name: ansible_ssh_user
252 cli:
253 - name: user
254 keyword:
255 - name: remote_user
256 pipelining:
257 env:
258 - name: ANSIBLE_PIPELINING
259 - name: ANSIBLE_SSH_PIPELINING
260 ini:
261 - section: defaults
262 key: pipelining
263 - section: connection
264 key: pipelining
265 - section: ssh_connection
266 key: pipelining
267 vars:
268 - name: ansible_pipelining
269 - name: ansible_ssh_pipelining
270 private_key_file:
271 description:
272 - Path to private key file to use for authentication.
273 type: string
274 ini:
275 - section: defaults
276 key: private_key_file
277 env:
278 - name: ANSIBLE_PRIVATE_KEY_FILE
279 vars:
280 - name: ansible_private_key_file
281 - name: ansible_ssh_private_key_file
282 cli:
283 - name: private_key_file
284 option: '--private-key'
285 private_key:
286 description:
287 - Private key contents in PEM format. Requires the C(SSH_AGENT) configuration to be enabled.
288 type: string
289 secret: true
290 env:
291 - name: ANSIBLE_PRIVATE_KEY
292 vars:
293 - name: ansible_private_key
294 - name: ansible_ssh_private_key
295 version_added: '2.19'
296 private_key_passphrase:
297 description:
298 - Private key passphrase, dependent on O(private_key).
299 - This does NOT have any effect when used with O(private_key_file).
300 type: string
301 secret: true
302 env:
303 - name: ANSIBLE_PRIVATE_KEY_PASSPHRASE
304 vars:
305 - name: ansible_private_key_passphrase
306 - name: ansible_ssh_private_key_passphrase
307 version_added: '2.19'
308 control_path:
309 description:
310 - This is the location to save SSH's ControlPath sockets, it uses SSH's variable substitution.
311 - Since 2.3, if null (default), ansible will generate a unique hash. Use ``%(directory)s`` to indicate where to use the control dir path setting.
312 - Before 2.3 it defaulted to ``control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r``.
313 - Be aware that this setting is ignored if C(-o ControlPath) is set in ssh args.
314 type: string
315 env:
316 - name: ANSIBLE_SSH_CONTROL_PATH
317 ini:
318 - key: control_path
319 section: ssh_connection
320 vars:
321 - name: ansible_control_path
322 version_added: '2.7'
323 control_path_dir:
324 default: ~/.ansible/cp
325 description:
326 - This sets the directory to use for ssh control path if the control path setting is null.
327 - Also, provides the ``%(directory)s`` variable for the control path setting.
328 type: string
329 env:
330 - name: ANSIBLE_SSH_CONTROL_PATH_DIR
331 ini:
332 - section: ssh_connection
333 key: control_path_dir
334 vars:
335 - name: ansible_control_path_dir
336 version_added: '2.7'
337 sftp_batch_mode:
338 default: true
339 description:
340 - When set to C(True), sftp will be run in batch mode, allowing detection of transfer errors.
341 - When set to C(False), sftp will not be run in batch mode, preventing detection of transfer errors.
342 env: [{name: ANSIBLE_SFTP_BATCH_MODE}]
343 ini:
344 - {key: sftp_batch_mode, section: ssh_connection}
345 type: bool
346 vars:
347 - name: ansible_sftp_batch_mode
348 version_added: '2.7'
349 ssh_transfer_method:
350 description: Preferred method to use when transferring files over ssh
351 choices:
352 sftp: This is the most reliable way to copy things with SSH.
353 scp: Deprecated in OpenSSH. For OpenSSH >=9.0 you must add an additional option to enable scp C(scp_extra_args="-O").
354 piped: Creates an SSH pipe with C(dd) on either side to copy the data.
355 smart: Tries each method in order (sftp > scp > piped), until one succeeds or they all fail.
356 default: smart
357 type: string
358 env: [{name: ANSIBLE_SSH_TRANSFER_METHOD}]
359 ini:
360 - {key: transfer_method, section: ssh_connection}
361 vars:
362 - name: ansible_ssh_transfer_method
363 version_added: '2.12'
364 use_tty:
365 version_added: '2.5'
366 default: true
367 description: add -tt to ssh commands to force tty allocation.
368 env: [{name: ANSIBLE_SSH_USETTY}]
369 ini:
370 - {key: usetty, section: ssh_connection}
371 type: bool
372 vars:
373 - name: ansible_ssh_use_tty
374 version_added: '2.7'
375 timeout:
376 default: 10
377 description:
378 - This is the default amount of time we will wait while establishing an SSH connection.
379 - It also controls how long we can wait to access reading the connection once established (select on the socket).
380 env:
381 - name: ANSIBLE_TIMEOUT
382 - name: ANSIBLE_SSH_TIMEOUT
383 version_added: '2.11'
384 ini:
385 - key: timeout
386 section: defaults
387 - key: timeout
388 section: ssh_connection
389 version_added: '2.11'
390 vars:
391 - name: ansible_ssh_timeout
392 version_added: '2.11'
393 cli:
394 - name: timeout
395 type: integer
396 pkcs11_provider:
397 version_added: '2.12'
398 default: ""
399 type: string
400 description:
401 - "PKCS11 SmartCard provider such as opensc, example: /usr/local/lib/opensc-pkcs11.so"
402 env: [{name: ANSIBLE_PKCS11_PROVIDER}]
403 ini:
404 - {key: pkcs11_provider, section: ssh_connection}
405 vars:
406 - name: ansible_ssh_pkcs11_provider
407 verbosity:
408 version_added: '2.19'
409 default: 0
410 type: int
411 description:
412 - Requested verbosity level for the SSH CLI.
413 env: [{name: ANSIBLE_SSH_VERBOSITY}]
414 ini:
415 - {key: verbosity, section: ssh_connection}
416 vars:
417 - name: ansible_ssh_verbosity
418 """
419
420 import collections.abc as c
421 import argparse
422 import errno
423 import contextlib
424 import fcntl
425 import hashlib
426 import io
427 import json
428 import os
429 import pathlib
430 import pty
431 import re
432 import selectors
433 import shlex
434 import shutil
435 import subprocess
436 import sys
437 import tempfile
438 import time
439 import typing as t
440 from functools import wraps
441 from multiprocessing.shared_memory import SharedMemory
442
443 from ansible import constants as C
444 from ansible._internal._powershell import _clixml
445 from ansible.errors import (
446 AnsibleAuthenticationFailure,
447 AnsibleConnectionFailure,
448 AnsibleError,
449 AnsibleFileNotFound,
450 )
451 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
452 from ansible.plugins.connection import ConnectionBase, BUFSIZE
453 from ansible.utils.display import Display
454 from ansible.utils.path import unfrackpath, makedirs_safe
455 from ansible._internal._ssh import _ssh_agent
456
457 try:
458 from cryptography.hazmat.primitives import serialization
459 except ImportError:
460 HAS_CRYPTOGRAPHY = False
461 else:
462 HAS_CRYPTOGRAPHY = True
463
464
465 display = Display()
466
467 # error messages that indicate 255 return code is not from ssh itself.
468 b_NOT_SSH_ERRORS = (b'Traceback (most recent call last):', # Python-2.6 when there's an exception
469 # while invoking a script via -m
470 b'PHP Parse error:', # Php always returns with error
471 b'chmod: invalid mode', # chmod, but really only on AIX
472 b'chmod: A flag or octal number is not correct.', # chmod, other AIX
473 )
474
475 SSHPASS_AVAILABLE = None
476 SSH_DEBUG = re.compile(r'^debug\d+: .*')
477
478 PKCS11_DEFAULT_PROMPT = 'Enter PIN for '
479 SSH_ASKPASS_DEFAULT_PROMPT = 'assword'
480
481
482 class AnsibleControlPersistBrokenPipeError(AnsibleError):
483 """ ControlPersist broken pipe """
484 pass
485
486
487 def _handle_error(
488 remaining_retries: int,
489 command: bytes,
490 return_tuple: tuple[int, bytes, bytes],
491 no_log: bool,
492 host: str,
493 display: Display = display,
494 ) -> None:
495
496 # sshpass errors
497 if command == b'sshpass':
498 # Error 5 is invalid/incorrect password. Raise an exception to prevent retries from locking the account.
499 if return_tuple[0] == 5:
500 msg = 'Invalid/incorrect username/password. Skipping remaining {0} retries to prevent account lockout:'.format(remaining_retries)
501 if remaining_retries <= 0:
502 msg = 'Invalid/incorrect password:'
503 if no_log:
504 msg = '{0} <error censored due to no log>'.format(msg)
505 else:
506 msg = '{0} {1}'.format(msg, to_native(return_tuple[2]).rstrip())
507 raise AnsibleAuthenticationFailure(msg)
508
509 # sshpass returns codes are 1-6. We handle 5 previously, so this catches other scenarios.
510 # No exception is raised, so the connection is retried - except when attempting to use
511 # sshpass_prompt with an sshpass that won't let us pass -P, in which case we fail loudly.
512 elif return_tuple[0] in [1, 2, 3, 4, 6]:
513 msg = 'sshpass error:'
514 if no_log:
515 msg = '{0} <error censored due to no log>'.format(msg)
516 else:
517 details = to_native(return_tuple[2]).rstrip()
518 if "sshpass: invalid option -- 'P'" in details:
519 details = 'Installed sshpass version does not support customized password prompts. ' \
520 'Upgrade sshpass to use sshpass_prompt, or otherwise switch to ssh keys.'
521 raise AnsibleError('{0} {1}'.format(msg, details))
522 msg = '{0} {1}'.format(msg, details)
523 raise AnsibleConnectionFailure(msg)
524
525 if return_tuple[0] == 255:
526 SSH_ERROR = True
527 for signature in b_NOT_SSH_ERRORS:
528 # 1 == stout, 2 == stderr
529 if signature in return_tuple[1] or signature in return_tuple[2]:
530 SSH_ERROR = False
531 break
532
533 if SSH_ERROR:
534 msg = "Failed to connect to the host via ssh:"
535 if no_log:
536 msg = '{0} <error censored due to no log>'.format(msg)
537 else:
538 msg = '{0} {1}'.format(msg, to_native(return_tuple[2]).rstrip())
539 raise AnsibleConnectionFailure(msg)
540
541 # For other errors, no exception is raised so the connection is retried and we only log the messages
542 if 1 <= return_tuple[0] <= 254:
543 msg = u"Failed to connect to the host via ssh:"
544 if no_log:
545 msg = u'{0} <error censored due to no log>'.format(msg)
546 else:
547 msg = u'{0} {1}'.format(msg, to_text(return_tuple[2]).rstrip())
548 display.vvv(msg, host=host)
549
550
551 def _ssh_retry[**P](
552 func: c.Callable[t.Concatenate[Connection, P], tuple[int, bytes, bytes]],
553 ) -> c.Callable[t.Concatenate[Connection, P], tuple[int, bytes, bytes]]:
554 """
555 Decorator to retry ssh/scp/sftp in the case of a connection failure
556
557 Will retry if:
558 * an exception is caught
559 * ssh returns 255
560 Will not retry if
561 * sshpass returns 5 (invalid password, to prevent account lockouts)
562 * remaining_tries is < 2
563 * retries limit reached
564 """
565 @wraps(func)
566 def wrapped(self: Connection, *args: P.args, **kwargs: P.kwargs) -> tuple[int, bytes, bytes]:
567 remaining_tries = int(self.get_option('reconnection_retries')) + 1
568 cmd_summary = u"%s..." % to_text(args[0])
569 for attempt in range(remaining_tries):
570 try:
571 try:
572 return_tuple = func(self, *args, **kwargs)
573 display.vvv(u'rc=%s' % return_tuple[0], host=self.host)
574 # The raw output is only shown under ANSIBLE_DEBUG. Module output may contain secrets which are
575 # not registered with the secret masker until the result has been parsed by the action plugin,
576 # so displaying the raw output here at a normal verbosity level could leak them.
577 # TODO: this should come from task
578 if self._play_context.no_log:
579 display.debug(u'stdout and stderr censored due to no log')
580 else:
581 display.debug(u'stdout and stderr: %s' % str(return_tuple[1:]))
582 # 0 = success
583 # 1-254 = remote command return code
584 # 255 could be a failure from the ssh command itself
585 except (AnsibleControlPersistBrokenPipeError):
586 # Retry one more time because of the ControlPersist broken pipe (see #16731)
587 display.vvv(u"RETRYING BECAUSE OF CONTROLPERSIST BROKEN PIPE")
588 return_tuple = func(self, *args, **kwargs)
589
590 remaining_retries = remaining_tries - attempt - 1
591 cmd = t.cast(list[bytes], args[0])
592 _handle_error(remaining_retries, cmd[0], return_tuple, self._play_context.no_log, self.host)
593
594 break
595
596 # 5 = Invalid/incorrect password from sshpass
597 except AnsibleAuthenticationFailure:
598 # Raising this exception, which is subclassed from AnsibleConnectionFailure, prevents further retries
599 raise
600
601 except (AnsibleConnectionFailure, Exception) as e:
602
603 if attempt == remaining_tries - 1:
604 raise
605 else:
606 pause = 2 ** attempt - 1
607 if pause > 30:
608 pause = 30
609
610 if isinstance(e, AnsibleConnectionFailure):
611 msg = u"ssh_retry: attempt: %d, ssh return code is 255. cmd (%s), pausing for %d seconds" % (attempt + 1, cmd_summary, pause)
612 else:
613 msg = (u"ssh_retry: attempt: %d, caught exception(%s) from cmd (%s), "
614 u"pausing for %d seconds" % (attempt + 1, to_text(e), cmd_summary, pause))
615
616 display.vv(msg, host=self.host)
617
618 time.sleep(pause)
619 continue
620
621 return return_tuple
622 return wrapped
623
624
625 def _clean_resources(func):
626 @wraps(func)
627 def inner(self, *args, **kwargs):
628 try:
629 ret = func(self, *args, **kwargs)
630 finally:
631 for fd in self.sshpass_pipe or ():
632 try:
633 os.close(fd)
634 except OSError:
635 pass
636 if self.shm:
637 self.shm.close()
638 with contextlib.suppress(FileNotFoundError):
639 self.shm.unlink()
640 return ret
641 return inner
642
643
644 class Connection(ConnectionBase):
645 """ ssh based connections """
646
647 transport = 'ssh'
648 has_pipelining = True
649
650 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
651 super(Connection, self).__init__(*args, **kwargs)
652
653 # TODO: all should come from get_option(), but not might be set at this point yet
654 self.host = self._play_context.remote_addr
655 self.port = self._play_context.port
656 self.user = self._play_context.remote_user
657 self.control_path: str | None = None
658 self.control_path_dir: str | None = None
659 self.shm: SharedMemory | None = None
660 self.sshpass_pipe: tuple[int, int] | None = None
661
662 # Windows operates differently from a POSIX connection/shell plugin,
663 # we need to set various properties to ensure SSH on Windows continues
664 # to work
665 if getattr(self._shell, "_IS_WINDOWS", False):
666 self.module_implementation_preferences = ('.ps1', '.exe', '')
667 self.allow_executable = False
668
669 # parser to discover 'passed options', used later on for pipelining resolution
670 # exit_on_error=False so malformed args raise ArgumentError instead of calling sys.exit()
671 self._tty_parser = argparse.ArgumentParser(exit_on_error=False)
672 self._tty_parser.add_argument('-t', action='count')
673 self._tty_parser.add_argument('-o', action='append')
674
675 self._populated_agent: pathlib.Path | None = None
676
677 # The connection is created by running ssh/scp/sftp from the exec_command,
678 # put_file, and fetch_file methods, so we don't need to do any connection
679 # management here.
680
681 def _connect(self) -> Connection:
682 return self
683
684 @staticmethod
685 def _create_control_path(
686 host: str | None,
687 port: int | None,
688 user: str | None,
689 connection: ConnectionBase | None = None,
690 pid: int | None = None,
691 ) -> str:
692 """Make a hash for the controlpath based on con attributes"""
693 pstring = '%s-%s-%s' % (host, port, user)
694 if connection:
695 pstring += '-%s' % connection
696 if pid:
697 pstring += '-%s' % to_text(pid)
698 m = hashlib.sha1()
699 m.update(to_bytes(pstring))
700 digest = m.hexdigest()
701 cpath = '%(directory)s/' + digest[:10]
702 return cpath
703
704 @staticmethod
705 def _sshpass_available() -> bool:
706 global SSHPASS_AVAILABLE
707
708 # We test once if sshpass is available, and remember the result.
709
710 if SSHPASS_AVAILABLE is None:
711 SSHPASS_AVAILABLE = shutil.which('sshpass') is not None
712
713 return SSHPASS_AVAILABLE
714
715 @staticmethod
716 def _persistence_controls(b_command: list[bytes]) -> tuple[bool, bool]:
717 """
718 Takes a command array and scans it for ControlPersist and ControlPath
719 settings and returns two booleans indicating whether either was found.
720 This could be smarter, e.g. returning false if ControlPersist is 'no',
721 but for now we do it simple way.
722 """
723
724 controlpersist = False
725 controlpath = False
726
727 for b_arg in (a.lower() for a in b_command):
728 if b'controlpersist' in b_arg:
729 controlpersist = True
730 elif b'controlpath' in b_arg:
731 controlpath = True
732
733 return controlpersist, controlpath
734
735 def _add_args(self, b_command: list[bytes], b_args: t.Iterable[bytes], explanation: str) -> None:
736 """
737 Adds arguments to the ssh command and displays a caller-supplied explanation of why.
738
739 :arg b_command: A list containing the command to add the new arguments to.
740 This list will be modified by this method.
741 :arg b_args: An iterable of new arguments to add. This iterable is used
742 more than once so it must be persistent (ie: a list is okay but a
743 StringIO would not)
744 :arg explanation: A text string containing explaining why the arguments
745 were added. It will be displayed with a high enough verbosity.
746 .. note:: This function does its work via side-effect. The b_command list has the new arguments appended.
747 """
748 display.vvvvv(u'SSH: %s: (%s)' % (explanation, ')('.join(to_text(a) for a in b_args)), host=self.host)
749 b_command += b_args
750
751 def _populate_agent(self) -> pathlib.Path:
752 """Adds configured private key identity to the SSH agent. Returns a path to a file containing the public key."""
753 if self._populated_agent:
754 return self._populated_agent
755
756 if (auth_sock := C.config.get_config_value('SSH_AGENT')) == 'none':
757 raise AnsibleError('Cannot utilize private_key with SSH_AGENT disabled')
758
759 key_data = self.get_option('private_key')
760 passphrase = self.get_option('private_key_passphrase')
761
762 private_key, public_key, fingerprint = _ssh_agent.key_data_into_crypto_objects(
763 to_bytes(key_data),
764 to_bytes(passphrase) if passphrase else None,
765 )
766
767 with _ssh_agent.SshAgentClient(auth_sock) as client:
768 if public_key not in client:
769 display.vvv(f'SSH: SSH_AGENT adding {fingerprint} to agent', host=self.host)
770 client.add(
771 private_key,
772 f'[added by ansible: PID={os.getpid()}, UID={os.getuid()}, EUID={os.geteuid()}, TIME={time.time()}]',
773 C.config.get_config_value('SSH_AGENT_KEY_LIFETIME'),
774 )
775 else:
776 display.vvv(f'SSH: SSH_AGENT {fingerprint} exists in agent', host=self.host)
777 # Write the public key to disk, to be provided as IdentityFile.
778 # This allows ssh to pick an explicit key in the agent to use,
779 # preventing ssh from attempting all keys in the agent.
780 pubkey_path = self._populated_agent = pathlib.Path(C.DEFAULT_LOCAL_TMP).joinpath(
781 fingerprint.replace('/', '-') + '.pub'
782 )
783 if os.path.exists(pubkey_path):
784 return pubkey_path
785
786 with tempfile.NamedTemporaryFile(dir=C.DEFAULT_LOCAL_TMP, delete=False) as f:
787 f.write(public_key.public_bytes(
788 encoding=serialization.Encoding.OpenSSH,
789 format=serialization.PublicFormat.OpenSSH
790 ))
791 # move atomically to prevent race conditions, silently succeeds if the target exists
792 os.rename(f.name, pubkey_path)
793 os.chmod(pubkey_path, mode=0o400)
794
795 return self._populated_agent
796
797 def _build_command(self, binary: str, subsystem: str, *other_args: bytes | str) -> list[bytes]:
798 """
799 Takes an executable (ssh, scp, sftp or wrapper) and optional extra arguments and returns the remote command
800 wrapped in local ssh shell commands and ready for execution.
801
802 :arg binary: actual executable to use to execute command.
803 :arg subsystem: type of executable provided, ssh/sftp/scp, needed because wrappers for ssh might have diff names.
804 :arg other_args: dict of, value pairs passed as arguments to the ssh binary
805 """
806 conn_password = self.get_option('password') or self._play_context.password
807 pkcs11_provider = self.get_option("pkcs11_provider")
808 password_mechanism = self.get_option('password_mechanism')
809
810 #
811 # First, the command to invoke
812 #
813
814 b_command = [to_bytes(binary, errors='surrogate_or_strict')]
815
816 #
817 # Next, additional arguments based on the configuration.
818 #
819
820 # pkcs11 mode allows the use of Smartcards or Yubikey devices
821 if conn_password and pkcs11_provider:
822 self._add_args(b_command,
823 (b"-o", b"KbdInteractiveAuthentication=no",
824 b"-o", b"PreferredAuthentications=publickey",
825 b"-o", b"PasswordAuthentication=no",
826 b'-o', to_bytes(u'PKCS11Provider=%s' % pkcs11_provider)),
827 u'Enable pkcs11')
828
829 # sftp batch mode allows us to correctly catch failed transfers, but can
830 # be disabled if the client side doesn't support the option. However,
831 # sftp batch mode does not prompt for passwords so it must be disabled
832 # if not using controlpersist and using password auth
833 b_args: t.Iterable[bytes]
834 if subsystem == 'sftp' and self.get_option('sftp_batch_mode'):
835 if conn_password:
836 b_args = [b'-o', b'BatchMode=no']
837 self._add_args(b_command, b_args, u'disable batch mode for password auth')
838 b_command += [b'-b', b'-']
839
840 if (verbosity := self.get_option('verbosity')) > 0:
841 b_command.append(b'-' + (b'v' * verbosity))
842
843 # Next, we add ssh_args
844 ssh_args = self.get_option('ssh_args')
845 if ssh_args:
846 b_args = [to_bytes(a, errors='surrogate_or_strict') for a in
847 self._split_ssh_args(ssh_args)]
848 self._add_args(b_command, b_args, u"ansible.cfg set ssh_args")
849
850 # Now we add various arguments that have their own specific settings defined in docs above.
851 if self.get_option('host_key_checking') is False:
852 b_args = (b"-o", b"StrictHostKeyChecking=no")
853 self._add_args(b_command, b_args, u"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled")
854
855 self.port = self.get_option('port')
856 if self.port is not None:
857 b_args = (b"-o", b"Port=" + to_bytes(self.port, nonstring='simplerepr', errors='surrogate_or_strict'))
858 self._add_args(b_command, b_args, u"ANSIBLE_REMOTE_PORT/remote_port/ansible_port set")
859
860 if self.get_option('private_key'):
861 try:
862 key = self._populate_agent()
863 except Exception as e:
864 raise AnsibleAuthenticationFailure('Failed to add configured private key into ssh-agent.') from e
865 b_args = (b'-o', b'IdentitiesOnly=yes', b'-o', to_bytes(f'IdentityFile="{key}"', errors='surrogate_or_strict'))
866 self._add_args(b_command, b_args, "ANSIBLE_PRIVATE_KEY/private_key set")
867 elif key := self.get_option('private_key_file'):
868 b_args = (b"-o", b'IdentityFile="' + to_bytes(os.path.expanduser(key), errors='surrogate_or_strict') + b'"')
869 self._add_args(b_command, b_args, u"ANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set")
870
871 if not conn_password:
872 self._add_args(
873 b_command, (
874 b"-o", b"KbdInteractiveAuthentication=no",
875 b"-o", b"PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey",
876 b"-o", b"PasswordAuthentication=no"
877 ),
878 u"ansible_password/ansible_ssh_password not set"
879 )
880
881 self.user = self.get_option('remote_user')
882 if self.user:
883 self._add_args(
884 b_command,
885 (b"-o", b'User="%s"' % to_bytes(self.user, errors='surrogate_or_strict')),
886 u"ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u set"
887 )
888
889 timeout = self.get_option('timeout')
890 self._add_args(
891 b_command,
892 (b"-o", b"ConnectTimeout=" + to_bytes(timeout, errors='surrogate_or_strict', nonstring='simplerepr')),
893 u"ANSIBLE_TIMEOUT/timeout set"
894 )
895
896 # Add in any common or binary-specific arguments from the PlayContext
897 # (i.e. inventory or task settings or overrides on the command line).
898
899 for opt in (u'ssh_common_args', u'{0}_extra_args'.format(subsystem)):
900 attr = self.get_option(opt)
901 if attr is not None:
902 b_args = [to_bytes(a, errors='surrogate_or_strict') for a in self._split_ssh_args(attr)]
903 self._add_args(b_command, b_args, u"Set %s" % opt)
904
905 # Check if ControlPersist is enabled and add a ControlPath if one hasn't
906 # already been set.
907
908 controlpersist, controlpath = self._persistence_controls(b_command)
909
910 if controlpersist:
911 self._persistent = True
912
913 if not controlpath:
914 self.control_path_dir = self.get_option('control_path_dir')
915 cpdir = unfrackpath(self.control_path_dir)
916 b_cpdir = to_bytes(cpdir, errors='surrogate_or_strict')
917
918 # The directory must exist and be writable.
919 makedirs_safe(b_cpdir, 0o700)
920 if not os.access(b_cpdir, os.W_OK):
921 raise AnsibleError("Cannot write to ControlPath %s" % to_native(cpdir))
922
923 self.control_path = self.get_option('control_path')
924 if not self.control_path:
925 self.control_path = self._create_control_path(
926 self.host,
927 self.port,
928 self.user
929 )
930 b_args = (b"-o", b'ControlPath="%s"' % to_bytes(self.control_path % dict(directory=cpdir), errors='surrogate_or_strict'))
931 self._add_args(b_command, b_args, u"found only ControlPersist; added ControlPath")
932
933 if password_mechanism == "ssh_askpass":
934 self._add_args(
935 b_command,
936 (b"-o", b"NumberOfPasswordPrompts=1"),
937 "Restrict number of password prompts in case incorrect password is provided.",
938 )
939
940 # Finally, we add any caller-supplied extras.
941 if other_args:
942 b_command += [to_bytes(a) for a in other_args]
943
944 return b_command
945
946 def _send_initial_data(self, fh: io.IOBase, in_data: bytes, ssh_process: subprocess.Popen) -> None:
947 """
948 Writes initial data to the stdin filehandle of the subprocess and closes
949 it. (The handle must be closed; otherwise, for example, "sftp -b -" will
950 just hang forever waiting for more commands.)
951 """
952
953 display.debug(u'Sending initial data')
954
955 try:
956 fh.write(to_bytes(in_data))
957 fh.close()
958 except OSError as ex:
959 # The ssh connection may have already terminated at this point, with a more useful error
960 # Only raise AnsibleConnectionFailure if the ssh process is still alive
961 time.sleep(0.001)
962 ssh_process.poll()
963 if getattr(ssh_process, 'returncode', None) is None:
964 raise AnsibleConnectionFailure(f'Data could not be sent to remote host {self.host!r}. Make sure this host can be reached over SSH.') from ex
965
966 display.debug(u'Sent initial data (%d bytes)' % len(in_data))
967
968 # Used by _run() to kill processes on failures
969 @staticmethod
970 def _terminate_process(p: subprocess.Popen) -> None:
971 """ Terminate a process, ignoring errors """
972 try:
973 p.terminate()
974 except OSError:
975 pass
976
977 # This is separate from _run() because we need to do the same thing for stdout
978 # and stderr.
979 def _examine_output(self, source: str, state: str, b_chunk: bytes, sudoable: bool) -> tuple[bytes, bytes]:
980 """
981 Takes a string, extracts complete lines from it, tests to see if they
982 are a prompt, error message, etc., and sets appropriate flags in self.
983 Prompt and success lines are removed.
984
985 Returns the processed (i.e. possibly-edited) output and the unprocessed
986 remainder (to be processed with the next chunk) as strings.
987 """
988
989 output = []
990 for b_line in b_chunk.splitlines(True):
991 display_line = to_text(b_line).rstrip('\r\n')
992 suppress_output = False
993
994 # display.debug("Examining line (source=%s, state=%s): '%s'" % (source, state, display_line))
995 if SSH_DEBUG.match(display_line):
996 # skip lines from ssh debug output to avoid false matches
997 pass
998 elif self.become.expect_prompt() and self.become.check_password_prompt(b_line):
999 display.debug(u"become_prompt: (source=%s, state=%s): '%s'" % (source, state, display_line))
1000 self._flags['become_prompt'] = True
1001 suppress_output = True
1002 elif self.become.success and self.become.check_success(b_line):
1003 display.debug(u"become_success: (source=%s, state=%s): '%s'" % (source, state, display_line))
1004 self._flags['become_success'] = True
1005 suppress_output = True
1006 elif sudoable and self.become.check_incorrect_password(b_line):
1007 display.debug(u"become_error: (source=%s, state=%s): '%s'" % (source, state, display_line))
1008 self._flags['become_error'] = True
1009 elif sudoable and self.become.check_missing_password(b_line):
1010 display.debug(u"become_nopasswd_error: (source=%s, state=%s): '%s'" % (source, state, display_line))
1011 self._flags['become_nopasswd_error'] = True
1012
1013 if not suppress_output:
1014 output.append(b_line)
1015
1016 # The chunk we read was most likely a series of complete lines, but just
1017 # in case the last line was incomplete (and not a prompt, which we would
1018 # have removed from the output), we retain it to be processed with the
1019 # next chunk.
1020
1021 remainder = b''
1022 if output and not output[-1].endswith(b'\n'):
1023 remainder = output[-1]
1024 output = output[:-1]
1025
1026 return b''.join(output), remainder
1027
1028 def _init_shm(self) -> dict[str, t.Any]:
1029 popen_kwargs: dict[str, t.Any] = {}
1030
1031 if self.get_option('password_mechanism') != 'ssh_askpass':
1032 return popen_kwargs
1033
1034 conn_password = self.get_option('password') or self._play_context.password
1035 pkcs11_provider = self.get_option("pkcs11_provider")
1036 if not conn_password and pkcs11_provider:
1037 raise AnsibleError("to use pkcs11_provider you must specify a password/pin")
1038
1039 if not conn_password:
1040 return popen_kwargs
1041
1042 self.shm = shm = SharedMemory(create=True, size=16384, track=False)
1043
1044 sshpass_prompt = self.get_option('sshpass_prompt')
1045 if not sshpass_prompt and pkcs11_provider:
1046 sshpass_prompt = PKCS11_DEFAULT_PROMPT
1047 elif not sshpass_prompt:
1048 sshpass_prompt = SSH_ASKPASS_DEFAULT_PROMPT
1049
1050 data = json.dumps({
1051 'password': conn_password,
1052 'prompt': sshpass_prompt,
1053 }).encode('utf-8')
1054 shm.buf[:len(data)] = bytearray(data)
1055 shm.close()
1056
1057 env = os.environ.copy()
1058 env['_ANSIBLE_SSH_ASKPASS_SHM'] = str(self.shm.name)
1059 adhoc = pathlib.Path(sys.argv[0]).with_name('ansible')
1060 env['SSH_ASKPASS'] = str(adhoc) if adhoc.is_file() else 'ansible'
1061
1062 # SSH_ASKPASS_REQUIRE was added in openssh 8.4, prior to 8.4 there must be no tty, and DISPLAY must be set
1063 env['SSH_ASKPASS_REQUIRE'] = 'force'
1064 if not env.get('DISPLAY'):
1065 # If the user has DISPLAY set, assume it is there for a reason
1066 env['DISPLAY'] = '-'
1067
1068 popen_kwargs['env'] = env
1069 # start_new_session runs setsid which detaches the tty to support the use of ASKPASS prior to openssh 8.4
1070 popen_kwargs['start_new_session'] = True
1071
1072 return popen_kwargs
1073
1074 def _sshpass_cmd(self) -> list[bytes]:
1075 # If we want to use sshpass for password authentication, we have to set up a pipe to
1076 # write the password to sshpass.
1077 conn_password = self.get_option('password') or self._play_context.password
1078 pkcs11_provider = self.get_option("pkcs11_provider")
1079 if not (self.get_option('password_mechanism') == 'sshpass' and (conn_password or pkcs11_provider)):
1080 return []
1081
1082 if not self._sshpass_available():
1083 raise AnsibleError("to use the password_mechanism=sshpass, you must install the sshpass program")
1084 if not conn_password and pkcs11_provider:
1085 raise AnsibleError("to use pkcs11_provider you must specify a password/pin")
1086
1087 self.sshpass_pipe = os.pipe()
1088 b_command = [b'sshpass', b'-d' + to_bytes(self.sshpass_pipe[0], nonstring='simplerepr', errors='surrogate_or_strict')]
1089
1090 password_prompt = self.get_option('sshpass_prompt')
1091 if not password_prompt and pkcs11_provider:
1092 # Set default password prompt for pkcs11_provider to make it clear it's a PIN
1093 password_prompt = PKCS11_DEFAULT_PROMPT
1094
1095 if password_prompt:
1096 b_command += [b'-P', to_bytes(password_prompt, errors='surrogate_or_strict')]
1097 return b_command
1098
1099 @_clean_resources
1100 def _bare_run(self, cmd: list[bytes], in_data: bytes | None, sudoable: bool = True, checkrc: bool = True) -> tuple[int, bytes, bytes]:
1101 """
1102 Starts the command and communicates with it until it ends.
1103 """
1104
1105 # We don't use _shell.quote as this is run on the controller and independent from the shell plugin chosen
1106 display_cmd = u' '.join(shlex.quote(to_text(c)) for c in cmd)
1107 display.vvv(u'SSH: EXEC {0}'.format(display_cmd), host=self.host)
1108
1109 conn_password = self.get_option('password') or self._play_context.password
1110 password_mechanism = self.get_option('password_mechanism')
1111
1112 # Start the given command. If we don't need to pipeline data, we can try
1113 # to use a pseudo-tty (ssh will have been invoked with -tt). If we are
1114 # pipelining data, or can't create a pty, we fall back to using plain
1115 # old pipes.
1116
1117 p = None
1118
1119 popen_kwargs = self._init_shm()
1120
1121 is_ssh = to_bytes(self.get_option('ssh_executable')) == cmd[0]
1122
1123 if b_ssh_pass_cmd := self._sshpass_cmd():
1124 cmd[:0] = b_ssh_pass_cmd
1125 popen_kwargs['pass_fds'] = self.sshpass_pipe
1126
1127 if not in_data:
1128 try:
1129 # Make sure stdin is a proper pty to avoid tcgetattr errors
1130 master, slave = pty.openpty()
1131 p = subprocess.Popen(cmd, stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **popen_kwargs)
1132 stdin = os.fdopen(master, 'wb', 0)
1133 os.close(slave)
1134 except OSError:
1135 p = None
1136
1137 if not p:
1138 try:
1139 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1140 stderr=subprocess.PIPE, **popen_kwargs)
1141 stdin = p.stdin # type: ignore[assignment] # stdin will be set and not None due to the calls above
1142 except OSError as ex:
1143 raise AnsibleError('Unable to execute ssh command line on a controller.') from ex
1144
1145 if self.sshpass_pipe:
1146 os.close(self.sshpass_pipe[0])
1147 try:
1148 os.write(self.sshpass_pipe[1], to_bytes(conn_password) + b'\n')
1149 except OSError as e:
1150 # Ignore broken pipe errors if the sshpass process has exited.
1151 if e.errno != errno.EPIPE or p.poll() is None:
1152 raise
1153 os.close(self.sshpass_pipe[1])
1154 self.sshpass_pipe = None
1155
1156 #
1157 # SSH state machine
1158 #
1159
1160 # Now we read and accumulate output from the running process until it
1161 # exits. Depending on the circumstances, we may also need to write an
1162 # escalation password and/or pipelined input to the process.
1163
1164 states = [
1165 'awaiting_prompt', 'awaiting_escalation', 'ready_to_send', 'awaiting_exit'
1166 ]
1167
1168 # Are we requesting privilege escalation? Right now, we may be invoked
1169 # to execute sftp/scp with sudoable=True, but we can request escalation
1170 # only when using ssh. Otherwise, we can send initial data straight away.
1171
1172 state = states.index('ready_to_send')
1173 if is_ssh and sudoable:
1174 prompt = getattr(self.become, 'prompt', None)
1175 if prompt:
1176 # We're requesting escalation with a password, so we have to
1177 # wait for a password prompt.
1178 state = states.index('awaiting_prompt')
1179 display.debug(u'Initial state: %s: %s' % (states[state], to_text(prompt)))
1180 elif self.become and self.become.success:
1181 # We're requesting escalation without a password, so we have to
1182 # detect success/failure before sending any initial data.
1183 state = states.index('awaiting_escalation')
1184 display.debug(u'Initial state: %s: %s' % (states[state], to_text(self.become.success)))
1185
1186 # We store accumulated stdout and stderr output from the process here,
1187 # but strip any privilege escalation prompt/confirmation lines first.
1188 # Output is accumulated into tmp_*, complete lines are extracted into
1189 # an array, then checked and removed or copied to stdout or stderr. We
1190 # set any flags based on examining the output in self._flags.
1191
1192 b_stdout = b_stderr = b''
1193 b_tmp_stdout = b_tmp_stderr = b''
1194
1195 self._flags = dict(
1196 become_prompt=False, become_success=False,
1197 become_error=False, become_nopasswd_error=False
1198 )
1199
1200 # select timeout should be longer than the connect timeout, otherwise
1201 # they will race each other when we can't connect, and the connect
1202 # timeout usually fails
1203 timeout = 2 + self.get_option('timeout')
1204 for fd in (p.stdout, p.stderr):
1205 fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
1206
1207 # TODO: bcoca would like to use SelectSelector() when open
1208 # select is faster when filehandles is low and we only ever handle 1.
1209 selector = selectors.DefaultSelector()
1210 selector.register(p.stdout, selectors.EVENT_READ)
1211 selector.register(p.stderr, selectors.EVENT_READ)
1212
1213 # If we can send initial data without waiting for anything, we do so
1214 # before we start polling
1215 if states[state] == 'ready_to_send' and in_data:
1216 self._send_initial_data(stdin, in_data, p)
1217 state += 1
1218
1219 try:
1220 while True:
1221 poll = p.poll()
1222 events = selector.select(timeout)
1223
1224 # We pay attention to timeouts only while negotiating a prompt.
1225
1226 if not events:
1227 # We timed out
1228 if state <= states.index('awaiting_escalation'):
1229 # If the process has already exited, then it's not really a
1230 # timeout; we'll let the normal error handling deal with it.
1231 if poll is not None:
1232 break
1233 self._terminate_process(p)
1234 raise AnsibleConnectionFailure('Timeout (%ds) waiting for privilege escalation prompt: %s' % (timeout, to_native(b_stdout)))
1235
1236 display.vvvvv(f'SSH: Timeout ({timeout}s) waiting for the output', host=self.host)
1237
1238 # Read whatever output is available on stdout and stderr, and stop
1239 # listening to the pipe if it's been closed.
1240
1241 for key, event in events:
1242 if key.fileobj == p.stdout:
1243 b_chunk = p.stdout.read()
1244 if b_chunk == b'':
1245 # stdout has been closed, stop watching it
1246 selector.unregister(p.stdout)
1247 # When ssh has ControlMaster (+ControlPath/Persist) enabled, the
1248 # first connection goes into the background and we never see EOF
1249 # on stderr. If we see EOF on stdout, lower the select timeout
1250 # to reduce the time wasted selecting on stderr if we observe
1251 # that the process has not yet existed after this EOF. Otherwise
1252 # we may spend a long timeout period waiting for an EOF that is
1253 # not going to arrive until the persisted connection closes.
1254 timeout = 1
1255 b_tmp_stdout += b_chunk
1256 # Known limitation: under ANSIBLE_DEBUG the raw chunks are shown before any secrets in module output
1257 # have been registered with the secret masker, so they may be shown in plaintext.
1258 display.debug(u"stdout chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk)))
1259 elif key.fileobj == p.stderr:
1260 b_chunk = p.stderr.read()
1261 if b_chunk == b'':
1262 # stderr has been closed, stop watching it
1263 selector.unregister(p.stderr)
1264 b_tmp_stderr += b_chunk
1265 display.debug("stderr chunk (state=%s):\n>>>%s<<<\n" % (state, to_text(b_chunk)))
1266
1267 # We examine the output line-by-line until we have negotiated any
1268 # privilege escalation prompt and subsequent success/error message.
1269 # Afterwards, we can accumulate output without looking at it.
1270
1271 if state < states.index('ready_to_send'):
1272 if b_tmp_stdout:
1273 b_output, b_unprocessed = self._examine_output('stdout', states[state], b_tmp_stdout, sudoable)
1274 b_stdout += b_output
1275 b_tmp_stdout = b_unprocessed
1276
1277 if b_tmp_stderr:
1278 b_output, b_unprocessed = self._examine_output('stderr', states[state], b_tmp_stderr, sudoable)
1279 b_stderr += b_output
1280 b_tmp_stderr = b_unprocessed
1281 else:
1282 b_stdout += b_tmp_stdout
1283 b_stderr += b_tmp_stderr
1284 b_tmp_stdout = b_tmp_stderr = b''
1285
1286 # If we see a privilege escalation prompt, we send the password.
1287 # (If we're expecting a prompt but the escalation succeeds, we
1288 # didn't need the password and can carry on regardless.)
1289
1290 if states[state] == 'awaiting_prompt':
1291 if self._flags['become_prompt']:
1292 display.debug(u'Sending become_password in response to prompt')
1293 become_pass = self.become.get_option('become_pass', playcontext=self._play_context)
1294 stdin.write(to_bytes(become_pass, errors='surrogate_or_strict') + b'\n')
1295 # On python3 stdin is a BufferedWriter, and we don't have a guarantee
1296 # that the write will happen without a flush
1297 stdin.flush()
1298 self._flags['become_prompt'] = False
1299 state += 1
1300 elif self._flags['become_success']:
1301 state += 1
1302
1303 # We've requested escalation (with or without a password), now we
1304 # wait for an error message or a successful escalation.
1305
1306 if states[state] == 'awaiting_escalation':
1307 if self._flags['become_success']:
1308 display.vvv(u'Escalation succeeded', host=self.host)
1309 self._flags['become_success'] = False
1310 state += 1
1311 elif self._flags['become_error']:
1312 display.vvv(u'Escalation failed', host=self.host)
1313 self._terminate_process(p)
1314 self._flags['become_error'] = False
1315 raise AnsibleError('Incorrect %s password' % self.become.name)
1316 elif self._flags['become_nopasswd_error']:
1317 display.vvv(u'Escalation requires password', host=self.host)
1318 self._terminate_process(p)
1319 self._flags['become_nopasswd_error'] = False
1320 raise AnsibleError('Missing %s password' % self.become.name)
1321 elif self._flags['become_prompt']:
1322 # This shouldn't happen, because we should see the "Sorry,
1323 # try again" message first.
1324 display.vvv(u'Escalation prompt repeated', host=self.host)
1325 self._terminate_process(p)
1326 self._flags['become_prompt'] = False
1327 raise AnsibleError('Incorrect %s password' % self.become.name)
1328
1329 # Once we're sure that the privilege escalation prompt, if any, has
1330 # been dealt with, we can send any initial data and start waiting
1331 # for output.
1332
1333 if states[state] == 'ready_to_send':
1334 if in_data:
1335 self._send_initial_data(stdin, in_data, p)
1336 state += 1
1337
1338 # Now we're awaiting_exit: has the child process exited? If it has,
1339 # and we've read all available output from it, we're done.
1340
1341 if poll is not None:
1342 if not selector.get_map() or not events:
1343 break
1344 # We should not see further writes to the stdout/stderr file
1345 # descriptors after the process has closed, set the select
1346 # timeout to gather any last writes we may have missed.
1347 timeout = 0
1348 continue
1349
1350 # If the process has not yet exited, but we've already read EOF from
1351 # its stdout and stderr (and thus no longer watching any file
1352 # descriptors), we can just wait for it to exit.
1353
1354 elif not selector.get_map():
1355 p.wait()
1356 break
1357
1358 # Otherwise there may still be outstanding data to read.
1359 finally:
1360 selector.close()
1361 # close stdin, stdout, and stderr after process is terminated and
1362 # stdout/stderr are read completely (see also issues #848, #64768).
1363 stdin.close()
1364 p.stdout.close()
1365 p.stderr.close()
1366
1367 conn_password = self.get_option('password') or self._play_context.password
1368 hostkey_fail = any((
1369 (cmd[0] == b"sshpass" and p.returncode == 6),
1370 b"read_passphrase: can't open /dev/tty" in b_stderr,
1371 b"Host key verification failed" in b_stderr,
1372 ))
1373 if password_mechanism and self.get_option('host_key_checking') and conn_password and hostkey_fail:
1374 raise AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled. '
1375 'Please add this host\'s fingerprint to your known_hosts file to manage this host.')
1376
1377 controlpersisterror = b'Bad configuration option: ControlPersist' in b_stderr or b'unknown configuration option: ControlPersist' in b_stderr
1378 if p.returncode != 0 and controlpersisterror:
1379 raise AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" '
1380 '(or ssh_args in [ssh_connection] section of the config file) before running again')
1381
1382 # If we find a broken pipe because of ControlPersist timeout expiring (see #16731),
1383 # we raise a special exception so that we can retry a connection.
1384 controlpersist_broken_pipe = b'mux_client_hello_exchange: write packet: Broken pipe' in b_stderr
1385 if p.returncode == 255:
1386
1387 additional = to_native(b_stderr)
1388 if controlpersist_broken_pipe:
1389 raise AnsibleControlPersistBrokenPipeError('Data could not be sent because of ControlPersist broken pipe: %s' % additional)
1390
1391 elif in_data and checkrc:
1392 raise AnsibleConnectionFailure('Data could not be sent to remote host "%s". Make sure this host can be reached over ssh: %s'
1393 % (self.host, additional))
1394
1395 return (p.returncode, b_stdout, b_stderr)
1396
1397 @_ssh_retry
1398 def _run(self, cmd: list[bytes], in_data: bytes | None, sudoable: bool = True, checkrc: bool = True) -> tuple[int, bytes, bytes]:
1399 """Wrapper around _bare_run that retries the connection
1400 """
1401 return self._bare_run(cmd, in_data, sudoable=sudoable, checkrc=checkrc)
1402
1403 @_ssh_retry
1404 def _file_transport_command(self, in_path: str, out_path: str, sftp_action: str) -> tuple[int, bytes, bytes]:
1405 # scp and sftp require square brackets for IPv6 addresses, but
1406 # accept them for hostnames and IPv4 addresses too.
1407 host = '[%s]' % self.host
1408
1409 smart_methods = ['sftp', 'scp', 'piped']
1410
1411 # Windows does not support dd so we cannot use the piped method
1412 if getattr(self._shell, "_IS_WINDOWS", False):
1413 smart_methods.remove('piped')
1414
1415 # Transfer methods to try
1416 methods = []
1417
1418 # Use the transfer_method option if set
1419 ssh_transfer_method = self.get_option('ssh_transfer_method')
1420
1421 if ssh_transfer_method == 'smart':
1422 methods = smart_methods
1423 else:
1424 methods = [ssh_transfer_method]
1425
1426 # NOTE: if passing a list to build_command, no need to quote those paths,
1427 # for strings use shlex.quote for local/controller and self._shell.quote for target
1428 for method in methods:
1429 returncode = stdout = stderr = None
1430 match method:
1431 case 'sftp':
1432 cmd = self._build_command(self.get_option('sftp_executable'), method, to_bytes(host))
1433 in_data = f"{sftp_action} {shlex.quote(in_path)} {shlex.quote(out_path)}\n"
1434 in_data = to_bytes(in_data, nonstring='passthru')
1435 (returncode, stdout, stderr) = self._bare_run(cmd, in_data, checkrc=False)
1436 case 'scp':
1437 scp = self.get_option('scp_executable')
1438 if sftp_action == 'get':
1439 cmd = self._build_command(scp, method, f'{host}:{self._shell.quote(in_path)}', out_path)
1440 else:
1441 cmd = self._build_command(scp, method, in_path, f'{host}:{self._shell.quote(out_path)}')
1442 in_data = None
1443 (returncode, stdout, stderr) = self._bare_run(cmd, in_data, checkrc=False)
1444 case 'piped':
1445 if sftp_action == 'get':
1446 # we pass sudoable=False to disable pty allocation, which
1447 # would end up mixing stdout/stderr and screwing with newlines
1448 (returncode, stdout, stderr) = self.exec_command(f'dd if={self._shell.quote(in_path)} bs={BUFSIZE}', sudoable=False)
1449 with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file:
1450 out_file.write(stdout)
1451 else:
1452 with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as f:
1453 in_data = to_bytes(f.read(), nonstring='passthru')
1454 if not in_data:
1455 count = ' count=0'
1456 else:
1457 count = ''
1458 (returncode, stdout, stderr) = self.exec_command(f'dd of={self._shell.quote(out_path)} bs={BUFSIZE}{count}',
1459 in_data=in_data, sudoable=False)
1460
1461 # Check the return code and rollover to next method if failed
1462 if returncode == 0:
1463 return (returncode, stdout, stderr)
1464 else:
1465 # If not in smart mode, the data will be printed by the raise below
1466 if len(methods) > 1:
1467 display.warning(u'%s transfer mechanism failed on %s. Use ANSIBLE_DEBUG=1 to see detailed information' % (method, host))
1468 display.debug(u'%s' % to_text(stdout))
1469 display.debug(u'%s' % to_text(stderr))
1470
1471 if returncode == 255:
1472 raise AnsibleConnectionFailure("Failed to connect to the host via %s: %s" % (method, to_native(stderr)))
1473 else:
1474 raise AnsibleError("failed to transfer file to %s %s:\n%s\n%s" %
1475 (to_native(in_path), to_native(out_path), to_native(stdout), to_native(stderr)))
1476
1477 def _escape_win_path(self, path: str) -> str:
1478 """ converts a Windows path to one that's supported by SFTP and SCP """
1479 # If using a root path then we need to start with /
1480 prefix = ""
1481 if re.match(r'^\w{1}:', path):
1482 prefix = "/"
1483
1484 # Convert all '\' to '/'
1485 return "%s%s" % (prefix, path.replace("\\", "/"))
1486
1487 #
1488 # Main public methods
1489 #
1490 def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
1491 """ run a command on the remote host """
1492
1493 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
1494
1495 self.host = self.get_option('host') or self._play_context.remote_addr
1496
1497 display.vvv(u"ESTABLISH SSH CONNECTION FOR USER: {0}".format(self.user), host=self.host)
1498
1499 if getattr(self._shell, "_IS_WINDOWS", False):
1500 # Become method 'runas' is done in the wrapper that is executed,
1501 # need to disable sudoable so the bare_run is not waiting for a
1502 # prompt that will not occur
1503 sudoable = False
1504
1505 # we can only use tty when we are not pipelining the modules. piping
1506 # data into /usr/bin/python inside a tty automatically invokes the
1507 # python interactive-mode but the modules are not compatible with the
1508 # interactive-mode ("unexpected indent" mainly because of empty lines)
1509
1510 ssh_executable = self.get_option('ssh_executable')
1511
1512 # -tt can cause various issues in some environments so allow the user
1513 # to disable it as a troubleshooting method.
1514 use_tty = self.get_option('use_tty')
1515
1516 args: tuple[str, ...]
1517 if not in_data and sudoable and use_tty:
1518 args = ('-tt', self.host, cmd)
1519 else:
1520 args = (self.host, cmd)
1521
1522 cmd = self._build_command(ssh_executable, 'ssh', *args)
1523 (returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable)
1524
1525 # When running on Windows, stderr may contain CLIXML encoded output
1526 if getattr(self._shell, "_IS_WINDOWS", False):
1527 stderr = _clixml.replace_stderr_clixml(stderr)
1528
1529 return (returncode, stdout, stderr)
1530
1531 def put_file(self, in_path: str, out_path: str) -> tuple[int, bytes, bytes]: # type: ignore[override] # Used by tests and would break API
1532 """ transfer a file from local to remote """
1533
1534 super(Connection, self).put_file(in_path, out_path)
1535
1536 self.host = self.get_option('host') or self._play_context.remote_addr
1537
1538 display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self.host)
1539 if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
1540 raise AnsibleFileNotFound("file or module does not exist: {0}".format(to_native(in_path)))
1541
1542 if getattr(self._shell, "_IS_WINDOWS", False):
1543 out_path = self._escape_win_path(out_path)
1544
1545 return self._file_transport_command(in_path, out_path, 'put')
1546
1547 def fetch_file(self, in_path: str, out_path: str) -> tuple[int, bytes, bytes]: # type: ignore[override] # Used by tests and would break API
1548 """ fetch a file from remote to local """
1549
1550 super(Connection, self).fetch_file(in_path, out_path)
1551
1552 self.host = self.get_option('host') or self._play_context.remote_addr
1553
1554 display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self.host)
1555
1556 # need to add / if path is rooted
1557 if getattr(self._shell, "_IS_WINDOWS", False):
1558 in_path = self._escape_win_path(in_path)
1559
1560 return self._file_transport_command(in_path, out_path, 'get')
1561
1562 def reset(self) -> None:
1563 self.host = self.get_option('host') or self._play_context.remote_addr
1564
1565 # If we have a persistent ssh connection (ControlPersist), we can ask it to stop listening.
1566 # only run the reset if the ControlPath already exists or if it isn't configured and ControlPersist is set
1567 # 'check' will determine this.
1568 cmd = self._build_command(self.get_option('ssh_executable'), 'ssh', '-O', 'check', self.host)
1569 display.vvv('sending connection check: %s' % to_text(cmd), host=self.host)
1570 p = subprocess.run(cmd, stderr=subprocess.PIPE, check=False, text=True)
1571 if p.returncode != 0:
1572 display.vvv(f"No connection to reset: {p.stderr}", host=self.host)
1573 else:
1574 cmd = self._build_command(self.get_option('ssh_executable'), 'ssh', '-O', 'stop', self.host)
1575 display.vvv('sending connection stop: %s' % to_text(cmd), host=self.host)
1576 p = subprocess.run(cmd, stderr=subprocess.PIPE, check=False, text=True)
1577 if p.returncode != 0:
1578 display.warning(f"Failed to reset connection: {p.stderr}")
1579
1580 self.close()
1581
1582 def close(self) -> None:
1583 self._connected = False
1584
1585 @property
1586 def has_tty(self):
1587 return self._is_tty_requested()
1588
1589 def _is_tty_requested(self):
1590
1591 # check if we require tty (only from our args, cannot see options in configuration files)
1592 opts = []
1593 for opt in ('ssh_args', 'ssh_common_args', 'ssh_extra_args'):
1594 attr = self.get_option(opt)
1595 if attr is not None:
1596 opts.extend(self._split_ssh_args(attr))
1597
1598 try:
1599 args, dummy = self._tty_parser.parse_known_args(opts)
1600 except argparse.ArgumentError:
1601 # malformed args; cannot tell if a tty was requested, ssh itself will report the problem when the command runs
1602 return False
1603
1604 if args.t:
1605 return True
1606
1607 for arg in args.o or []:
1608 if '=' in arg:
1609 val = arg.split('=', 1)
1610 else:
1611 val = arg.split(maxsplit=1)
1612
1613 if val[0].lower().strip() == 'requesttty':
1614 if val[1].lower().strip() in ('yes', 'force'):
1615 return True
1616
1617 return False
1618
1619 def is_pipelining_enabled(self, wrap_async=False):
1620 """ override parent method and ensure we don't request a tty """
1621
1622 if getattr(self._shell, "_IS_WINDOWS", False):
1623 # pipelining is always used on Windows
1624 return True
1625 elif self._is_tty_requested():
1626 return False
1627 else:
1628 return super(Connection, self).is_pipelining_enabled(wrap_async)