Debian Codegraph @

ansible_collections/community/general/plugins/connection/jail.py

raw
1 # Based on local.py by Michael DeHaan <[email protected]>
2 # and chroot.py by Maykel Moya <[email protected]>
3 # Copyright (c) 2013, Michael Scherer <[email protected]>
4 # Copyright (c) 2015, Toshio Kuratomi <[email protected]>
5 # Copyright (c) 2017 Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 author: Ansible Core Team
13 name: jail
14 short_description: Run tasks in jails
15 description:
16 - Run commands or put/fetch files to an existing jail.
17 options:
18 remote_addr:
19 description:
20 - Path to the jail.
21 type: string
22 default: inventory_hostname
23 vars:
24 - name: inventory_hostname
25 - name: ansible_host
26 - name: ansible_jail_host
27 remote_user:
28 description:
29 - User to execute as inside the jail.
30 type: string
31 vars:
32 - name: ansible_user
33 - name: ansible_jail_user
34 """
35
36 import os
37 import os.path
38 import subprocess
39 import traceback
40 from shlex import quote as shlex_quote
41
42 from ansible.errors import AnsibleError
43 from ansible.module_utils.common.process import get_bin_path
44 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
45 from ansible.plugins.connection import BUFSIZE, ConnectionBase
46 from ansible.utils.display import Display
47
48 display = Display()
49
50
51 class Connection(ConnectionBase):
52 """Local BSD Jail based connections"""
53
54 modified_jailname_key = "conn_jail_name"
55
56 transport = "community.general.jail"
57 # Pipelining may work. Someone needs to test by setting this to True and
58 # having pipelining=True in their ansible.cfg
59 has_pipelining = True
60 has_tty = False
61
62 def __init__(self, play_context, new_stdin, *args, **kwargs):
63 super().__init__(play_context, new_stdin, *args, **kwargs)
64
65 self.jail = self._play_context.remote_addr
66 if self.modified_jailname_key in kwargs:
67 self.jail = kwargs[self.modified_jailname_key]
68
69 if os.geteuid() != 0:
70 raise AnsibleError("jail connection requires running as root")
71
72 self.jls_cmd = self._search_executable("jls")
73 self.jexec_cmd = self._search_executable("jexec")
74
75 if self.jail not in self.list_jails():
76 raise AnsibleError(f"incorrect jail name {self.jail}")
77
78 @staticmethod
79 def _search_executable(executable):
80 try:
81 return get_bin_path(executable)
82 except ValueError as e:
83 raise AnsibleError(f"{executable} command not found in PATH") from e
84
85 def list_jails(self):
86 p = subprocess.Popen(
87 [self.jls_cmd, "-q", "name"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
88 )
89
90 stdout, stderr = p.communicate()
91
92 return to_text(stdout, errors="surrogate_or_strict").split()
93
94 def _connect(self):
95 """connect to the jail; nothing to do here"""
96 super()._connect()
97 if not self._connected:
98 display.vvv(f"ESTABLISH JAIL CONNECTION FOR USER: {self._play_context.remote_user}", host=self.jail)
99 self._connected = True
100
101 def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
102 """run a command on the jail. This is only needed for implementing
103 put_file() get_file() so that we don't have to read the whole file
104 into memory.
105
106 compared to exec_command() it looses some niceties like being able to
107 return the process's exit code immediately.
108 """
109
110 local_cmd = [self.jexec_cmd]
111 set_env = ""
112
113 if self._play_context.remote_user is not None:
114 local_cmd += ["-U", self._play_context.remote_user]
115 # update HOME since -U does not update the jail environment
116 set_env = f"HOME=~{self._play_context.remote_user} "
117
118 local_cmd += [self.jail, self._play_context.executable, "-c", set_env + cmd]
119
120 display.vvv(f"EXEC {local_cmd}", host=self.jail)
121 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
122 p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
123
124 return p
125
126 def exec_command(self, cmd, in_data=None, sudoable=False):
127 """run a command on the jail"""
128 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
129
130 p = self._buffered_exec_command(cmd)
131
132 stdout, stderr = p.communicate(in_data)
133 return p.returncode, stdout, stderr
134
135 @staticmethod
136 def _prefix_login_path(remote_path):
137 """Make sure that we put files into a standard path
138
139 If a path is relative, then we need to choose where to put it.
140 ssh chooses $HOME but we aren't guaranteed that a home dir will
141 exist in any given chroot. So for now we're choosing "/" instead.
142 This also happens to be the former default.
143
144 Can revisit using $HOME instead if it is a problem
145 """
146 if not remote_path.startswith(os.path.sep):
147 remote_path = os.path.join(os.path.sep, remote_path)
148 return os.path.normpath(remote_path)
149
150 def put_file(self, in_path, out_path):
151 """transfer a file from local to jail"""
152 super().put_file(in_path, out_path)
153 display.vvv(f"PUT {in_path} TO {out_path}", host=self.jail)
154
155 out_path = shlex_quote(self._prefix_login_path(out_path))
156 try:
157 with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file:
158 if not os.fstat(in_file.fileno()).st_size:
159 count = " count=0"
160 else:
161 count = ""
162 try:
163 p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file)
164 except OSError as e:
165 raise AnsibleError("jail connection requires dd command in the jail") from e
166 try:
167 stdout, stderr = p.communicate()
168 except Exception as e:
169 traceback.print_exc()
170 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
171 if p.returncode != 0:
172 raise AnsibleError(
173 f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}"
174 )
175 except OSError as e:
176 raise AnsibleError(f"file or module does not exist at: {in_path}") from e
177
178 def fetch_file(self, in_path, out_path):
179 """fetch a file from jail to local"""
180 super().fetch_file(in_path, out_path)
181 display.vvv(f"FETCH {in_path} TO {out_path}", host=self.jail)
182
183 in_path = shlex_quote(self._prefix_login_path(in_path))
184 try:
185 p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}")
186 except OSError as e:
187 raise AnsibleError("jail connection requires dd command in the jail") from e
188
189 with open(to_bytes(out_path, errors="surrogate_or_strict"), "wb+") as out_file:
190 try:
191 chunk = p.stdout.read(BUFSIZE)
192 while chunk:
193 out_file.write(chunk)
194 chunk = p.stdout.read(BUFSIZE)
195 except Exception as e:
196 traceback.print_exc()
197 raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e
198 stdout, stderr = p.communicate()
199 if p.returncode != 0:
200 raise AnsibleError(
201 f"failed to transfer file {in_path} to {out_path}:\n{to_native(stdout)}\n{to_native(stderr)}"
202 )
203
204 def close(self):
205 """terminate the connection; nothing to do here"""
206 super().close()
207 self._connected = False