Debian Codegraph @

ansible_collections/community/docker/plugins/connection/nsenter.py

raw
1 # Copyright (c) 2021 Jeff Goldschrafe <[email protected]>
2 # Based on Ansible local connection plugin by:
3 # Copyright (c) 2012 Michael DeHaan <[email protected]>
4 # Copyright (c) 2015, 2017 Toshio Kuratomi <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 name: nsenter
12 short_description: execute on host running controller container
13 version_added: 1.9.0
14 description:
15 - This connection plugin allows Ansible, running in a privileged container, to execute tasks on the container host instead
16 of in the container itself.
17 - This is useful for running Ansible in a pull model, while still keeping the Ansible control node containerized.
18 - It relies on having privileged access to run C(nsenter) in the host's PID namespace, allowing it to enter the namespaces
19 of the provided PID (default PID 1, or init/systemd).
20 author: Jeff Goldschrafe (@jgoldschrafe)
21 options:
22 nsenter_pid:
23 description:
24 - PID to attach with using nsenter.
25 - The default should be fine unless you are attaching as a non-root user.
26 type: int
27 default: 1
28 vars:
29 - name: ansible_nsenter_pid
30 env:
31 - name: ANSIBLE_NSENTER_PID
32 ini:
33 - section: nsenter_connection
34 key: nsenter_pid
35 notes:
36 - The remote user is ignored; this plugin always runs as root.
37 - "This plugin requires the Ansible controller container to be launched in the following way: (1) The container image contains
38 the C(nsenter) program; (2) The container is launched in privileged mode; (3) The container is launched in the host's
39 PID namespace (C(--pid host))."
40 """
41
42 import fcntl
43 import os
44 import pty
45 import selectors
46 import shlex
47 import subprocess
48 import typing as t
49
50 import ansible.constants as C
51 from ansible.errors import AnsibleError
52 from ansible.module_utils.common.text.converters import to_bytes, to_text
53 from ansible.plugins.connection import ConnectionBase
54 from ansible.utils.display import Display
55 from ansible.utils.path import unfrackpath
56
57 display = Display()
58
59
60 class Connection(ConnectionBase):
61 """Connections to a container host using nsenter"""
62
63 transport = "community.docker.nsenter"
64 has_pipelining = False
65
66 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
67 super().__init__(*args, **kwargs)
68 self.cwd = None
69 self._nsenter_pid = None
70
71 def _connect(self) -> t.Self:
72 self._nsenter_pid = self.get_option("nsenter_pid")
73
74 # Because nsenter requires very high privileges, our remote user
75 # is always assumed to be root.
76 self._play_context.remote_user = "root"
77
78 if not self._connected:
79 display.vvv(
80 f"ESTABLISH NSENTER CONNECTION FOR USER: {self._play_context.remote_user}",
81 host=self._play_context.remote_addr,
82 )
83 self._connected = True
84 return self
85
86 def exec_command(
87 self, cmd: str, in_data: bytes | None = None, sudoable: bool = True
88 ) -> tuple[int, bytes, bytes]:
89 super().exec_command(cmd, in_data=in_data, sudoable=sudoable) # type: ignore[safe-super]
90
91 display.debug("in nsenter.exec_command()")
92
93 # pylint: disable-next=no-member
94 def_executable: str | None = C.DEFAULT_EXECUTABLE # type: ignore[attr-defined]
95 executable = def_executable.split()[0] if def_executable else None
96
97 if not os.path.exists(to_bytes(executable, errors="surrogate_or_strict")):
98 raise AnsibleError(
99 f"failed to find the executable specified {executable}."
100 " Please verify if the executable exists and re-try."
101 )
102
103 # Rewrite the provided command to prefix it with nsenter
104 nsenter_cmd_parts = [
105 "nsenter",
106 "--ipc",
107 "--mount",
108 "--net",
109 "--pid",
110 "--uts",
111 "--preserve-credentials",
112 f"--target={self._nsenter_pid}",
113 "--",
114 ]
115
116 cmd_parts = nsenter_cmd_parts + [cmd]
117 cmd_b = to_bytes(" ".join(cmd_parts))
118
119 display.vvv(f"EXEC {to_text(cmd_b)}", host=self._play_context.remote_addr)
120 display.debug("opening command with Popen()")
121
122 master = None
123 stdin = subprocess.PIPE
124
125 # This plugin does not support pipelining. This diverges from the behavior of
126 # the core "local" connection plugin that this one derives from.
127 if sudoable and self.become and self.become.expect_prompt():
128 # Create a pty if sudoable for privilege escalation that needs it.
129 # Falls back to using a standard pipe if this fails, which may
130 # cause the command to fail in certain situations where we are escalating
131 # privileges or the command otherwise needs a pty.
132 try:
133 master, stdin = pty.openpty()
134 except (IOError, OSError) as e:
135 display.debug(f"Unable to open pty: {e}")
136
137 with subprocess.Popen(
138 cmd_b,
139 shell=True,
140 executable=executable,
141 cwd=self.cwd,
142 stdin=stdin,
143 stdout=subprocess.PIPE,
144 stderr=subprocess.PIPE,
145 ) as p:
146 assert p.stderr is not None
147 assert p.stdin is not None
148 assert p.stdout is not None
149 # if we created a master, we can close the other half of the pty now, otherwise master is stdin
150 if master is not None:
151 os.close(stdin)
152
153 display.debug("done running command with Popen()")
154
155 if self.become and self.become.expect_prompt() and sudoable:
156 fcntl.fcntl(
157 p.stdout,
158 fcntl.F_SETFL,
159 fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK,
160 )
161 fcntl.fcntl(
162 p.stderr,
163 fcntl.F_SETFL,
164 fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK,
165 )
166 selector = selectors.DefaultSelector()
167 selector.register(p.stdout, selectors.EVENT_READ)
168 selector.register(p.stderr, selectors.EVENT_READ)
169
170 become_output = b""
171 try:
172 while not self.become.check_success(
173 become_output
174 ) and not self.become.check_password_prompt(become_output):
175 events = selector.select(self._play_context.timeout)
176 if not events:
177 stdout, stderr = p.communicate()
178 raise AnsibleError(
179 "timeout waiting for privilege escalation password prompt:\n"
180 + to_text(become_output)
181 )
182
183 chunks = b""
184 for key, dummy_event in events:
185 if key.fileobj == p.stdout:
186 chunk = p.stdout.read()
187 if chunk:
188 chunks += chunk
189 elif key.fileobj == p.stderr:
190 chunk = p.stderr.read()
191 if chunk:
192 chunks += chunk
193
194 if not chunks:
195 stdout, stderr = p.communicate()
196 raise AnsibleError(
197 "privilege output closed while waiting for password prompt:\n"
198 + to_text(become_output)
199 )
200 become_output += chunks
201 finally:
202 selector.close()
203
204 if not self.become.check_success(become_output):
205 become_pass = self.become.get_option(
206 "become_pass", playcontext=self._play_context
207 )
208 if master is None:
209 p.stdin.write(
210 to_bytes(become_pass, errors="surrogate_or_strict") + b"\n"
211 )
212 else:
213 os.write(
214 master,
215 to_bytes(become_pass, errors="surrogate_or_strict") + b"\n",
216 )
217
218 fcntl.fcntl(
219 p.stdout,
220 fcntl.F_SETFL,
221 fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK,
222 )
223 fcntl.fcntl(
224 p.stderr,
225 fcntl.F_SETFL,
226 fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK,
227 )
228
229 display.debug("getting output with communicate()")
230 stdout, stderr = p.communicate(in_data)
231 display.debug("done communicating")
232
233 # finally, close the other half of the pty, if it was created
234 if master:
235 os.close(master)
236
237 display.debug("done with nsenter.exec_command()")
238 return (p.returncode, stdout, stderr)
239
240 def put_file(self, in_path: str, out_path: str) -> None:
241 super().put_file(in_path, out_path) # type: ignore[safe-super]
242
243 in_path = unfrackpath(in_path, basedir=self.cwd)
244 out_path = unfrackpath(out_path, basedir=self.cwd)
245
246 display.vvv(f"PUT {in_path} to {out_path}", host=self._play_context.remote_addr)
247 try:
248 with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
249 in_data = in_file.read()
250 rc, dummy_out, err = self.exec_command(
251 cmd=f"tee {shlex.quote(out_path)}", in_data=in_data
252 )
253 if rc != 0:
254 raise AnsibleError(
255 f"failed to transfer file to {out_path}: {to_text(err)}"
256 )
257 except IOError as e:
258 raise AnsibleError(f"failed to transfer file to {out_path}: {e}") from e
259
260 def fetch_file(self, in_path: str, out_path: str) -> None:
261 super().fetch_file(in_path, out_path) # type: ignore[safe-super]
262
263 in_path = unfrackpath(in_path, basedir=self.cwd)
264 out_path = unfrackpath(out_path, basedir=self.cwd)
265
266 try:
267 rc, out, err = self.exec_command(cmd=f"cat {shlex.quote(in_path)}")
268 display.vvv(
269 f"FETCH {in_path} TO {out_path}", host=self._play_context.remote_addr
270 )
271 if rc != 0:
272 raise AnsibleError(
273 f"failed to transfer file to {in_path}: {to_text(err)}"
274 )
275 with open(
276 to_bytes(out_path, errors="surrogate_or_strict"), "wb"
277 ) as out_file:
278 out_file.write(out)
279 except IOError as e:
280 raise AnsibleError(
281 f"failed to transfer file to {to_text(out_path)}: {e}"
282 ) from e
283
284 def close(self) -> None:
285 """terminate the connection; nothing to do here"""
286 self._connected = False