Debian Codegraph @

src/ssh-generator/ssh-generator.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "alloc-util.h"
6 #include "creds-util.h"
7 #include "errno-util.h"
8 #include "fd-util.h"
9 #include "fileio.h"
10 #include "generator.h"
11 #include "install.h"
12 #include "log.h"
13 #include "parse-util.h"
14 #include "path-lookup.h"
15 #include "path-util.h"
16 #include "proc-cmdline.h"
17 #include "socket-netlink.h"
18 #include "socket-util.h"
19 #include "special.h"
20 #include "ssh-util.h"
21 #include "string-util.h"
22 #include "strv.h"
23 #include "virt.h"
24
25 /* A small generator binding potentially five or more SSH sockets:
26 *
27 * 1. Listen on AF_VSOCK port 22 if we run in a VM with AF_VSOCK enabled
28 * 2. Listen on AF_UNIX socket /run/host/unix-export/ssh if we run in a container with /run/host/ support
29 * 3. Listen on AF_UNIX socket /run/ssh-unix-local/socket (always)
30 * 4. Listen on any socket specified via kernel command line option systemd.ssh_listen=
31 * 5. Similar, but from system credential ssh.listen
32 *
33 * The first two provide a nice way for hosts to connect to containers and VMs they invoke via the usual SSH
34 * logic, but without waiting for networking or suchlike. The third allows the same for local clients. */
35
36 static bool arg_auto = true;
37 static char **arg_listen_extra = NULL;
38
39 STATIC_DESTRUCTOR_REGISTER(arg_listen_extra, strv_freep);
40
41 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
42 int r;
43
44 assert(key);
45
46 if (proc_cmdline_key_streq(key, "systemd.ssh_auto")) {
47 r = value ? parse_boolean(value) : 1;
48 if (r < 0)
49 log_warning_errno(r, "Failed to parse systemd.ssh_auto switch \"%s\", ignoring: %m", value);
50 else
51 arg_auto = r;
52
53 } else if (proc_cmdline_key_streq(key, "systemd.ssh_listen")) {
54
55 if (proc_cmdline_value_missing(key, value))
56 return 0;
57
58 SocketAddress sa;
59 r = socket_address_parse(&sa, value);
60 if (r < 0)
61 log_warning_errno(r, "Failed to parse systemd.ssh_listen= expression, ignoring: %s", value);
62 else {
63 _cleanup_free_ char *s = NULL;
64 r = socket_address_print(&sa, &s);
65 if (r < 0)
66 return log_error_errno(r, "Failed to format socket address: %m");
67
68 if (strv_consume(&arg_listen_extra, TAKE_PTR(s)) < 0)
69 return log_oom();
70 }
71 }
72
73 return 0;
74 }
75
76 static int make_sshd_template_unit(
77 const char *dest,
78 const char *template,
79 const char *sshd_binary,
80 const char *found_sshd_template_service,
81 char **generated_sshd_template_unit) {
82
83 int r;
84
85 assert(dest);
86 assert(template);
87 assert(sshd_binary);
88 assert(generated_sshd_template_unit);
89
90 /* If the system has a suitable template already, symlink it under the name we want to use */
91 if (found_sshd_template_service)
92 return generator_add_symlink(
93 dest,
94 template,
95 /* dep_type= */ NULL,
96 found_sshd_template_service);
97
98 if (!*generated_sshd_template_unit) {
99 _cleanup_fclose_ FILE *f = NULL;
100
101 /* We use a generic name for the unit, since we'll use it for both AF_UNIX and AF_VSOCK */
102 r = generator_open_unit_file_full(
103 dest,
104 /* source= */ NULL,
105 "[email protected]",
106 &f,
107 generated_sshd_template_unit,
108 /* ret_temp_path= */ NULL);
109 if (r < 0)
110 return r;
111
112 /* sshd reads AuthorizedKeysFile after dropping to the authenticating user's UID, so the
113 * 0400 credential file under $CREDENTIALS_DIRECTORY is unreadable for non-root users.
114 * Materialize a 0444 copy in a RuntimeDirectory so the ephemeral key works for any user. */
115 fprintf(f,
116 "[Unit]\n"
117 "Description=OpenSSH Per-Connection Server Daemon\n"
118 "Documentation=man:systemd-ssh-generator(8) man:sshd(8)\n"
119 "\n"
120 "[Service]\n"
121 "ExecStartPre=systemd-tmpfiles --create --inline 'f^ /run/sshd-generated-%%i/authorized_keys 0444 root root - ssh.ephemeral-authorized_keys-all'\n"
122 "ExecStart=-%s -i -o \"AuthorizedKeysFile /run/sshd-generated-%%i/authorized_keys .ssh/authorized_keys\"\n"
123 "StandardInput=socket\n"
124 "ImportCredential=ssh.ephemeral-authorized_keys-all\n"
125 "RuntimeDirectory=sshd-generated-%%i\n",
126 sshd_binary);
127
128 r = fflush_and_check(f);
129 if (r < 0)
130 return log_error_errno(r, "Failed to write sshd template: %m");
131 }
132
133 return generator_add_symlink(
134 dest,
135 template,
136 /* dep_type= */ NULL,
137 *generated_sshd_template_unit);
138 }
139
140 static int write_socket_unit(
141 const char *dest,
142 const char *unit,
143 const char *listen_stream,
144 const char *comment,
145 const char *extra,
146 bool with_ssh_access_target_dependency) {
147
148 int r;
149
150 assert(dest);
151 assert(unit);
152 assert(listen_stream);
153 assert(comment);
154
155 _cleanup_fclose_ FILE *f = NULL;
156 r = generator_open_unit_file(
157 dest,
158 /* source= */ NULL,
159 unit,
160 &f);
161 if (r < 0)
162 return r;
163
164 fprintf(f,
165 "[Unit]\n"
166 "Description=OpenSSH Server Socket (systemd-ssh-generator, %s)\n"
167 "Documentation=man:systemd-ssh-generator(8)\n",
168 comment);
169
170 /* When this is a remotely accessible socket let's mark this with a milestone: ssh-access.target */
171 if (with_ssh_access_target_dependency)
172 fputs("Wants=ssh-access.target\n"
173 "Before=ssh-access.target\n",
174 f);
175
176 fprintf(f,
177 "\n[Socket]\n"
178 "ListenStream=%s\n"
179 "Accept=yes\n"
180 "PollLimitIntervalSec=30s\n"
181 "PollLimitBurst=50\n",
182 listen_stream);
183
184 if (extra)
185 fputs(extra, f);
186
187 r = fflush_and_check(f);
188 if (r < 0)
189 return log_error_errno(r, "Failed to write %s SSH socket unit: %m", comment);
190
191 r = generator_add_symlink(
192 dest,
193 SPECIAL_SOCKETS_TARGET,
194 "wants",
195 unit);
196 if (r < 0)
197 return r;
198
199 return 0;
200 }
201
202 static int add_vsock_socket(
203 const char *dest,
204 const char *sshd_binary,
205 const char *found_sshd_template_unit,
206 char **generated_sshd_template_unit) {
207
208 int r;
209
210 assert(dest);
211 assert(generated_sshd_template_unit);
212
213 Virtualization v = detect_virtualization();
214 if (v < 0)
215 return log_error_errno(v, "Failed to detect if we run in a VM: %m");
216 if (!VIRTUALIZATION_IS_VM(v)) {
217 /* NB: if we are running in a container inside a VM, then we'll *not* do AF_VSOCK stuff */
218 log_debug("Not running in a VM, not listening on AF_VSOCK.");
219 return 0;
220 }
221
222 r = vsock_open_or_warn(/* ret= */ NULL);
223 if (r <= 0)
224 return r;
225
226 /* Determine the local CID so that we can log it to help users to connect to this VM */
227 unsigned local_cid;
228 r = vsock_get_local_cid_or_warn(&local_cid);
229 if (r <= 0)
230 return r;
231
232 r = make_sshd_template_unit(
233 dest,
234 "[email protected]",
235 sshd_binary,
236 found_sshd_template_unit,
237 generated_sshd_template_unit);
238 if (r < 0)
239 return r;
240
241 r = write_socket_unit(
242 dest,
243 "sshd-vsock.socket",
244 "vsock::22",
245 "AF_VSOCK",
246 "ExecStartPost=-/usr/lib/systemd/systemd-ssh-issue make-vsock\n"
247 "ExecStopPre=-/usr/lib/systemd/systemd-ssh-issue rm-vsock\n",
248 /* with_ssh_access_target_dependency= */ true);
249 if (r < 0)
250 return r;
251
252 log_debug("Binding SSH to AF_VSOCK vsock::22.\n"
253 "→ connect via 'ssh vsock/%u' from host", local_cid);
254 return 0;
255 }
256
257 static int add_local_unix_socket(
258 const char *dest,
259 const char *sshd_binary,
260 const char *found_sshd_template_unit,
261 char **generated_sshd_template_unit) {
262
263 int r;
264
265 assert(dest);
266 assert(sshd_binary);
267 assert(generated_sshd_template_unit);
268
269 r = make_sshd_template_unit(
270 dest,
271 "[email protected]",
272 sshd_binary,
273 found_sshd_template_unit,
274 generated_sshd_template_unit);
275 if (r < 0)
276 return r;
277
278 r = write_socket_unit(
279 dest,
280 "sshd-unix-local.socket",
281 "/run/ssh-unix-local/socket",
282 "AF_UNIX Local",
283 /* extra= */ NULL,
284 /* with_ssh_access_target_dependency= */ false);
285 if (r < 0)
286 return r;
287
288 log_debug("Binding SSH to AF_UNIX socket /run/ssh-unix-local/socket.\n"
289 "→ connect via 'ssh .host' locally");
290 return 0;
291 }
292
293 static int add_export_unix_socket(
294 const char *dest,
295 const char *sshd_binary,
296 const char *found_sshd_template_unit,
297 char **generated_sshd_template_unit) {
298
299 int r;
300
301 assert(dest);
302 assert(sshd_binary);
303 assert(generated_sshd_template_unit);
304
305 Virtualization v = detect_container();
306 if (v < 0)
307 return log_error_errno(v, "Failed to detect if we run in a container: %m");
308 if (v == VIRTUALIZATION_NONE) {
309 log_debug("Not running in container, not listening on /run/host/unix-export/ssh");
310 return 0;
311 }
312
313 if (access("/run/host/unix-export/", W_OK) < 0) {
314 if (errno == ENOENT) {
315 log_debug("Container manager does not provide /run/host/unix-export/ mount, not binding AF_UNIX socket there.");
316 return 0;
317 }
318 if (ERRNO_IS_FS_WRITE_REFUSED(errno)) {
319 log_debug("Container manager does not provide write access to /run/host/unix-export/, not binding AF_UNIX socket there.");
320 return 0;
321 }
322
323 return log_error_errno(errno, "Unable to check if /run/host/unix-export exists: %m");
324 }
325
326 r = make_sshd_template_unit(
327 dest,
328 "[email protected]",
329 sshd_binary,
330 found_sshd_template_unit,
331 generated_sshd_template_unit);
332 if (r < 0)
333 return r;
334
335 r = write_socket_unit(
336 dest,
337 "sshd-unix-export.socket",
338 "/run/host/unix-export/ssh",
339 "AF_UNIX Export",
340 /* extra= */ NULL,
341 /* with_ssh_access_target_dependency= */ true);
342 if (r < 0)
343 return r;
344
345 log_debug("Binding SSH to AF_UNIX socket /run/host/unix-export/ssh\n"
346 "→ connect via 'ssh unix/run/systemd/nspawn/\?\?\?/unix-export/ssh' from host");
347
348 return 0;
349 }
350
351 static int add_extra_sockets(
352 const char *dest,
353 const char *sshd_binary,
354 const char *found_sshd_template_unit,
355 char **generated_sshd_template_unit) {
356
357 unsigned n = 1;
358 int r;
359
360 assert(dest);
361 assert(sshd_binary);
362 assert(generated_sshd_template_unit);
363
364 STRV_FOREACH(i, arg_listen_extra) {
365 _cleanup_free_ char *service = NULL, *socket = NULL;
366
367 if (n > 1) {
368 if (asprintf(&service, "sshd-extra-%[email protected]", n) < 0)
369 return log_oom();
370
371 if (asprintf(&socket, "sshd-extra-%u.socket", n) < 0)
372 return log_oom();
373 }
374
375 r = make_sshd_template_unit(
376 dest,
377 service ?: "[email protected]",
378 sshd_binary,
379 found_sshd_template_unit,
380 generated_sshd_template_unit);
381 if (r < 0)
382 return r;
383
384 r = write_socket_unit(
385 dest,
386 socket ?: "sshd-extra.socket",
387 *i,
388 *i,
389 /* extra= */ NULL,
390 /* with_ssh_access_target_dependency= */ true);
391 if (r < 0)
392 return r;
393
394 log_debug("Binding SSH to socket %s.", *i);
395 n++;
396 }
397
398 return 0;
399 }
400
401 static int parse_credentials(void) {
402 _cleanup_free_ char *b = NULL;
403 size_t sz = 0;
404 int r;
405
406 r = read_credential_with_decryption("ssh.listen", (void**) &b, &sz);
407 if (r <= 0)
408 return r;
409
410 _cleanup_fclose_ FILE *f = NULL;
411 f = fmemopen_unlocked(b, sz, "r");
412 if (!f)
413 return log_oom();
414
415 for (;;) {
416 _cleanup_free_ char *item = NULL;
417
418 r = read_stripped_line(f, LINE_MAX, &item);
419 if (r == 0)
420 break;
421 if (r < 0) {
422 log_error_errno(r, "Failed to parse credential 'ssh.listen': %m");
423 break;
424 }
425
426 if (startswith(item, "#"))
427 continue;
428
429 SocketAddress sa;
430 r = socket_address_parse(&sa, item);
431 if (r < 0) {
432 log_warning_errno(r, "Failed to parse systemd.ssh_listen= expression, ignoring: %s", item);
433 continue;
434 }
435
436 _cleanup_free_ char *s = NULL;
437 r = socket_address_print(&sa, &s);
438 if (r < 0)
439 return log_error_errno(r, "Failed to format socket address: %m");
440
441 if (strv_consume(&arg_listen_extra, TAKE_PTR(s)) < 0)
442 return log_oom();
443 }
444
445 return 0;
446 }
447
448 static int run(const char *dest, const char *dest_early, const char *dest_late) {
449 int r;
450
451 assert(dest);
452
453 r = proc_cmdline_parse(parse_proc_cmdline_item, /* userdata= */ NULL, /* flags= */ 0);
454 if (r < 0)
455 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
456
457 (void) parse_credentials();
458
459 strv_sort_uniq(arg_listen_extra);
460
461 if (!arg_auto && strv_isempty(arg_listen_extra)) {
462 log_debug("Disabling SSH generator logic, because it has been turned off explicitly.");
463 return 0;
464 }
465
466 _cleanup_free_ char *sshd_binary = NULL;
467 r = find_executable("sshd", &sshd_binary);
468 if (r == -ENOENT) {
469 log_debug("Disabling SSH generator logic, since sshd is not installed.");
470 return 0;
471 }
472 if (r < 0)
473 return log_error_errno(r, "Failed to determine if sshd is installed: %m");
474
475 _cleanup_(lookup_paths_done) LookupPaths lp = {};
476 r = lookup_paths_init_or_warn(&lp, RUNTIME_SCOPE_SYSTEM, LOOKUP_PATHS_EXCLUDE_GENERATED, /* root_dir= */ NULL);
477 if (r < 0)
478 return r;
479
480 _cleanup_free_ char *found_sshd_template_unit = NULL;
481 r = unit_file_exists_full(RUNTIME_SCOPE_SYSTEM, &lp,
482 SEARCH_FOLLOW_CONFIG_SYMLINKS,
483 "[email protected]",
484 &found_sshd_template_unit);
485 if (r < 0)
486 return log_error_errno(r, "Unable to detect if [email protected] exists: %m");
487
488 _cleanup_free_ char *generated_sshd_template_unit = NULL;
489 RET_GATHER(r, add_extra_sockets(dest, sshd_binary, found_sshd_template_unit, &generated_sshd_template_unit));
490
491 if (arg_auto) {
492 RET_GATHER(r, add_vsock_socket(dest, sshd_binary, found_sshd_template_unit, &generated_sshd_template_unit));
493 RET_GATHER(r, add_local_unix_socket(dest, sshd_binary, found_sshd_template_unit, &generated_sshd_template_unit));
494 RET_GATHER(r, add_export_unix_socket(dest, sshd_binary, found_sshd_template_unit, &generated_sshd_template_unit));
495 }
496
497 return r;
498 }
499
500 DEFINE_MAIN_GENERATOR_FUNCTION(run);