| 1 |
# Based on local.py (c) 2012, Michael DeHaan <[email protected]> |
| 2 |
# |
| 3 |
# (c) 2013, Maykel Moya <[email protected]> |
| 4 |
# (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: Maykel Moya (!UNKNOWN) <[email protected]> |
| 13 |
name: chroot |
| 14 |
short_description: Interact with local chroot |
| 15 |
description: |
| 16 |
- Run commands or put/fetch files to an existing chroot on the Ansible controller. |
| 17 |
options: |
| 18 |
remote_addr: |
| 19 |
description: |
| 20 |
- The path of the chroot you want to access. |
| 21 |
type: string |
| 22 |
default: inventory_hostname |
| 23 |
vars: |
| 24 |
- name: inventory_hostname |
| 25 |
- name: ansible_host |
| 26 |
executable: |
| 27 |
description: |
| 28 |
- User specified executable shell. |
| 29 |
type: string |
| 30 |
ini: |
| 31 |
- section: defaults |
| 32 |
key: executable |
| 33 |
env: |
| 34 |
- name: ANSIBLE_EXECUTABLE |
| 35 |
vars: |
| 36 |
- name: ansible_executable |
| 37 |
default: /bin/sh |
| 38 |
chroot_exe: |
| 39 |
description: |
| 40 |
- User specified chroot binary. |
| 41 |
type: string |
| 42 |
ini: |
| 43 |
- section: chroot_connection |
| 44 |
key: exe |
| 45 |
env: |
| 46 |
- name: ANSIBLE_CHROOT_EXE |
| 47 |
vars: |
| 48 |
- name: ansible_chroot_exe |
| 49 |
default: chroot |
| 50 |
disable_root_check: |
| 51 |
description: |
| 52 |
- Do not check that the user is not root. |
| 53 |
ini: |
| 54 |
- section: chroot_connection |
| 55 |
key: disable_root_check |
| 56 |
env: |
| 57 |
- name: ANSIBLE_CHROOT_DISABLE_ROOT_CHECK |
| 58 |
vars: |
| 59 |
- name: ansible_chroot_disable_root_check |
| 60 |
default: false |
| 61 |
type: bool |
| 62 |
version_added: 7.3.0 |
| 63 |
""" |
| 64 |
|
| 65 |
EXAMPLES = r""" |
| 66 |
- hosts: chroots |
| 67 |
connection: community.general.chroot |
| 68 |
tasks: |
| 69 |
- debug: |
| 70 |
msg: "This is coming from chroot environment" |
| 71 |
""" |
| 72 |
|
| 73 |
import os |
| 74 |
import os.path |
| 75 |
import subprocess |
| 76 |
import traceback |
| 77 |
from shlex import quote as shlex_quote |
| 78 |
|
| 79 |
from ansible.errors import AnsibleError |
| 80 |
from ansible.module_utils.basic import is_executable |
| 81 |
from ansible.module_utils.common.process import get_bin_path |
| 82 |
from ansible.module_utils.common.text.converters import to_bytes |
| 83 |
from ansible.plugins.connection import BUFSIZE, ConnectionBase |
| 84 |
from ansible.utils.display import Display |
| 85 |
|
| 86 |
display = Display() |
| 87 |
|
| 88 |
|
| 89 |
class Connection(ConnectionBase): |
| 90 |
"""Local chroot based connections""" |
| 91 |
|
| 92 |
transport = "community.general.chroot" |
| 93 |
has_pipelining = True |
| 94 |
# su currently has an undiagnosed issue with calculating the file |
| 95 |
# checksums (so copy, for instance, doesn't work right) |
| 96 |
# Have to look into that before re-enabling this |
| 97 |
has_tty = False |
| 98 |
|
| 99 |
default_user = "root" |
| 100 |
|
| 101 |
def __init__(self, play_context, new_stdin, *args, **kwargs): |
| 102 |
super().__init__(play_context, new_stdin, *args, **kwargs) |
| 103 |
|
| 104 |
self.chroot = self._play_context.remote_addr |
| 105 |
|
| 106 |
# do some trivial checks for ensuring 'host' is actually a chroot'able dir |
| 107 |
if not os.path.isdir(self.chroot): |
| 108 |
raise AnsibleError(f"{self.chroot} is not a directory") |
| 109 |
|
| 110 |
chrootsh = os.path.join(self.chroot, "bin/sh") |
| 111 |
# Want to check for a usable bourne shell inside the chroot. |
| 112 |
# is_executable() == True is sufficient. For symlinks it |
| 113 |
# gets really complicated really fast. So we punt on finding that |
| 114 |
# out. As long as it is a symlink we assume that it will work |
| 115 |
if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))): |
| 116 |
raise AnsibleError(f"{self.chroot} does not look like a chrootable dir (/bin/sh missing)") |
| 117 |
|
| 118 |
def _connect(self): |
| 119 |
"""connect to the chroot""" |
| 120 |
if not self.get_option("disable_root_check") and os.geteuid() != 0: |
| 121 |
raise AnsibleError( |
| 122 |
"chroot connection requires running as root. " |
| 123 |
"You can override this check with the `disable_root_check` option." |
| 124 |
) |
| 125 |
|
| 126 |
if os.path.isabs(self.get_option("chroot_exe")): |
| 127 |
self.chroot_cmd = self.get_option("chroot_exe") |
| 128 |
else: |
| 129 |
try: |
| 130 |
self.chroot_cmd = get_bin_path(self.get_option("chroot_exe")) |
| 131 |
except ValueError as e: |
| 132 |
raise AnsibleError(str(e)) from e |
| 133 |
|
| 134 |
super()._connect() |
| 135 |
if not self._connected: |
| 136 |
display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot) |
| 137 |
self._connected = True |
| 138 |
|
| 139 |
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE): |
| 140 |
"""run a command on the chroot. This is only needed for implementing |
| 141 |
put_file() get_file() so that we don't have to read the whole file |
| 142 |
into memory. |
| 143 |
|
| 144 |
compared to exec_command() it looses some niceties like being able to |
| 145 |
return the process's exit code immediately. |
| 146 |
""" |
| 147 |
executable = self.get_option("executable") |
| 148 |
local_cmd = [self.chroot_cmd, self.chroot, executable, "-c", cmd] |
| 149 |
|
| 150 |
display.vvv(f"EXEC {local_cmd}", host=self.chroot) |
| 151 |
local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd] |
| 152 |
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 153 |
|
| 154 |
return p |
| 155 |
|
| 156 |
def exec_command(self, cmd, in_data=None, sudoable=False): |
| 157 |
"""run a command on the chroot""" |
| 158 |
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 159 |
|
| 160 |
p = self._buffered_exec_command(cmd) |
| 161 |
|
| 162 |
stdout, stderr = p.communicate(in_data) |
| 163 |
return p.returncode, stdout, stderr |
| 164 |
|
| 165 |
@staticmethod |
| 166 |
def _prefix_login_path(remote_path): |
| 167 |
"""Make sure that we put files into a standard path |
| 168 |
|
| 169 |
If a path is relative, then we need to choose where to put it. |
| 170 |
ssh chooses $HOME but we aren't guaranteed that a home dir will |
| 171 |
exist in any given chroot. So for now we're choosing "/" instead. |
| 172 |
This also happens to be the former default. |
| 173 |
|
| 174 |
Can revisit using $HOME instead if it is a problem |
| 175 |
""" |
| 176 |
if not remote_path.startswith(os.path.sep): |
| 177 |
remote_path = os.path.join(os.path.sep, remote_path) |
| 178 |
return os.path.normpath(remote_path) |
| 179 |
|
| 180 |
def put_file(self, in_path, out_path): |
| 181 |
"""transfer a file from local to chroot""" |
| 182 |
super().put_file(in_path, out_path) |
| 183 |
display.vvv(f"PUT {in_path} TO {out_path}", host=self.chroot) |
| 184 |
|
| 185 |
out_path = shlex_quote(self._prefix_login_path(out_path)) |
| 186 |
try: |
| 187 |
with open(to_bytes(in_path, errors="surrogate_or_strict"), "rb") as in_file: |
| 188 |
if not os.fstat(in_file.fileno()).st_size: |
| 189 |
count = " count=0" |
| 190 |
else: |
| 191 |
count = "" |
| 192 |
try: |
| 193 |
p = self._buffered_exec_command(f"dd of={out_path} bs={BUFSIZE}{count}", stdin=in_file) |
| 194 |
except OSError as e: |
| 195 |
raise AnsibleError("chroot connection requires dd command in the chroot") from e |
| 196 |
try: |
| 197 |
stdout, stderr = p.communicate() |
| 198 |
except Exception as e: |
| 199 |
traceback.print_exc() |
| 200 |
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e |
| 201 |
if p.returncode != 0: |
| 202 |
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}") |
| 203 |
except OSError as e: |
| 204 |
raise AnsibleError(f"file or module does not exist at: {in_path}") from e |
| 205 |
|
| 206 |
def fetch_file(self, in_path, out_path): |
| 207 |
"""fetch a file from chroot to local""" |
| 208 |
super().fetch_file(in_path, out_path) |
| 209 |
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.chroot) |
| 210 |
|
| 211 |
in_path = shlex_quote(self._prefix_login_path(in_path)) |
| 212 |
try: |
| 213 |
p = self._buffered_exec_command(f"dd if={in_path} bs={BUFSIZE}") |
| 214 |
except OSError as e: |
| 215 |
raise AnsibleError("chroot connection requires dd command in the chroot") from e |
| 216 |
|
| 217 |
with open(to_bytes(out_path, errors="surrogate_or_strict"), "wb+") as out_file: |
| 218 |
try: |
| 219 |
chunk = p.stdout.read(BUFSIZE) |
| 220 |
while chunk: |
| 221 |
out_file.write(chunk) |
| 222 |
chunk = p.stdout.read(BUFSIZE) |
| 223 |
except Exception as e: |
| 224 |
traceback.print_exc() |
| 225 |
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}") from e |
| 226 |
stdout, stderr = p.communicate() |
| 227 |
if p.returncode != 0: |
| 228 |
raise AnsibleError(f"failed to transfer file {in_path} to {out_path}:\n{stdout}\n{stderr}") |
| 229 |
|
| 230 |
def close(self): |
| 231 |
"""terminate the connection; nothing to do here""" |
| 232 |
super().close() |
| 233 |
self._connected = False |