Debian Codegraph @

lib/ansible/plugins/become/__init__.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2018, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 import re
7 import shlex
8
9 from abc import abstractmethod
10 from secrets import choice
11 from string import ascii_lowercase
12 from gettext import dgettext
13
14 from ansible.errors import AnsibleError
15 from ansible.module_utils.common.text.converters import to_bytes
16 from ansible.plugins import AnsiblePlugin
17 from ansible.utils import display as _display
18
19
20 def _gen_id(length=32):
21 """ return random string used to identify the current privilege escalation """
22 return ''.join(choice(ascii_lowercase) for x in range(length))
23
24
25 class BecomeBase(AnsiblePlugin):
26
27 name = None # type: str | None
28
29 # messages for detecting prompted password issues
30 fail = tuple() # type: tuple[str, ...]
31 missing = tuple() # type: tuple[str, ...]
32
33 # many connection plugins cannot provide tty, set to True if your become
34 # plugin requires a tty, i.e su
35 require_tty = False
36
37 # plugin allows for pipelining execution
38 pipelining = True
39
40 # prompt to match
41 prompt = ''
42
43 def __init__(self):
44 super(BecomeBase, self).__init__()
45 self._id = ''
46 self.success = ''
47
48 def get_option(self, option, hostvars=None, playcontext=None):
49 """ Overrides the base get_option to provide a fallback to playcontext vars in case a 3rd party plugin did not
50 implement the base become options required in Ansible. """
51 # TODO: add deprecation warning for ValueError in devel that removes the playcontext fallback
52 try:
53 return super(BecomeBase, self).get_option(option, hostvars=hostvars)
54 except KeyError:
55 pc_fallback = ['become_user', 'become_pass', 'become_flags', 'become_exe']
56 if option not in pc_fallback:
57 raise
58
59 return getattr(playcontext, option, None)
60
61 def expect_prompt(self) -> bool:
62 """This function assists connection plugins in determining if they need to wait for
63 a prompt. Both a prompt and a password are required.
64 """
65 return bool(self.prompt and self.get_option('become_pass'))
66
67 def _build_success_command(self, cmd, shell, noexe=False):
68 if not all((cmd, shell, self.success)):
69 return cmd
70
71 try:
72 cmd = shlex.quote('%s %s %s %s' % (shell.ECHO, self.success, shell.COMMAND_SEP, cmd))
73 except AttributeError as ex:
74 raise AnsibleError(f'The {shell._load_name!r} shell plugin does not support become. It is missing the {ex.name!r} attribute.')
75 exe = getattr(shell, 'executable', None)
76 if exe and not noexe:
77 cmd = '%s -c %s' % (exe, cmd)
78 return cmd
79
80 @abstractmethod
81 def build_become_command(self, cmd, shell):
82 self._id = _gen_id()
83 self.success = 'BECOME-SUCCESS-%s' % self._id
84
85 def strip_become_prompt(self, data: bytes) -> bytes:
86 """
87 Strips the first found configured become prompt from `data`, trailing whitespace and anything that precedes the prompt, then returns the result.
88 If no prompt is expected, or the prompt is not `str` or `bytes`, `data` will be returned as-is.
89 """
90 if not self.prompt or not isinstance(self.prompt, (str, bytes)) or not self.expect_prompt():
91 return data
92
93 return self._strip_through_prefix(self.prompt, data)
94
95 def strip_become_success(self, data: bytes) -> bytes:
96 """Strips the first found success marker from `data`, trailing whitespace and anything that precedes the success marker, then returns the result."""
97 return self._strip_through_prefix(self.success, data)
98
99 @staticmethod
100 def _strip_through_prefix(match: str | bytes, data: bytes) -> bytes:
101 """Strips the first occurrence of `match` from `data`, trailing whitespace and anything that precedes `match`, then returns the result."""
102 return re.sub(br'^.*?' + re.escape(to_bytes(match)) + br'\s*', b'', data, count=1, flags=re.DOTALL)
103
104 def check_success(self, b_output):
105 b_success = to_bytes(self.success)
106 return any(b_success in l.rstrip() for l in b_output.splitlines(True))
107
108 def check_password_prompt(self, b_output: bytes) -> bool:
109 """ checks if the expected password prompt exists in b_output """
110 if self.prompt:
111 b_prompt = to_bytes(self.prompt).strip()
112 return any(l.strip().startswith(b_prompt) for l in b_output.splitlines())
113 return False
114
115 def _check_password_error(self, b_out, msg):
116 """ returns True/False if domain specific i18n version of msg is found in b_out """
117 b_fail = to_bytes(dgettext(self.name, msg))
118 return b_fail and b_fail in b_out
119
120 def check_incorrect_password(self, b_output):
121 for errstring in self.fail:
122 if self._check_password_error(b_output, errstring):
123 return True
124 return False
125
126 def check_missing_password(self, b_output):
127 for errstring in self.missing:
128 if self._check_password_error(b_output, errstring):
129 return True
130 return False