Debian Codegraph @

src/cockpit/bridge.py

raw
1 #
2 # Copyright (C) 2022 Red Hat, Inc.
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5
6 import argparse
7 import asyncio
8 import contextlib
9 import grp
10 import json
11 import logging
12 import os
13 import pwd
14 import shlex
15 import socket
16 import stat
17 import subprocess
18 import sys
19 from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Type
20
21 from cockpit._vendor.ferny import interaction_client
22 from cockpit._vendor.systemd_ctypes import bus, run_async
23
24 from . import polyfills
25 from ._version import __version__
26 from .channel import ChannelRoutingRule
27 from .channels import CHANNEL_TYPES
28 from .config import Config, Environment
29 from .internal_endpoints import EXPORTS
30 from .jsonutil import JsonError, JsonObject, JsonValue, get_dict
31 from .packages import BridgeConfig, Packages, PackagesListener
32 from .peer import PeersRoutingRule
33 from .remote import HostRoutingRule
34 from .router import Router
35 from .superuser import SuperuserRoutingRule
36 from .transports import StdioTransport
37
38 logger = logging.getLogger(__name__)
39
40
41 class InternalBus:
42 exportees: List[bus.Slot]
43
44 def __init__(self, exports: Iterable[Tuple[str, Type[bus.BaseObject]]]):
45 client_socket, server_socket = socket.socketpair()
46 self.client = bus.Bus.new(fd=client_socket.detach())
47 self.server = bus.Bus.new(fd=server_socket.detach(), server=True)
48 self.exportees = [self.server.add_object(path, cls()) for path, cls in exports]
49
50 def export(self, path: str, obj: bus.BaseObject) -> None:
51 self.exportees.append(self.server.add_object(path, obj))
52
53
54 class Bridge(Router, PackagesListener):
55 channels: ChannelRoutingRule
56 internal_bus: InternalBus
57 packages: Optional[Packages]
58 bridge_configs: Sequence[BridgeConfig]
59 args: argparse.Namespace
60
61 def __init__(self, args: argparse.Namespace):
62 self.internal_bus = InternalBus(EXPORTS)
63 self.bridge_configs = []
64 self.args = args
65
66 self.superuser_rule = SuperuserRoutingRule(self, privileged=args.privileged)
67 self.internal_bus.export('/superuser', self.superuser_rule)
68
69 config = Config()
70 self.internal_bus.export('/config', config)
71 self.internal_bus.export('/environment', Environment())
72
73 self.peers_rule = PeersRoutingRule(self)
74
75 if args.beipack:
76 # Some special stuff for beipack
77 self.superuser_rule.set_configs((
78 BridgeConfig({
79 "privileged": True,
80 "spawn": ["sudo", "-k", "-A", "python3", "-ic", "# cockpit-bridge", "--privileged"],
81 "environ": ["SUDO_ASKPASS=ferny-askpass"],
82 }),
83 BridgeConfig({
84 "privileged": True,
85 "polkit": True,
86 "method": "StartTransientUnit",
87 "spawn": [sys.executable, "-ic", "# cockpit-bridge", "--privileged"],
88 }),
89 ))
90 self.packages = None
91 elif args.privileged:
92 self.packages = None
93 else:
94 self.packages = Packages(self)
95 self.internal_bus.export('/packages', self.packages)
96 self.packages_loaded()
97
98 self.channels = ChannelRoutingRule(self, CHANNEL_TYPES)
99
100 session_timeout = 0
101 if not args.privileged:
102 session_timeout = config.get_u_int("Session", "IdleTimeout", 0, 240, 0) * 60
103
104 super().__init__([
105 HostRoutingRule(self),
106 self.superuser_rule,
107 self.channels,
108 self.peers_rule,
109 ], session_timeout=session_timeout)
110
111 def info(self) -> JsonObject:
112 pw = pwd.getpwuid(os.getuid())
113
114 # We want the primary group first in the list, without duplicates.
115 # This is a bit awkward because `set()` is unordered...
116 group = grp.getgrgid(pw.pw_gid).gr_name
117 groups = [group]
118 for gr in grp.getgrall():
119 if pw.pw_name in gr.gr_mem and gr.gr_name not in groups:
120 groups.append(gr.gr_name)
121
122 return {
123 'channels': self.channels.capabilities(),
124 'os_release': self.get_os_release(),
125 'user': {
126 'fullname': pw.pw_gecos,
127 'gid': pw.pw_gid,
128 'group': group,
129 'groups': groups,
130 'home': pw.pw_dir,
131 'name': pw.pw_name,
132 'shell': pw.pw_shell,
133 'uid': pw.pw_uid,
134 },
135 }
136
137 @staticmethod
138 def get_os_release() -> JsonObject:
139 try:
140 file = open('/etc/os-release', encoding='utf-8')
141 except FileNotFoundError:
142 try:
143 file = open('/usr/lib/os-release', encoding='utf-8')
144 except FileNotFoundError:
145 logger.warning("Neither /etc/os-release nor /usr/lib/os-release exists")
146 return {}
147
148 with file:
149 return parse_os_release(file.read())
150
151 def do_init(self, message: JsonObject) -> None:
152 # we're only interested in the case where this is a dict, but
153 # 'superuser' may well be `False` and that's not an error
154 with contextlib.suppress(JsonError):
155 superuser = get_dict(message, 'superuser')
156 self.superuser_rule.init(superuser)
157
158 def do_send_init(self) -> None:
159 init_args: 'dict[str, JsonValue]' = {
160 'capabilities': {'explicit-superuser': True},
161 'command': 'init',
162 'os-release': self.get_os_release(),
163 'version': 1,
164 }
165
166 if self.packages is not None:
167 init_args['packages'] = dict.fromkeys(self.packages.packages)
168
169 self.write_control(init_args)
170
171 # PackagesListener interface
172 def packages_loaded(self) -> None:
173 assert self.packages
174 bridge_configs = self.packages.get_bridge_configs()
175 if self.bridge_configs != bridge_configs:
176 self.superuser_rule.set_configs(bridge_configs)
177 self.peers_rule.set_configs(bridge_configs)
178 self.bridge_configs = bridge_configs
179
180
181 async def run(args) -> None:
182 logger.debug("Hi. How are you today?")
183
184 # Unit tests require this
185 me = pwd.getpwuid(os.getuid())
186 os.environ['HOME'] = me.pw_dir
187 os.environ['SHELL'] = me.pw_shell
188 os.environ['USER'] = me.pw_name
189
190 logger.debug('Starting the router.')
191 router = Bridge(args)
192 StdioTransport(asyncio.get_running_loop(), router)
193
194 logger.debug('Startup done. Looping until connection closes.')
195
196 try:
197 await router.communicate()
198 except (BrokenPipeError, ConnectionResetError):
199 # not unexpected if the peer doesn't hang up cleanly
200 pass
201
202
203 def try_to_receive_stderr() -> None:
204 try:
205 ours, theirs = socket.socketpair()
206 with ours:
207 with theirs:
208 interaction_client.command(2, 'cockpit.send-stderr', fds=[theirs.fileno()])
209 _msg, fds, _flags, _addr = socket.recv_fds(ours, 1, 1)
210 except OSError:
211 return
212
213 try:
214 stderr_fd, = fds
215 # We're about to abruptly drop our end of the stderr socketpair that we
216 # share with the ferny agent. ferny would normally treat that as an
217 # unexpected error. Instruct it to do a clean exit, instead.
218 interaction_client.command(2, 'ferny.end')
219 os.dup2(stderr_fd, 2)
220 finally:
221 for fd in fds:
222 os.close(fd)
223
224
225 def setup_journald() -> bool:
226 # If stderr is a socket, prefer systemd-journal logging. This covers the
227 # case we're already connected to the journal but also the case where we're
228 # talking to the ferny agent, while leaving logging to file or terminal
229 # unaffected.
230 if not stat.S_ISSOCK(os.fstat(2).st_mode):
231 # not a socket? Don't redirect.
232 return False
233
234 try:
235 import systemd.journal # type: ignore[import]
236 except ImportError:
237 # No python3-systemd? Don't redirect.
238 return False
239
240 logging.root.addHandler(systemd.journal.JournalHandler())
241 return True
242
243
244 def setup_logging(*, debug: bool) -> None:
245 """Setup our logger with optional filtering of modules if COCKPIT_DEBUG env is set"""
246
247 modules = os.getenv('COCKPIT_DEBUG', '')
248
249 # Either setup logging via journal or via formatted messages to stderr
250 if not setup_journald():
251 logging.basicConfig(format='%(name)s-%(levelname)s: %(message)s')
252
253 if debug or modules == 'all':
254 logging.getLogger().setLevel(level=logging.DEBUG)
255 elif modules:
256 for module in modules.split(','):
257 module = module.strip()
258 if not module:
259 continue
260
261 logging.getLogger(module).setLevel(logging.DEBUG)
262
263
264 def parse_os_release(text: str) -> Dict[str, str]:
265 os_release = {}
266 for line in text.splitlines():
267 line = line.strip()
268 if not line or line.startswith('#'):
269 continue
270 try:
271 k, v = line.split('=')
272 (v_parsed, ) = shlex.split(v) # expect exactly one token
273 except ValueError:
274 logger.warning('Ignoring invalid line in os-release: %r', line)
275 continue
276 os_release[k] = v_parsed
277 return os_release
278
279
280 def start_ssh_agent() -> None:
281 # Launch the agent so that it goes down with us on EOF; PDEATHSIG would be more robust,
282 # but it gets cleared on setgid ssh-agent, which some distros still do
283 try:
284 proc = subprocess.Popen(['ssh-agent', 'sh', '-ec', 'echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK; read a'],
285 stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
286 assert proc.stdout is not None
287
288 # Wait for the agent to write at least one line and look for the
289 # listener socket. If we fail to find it, kill the agent — something
290 # went wrong.
291 for token in shlex.shlex(proc.stdout.readline(), punctuation_chars=True):
292 if token.startswith('SSH_AUTH_SOCK='):
293 os.environ['SSH_AUTH_SOCK'] = token.replace('SSH_AUTH_SOCK=', '', 1)
294 break
295 else:
296 proc.terminate()
297 proc.wait()
298
299 except FileNotFoundError:
300 logger.debug("Couldn't start ssh-agent (FileNotFoundError)")
301
302 except OSError as exc:
303 logger.warning("Could not start ssh-agent: %s", exc)
304
305
306 def main(*, beipack: bool = False) -> None:
307 polyfills.install()
308
309 parser = argparse.ArgumentParser(description='cockpit-bridge is run automatically inside of a Cockpit session.')
310 parser.add_argument('--privileged', action='store_true', help='Privileged copy of the bridge')
311 parser.add_argument('--packages', action='store_true', help='Show Cockpit package information')
312 parser.add_argument('--bridges', action='store_true', help='Show Cockpit bridges information')
313 parser.add_argument('--debug', action='store_true', help='Enable debug output (very verbose)')
314 parser.add_argument('--version', action='store_true', help='Show Cockpit version information')
315 args = parser.parse_args()
316
317 # This is determined by who calls us
318 args.beipack = beipack
319
320 # If we were run with --privileged then our stderr is currently being
321 # consumed by the main bridge looking for startup-related error messages.
322 # Let's switch back to the original stderr stream, which has a side-effect
323 # of indicating that our startup is more or less complete. Any errors
324 # after this point will land in the journal.
325 if args.privileged:
326 try_to_receive_stderr()
327
328 setup_logging(debug=args.debug)
329
330 # Special modes
331 if args.packages:
332 Packages().show()
333 return
334 elif args.version:
335 print(f'Version: {__version__}\nProtocol: 1')
336 return
337 elif args.bridges:
338 print(json.dumps([config.__dict__ for config in Packages().get_bridge_configs()], indent=2))
339 return
340
341 # The privileged bridge doesn't need ssh-agent, but the main one does
342 if 'SSH_AUTH_SOCK' not in os.environ and not args.privileged:
343 start_ssh_agent()
344
345 # asyncio.run() shim for Python 3.6 support
346 run_async(run(args), debug=args.debug)
347
348
349 if __name__ == '__main__':
350 main()