Debian Codegraph @

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

raw
1 # Based on the buildah connection plugin
2 # Copyright (c) 2017 Ansible Project
3 # 2018 Kushal Das
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6 #
7 #
8 # Written by: Kushal Das (https://github.com/kushaldas)
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 name: qubes
14 short_description: Interact with an existing QubesOS AppVM
15
16 description:
17 - Run commands or put/fetch files to an existing Qubes AppVM using qubes tools.
18 author: Kushal Das (@kushaldas)
19
20
21 options:
22 remote_addr:
23 description:
24 - VM name.
25 type: string
26 default: inventory_hostname
27 vars:
28 - name: ansible_host
29 remote_user:
30 description:
31 - The user to execute as inside the VM.
32 type: string
33 default: The I(user) account as default in Qubes OS.
34 vars:
35 - name: ansible_user
36 # keyword:
37 # - name: hosts
38 """
39
40 import subprocess
41
42 from ansible.errors import AnsibleConnectionFailure
43 from ansible.module_utils.common.text.converters import to_bytes
44 from ansible.plugins.connection import ConnectionBase, ensure_connect
45 from ansible.utils.display import Display
46
47 display = Display()
48
49
50 # this _has to be_ named Connection
51 class Connection(ConnectionBase):
52 """This is a connection plugin for qubes: it uses qubes-run-vm binary to interact with the containers."""
53
54 # String used to identify this Connection class from other classes
55 transport = "community.general.qubes"
56 has_pipelining = True
57
58 def __init__(self, play_context, new_stdin, *args, **kwargs):
59 super().__init__(play_context, new_stdin, *args, **kwargs)
60
61 self._remote_vmname = self._play_context.remote_addr
62 self._connected = False
63 # Default username in Qubes
64 self.user = "user"
65 if self._play_context.remote_user:
66 self.user = self._play_context.remote_user
67
68 def _qubes(self, cmd=None, in_data=None, shell="qubes.VMShell"):
69 """run qvm-run executable
70
71 :param cmd: cmd string for remote system
72 :param in_data: data passed to qvm-run-vm's stdin
73 :return: return code, stdout, stderr
74 """
75 display.vvvv("CMD: ", cmd)
76 if not cmd.endswith("\n"):
77 cmd = f"{cmd}\n"
78 local_cmd = []
79
80 # For dom0
81 local_cmd.extend(["qvm-run", "--pass-io", "--service"])
82 if self.user != "user":
83 # Means we have a remote_user value
84 local_cmd.extend(["-u", self.user])
85
86 local_cmd.append(self._remote_vmname)
87
88 local_cmd.append(shell)
89
90 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
91
92 display.vvvv("Local cmd: ", local_cmd)
93
94 display.vvv(f"RUN {local_cmd}", host=self._remote_vmname)
95 p = subprocess.Popen(
96 local_cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
97 )
98
99 # Here we are writing the actual command to the remote bash
100 p.stdin.write(to_bytes(cmd, errors="surrogate_or_strict"))
101 stdout, stderr = p.communicate(input=in_data)
102 return p.returncode, stdout, stderr
103
104 def _connect(self):
105 """No persistent connection is being maintained."""
106 super()._connect()
107 self._connected = True
108
109 @ensure_connect # type: ignore # TODO: for some reason, the type infos for ensure_connect suck...
110 def exec_command(self, cmd, in_data=None, sudoable=False):
111 """Run specified command in a running QubesVM"""
112 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
113
114 display.vvvv(f"CMD IS: {cmd}")
115
116 rc, stdout, stderr = self._qubes(cmd)
117
118 display.vvvvv(f"STDOUT {stdout!r} STDERR {stderr!r}")
119 return rc, stdout, stderr
120
121 def put_file(self, in_path, out_path):
122 """Place a local file located in 'in_path' inside VM at 'out_path'"""
123 super().put_file(in_path, out_path)
124 display.vvv(f"PUT {in_path} TO {out_path}", host=self._remote_vmname)
125
126 with open(in_path, "rb") as fobj:
127 source_data = fobj.read()
128
129 retcode, dummy, dummy = self._qubes(f'cat > "{out_path}"\n', source_data, "qubes.VMRootShell")
130 # if qubes.VMRootShell service not supported, fallback to qubes.VMShell and
131 # hope it will have appropriate permissions
132 if retcode == 127:
133 retcode, dummy, dummy = self._qubes(f'cat > "{out_path}"\n', source_data)
134
135 if retcode != 0:
136 raise AnsibleConnectionFailure(f"Failed to put_file to {out_path}")
137
138 def fetch_file(self, in_path, out_path):
139 """Obtain file specified via 'in_path' from the container and place it at 'out_path'"""
140 super().fetch_file(in_path, out_path)
141 display.vvv(f"FETCH {in_path} TO {out_path}", host=self._remote_vmname)
142
143 # We are running in dom0
144 cmd_args_list = ["qvm-run", "--pass-io", self._remote_vmname, f"cat {in_path}"]
145 with open(out_path, "wb") as fobj:
146 p = subprocess.Popen(cmd_args_list, shell=False, stdout=fobj)
147 p.communicate()
148 if p.returncode != 0:
149 raise AnsibleConnectionFailure(f"Failed to fetch file to {out_path}")
150
151 def close(self):
152 """Closing the connection"""
153 super().close()
154 self._connected = False