Debian Codegraph @

lib/ansible/cli/_ssh_askpass.py

raw
1 # Copyright: Contributors to the Ansible project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 import json
6 import os
7 import re
8 import sys
9 import typing as t
10
11 from multiprocessing.shared_memory import SharedMemory
12
13
14 def main() -> t.Never:
15 if len(sys.argv) > 1:
16 exit_code = 0 if handle_prompt(sys.argv[1]) else 1
17 else:
18 exit_code = 1
19
20 sys.exit(exit_code)
21
22
23 def handle_prompt(prompt: str) -> bool:
24 if (ssh_askpass_prompt := os.environ.get('SSH_ASKPASS_PROMPT')) == 'none':
25 return True
26
27 if (
28 ssh_askpass_prompt == 'confirm' or
29 re.search(r'(The authenticity of host |differs from the key for the IP address)', prompt)
30 ):
31 sys.stdout.write('no')
32 sys.stdout.flush()
33 return True
34
35 # This SharedMemory instance is intentionally not closed or unlinked.
36 # Closing will occur naturally in the SharedMemory finalizer.
37 # Unlinking is the responsibility of the process which created it.
38 shm = SharedMemory(name=os.environ['_ANSIBLE_SSH_ASKPASS_SHM'], track=False)
39
40 cfg = json.loads(shm.buf.tobytes().rstrip(b'\x00'))
41
42 if cfg['prompt'] not in prompt:
43 return False
44
45 # Report the password provided by the SharedMemory instance.
46 # The contents are left untouched after consumption to allow subsequent attempts to succeed.
47 # This can occur when multiple password prompting methods are enabled, such as password and keyboard-interactive, which is the default on macOS.
48 sys.stdout.write(cfg['password'])
49 sys.stdout.flush()
50 return True