Debian Codegraph @

src/core/exec-invoke.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <grp.h>
4 #include <linux/securebits.h>
5 #include <poll.h>
6 #include <sched.h>
7 #include <sys/eventfd.h>
8 #include <sys/ioctl.h>
9 #include <sys/ioprio.h>
10 #include <sys/keyctl.h>
11 #include <sys/mount.h>
12 #include <sys/prctl.h>
13 #include <sys/statvfs.h>
14 #include <unistd.h>
15
16 #include "sd-messages.h"
17 #include "sd-varlink.h"
18
19 #include "apparmor-util.h" /* IWYU pragma: keep */
20 #include "argv-util.h"
21 #include "ask-password-api.h"
22 #include "barrier.h"
23 #include "bitfield.h"
24 #include "bpf-util.h"
25 #include "bpf-restrict-fs.h"
26 #include "btrfs-util.h"
27 #include "capability-util.h"
28 #include "cgroup-setup.h"
29 #include "cgroup.h"
30 #include "chase.h"
31 #include "chattr-util.h"
32 #include "chown-recursive.h"
33 #include "constants.h"
34 #include "copy.h"
35 #include "coredump-util.h"
36 #include "cryptsetup-util.h"
37 #include "dissect-image.h"
38 #include "dynamic-user.h"
39 #include "env-util.h"
40 #include "escape.h"
41 #include "exec-credential.h"
42 #include "exec-invoke.h"
43 #include "execute.h"
44 #include "exit-status.h"
45 #include "fd-util.h"
46 #include "fs-util.h"
47 #include "hexdecoct.h"
48 #include "hostname-setup.h"
49 #include "image-policy.h"
50 #include "io-util.h"
51 #include "iovec-util.h"
52 #include "journal-send.h"
53 #include "libmount-util.h"
54 #include "manager.h"
55 #include "memfd-util.h"
56 #include "mkdir.h"
57 #include "mount-util.h"
58 #include "mountpoint-util.h"
59 #include "mstack.h"
60 #include "namespace-util.h"
61 #include "nsflags.h"
62 #include "nsresource.h"
63 #include "open-file.h"
64 #include "osc-context.h"
65 #include "pam-util.h"
66 #include "path-util.h"
67 #include "pidfd-util.h"
68 #include "pidref.h"
69 #include "proc-cmdline.h"
70 #include "process-util.h"
71 #include "psi-util.h"
72 #include "quota-util.h"
73 #include "random-util.h"
74 #include "rlimit-util.h"
75 #include "seccomp-util.h"
76 #include "selinux-util.h"
77 #include "set.h"
78 #include "signal-util.h"
79 #include "siphash24.h"
80 #include "smack-util.h"
81 #include "socket-util.h"
82 #include "stat-util.h"
83 #include "string-table.h"
84 #include "strv.h"
85 #include "strxcpyx.h"
86 #include "terminal-util.h"
87 #include "uid-range.h"
88 #include "user-util.h"
89 #include "utmp-wtmp.h"
90 #include "vpick.h"
91
92 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
93 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
94
95 #define SNDBUF_SIZE (8*1024*1024)
96
97 /* Project id range for disk quotas */
98 #define PROJ_ID_MIN UINT32_C(2147483648)
99 #define PROJ_ID_MAX UINT32_C(4294967294)
100 #define PROJ_ID_CLAMP_INTO_QUOTA_RANGE(id) ((uint32_t) ((id) % (PROJ_ID_MAX - PROJ_ID_MIN + 1)) + PROJ_ID_MIN)
101
102 static int flag_fds(
103 const int fds[],
104 size_t n_socket_fds,
105 size_t n_fds,
106 bool nonblock) {
107
108 int r;
109
110 assert(fds || n_fds == 0);
111
112 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
113 * O_NONBLOCK only applies to socket activation though. */
114
115 for (size_t i = 0; i < n_fds; i++) {
116
117 if (i < n_socket_fds) {
118 r = fd_nonblock(fds[i], nonblock);
119 if (r < 0)
120 return r;
121 }
122
123 /* We unconditionally drop FD_CLOEXEC from the fds,
124 * since after all we want to pass these fds to our
125 * children */
126
127 r = fd_cloexec(fds[i], false);
128 if (r < 0)
129 return r;
130 }
131
132 return 0;
133 }
134
135 static int open_null_as(int flags, int nfd) {
136 int fd;
137
138 assert(nfd >= 0);
139
140 fd = open("/dev/null", flags|O_NOCTTY);
141 if (fd < 0)
142 return -errno;
143
144 return move_fd(fd, nfd, false);
145 }
146
147 static int connect_journal_socket(
148 int fd,
149 const char *log_namespace,
150 uid_t uid,
151 gid_t gid) {
152
153 uid_t olduid = UID_INVALID;
154 gid_t oldgid = GID_INVALID;
155 const char *j;
156 int r;
157
158 assert(fd >= 0);
159
160 j = journal_stream_path(log_namespace);
161 if (!j)
162 return -EINVAL;
163
164 if (gid_is_valid(gid)) {
165 oldgid = getgid();
166
167 if (setegid(gid) < 0)
168 return -errno;
169 }
170
171 if (uid_is_valid(uid)) {
172 olduid = getuid();
173
174 if (seteuid(uid) < 0) {
175 r = -errno;
176 goto restore_gid;
177 }
178 }
179
180 r = connect_unix_path(fd, AT_FDCWD, j);
181
182 /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
183 an LSM interferes. */
184
185 if (uid_is_valid(uid))
186 (void) seteuid(olduid);
187
188 restore_gid:
189 if (gid_is_valid(gid))
190 (void) setegid(oldgid);
191
192 return r;
193 }
194
195 static bool exec_output_forward_to_console(ExecOutput o) {
196 return IN_SET(o,
197 EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
198 EXEC_OUTPUT_KMSG_AND_CONSOLE);
199 }
200
201 static bool exec_output_forward_to_kmsg(ExecOutput o) {
202 return IN_SET(o,
203 EXEC_OUTPUT_KMSG,
204 EXEC_OUTPUT_KMSG_AND_CONSOLE);
205 }
206
207 static int connect_logger_as(
208 const ExecContext *context,
209 const ExecParameters *params,
210 ExecOutput output,
211 const char *ident,
212 int nfd,
213 uid_t uid,
214 gid_t gid) {
215
216 _cleanup_close_ int fd = -EBADF;
217 int r;
218
219 assert(context);
220 assert(params);
221 assert(output < _EXEC_OUTPUT_MAX);
222 assert(ident);
223 assert(nfd >= 0);
224
225 fd = socket(AF_UNIX, SOCK_STREAM, 0);
226 if (fd < 0)
227 return -errno;
228
229 r = connect_journal_socket(fd, context->log_namespace, uid, gid);
230 if (r < 0)
231 return r;
232
233 if (shutdown(fd, SHUT_RD) < 0)
234 return -errno;
235
236 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
237
238 if (dprintf(fd,
239 "%s\n"
240 "%s\n"
241 "%i\n"
242 "%i\n"
243 "%i\n"
244 "%i\n"
245 "%i\n",
246 context->syslog_identifier ?: ident,
247 params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
248 context->syslog_priority,
249 !!context->syslog_level_prefix,
250 false,
251 exec_output_forward_to_kmsg(output),
252 exec_output_forward_to_console(output)) < 0)
253 return -errno;
254
255 return move_fd(TAKE_FD(fd), nfd, false);
256 }
257
258 static int open_terminal_as(const char *path, int flags, int nfd) {
259 int fd;
260
261 assert(path);
262 assert(nfd >= 0);
263
264 fd = open_terminal(path, flags | O_NOCTTY);
265 if (fd < 0)
266 return fd;
267
268 return move_fd(fd, nfd, false);
269 }
270
271 static int acquire_path(const char *path, int flags, mode_t mode) {
272 _cleanup_close_ int fd = -EBADF;
273 int r;
274
275 assert(path);
276
277 if (IN_SET(flags & O_ACCMODE_STRICT, O_WRONLY, O_RDWR))
278 flags |= O_CREAT;
279
280 fd = open(path, flags|O_NOCTTY, mode);
281 if (fd >= 0)
282 return TAKE_FD(fd);
283
284 if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
285 return -errno;
286
287 /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
288
289 fd = socket(AF_UNIX, SOCK_STREAM, 0);
290 if (fd < 0)
291 return -errno;
292
293 r = connect_unix_path(fd, AT_FDCWD, path);
294 if (IN_SET(r, -ENOTSOCK, -EINVAL))
295 /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
296 * wasn't an AF_UNIX socket after all */
297 return -ENXIO;
298 if (r < 0)
299 return r;
300
301 if ((flags & O_ACCMODE_STRICT) == O_RDONLY)
302 r = shutdown(fd, SHUT_WR);
303 else if ((flags & O_ACCMODE_STRICT) == O_WRONLY)
304 r = shutdown(fd, SHUT_RD);
305 else
306 r = 0;
307 if (r < 0)
308 return -errno;
309
310 return TAKE_FD(fd);
311 }
312
313 static int fixup_input(
314 const ExecContext *context,
315 bool apply_tty_stdin) {
316
317 ExecInput std_input;
318
319 assert(context);
320
321 std_input = context->std_input;
322
323 if (exec_input_is_terminal(std_input) && !apply_tty_stdin)
324 return EXEC_INPUT_NULL;
325
326 if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
327 return EXEC_INPUT_NULL;
328
329 return std_input;
330 }
331
332 static int setup_input(
333 const ExecContext *context,
334 const ExecParameters *params,
335 int socket_fd,
336 const int named_iofds[static 3]) {
337
338 ExecInput i;
339 int r;
340
341 assert(context);
342 assert(params);
343 assert(named_iofds);
344
345 if (params->stdin_fd >= 0) {
346 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
347 return -errno;
348
349 /* Try to make this our controlling tty, if it is a tty */
350 if (isatty_safe(STDIN_FILENO) && ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE) < 0)
351 log_debug_errno(errno, "Failed to make standard input TTY our controlling terminal: %m");
352
353 return STDIN_FILENO;
354 }
355
356 i = fixup_input(context, params->flags & EXEC_APPLY_TTY_STDIN);
357
358 switch (i) {
359
360 case EXEC_INPUT_NULL:
361 return open_null_as(O_RDONLY, STDIN_FILENO);
362
363 case EXEC_INPUT_TTY:
364 case EXEC_INPUT_TTY_FORCE:
365 case EXEC_INPUT_TTY_FAIL: {
366 _cleanup_close_ int tty_fd = -EBADF;
367 _cleanup_free_ char *resolved = NULL;
368 const char *tty_path;
369
370 tty_path = ASSERT_PTR(exec_context_tty_path(context));
371
372 if (tty_is_console(tty_path)) {
373 r = resolve_dev_console(&resolved);
374 if (r < 0)
375 log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
376 else {
377 log_debug("Resolved /dev/console to %s", resolved);
378 tty_path = resolved;
379 }
380 }
381
382 tty_fd = acquire_terminal(tty_path,
383 i == EXEC_INPUT_TTY_FAIL ? ACQUIRE_TERMINAL_TRY :
384 i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
385 ACQUIRE_TERMINAL_WAIT,
386 USEC_INFINITY);
387 if (tty_fd < 0)
388 return tty_fd;
389
390 r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
391 if (r < 0)
392 return r;
393
394 TAKE_FD(tty_fd);
395 return r;
396 }
397
398 case EXEC_INPUT_SOCKET:
399 assert(socket_fd >= 0);
400
401 return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
402
403 case EXEC_INPUT_NAMED_FD:
404 assert(named_iofds[STDIN_FILENO] >= 0);
405
406 (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
407 return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
408
409 case EXEC_INPUT_DATA: {
410 int fd;
411
412 fd = memfd_new_and_seal("exec-input", context->stdin_data, context->stdin_data_size);
413 if (fd < 0)
414 return fd;
415
416 return move_fd(fd, STDIN_FILENO, false);
417 }
418
419 case EXEC_INPUT_FILE: {
420 bool rw;
421 int fd;
422
423 assert(context->stdio_file[STDIN_FILENO]);
424
425 rw = (context->std_output == EXEC_OUTPUT_FILE && path_equal(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
426 (context->std_error == EXEC_OUTPUT_FILE && path_equal(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
427
428 fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
429 if (fd < 0)
430 return fd;
431
432 return move_fd(fd, STDIN_FILENO, false);
433 }
434
435 default:
436 assert_not_reached();
437 }
438 }
439
440 static bool can_inherit_stderr_from_stdout(const ExecContext *context) {
441 ExecOutput o, e;
442
443 assert(context);
444
445 /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
446 * stderr fd */
447
448 o = context->std_output;
449 e = context->std_error;
450
451 if (e == EXEC_OUTPUT_INHERIT)
452 return true;
453 if (e != o)
454 return false;
455
456 /* Let's not shortcut named fds here, even though we in theory can by comparing fd names, since
457 * we have the named_iofds array readily available, and the inherit practice would simply be duplicative. */
458 if (e == EXEC_OUTPUT_NAMED_FD)
459 return false;
460
461 if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
462 return path_equal(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
463
464 return true;
465 }
466
467 static int maybe_inherit_stdout_from_stdin(const ExecContext *context, ExecInput i) {
468 int r;
469
470 assert(context);
471
472 if (context->std_output != EXEC_OUTPUT_INHERIT)
473 return 0;
474
475 /* If input got downgraded, inherit the original value */
476 if (i == EXEC_INPUT_NULL && exec_input_is_terminal(context->std_input))
477 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, STDOUT_FILENO);
478
479 if (!exec_input_is_inheritable(i))
480 goto fallback;
481
482 r = fd_is_writable(STDIN_FILENO);
483 if (r <= 0) {
484 if (r < 0)
485 log_warning_errno(r, "Failed to check if inherited stdin is writable for stdout, using fallback: %m");
486 else
487 log_warning("Inherited stdin is not writable for stdout, using fallback: %m");
488 goto fallback;
489 }
490
491 return RET_NERRNO(dup2(STDIN_FILENO, STDOUT_FILENO));
492
493 fallback:
494 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
495 if (getppid() != 1)
496 return STDOUT_FILENO;
497
498 /* We need to open /dev/null here anew, to get the right access mode. */
499 return open_null_as(O_WRONLY, STDOUT_FILENO);
500 }
501
502 static int setup_output(
503 const ExecContext *context,
504 const ExecParameters *params,
505 int fileno,
506 int socket_fd,
507 const int named_iofds[static 3],
508 const char *ident,
509 uid_t uid,
510 gid_t gid,
511 dev_t *journal_stream_dev,
512 ino_t *journal_stream_ino) {
513
514 ExecOutput o;
515 ExecInput i;
516 int r;
517
518 assert(context);
519 assert(params);
520 assert(ident);
521 assert(journal_stream_dev);
522 assert(journal_stream_ino);
523
524 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
525
526 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
527 return -errno;
528
529 return STDOUT_FILENO;
530 }
531
532 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
533 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
534 return -errno;
535
536 return STDERR_FILENO;
537 }
538
539 i = fixup_input(context, params->flags & EXEC_APPLY_TTY_STDIN);
540
541 if (fileno == STDERR_FILENO) {
542 /* This expects the input and output are already set up */
543
544 /* Don't change the stderr file descriptor if we inherit all
545 * the way and are not on a tty */
546 if (context->std_error == EXEC_OUTPUT_INHERIT &&
547 context->std_output == EXEC_OUTPUT_INHERIT &&
548 i == EXEC_INPUT_NULL && !exec_input_is_terminal(context->std_input) &&
549 getppid() != 1)
550 return fileno;
551
552 /* Duplicate from stdout if possible */
553 if (can_inherit_stderr_from_stdout(context))
554 return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
555
556 o = context->std_error;
557
558 } else {
559 assert(fileno == STDOUT_FILENO);
560
561 r = maybe_inherit_stdout_from_stdin(context, i);
562 if (r != 0)
563 return r;
564
565 o = context->std_output;
566 }
567
568 switch (o) {
569
570 case EXEC_OUTPUT_NULL:
571 return open_null_as(O_WRONLY, fileno);
572
573 case EXEC_OUTPUT_TTY:
574 if (exec_input_is_terminal(i)) {
575 r = fd_is_writable(STDIN_FILENO);
576 if (r <= 0) {
577 if (r < 0)
578 log_warning_errno(r, "Failed to check if inherited stdin is writable for TTY's %s, falling back to opening terminal.",
579 fileno == STDOUT_FILENO ? "stdout" : "stderr");
580 else
581 log_warning("Inherited stdin is not writable for TTY's %s, falling back to opening terminal.",
582 fileno == STDOUT_FILENO ? "stdout" : "stderr");
583 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
584 }
585 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
586 }
587
588 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
589
590 case EXEC_OUTPUT_KMSG:
591 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
592 case EXEC_OUTPUT_JOURNAL:
593 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
594 r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
595 if (r < 0) {
596 log_warning_errno(r, "Failed to connect %s to the journal socket, ignoring: %m",
597 fileno == STDOUT_FILENO ? "stdout" : "stderr");
598 r = open_null_as(O_WRONLY, fileno);
599 } else {
600 struct stat st;
601
602 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
603 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
604 * services to detect whether they are connected to the journal or not.
605 *
606 * If both stdout and stderr are connected to a stream then let's make sure to store the data
607 * about STDERR as that's usually the best way to do logging. */
608
609 if (fstat(fileno, &st) >= 0 &&
610 (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
611 *journal_stream_dev = st.st_dev;
612 *journal_stream_ino = st.st_ino;
613 }
614 }
615 return r;
616
617 case EXEC_OUTPUT_SOCKET:
618 assert(socket_fd >= 0);
619
620 return RET_NERRNO(dup2(socket_fd, fileno));
621
622 case EXEC_OUTPUT_NAMED_FD:
623 assert(named_iofds[fileno] >= 0);
624
625 (void) fd_nonblock(named_iofds[fileno], false);
626 return RET_NERRNO(dup2(named_iofds[fileno], fileno));
627
628 case EXEC_OUTPUT_FILE:
629 case EXEC_OUTPUT_FILE_APPEND:
630 case EXEC_OUTPUT_FILE_TRUNCATE: {
631 int fd, flags;
632
633 assert(context->stdio_file[fileno]);
634
635 /* stdin points to the same file hence setup_input() opened it as rw already?
636 * Then just duplicate it. */
637 if (context->std_input == EXEC_INPUT_FILE &&
638 path_equal(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]))
639 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
640
641 flags = O_WRONLY;
642 if (o == EXEC_OUTPUT_FILE_APPEND)
643 flags |= O_APPEND;
644 else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
645 flags |= O_TRUNC;
646
647 fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
648 if (fd < 0)
649 return fd;
650
651 return move_fd(fd, fileno, 0);
652 }
653
654 default:
655 assert_not_reached();
656 }
657 }
658
659 static int chown_terminal(int fd, uid_t uid) {
660 int r;
661
662 assert(fd >= 0);
663
664 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
665 if (!isatty_safe(fd))
666 return 0;
667
668 /* This might fail. What matters are the results. */
669 r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
670 if (r < 0)
671 return r;
672
673 return 1;
674 }
675
676 static int setup_confirm_stdio(
677 const ExecContext *context,
678 const char *vc,
679 int *ret_saved_stdin,
680 int *ret_saved_stdout) {
681
682 _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
683 int r;
684
685 assert(context);
686 assert(ret_saved_stdin);
687 assert(ret_saved_stdout);
688
689 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);
690 if (saved_stdin < 0)
691 return -errno;
692
693 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);
694 if (saved_stdout < 0)
695 return -errno;
696
697 fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
698 if (fd < 0)
699 return fd;
700
701 _cleanup_close_ int lock_fd = lock_dev_console();
702 if (lock_fd < 0)
703 log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
704
705 r = chown_terminal(fd, getuid());
706 if (r < 0)
707 return r;
708
709 r = terminal_reset_defensive(fd, TERMINAL_RESET_SWITCH_TO_TEXT);
710 if (r < 0)
711 return r;
712
713 r = exec_context_apply_tty_size(context, fd, fd, vc);
714 if (r < 0)
715 return r;
716
717 r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
718 TAKE_FD(fd);
719 if (r < 0)
720 return r;
721
722 *ret_saved_stdin = TAKE_FD(saved_stdin);
723 *ret_saved_stdout = TAKE_FD(saved_stdout);
724 return 0;
725 }
726
727 static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
728 assert(err != 0);
729 assert(fd >= 0);
730 assert(unit_id);
731
732 errno = abs(err);
733
734 if (errno == ETIMEDOUT)
735 dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
736 else
737 dprintf(fd, "Couldn't ask confirmation for %s, assuming positive response: %m\n", unit_id);
738 }
739
740 static void write_confirm_error(int err, const char *vc, const char *unit_id) {
741 _cleanup_close_ int fd = -EBADF;
742
743 assert(vc);
744
745 fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
746 if (fd < 0)
747 return;
748
749 write_confirm_error_fd(err, fd, unit_id);
750 }
751
752 static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
753 int r = 0;
754
755 assert(saved_stdin);
756 assert(saved_stdout);
757
758 release_terminal();
759
760 if (*saved_stdin >= 0)
761 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
762 r = -errno;
763
764 if (*saved_stdout >= 0)
765 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
766 r = -errno;
767
768 *saved_stdin = safe_close(*saved_stdin);
769 *saved_stdout = safe_close(*saved_stdout);
770
771 return r;
772 }
773
774 enum {
775 CONFIRM_PRETEND_FAILURE = -1,
776 CONFIRM_PRETEND_SUCCESS = 0,
777 CONFIRM_EXECUTE = 1,
778 };
779
780 static bool confirm_spawn_disabled(void) {
781 return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
782 }
783
784 static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
785 int saved_stdout = -EBADF, saved_stdin = -EBADF, r;
786 _cleanup_free_ char *e = NULL;
787 char c;
788
789 assert(context);
790 assert(params);
791
792 /* For any internal errors, assume a positive response. */
793 r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
794 if (r < 0) {
795 write_confirm_error(r, params->confirm_spawn, params->unit_id);
796 return CONFIRM_EXECUTE;
797 }
798
799 /* confirm_spawn might have been disabled while we were sleeping. */
800 if (!params->confirm_spawn || confirm_spawn_disabled()) {
801 r = 1;
802 goto restore_stdio;
803 }
804
805 e = ellipsize(cmdline, 60, 100);
806 if (!e) {
807 log_oom();
808 r = CONFIRM_EXECUTE;
809 goto restore_stdio;
810 }
811
812 for (;;) {
813 r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
814 if (r < 0) {
815 write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
816 r = CONFIRM_EXECUTE;
817 goto restore_stdio;
818 }
819
820 switch (c) {
821 case 'c':
822 printf("Resuming normal execution.\n");
823 manager_disable_confirm_spawn();
824 r = 1;
825 break;
826 case 'D':
827 printf(" Unit: %s\n",
828 params->unit_id);
829 exec_context_dump(context, stdout, " ");
830 exec_params_dump(params, stdout, " ");
831 continue; /* ask again */
832 case 'f':
833 printf("Failing execution.\n");
834 r = CONFIRM_PRETEND_FAILURE;
835 break;
836 case 'h':
837 printf(" c - continue, proceed without asking anymore\n"
838 " D - dump, show the state of the unit\n"
839 " f - fail, don't execute the command and pretend it failed\n"
840 " h - help\n"
841 " i - info, show a short summary of the unit\n"
842 " j - jobs, show jobs that are in progress\n"
843 " s - skip, don't execute the command and pretend it succeeded\n"
844 " y - yes, execute the command\n");
845 continue; /* ask again */
846 case 'i':
847 printf(" Unit: %s\n"
848 " Command: %s\n",
849 params->unit_id, cmdline);
850 continue; /* ask again */
851 case 'j':
852 if (sigqueue(getppid(),
853 SIGRTMIN+18,
854 (const union sigval) { .sival_int = MANAGER_SIGNAL_COMMAND_DUMP_JOBS }) < 0)
855 return -errno;
856
857 continue; /* ask again */
858 case 'n':
859 /* 'n' was removed in favor of 'f'. */
860 printf("Didn't understand 'n', did you mean 'f'?\n");
861 continue; /* ask again */
862 case 's':
863 printf("Skipping execution.\n");
864 r = CONFIRM_PRETEND_SUCCESS;
865 break;
866 case 'y':
867 r = CONFIRM_EXECUTE;
868 break;
869 default:
870 assert_not_reached();
871 }
872 break;
873 }
874
875 restore_stdio:
876 restore_confirm_stdio(&saved_stdin, &saved_stdout);
877 return r;
878 }
879
880 static int get_supplementary_groups(
881 const ExecContext *c,
882 const char *user,
883 gid_t gid,
884 gid_t **ret_gids) {
885
886 int r;
887
888 assert(c);
889 assert(ret_gids);
890
891 /*
892 * If user is given, then lookup GID and supplementary groups list.
893 * We avoid NSS lookups for gid=0. Also we have to initialize groups
894 * here and as early as possible so we keep the list of supplementary
895 * groups of the caller.
896 */
897 bool keep_groups = false;
898 if (user && gid_is_valid(gid) && gid != 0) {
899 /* First step, initialize groups from /etc/groups */
900 if (initgroups(user, gid) < 0) {
901 /* If our primary gid is already the one specified in Group= (i.e. we're running in
902 * user mode), gracefully handle the case where we have no privilege to re-initgroups().
903 *
904 * Note that group memberships of the current user might have been modified, but
905 * the change will only take effect after re-login. It's better to continue on with
906 * existing credentials rather than erroring out. */
907 if (!ERRNO_IS_PRIVILEGE(errno) || gid != getgid())
908 return -errno;
909 }
910
911 keep_groups = true;
912 }
913
914 if (strv_isempty(c->supplementary_groups)) {
915 *ret_gids = NULL;
916 return 0;
917 }
918
919 /*
920 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
921 * be positive, otherwise fail.
922 */
923 errno = 0;
924 int ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
925 if (ngroups_max <= 0)
926 return errno_or_else(EOPNOTSUPP);
927
928 _cleanup_free_ gid_t *l_gids = new(gid_t, ngroups_max);
929 if (!l_gids)
930 return -ENOMEM;
931
932 int k = 0;
933 if (keep_groups) {
934 /*
935 * Lookup the list of groups that the user belongs to, we
936 * avoid NSS lookups here too for gid=0.
937 */
938 k = ngroups_max;
939 if (getgrouplist(user, gid, l_gids, &k) < 0)
940 return -EINVAL;
941 }
942
943 STRV_FOREACH(i, c->supplementary_groups) {
944 if (k >= ngroups_max)
945 return -E2BIG;
946
947 r = get_group_creds(*i, /* flags= */ 0, /* ret_name= */ NULL, l_gids + k);
948 if (r < 0)
949 return r;
950
951 k++;
952 }
953
954 if (k == 0) {
955 *ret_gids = NULL;
956 return 0;
957 }
958
959 /* Otherwise get the final list of supplementary groups */
960 gid_t *groups = newdup(gid_t, l_gids, k);
961 if (!groups)
962 return -ENOMEM;
963
964 *ret_gids = groups;
965 return k;
966 }
967
968 static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
969 int r;
970
971 /* Handle SupplementaryGroups= if it is not empty */
972 if (ngids > 0) {
973 r = maybe_setgroups(ngids, supplementary_gids);
974 if (r < 0)
975 return r;
976 }
977
978 if (gid_is_valid(gid)) {
979 /* Then set our gids */
980 if (setresgid(gid, gid, gid) < 0)
981 return -errno;
982 }
983
984 return 0;
985 }
986
987 static int set_securebits(unsigned bits, unsigned mask) {
988 unsigned applied;
989 int current;
990
991 current = prctl(PR_GET_SECUREBITS);
992 if (current < 0)
993 return -errno;
994
995 /* Clear all securebits defined in mask and set bits */
996 applied = ((unsigned) current & ~mask) | bits;
997 if ((unsigned) current == applied)
998 return 0;
999
1000 if (prctl(PR_SET_SECUREBITS, applied) < 0)
1001 return -errno;
1002
1003 return 1;
1004 }
1005
1006 static int enforce_user(
1007 const ExecContext *context,
1008 uid_t uid,
1009 uint64_t capability_ambient_set) {
1010
1011 int r;
1012
1013 assert(context);
1014
1015 if (!uid_is_valid(uid))
1016 return 0;
1017
1018 /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
1019 * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
1020 * case. */
1021
1022 if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
1023
1024 /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1025 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1026 r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
1027 if (r < 0)
1028 return r;
1029 }
1030
1031 /* Second step: actually set the uids */
1032 if (setresuid(uid, uid, uid) < 0)
1033 return -errno;
1034
1035 /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1036 * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1037 * outside of this call. */
1038 return 0;
1039 }
1040
1041 #if HAVE_PAM
1042
1043 static void pam_response_done(struct pam_response *response) {
1044 erase_and_free(ASSERT_PTR(response)->resp);
1045 }
1046
1047 static DEFINE_ARRAY_FREE_FUNC(pam_response_free_array, struct pam_response, pam_response_done);
1048
1049 typedef struct AskPasswordConvData {
1050 const ExecContext *context;
1051 const ExecParameters *params;
1052 } AskPasswordConvData;
1053
1054 static int ask_password_conv(
1055 int num_msg,
1056 const struct pam_message *msg[],
1057 struct pam_response **ret,
1058 void *userdata) {
1059
1060 AskPasswordConvData *data = ASSERT_PTR(userdata);
1061 bool set_credential_env_var = false;
1062 int r;
1063
1064 assert(num_msg >= 0);
1065 assert(msg);
1066 assert(data->context);
1067 assert(data->params);
1068
1069 size_t n = num_msg;
1070 struct pam_response *responses = new0(struct pam_response, n);
1071 if (!responses)
1072 return PAM_BUF_ERR;
1073 CLEANUP_ARRAY(responses, n, pam_response_free_array);
1074
1075 for (size_t i = 0; i < n; i++) {
1076 const struct pam_message *mi = *msg + i;
1077
1078 switch (mi->msg_style) {
1079
1080 case PAM_PROMPT_ECHO_ON:
1081 case PAM_PROMPT_ECHO_OFF: {
1082
1083 /* Locally set the $CREDENTIALS_DIRECTORY to the credentials directory we just populated */
1084 if (!set_credential_env_var) {
1085 _cleanup_free_ char *creds_dir = NULL;
1086 r = exec_context_get_credential_directory(data->context, data->params, data->params->unit_id, &creds_dir);
1087 if (r < 0)
1088 return log_error_errno(r, "Failed to determine credentials directory: %m");
1089
1090 if (creds_dir) {
1091 if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
1092 return log_error_errno(r, "Failed to set $CREDENTIALS_DIRECTORY: %m");
1093 } else
1094 (void) unsetenv("CREDENTIALS_DIRECTORY");
1095
1096 set_credential_env_var = true;
1097 }
1098
1099 _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
1100 if (!credential_name)
1101 return log_oom();
1102
1103 AskPasswordRequest req = {
1104 .message = mi->msg,
1105 .credential = credential_name,
1106 .tty_fd = -EBADF,
1107 .hup_fd = -EBADF,
1108 .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
1109 };
1110
1111 _cleanup_strv_free_erase_ char **acquired = NULL;
1112 r = ask_password_auto(
1113 &req,
1114 ASK_PASSWORD_ACCEPT_CACHED|
1115 ASK_PASSWORD_NO_TTY|
1116 (mi->msg_style == PAM_PROMPT_ECHO_ON ? ASK_PASSWORD_ECHO : 0),
1117 &acquired);
1118 if (r < 0) {
1119 log_error_errno(r, "Failed to query for password: %m");
1120 return PAM_CONV_ERR;
1121 }
1122
1123 responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
1124 if (!responses[i].resp) {
1125 log_oom();
1126 return PAM_BUF_ERR;
1127 }
1128 break;
1129 }
1130
1131 case PAM_ERROR_MSG:
1132 log_error("PAM: %s", mi->msg);
1133 break;
1134
1135 case PAM_TEXT_INFO:
1136 log_info("PAM: %s", mi->msg);
1137 break;
1138
1139 default:
1140 return PAM_CONV_ERR;
1141 }
1142 }
1143
1144 *ret = TAKE_PTR(responses);
1145 n = 0;
1146
1147 return PAM_SUCCESS;
1148 }
1149
1150 static int pam_close_session_and_delete_credentials(pam_handle_t *pamh, int flags) {
1151 int r, s;
1152
1153 assert(pamh);
1154
1155 r = sym_pam_close_session(pamh, flags);
1156 if (r != PAM_SUCCESS)
1157 pam_syslog_pam_error(pamh, LOG_DEBUG, r, "pam_close_session() failed: @PAMERR@");
1158
1159 s = sym_pam_setcred(pamh, PAM_DELETE_CRED | flags);
1160 if (s != PAM_SUCCESS)
1161 pam_syslog_pam_error(pamh, LOG_DEBUG, r, "pam_setcred(PAM_DELETE_CRED) failed: @PAMERR@");
1162
1163 return r != PAM_SUCCESS ? r : s;
1164 }
1165 #endif
1166
1167 static int attach_to_subcgroup(
1168 const ExecContext *context,
1169 const CGroupContext *cgroup_context,
1170 const ExecParameters *params,
1171 const char *prefix) {
1172
1173 _cleanup_free_ char *subgroup = NULL;
1174 int r;
1175
1176 assert(context);
1177 assert(cgroup_context);
1178 assert(params);
1179
1180 /* If we're a control process that needs a subgroup, we've already been spawned into it as otherwise
1181 * we'd violate the "no inner processes" rule, so no need to do anything. */
1182 if (exec_params_needs_control_subcgroup(params))
1183 return 0;
1184
1185 r = exec_params_get_cgroup_path(params, cgroup_context, prefix, &subgroup);
1186 if (r < 0)
1187 return log_error_errno(r, "Failed to acquire cgroup path: %m");
1188 /* No subgroup required? Then there's nothing to do. */
1189 if (r == 0)
1190 return 0;
1191
1192 r = cg_attach(subgroup, 0);
1193 if (r == -EUCLEAN)
1194 return log_error_errno(r,
1195 "Failed to attach process " PID_FMT " to cgroup '%s', "
1196 "because the cgroup or one of its parents or "
1197 "siblings is in the threaded mode.",
1198 getpid_cached(), subgroup);
1199 if (r < 0)
1200 return log_error_errno(r,
1201 "Failed to attach process " PID_FMT " to cgroup %s: %m",
1202 getpid_cached(), subgroup);
1203
1204 return 0;
1205 }
1206
1207 #if HAVE_PAM
1208 static int exec_context_get_tty_for_pam(const ExecContext *context, char **ret) {
1209 _cleanup_free_ char *tty = NULL;
1210 int r;
1211
1212 assert(context);
1213 assert(ret);
1214
1215 /* First, let's get TTY from STDIN. We may already set STDIN in setup_output(). */
1216 r = getttyname_malloc(STDIN_FILENO, &tty);
1217 if (r == -ENOMEM)
1218 return log_oom_debug();
1219 if (r >= 0) {
1220 _cleanup_free_ char *q = path_join("/dev/", tty);
1221 if (!q)
1222 return log_oom_debug();
1223
1224 log_debug("Got TTY '%s' from STDIN.", q);
1225 *ret = TAKE_PTR(q);
1226 return 1;
1227 }
1228
1229 /* Do not implicitly configure TTY unless TTYPath= or StandardInput=tty is specified. See issue
1230 * #39334. Note, exec_context_tty_path() returns "/dev/console" when TTYPath= is unspecified, hence
1231 * explicitly check context->tty_path here. */
1232 if (!context->tty_path && !exec_input_is_terminal(context->std_input)) {
1233 *ret = NULL;
1234 return 0;
1235 }
1236
1237 /* Next, let's try to use the TTY specified in TTYPath=. */
1238 const char *t = exec_context_tty_path(context);
1239 if (!t) {
1240 *ret = NULL;
1241 return 0;
1242 }
1243
1244 /* If /dev/console is specified, resolve it. */
1245 if (tty_is_console(t)) {
1246 r = resolve_dev_console(&tty);
1247 if (r < 0) {
1248 log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
1249 *ret = NULL;
1250 return 0;
1251 }
1252
1253 log_debug("Got TTY '%s' from /dev/console.", tty);
1254 *ret = TAKE_PTR(tty);
1255 return 1;
1256 }
1257
1258 /* Otherwise, use the specified TTY as is. */
1259 if (path_startswith(t, "/dev/"))
1260 tty = strdup(t);
1261 else
1262 tty = path_join("/dev/", t);
1263 if (!tty)
1264 return log_oom_debug();
1265
1266 log_debug("Got TTY '%s' from TTYPath= setting.", tty);
1267 *ret = TAKE_PTR(tty);
1268 return 1;
1269 }
1270 #endif
1271
1272 static int setup_pam(
1273 const ExecContext *context,
1274 const CGroupContext *cgroup_context,
1275 ExecParameters *params,
1276 const char *user,
1277 uid_t uid,
1278 gid_t gid,
1279 char ***env, /* updated on success */
1280 bool needs_sandboxing,
1281 int exec_fd) {
1282
1283 #if HAVE_PAM
1284 AskPasswordConvData conv_data = {
1285 .context = context,
1286 .params = params,
1287 };
1288
1289 const struct pam_conv conv = {
1290 .conv = ask_password_conv,
1291 .appdata_ptr = &conv_data,
1292 };
1293
1294 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
1295 _cleanup_strv_free_ char **e = NULL;
1296 _cleanup_free_ char *tty = NULL;
1297 pam_handle_t *pamh = NULL;
1298 sigset_t old_ss;
1299 int pam_code = PAM_SUCCESS, r;
1300 bool close_session = false;
1301 pid_t parent_pid;
1302 int flags = 0;
1303
1304 assert(context);
1305 assert(params);
1306 assert(user);
1307 assert(uid_is_valid(uid));
1308 assert(gid_is_valid(gid));
1309 assert(env);
1310
1311 /* We set up PAM in the parent process, then fork. The child will then stay around until killed via
1312 * PR_GET_PDEATHSIG or systemd via the cgroup logic. It will then remove the PAM session again. The
1313 * parent process will exec() the actual daemon. We do things this way to ensure that the main PID of
1314 * the daemon is the one we initially fork()ed. */
1315
1316 r = DLOPEN_LIBPAM(LOG_ERR, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
1317 if (r < 0)
1318 return r;
1319
1320 r = barrier_create(&barrier);
1321 if (r < 0)
1322 goto fail;
1323
1324 if (log_get_max_level() < LOG_DEBUG)
1325 flags |= PAM_SILENT;
1326
1327 pam_code = sym_pam_start(context->pam_name, user, &conv, &pamh);
1328 if (pam_code != PAM_SUCCESS) {
1329 pamh = NULL;
1330 goto fail;
1331 }
1332
1333 r = exec_context_get_tty_for_pam(context, &tty);
1334 if (r < 0)
1335 goto fail;
1336 if (r > 0) {
1337 pam_code = sym_pam_set_item(pamh, PAM_TTY, tty);
1338 if (pam_code != PAM_SUCCESS)
1339 goto fail;
1340 }
1341
1342 STRV_FOREACH(nv, *env) {
1343 pam_code = sym_pam_putenv(pamh, *nv);
1344 if (pam_code != PAM_SUCCESS)
1345 goto fail;
1346 }
1347
1348 pam_code = sym_pam_acct_mgmt(pamh, flags);
1349 if (pam_code != PAM_SUCCESS)
1350 goto fail;
1351
1352 pam_code = sym_pam_setcred(pamh, PAM_ESTABLISH_CRED | flags);
1353 if (pam_code != PAM_SUCCESS)
1354 pam_syslog_pam_error(pamh, LOG_DEBUG, pam_code, "pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: @PAMERR@");
1355
1356 pam_code = sym_pam_open_session(pamh, flags);
1357 if (pam_code != PAM_SUCCESS)
1358 goto fail;
1359
1360 close_session = true;
1361
1362 e = sym_pam_getenvlist(pamh);
1363 if (!e) {
1364 pam_code = PAM_BUF_ERR;
1365 goto fail;
1366 }
1367
1368 /* Block SIGTERM, so that we know that it won't get lost in the child */
1369
1370 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
1371
1372 parent_pid = getpid_cached();
1373
1374 r = pidref_safe_fork("(sd-pam)", /* flags= */ 0, /* ret= */ NULL);
1375 if (r < 0)
1376 goto fail;
1377 if (r == 0) {
1378 int ret = EXIT_PAM;
1379
1380 if (needs_sandboxing && exec_needs_cgroup_namespace(context) && params->cgroup_path) {
1381 /* Move PAM process into subgroup immediately if the main process hasn't been moved
1382 * into the subgroup yet (when cgroup namespacing is enabled) and a subgroup is
1383 * configured. */
1384 r = attach_to_subcgroup(context, cgroup_context, params, params->cgroup_path);
1385 if (r < 0)
1386 return r;
1387 }
1388
1389 /* The child's job is to reset the PAM session on termination */
1390 barrier_set_role(&barrier, BARRIER_CHILD);
1391
1392 /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1393 * those fds are open here that have been opened by PAM. */
1394 close_many(params->fds, params->n_socket_fds + params->n_stashed_fds);
1395
1396 /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1397 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1398 * we'd never signal completion. */
1399 exec_fd = safe_close(exec_fd);
1400
1401 /* Drop privileges - we don't need any to pam_close_session and this will make
1402 * PR_SET_PDEATHSIG work in most cases. If this fails, ignore the error - but expect sd-pam
1403 * threads to fail to exit normally */
1404
1405 r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
1406 if (r < 0)
1407 log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
1408
1409 (void) ignore_signals(SIGPIPE);
1410
1411 /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1412 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1413 * this way. We rely on the control groups kill logic to do the rest for us. */
1414 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
1415 goto child_finish;
1416
1417 /* Tell the parent that our setup is done. This is especially important regarding dropping
1418 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1419 *
1420 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1421 (void) barrier_place(&barrier);
1422
1423 /* Check if our parent process might already have died? */
1424 if (getppid() == parent_pid) {
1425 sigset_t ss;
1426 int sig;
1427
1428 assert_se(sigemptyset(&ss) >= 0);
1429 assert_se(sigaddset(&ss, SIGTERM) >= 0);
1430
1431 assert_se(sigwait(&ss, &sig) == 0);
1432 assert(sig == SIGTERM);
1433 }
1434
1435 /* If our parent died we'll end the session */
1436 if (getppid() != parent_pid) {
1437 pam_code = pam_close_session_and_delete_credentials(pamh, flags);
1438 if (pam_code != PAM_SUCCESS)
1439 goto child_finish;
1440 }
1441
1442 ret = 0;
1443
1444 child_finish:
1445 /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1446 * know about this. See pam_end(3) */
1447 (void) sym_pam_end(pamh, pam_code | flags | PAM_DATA_SILENT);
1448 _exit(ret);
1449 }
1450
1451 barrier_set_role(&barrier, BARRIER_PARENT);
1452
1453 /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1454 * here. */
1455 pamh = NULL;
1456
1457 /* Unblock SIGTERM again in the parent */
1458 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
1459
1460 /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1461 * this fd around. */
1462 closelog();
1463
1464 /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1465 * recover. However, warn loudly if it happens. */
1466 if (!barrier_place_and_sync(&barrier))
1467 log_error("PAM initialization failed");
1468
1469 return strv_free_and_replace(*env, e);
1470
1471 fail:
1472 if (pam_code != PAM_SUCCESS) {
1473 pam_syslog_pam_error(pamh, LOG_ERR, pam_code, "PAM failed: @PAMERR@");
1474 r = -EPERM; /* PAM errors do not map to errno */
1475 } else
1476 log_error_errno(r, "PAM failed: %m");
1477
1478 if (pamh) {
1479 if (close_session)
1480 pam_code = pam_close_session_and_delete_credentials(pamh, flags);
1481
1482 (void) sym_pam_end(pamh, pam_code | flags);
1483 }
1484
1485 closelog();
1486 return r;
1487 #else
1488 return 0;
1489 #endif
1490 }
1491
1492 static void rename_process_from_path(const char *path) {
1493 int r;
1494
1495 assert(path);
1496
1497 _cleanup_free_ char *buf = NULL;
1498 r = path_extract_filename(path, &buf);
1499 if (r < 0) {
1500 log_debug_errno(r, "Failed to extract file name from '%s', ignoring: %m", path);
1501 return (void) rename_process("(...)");
1502 }
1503
1504 size_t len = strlen(buf);
1505 char comm[TASK_COMM_LEN], *p = comm;
1506 *p++ = '(';
1507 strnpcpy(&p, TASK_COMM_LEN - 2, buf, len); /* strnpcpy() accounts for NUL byte internally */
1508 *p++ = ')';
1509 *p = '\0';
1510
1511 size_t len_invocation = program_invocation_name ? strlen(program_invocation_name) : SIZE_MAX;
1512 _cleanup_free_ char *invocation = strjoin("(", buf + LESS_BY(len, len_invocation - 2), ")");
1513 if (!invocation)
1514 log_oom_debug();
1515
1516 (void) rename_process_full(comm, invocation ?: comm);
1517 }
1518
1519 static bool context_has_address_families(const ExecContext *c) {
1520 assert(c);
1521
1522 return c->address_families_allow_list ||
1523 !set_isempty(c->address_families);
1524 }
1525
1526 static bool context_has_syscall_filters(const ExecContext *c) {
1527 assert(c);
1528
1529 return c->syscall_allow_list ||
1530 !hashmap_isempty(c->syscall_filter);
1531 }
1532
1533 static bool context_has_syscall_logs(const ExecContext *c) {
1534 assert(c);
1535
1536 return c->syscall_log_allow_list ||
1537 !hashmap_isempty(c->syscall_log);
1538 }
1539
1540 static bool context_has_seccomp(const ExecContext *c) {
1541 assert(c);
1542
1543 /* We need NNP if we have any form of seccomp and are unprivileged */
1544 return c->lock_personality ||
1545 c->memory_deny_write_execute ||
1546 c->private_devices ||
1547 c->protect_clock ||
1548 c->protect_hostname == PROTECT_HOSTNAME_YES ||
1549 c->protect_kernel_tunables ||
1550 c->protect_kernel_modules ||
1551 c->protect_kernel_logs ||
1552 context_has_address_families(c) ||
1553 exec_context_restrict_namespaces_set(c) ||
1554 c->restrict_realtime ||
1555 c->restrict_suid_sgid ||
1556 !set_isempty(c->syscall_archs) ||
1557 context_has_syscall_filters(c) ||
1558 context_has_syscall_logs(c);
1559 }
1560
1561 static bool context_has_no_new_privileges(const ExecContext *c) {
1562 assert(c);
1563
1564 if (c->no_new_privileges)
1565 return true;
1566
1567 if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
1568 return false;
1569
1570 return context_has_seccomp(c);
1571 }
1572
1573 #if HAVE_SECCOMP
1574
1575 static bool seccomp_allows_drop_privileges(const ExecContext *c) {
1576 void *id, *val;
1577 bool have_capget = false, have_capset = false, have_prctl = false;
1578
1579 assert(c);
1580
1581 /* No libseccomp, all is fine */
1582 if (DLOPEN_LIBSECCOMP(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED) < 0)
1583 return true;
1584
1585 /* No syscall filter, we are allowed to drop privileges */
1586 if (hashmap_isempty(c->syscall_filter))
1587 return true;
1588
1589 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
1590 _cleanup_free_ char *name = NULL;
1591
1592 name = sym_seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
1593
1594 if (streq(name, "capget"))
1595 have_capget = true;
1596 else if (streq(name, "capset"))
1597 have_capset = true;
1598 else if (streq(name, "prctl"))
1599 have_prctl = true;
1600 }
1601
1602 if (c->syscall_allow_list)
1603 return have_capget && have_capset && have_prctl;
1604 else
1605 return !(have_capget || have_capset || have_prctl);
1606 }
1607
1608 static bool skip_seccomp_unavailable(const char *msg) {
1609 assert(msg);
1610
1611 if (is_seccomp_available())
1612 return false;
1613
1614 log_debug("SECCOMP features not detected in the kernel, skipping %s", msg);
1615 return true;
1616 }
1617
1618 static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
1619 uint32_t negative_action, default_action, action;
1620 int r;
1621
1622 assert(c);
1623 assert(p);
1624
1625 if (!context_has_syscall_filters(c))
1626 return 0;
1627
1628 if (skip_seccomp_unavailable("SystemCallFilter="))
1629 return 0;
1630
1631 negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? SCMP_ACT_KILL_PROCESS : SCMP_ACT_ERRNO(c->syscall_errno);
1632
1633 if (c->syscall_allow_list) {
1634 default_action = negative_action;
1635 action = SCMP_ACT_ALLOW;
1636 } else {
1637 default_action = SCMP_ACT_ALLOW;
1638 action = negative_action;
1639 }
1640
1641 /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall.
1642 *
1643 * Note: this mutates c->syscall_filter despite the 'const ExecContext *c' qualifier.
1644 * That is intentional and safe here because apply_syscall_filter() runs only in the
1645 * post-fork child, which holds a private copy of the address space; the hashmap
1646 * change is never visible to the manager process. */
1647 if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
1648 if (c->syscall_allow_list)
1649 log_debug("SystemCallFilter= allow-list in effect; adding 'write' syscall required for exec handoff.");
1650
1651 r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
1652 if (r < 0)
1653 return r;
1654 }
1655
1656 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1657 }
1658
1659 static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
1660 uint32_t default_action, action;
1661
1662 assert(c);
1663 assert(p);
1664
1665 if (!context_has_syscall_logs(c))
1666 return 0;
1667
1668 if (skip_seccomp_unavailable("SystemCallLog="))
1669 return 0;
1670
1671 if (c->syscall_log_allow_list) {
1672 /* Log nothing but the ones listed */
1673 default_action = SCMP_ACT_ALLOW;
1674 action = SCMP_ACT_LOG;
1675 } else {
1676 /* Log everything but the ones listed */
1677 default_action = SCMP_ACT_LOG;
1678 action = SCMP_ACT_ALLOW;
1679 }
1680
1681 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
1682 }
1683
1684 static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
1685 assert(c);
1686 assert(p);
1687
1688 if (set_isempty(c->syscall_archs))
1689 return 0;
1690
1691 if (skip_seccomp_unavailable("SystemCallArchitectures="))
1692 return 0;
1693
1694 return seccomp_restrict_archs(c->syscall_archs);
1695 }
1696
1697 static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
1698 assert(c);
1699 assert(p);
1700
1701 if (!context_has_address_families(c))
1702 return 0;
1703
1704 if (skip_seccomp_unavailable("RestrictAddressFamilies="))
1705 return 0;
1706
1707 return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
1708 }
1709
1710 static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
1711 int r;
1712
1713 assert(c);
1714 assert(p);
1715
1716 if (!c->memory_deny_write_execute)
1717 return 0;
1718
1719 /* use prctl() if kernel supports it (6.3) */
1720 r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1721 if (r == 0) {
1722 log_debug("Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1723 return 0;
1724 }
1725 if (r < 0 && errno != EINVAL)
1726 return log_debug_errno(errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
1727 /* else use seccomp */
1728 log_debug("Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
1729
1730 if (skip_seccomp_unavailable("MemoryDenyWriteExecute="))
1731 return 0;
1732
1733 return seccomp_memory_deny_write_execute();
1734 }
1735
1736 static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
1737 assert(c);
1738 assert(p);
1739
1740 if (!c->restrict_realtime)
1741 return 0;
1742
1743 if (skip_seccomp_unavailable("RestrictRealtime="))
1744 return 0;
1745
1746 return seccomp_restrict_realtime();
1747 }
1748
1749 static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
1750 assert(c);
1751 assert(p);
1752
1753 if (!c->restrict_suid_sgid)
1754 return 0;
1755
1756 if (skip_seccomp_unavailable("RestrictSUIDSGID="))
1757 return 0;
1758
1759 return seccomp_restrict_suid_sgid();
1760 }
1761
1762 static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
1763 assert(c);
1764 assert(p);
1765
1766 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1767 * let's protect even those systems where this is left on in the kernel. */
1768
1769 if (!c->protect_kernel_tunables)
1770 return 0;
1771
1772 if (skip_seccomp_unavailable("ProtectKernelTunables="))
1773 return 0;
1774
1775 return seccomp_protect_sysctl();
1776 }
1777
1778 static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
1779 assert(c);
1780 assert(p);
1781
1782 /* Turn off module syscalls on ProtectKernelModules=yes */
1783
1784 if (!c->protect_kernel_modules)
1785 return 0;
1786
1787 if (skip_seccomp_unavailable("ProtectKernelModules="))
1788 return 0;
1789
1790 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1791 }
1792
1793 static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
1794 assert(c);
1795 assert(p);
1796
1797 if (!c->protect_kernel_logs)
1798 return 0;
1799
1800 if (skip_seccomp_unavailable("ProtectKernelLogs="))
1801 return 0;
1802
1803 return seccomp_protect_syslog();
1804 }
1805
1806 static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
1807 assert(c);
1808 assert(p);
1809
1810 if (!c->protect_clock)
1811 return 0;
1812
1813 if (skip_seccomp_unavailable("ProtectClock="))
1814 return 0;
1815
1816 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
1817 }
1818
1819 static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
1820 assert(c);
1821 assert(p);
1822
1823 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1824
1825 if (!c->private_devices)
1826 return 0;
1827
1828 if (skip_seccomp_unavailable("PrivateDevices="))
1829 return 0;
1830
1831 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
1832 }
1833
1834 static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
1835 assert(c);
1836 assert(p);
1837
1838 if (!exec_context_restrict_namespaces_set(c))
1839 return 0;
1840
1841 if (skip_seccomp_unavailable("RestrictNamespaces="))
1842 return 0;
1843
1844 return seccomp_restrict_namespaces(c->restrict_namespaces);
1845 }
1846
1847 static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
1848 unsigned long personality;
1849 int r;
1850
1851 assert(c);
1852 assert(p);
1853
1854 if (!c->lock_personality)
1855 return 0;
1856
1857 if (skip_seccomp_unavailable("LockPersonality="))
1858 return 0;
1859
1860 personality = c->personality;
1861
1862 /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1863 if (personality == PERSONALITY_INVALID) {
1864
1865 r = opinionated_personality(&personality);
1866 if (r < 0)
1867 return r;
1868 }
1869
1870 return seccomp_lock_personality(personality);
1871 }
1872
1873 #endif
1874
1875 #if HAVE_LIBBPF
1876 static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
1877 int r;
1878
1879 assert(c);
1880 assert(p);
1881
1882 if (!exec_context_restrict_filesystems_set(c))
1883 return 0;
1884
1885 if (p->bpf_restrict_fs_map_fd < 0) {
1886 /* LSM BPF is unsupported or lsm_bpf_setup failed */
1887 log_debug("LSM BPF not supported, skipping RestrictFileSystems=");
1888 return 0;
1889 }
1890
1891 /* We are in a new binary, so dl-open again */
1892 r = DLOPEN_BPF(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
1893 if (r < 0)
1894 return r;
1895
1896 return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
1897 }
1898 #endif
1899
1900 static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
1901 int r;
1902
1903 assert(c);
1904 assert(p);
1905 assert(ret_exit_status);
1906
1907 if (c->protect_hostname == PROTECT_HOSTNAME_NO)
1908 return 0;
1909
1910 if (namespace_type_supported(NAMESPACE_UTS)) {
1911 if (unshare(CLONE_NEWUTS) < 0) {
1912 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
1913 *ret_exit_status = EXIT_NAMESPACE;
1914 return log_error_errno(errno, "Failed to set up UTS namespacing: %m");
1915 }
1916
1917 log_warning("ProtectHostname=%s is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.",
1918 protect_hostname_to_string(c->protect_hostname));
1919
1920 } else if (c->private_hostname) {
1921 r = sethostname_idempotent(c->private_hostname);
1922 if (r < 0) {
1923 *ret_exit_status = EXIT_NAMESPACE;
1924 return log_error_errno(r, "Failed to set private hostname '%s': %m", c->private_hostname);
1925 }
1926 }
1927 } else
1928 log_warning("ProtectHostname=%s is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.",
1929 protect_hostname_to_string(c->protect_hostname));
1930
1931 #if HAVE_SECCOMP
1932 if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
1933 if (skip_seccomp_unavailable("ProtectHostname="))
1934 return 0;
1935
1936 r = seccomp_protect_hostname();
1937 if (r < 0) {
1938 *ret_exit_status = EXIT_SECCOMP;
1939 return log_error_errno(r, "Failed to apply hostname restrictions: %m");
1940 }
1941 }
1942 #endif
1943
1944 return 1;
1945 }
1946
1947 static void do_idle_pipe_dance(int idle_pipe[static 4]) {
1948 assert(idle_pipe);
1949
1950 idle_pipe[1] = safe_close(idle_pipe[1]);
1951 idle_pipe[2] = safe_close(idle_pipe[2]);
1952
1953 if (idle_pipe[0] >= 0) {
1954 int r;
1955
1956 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1957
1958 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
1959 ssize_t n;
1960
1961 /* Signal systemd that we are bored and want to continue. */
1962 n = write(idle_pipe[3], "x", 1);
1963 if (n > 0)
1964 /* Wait for systemd to react to the signal above. */
1965 (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
1966 }
1967
1968 idle_pipe[0] = safe_close(idle_pipe[0]);
1969
1970 }
1971
1972 idle_pipe[3] = safe_close(idle_pipe[3]);
1973 }
1974
1975 /* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1976 * the service payload in. */
1977 static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1978 [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
1979 [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
1980 [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
1981 [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
1982 [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1983 };
1984
1985 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
1986
1987 static int build_environment(
1988 const ExecContext *c,
1989 const ExecParameters *p,
1990 const CGroupContext *cgroup_context,
1991 const char *home,
1992 const char *username,
1993 const char *shell,
1994 dev_t journal_stream_dev,
1995 ino_t journal_stream_ino,
1996 char *const *pressure_path,
1997 bool needs_sandboxing,
1998 char ***ret) {
1999
2000 _cleanup_strv_free_ char **e = NULL;
2001 _cleanup_free_ char *_username = NULL, *_home = NULL, *_shell = NULL;
2002 size_t n = 0;
2003 pid_t exec_pid;
2004 int r;
2005
2006 assert(c);
2007 assert(p);
2008 assert(cgroup_context);
2009 assert(ret);
2010
2011 exec_pid = needs_sandboxing && exec_needs_pid_namespace(c, p) ? 1 : getpid_cached();
2012
2013 if (p->n_socket_fds + p->n_stashed_fds > 0) {
2014 _cleanup_free_ char *joined = NULL;
2015
2016 r = strv_extendf_with_size(&e, &n, "LISTEN_PID="PID_FMT, exec_pid);
2017 if (r < 0)
2018 return r;
2019
2020 uint64_t pidfdid;
2021 if (pidfd_get_inode_id_self_cached(&pidfdid) >= 0) {
2022 r = strv_extendf_with_size(&e, &n, "LISTEN_PIDFDID=%"PRIu64, pidfdid);
2023 if (r < 0)
2024 return r;
2025 }
2026
2027 r = strv_extendf_with_size(&e, &n, "LISTEN_FDS=%zu", p->n_socket_fds + p->n_stashed_fds);
2028 if (r < 0)
2029 return r;
2030
2031 joined = strv_join(p->fd_names, ":");
2032 if (!joined)
2033 return -ENOMEM;
2034
2035 r = strv_extend_joined_with_size(&e, &n, "LISTEN_FDNAMES=", joined);
2036 if (r < 0)
2037 return r;
2038 }
2039
2040 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
2041 r = strv_extendf_with_size(&e, &n, "WATCHDOG_PID="PID_FMT, exec_pid);
2042 if (r < 0)
2043 return r;
2044
2045 r = strv_extendf_with_size(&e, &n, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec);
2046 if (r < 0)
2047 return r;
2048 }
2049
2050 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
2051 * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
2052 * PID 1 by disabling use of PID1's NSS interface for looking up dynamic users. */
2053 if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
2054 r = strv_extend_with_size(&e, &n, "SYSTEMD_NSS_DYNAMIC_BYPASS=1");
2055 if (r < 0)
2056 return r;
2057 }
2058
2059 /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
2060 * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL
2061 * don't really make much sense since we're not logged in. Hence we conditionalize the three based on
2062 * SetLoginEnvironment= switch. */
2063 if (!username && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2064 assert(!c->user);
2065
2066 r = get_user_creds("root", USER_CREDS_CLEAN, &_username, NULL, NULL, &_home, &_shell);
2067 if (r < 0) {
2068 log_debug_errno(r, "Failed to determine credentials for user root: %s",
2069 STRERROR_USER(r));
2070 return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
2071 }
2072
2073 username = _username;
2074 home = _home;
2075 shell = _shell;
2076 }
2077
2078 bool set_user_login_env = exec_context_get_set_login_environment(c);
2079
2080 if (username) {
2081 r = strv_extend_joined_with_size(&e, &n, "USER=", username);
2082 if (r < 0)
2083 return r;
2084
2085 if (set_user_login_env) {
2086 r = strv_extend_joined_with_size(&e, &n, "LOGNAME=", username);
2087 if (r < 0)
2088 return r;
2089 }
2090 }
2091
2092 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
2093 * (i.e. are "/" or "/bin/nologin"). */
2094
2095 if (home && set_user_login_env && !empty_or_root(home)) {
2096 _cleanup_free_ char *x = NULL;
2097
2098 r = path_simplify_alloc(home, &x);
2099 if (r < 0)
2100 return r;
2101
2102 r = strv_extend_joined_with_size(&e, &n, "HOME=", x);
2103 if (r < 0)
2104 return r;
2105 }
2106
2107 if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
2108 _cleanup_free_ char *x = NULL;
2109
2110 r = path_simplify_alloc(shell, &x);
2111 if (r < 0)
2112 return r;
2113
2114 r = strv_extend_joined_with_size(&e, &n, "SHELL=", x);
2115 if (r < 0)
2116 return r;
2117 }
2118
2119 if (!sd_id128_is_null(p->invocation_id)) {
2120 assert(!isempty(p->invocation_id_string));
2121
2122 r = strv_extend_joined_with_size(&e, &n, "INVOCATION_ID=", p->invocation_id_string);
2123 if (r < 0)
2124 return r;
2125 }
2126
2127 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
2128 r = strv_extendf_with_size(&e, &n, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino);
2129 if (r < 0)
2130 return r;
2131 }
2132
2133 if (c->log_namespace) {
2134 r = strv_extend_joined_with_size(&e, &n, "LOG_NAMESPACE=", c->log_namespace);
2135 if (r < 0)
2136 return r;
2137 }
2138
2139 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2140 _cleanup_free_ char *joined = NULL;
2141
2142 if (!p->prefix[t])
2143 continue;
2144
2145 if (c->directories[t].n_items == 0)
2146 continue;
2147
2148 const char *name = exec_directory_env_name_to_string(t);
2149 if (!name)
2150 continue;
2151
2152 for (size_t i = 0; i < c->directories[t].n_items; i++) {
2153 _cleanup_free_ char *prefixed = NULL;
2154
2155 prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2156 if (!prefixed)
2157 return -ENOMEM;
2158
2159 if (!strextend_with_separator(&joined, ":", prefixed))
2160 return -ENOMEM;
2161 }
2162
2163 r = strv_extend_joined_with_size(&e, &n, name, "=", joined);
2164 if (r < 0)
2165 return r;
2166 }
2167
2168 _cleanup_free_ char *creds_dir = NULL;
2169 r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
2170 if (r < 0)
2171 return r;
2172 if (r > 0) {
2173 r = strv_extend_joined_with_size(&e, &n, "CREDENTIALS_DIRECTORY=", creds_dir);
2174 if (r < 0)
2175 return r;
2176 }
2177
2178 r = strv_extendf_with_size(&e, &n, "SYSTEMD_EXEC_PID=" PID_FMT, exec_pid);
2179 if (r < 0)
2180 return r;
2181
2182 for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
2183 if (!pressure_path[t])
2184 continue;
2185
2186 const PressureResourceInfo *info = pressure_resource_get_info(t);
2187
2188 _cleanup_free_ char *env_watch = strjoin(info->env_watch, "=");
2189 if (!env_watch)
2190 return -ENOMEM;
2191
2192 r = strv_extend_joined_with_size(&e, &n, env_watch, pressure_path[t]);
2193 if (r < 0)
2194 return r;
2195
2196 if (!path_equal(pressure_path[t], "/dev/null")) {
2197 _cleanup_free_ char *b = NULL, *x = NULL;
2198
2199 if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
2200 PRESSURE_DEFAULT_TYPE,
2201 cgroup_context->pressure[t].threshold_usec == USEC_INFINITY ? PRESSURE_DEFAULT_THRESHOLD_USEC :
2202 CLAMP(cgroup_context->pressure[t].threshold_usec, 1U, PRESSURE_DEFAULT_WINDOW_USEC),
2203 PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2204 return -ENOMEM;
2205
2206 if (base64mem(b, strlen(b) + 1, &x) < 0)
2207 return -ENOMEM;
2208
2209 _cleanup_free_ char *env_write = strjoin(info->env_write, "=");
2210 if (!env_write)
2211 return -ENOMEM;
2212
2213 r = strv_extend_joined_with_size(&e, &n, env_write, x);
2214 if (r < 0)
2215 return r;
2216 }
2217 }
2218
2219 if (p->notify_socket) {
2220 r = strv_extend_joined_with_size(
2221 &e, &n, "NOTIFY_SOCKET=",
2222 exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
2223 if (r < 0)
2224 return r;
2225 }
2226
2227 assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
2228 if (needs_sandboxing &&
2229 c->private_var_tmp == PRIVATE_TMP_NO && c->private_tmp != PRIVATE_TMP_NO) {
2230 /* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
2231 * service to use /tmp/. */
2232
2233 r = strv_extend_with_size(&e, &n, "TMPDIR=/tmp");
2234 if (r < 0)
2235 return r;
2236 }
2237
2238 *ret = TAKE_PTR(e);
2239 return 0;
2240 }
2241
2242 static int build_pass_environment(const ExecContext *c, char ***ret) {
2243 _cleanup_strv_free_ char **pass_env = NULL;
2244 size_t n_env = 0;
2245
2246 assert(c);
2247 assert(ret);
2248
2249 STRV_FOREACH(i, c->pass_environment) {
2250 _cleanup_free_ char *x = NULL;
2251 char *v;
2252
2253 v = getenv(*i);
2254 if (!v)
2255 continue;
2256 x = strjoin(*i, "=", v);
2257 if (!x)
2258 return -ENOMEM;
2259
2260 if (!GREEDY_REALLOC(pass_env, n_env + 2))
2261 return -ENOMEM;
2262
2263 pass_env[n_env++] = TAKE_PTR(x);
2264 pass_env[n_env] = NULL;
2265 }
2266
2267 *ret = TAKE_PTR(pass_env);
2268 return 0;
2269 }
2270
2271 static int bpffs_helper(const ExecContext *c, int socket_fd) {
2272 assert(c);
2273 assert(socket_fd >= 0);
2274
2275 _cleanup_close_ int fs_fd = receive_one_fd(socket_fd, /* flags= */ 0);
2276 if (fs_fd < 0)
2277 return log_debug_errno(fs_fd, "Failed to receive file descriptor from parent: %m");
2278
2279 char number[STRLEN("0x") + sizeof(c->bpf_delegate_commands) * 2 + 1];
2280 xsprintf(number, "0x%"PRIx64, c->bpf_delegate_commands);
2281 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_cmds", number, /* aux= */ 0) < 0)
2282 return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
2283
2284 xsprintf(number, "0x%"PRIx64, c->bpf_delegate_maps);
2285 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_maps", number, /* aux= */ 0) < 0)
2286 return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
2287
2288 xsprintf(number, "0x%"PRIx64, c->bpf_delegate_programs);
2289 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_progs", number, /* aux= */ 0) < 0)
2290 return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
2291
2292 xsprintf(number, "0x%"PRIx64, c->bpf_delegate_attachments);
2293 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_attachs", number, /* aux= */ 0) < 0)
2294 return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
2295
2296 if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, /* key= */ NULL, /* value= */ NULL, /* aux= */ 0) < 0)
2297 return log_debug_errno(errno, "Failed to create bpffs superblock: %m");
2298
2299 return 0;
2300 }
2301
2302 static int bpffs_prepare(
2303 const ExecContext *c,
2304 PidRef *ret_pid,
2305 int *ret_sock_fd,
2306 int *ret_errno_pipe) {
2307
2308 _cleanup_close_pair_ int socket_fds[2] = EBADF_PAIR, errno_pipe[2] = EBADF_PAIR;
2309 int r;
2310
2311 assert(ret_sock_fd);
2312 assert(ret_pid);
2313 assert(ret_errno_pipe);
2314
2315 r = pipe2(errno_pipe, O_CLOEXEC|O_NONBLOCK);
2316 if (r < 0)
2317 return log_debug_errno(errno, "Failed to create pipe: %m");
2318
2319 r = socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, socket_fds);
2320 if (r < 0)
2321 return log_debug_errno(errno, "Failed to create socket pair: %m");
2322
2323 r = pidref_safe_fork("(sd-bpffs)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, ret_pid);
2324 if (r < 0)
2325 return log_debug_errno(r, "Failed to fork bpffs privileged helper: %m");
2326 if (r == 0) {
2327 errno_pipe[0] = safe_close(errno_pipe[0]);
2328 socket_fds[0] = safe_close(socket_fds[0]);
2329 report_errno_and_exit(errno_pipe[1], bpffs_helper(c, socket_fds[1]));
2330 }
2331
2332 *ret_sock_fd = TAKE_FD(socket_fds[0]);
2333 *ret_errno_pipe = TAKE_FD(errno_pipe[0]);
2334 return 0;
2335 }
2336
2337 static int setup_private_users_child(int unshare_ready_fd, const char *uid_map, const char *gid_map, bool allow_setgroups) {
2338 int r;
2339
2340 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
2341 * here, after the parent opened its own user namespace. */
2342
2343 pid_t ppid = getppid();
2344
2345 /* Wait until the parent unshared the user namespace */
2346 uint64_t c;
2347 ssize_t n = read(unshare_ready_fd, &c, sizeof(c));
2348 if (n < 0)
2349 return log_debug_errno(errno, "Failed to read from signaling eventfd: %m");
2350 if (n != sizeof(c))
2351 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Short read from signaling eventfd.");
2352
2353 /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2354 * and using the system service manager. */
2355 const char *a = procfs_file_alloca(ppid, "setgroups");
2356 const char *setgroups = allow_setgroups ? "allow" : "deny";
2357 r = write_string_file(a, setgroups, WRITE_STRING_FILE_DISABLE_BUFFER);
2358 if (r < 0)
2359 return log_debug_errno(r, "Failed to write '%s' to %s: %m", setgroups, a);
2360
2361 /* First write the GID map */
2362 a = procfs_file_alloca(ppid, "gid_map");
2363 r = write_string_file(a, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
2364 if (r < 0)
2365 return log_debug_errno(r, "Failed to write GID map to %s: %m", a);
2366
2367 /* Then write the UID map */
2368 a = procfs_file_alloca(ppid, "uid_map");
2369 r = write_string_file(a, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
2370 if (r < 0)
2371 return log_debug_errno(r, "Failed to write UID map to %s: %m", a);
2372
2373 return 0;
2374 }
2375
2376 static int setup_private_users(
2377 sd_varlink *nsresource_link,
2378 PrivateUsers private_users,
2379 uid_t saved_uid, /* service manager uid */
2380 gid_t saved_gid, /* service manager gid */
2381 uid_t *uid, /* unit uid (seen from inside) [input+output] */
2382 gid_t *gid, /* unit gid (ditto) [input+output] */
2383 uid_t *outside_uid, /* uid seen from the outside (which is the same as *uid, except of userns is used) */
2384 gid_t *outside_gid, /* gid seen from the outside (similar) */
2385 bool allow_setgroups) {
2386
2387 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
2388 _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
2389 _cleanup_close_ int unshare_ready_fd = -EBADF;
2390 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
2391 uint64_t c = 1;
2392 ssize_t n;
2393 int r;
2394
2395 assert(uid);
2396 assert(gid);
2397 assert(outside_uid);
2398 assert(outside_gid);
2399
2400 /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
2401 * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
2402 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
2403 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
2404 * which waits for the parent to create the new user namespace while staying in the original namespace. The
2405 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
2406 * continues execution normally.
2407 * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
2408 * does not need CAP_SETUID to write the single line mapping to itself. */
2409
2410 switch (private_users) { /* Prepare the UID mappings */
2411
2412 case PRIVATE_USERS_NO:
2413 return 0; /* Early exit */
2414
2415 case PRIVATE_USERS_MANAGED: {
2416 if (uid_is_valid(*uid) || uid_is_valid(*gid))
2417 return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "When allocating dynamic user namespace range, target UID/GID must be root, refusing.");
2418
2419 _cleanup_close_ int userns_fd = nsresource_allocate_userns(
2420 nsresource_link,
2421 /* name= */ NULL,
2422 NSRESOURCE_UIDS_64K);
2423 if (userns_fd < 0)
2424 return userns_fd;
2425
2426 _cleanup_(uid_range_freep) UIDRange *uid_range = NULL;
2427 r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &uid_range);
2428 if (r < 0)
2429 return log_debug_errno(r, "Failed to read outside userns UID range: %m");
2430
2431 _cleanup_(uid_range_freep) UIDRange *gid_range = NULL;
2432 r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &gid_range);
2433 if (r < 0)
2434 return log_debug_errno(r, "Failed to read outside userns GID range: %m");
2435
2436 if (setns(userns_fd, CLONE_NEWUSER) < 0)
2437 return log_debug_errno(errno, "Failed to join freshly allocated user namespace: %m");
2438
2439 /* In "managed" mode the originating UID is not mapped hence we need to explicitly become root in the new userns now. */
2440 r = reset_uid_gid();
2441 if (r < 0)
2442 return log_debug_errno(r, "Failed to reset UID/GID to root: %m");
2443
2444 /* Now report are new UIDs/GIDS, both inside and outside */
2445 *uid = 0;
2446 *gid = 0;
2447
2448 *outside_uid = uid_range_base(uid_range);
2449 *outside_gid = uid_range_base(gid_range);
2450
2451 return 1; /* Early exit */
2452 }
2453
2454 case PRIVATE_USERS_IDENTITY:
2455 uid_map = strdup("0 0 65536\n");
2456 if (!uid_map)
2457 return -ENOMEM;
2458 break;
2459
2460 case PRIVATE_USERS_FULL:
2461 /* Map all UID/GID from original to new user namespace.
2462 *
2463 * Note the kernel defines the UID range between 0 and UINT32_MAX so we map all UIDs even though
2464 * the UID range beyond INT32_MAX (e.g. i.e. the range above the signed 32-bit range) is
2465 * icky. For example, setfsuid() returns the old UID as signed integer. But units can decide to
2466 * use these UIDs/GIDs so we need to map them. */
2467 if (asprintf(&uid_map, "0 0 " UID_FMT "\n", (uid_t) UINT32_MAX) < 0)
2468 return -ENOMEM;
2469
2470 break;
2471
2472 case PRIVATE_USERS_SELF:
2473 /* Can only set up multiple mappings with CAP_SETUID. */
2474 if (uid_is_valid(*uid) && *uid != saved_uid && have_effective_cap(CAP_SETUID) > 0)
2475 r = asprintf(&uid_map,
2476 UID_FMT " " UID_FMT " 1\n" /* Map $OUID → $OUID */
2477 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
2478 saved_uid, saved_uid, *uid, *uid);
2479 else
2480 r = asprintf(&uid_map,
2481 UID_FMT " " UID_FMT " 1\n", /* Map $OUID → $OUID */
2482 saved_uid, saved_uid);
2483 if (r < 0)
2484 return -ENOMEM;
2485
2486 break;
2487
2488 default:
2489 assert_not_reached();
2490 }
2491
2492 switch (private_users) { /* Prepare the GID mappings */
2493
2494 case PRIVATE_USERS_IDENTITY:
2495 gid_map = strdup("0 0 65536\n");
2496 if (!gid_map)
2497 return -ENOMEM;
2498 break;
2499
2500 case PRIVATE_USERS_FULL:
2501 if (asprintf(&gid_map, "0 0 " GID_FMT "\n", (gid_t) UINT32_MAX) < 0)
2502 return -ENOMEM;
2503
2504 break;
2505
2506 case PRIVATE_USERS_SELF:
2507 /* Can only set up multiple mappings with CAP_SETGID. */
2508 if (gid_is_valid(*gid) && *gid != saved_gid && have_effective_cap(CAP_SETGID) > 0)
2509 r = asprintf(&gid_map,
2510 GID_FMT " " GID_FMT " 1\n" /* Map $OGID → $OGID */
2511 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
2512 saved_gid, saved_gid, *gid, *gid);
2513 else
2514 r = asprintf(&gid_map,
2515 GID_FMT " " GID_FMT " 1\n", /* Map $OGID -> $OGID */
2516 saved_gid, saved_gid);
2517 if (r < 0)
2518 return -ENOMEM;
2519 break;
2520
2521 default:
2522 assert_not_reached();
2523 }
2524
2525 /* Create a communication channel so that the parent can tell the child when it finished creating the user
2526 * namespace. */
2527 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
2528 if (unshare_ready_fd < 0)
2529 return -errno;
2530
2531 /* Create a communication channel so that the child can tell the parent a proper error code in case it
2532 * failed. */
2533 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2534 return -errno;
2535
2536 r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pidref);
2537 if (r < 0)
2538 return r;
2539 if (r == 0) {
2540 errno_pipe[0] = safe_close(errno_pipe[0]);
2541 r = setup_private_users_child(unshare_ready_fd, uid_map, gid_map, allow_setgroups);
2542 if (r < 0)
2543 report_errno_and_exit(errno_pipe[1], r);
2544 _exit(EXIT_SUCCESS);
2545 }
2546
2547 errno_pipe[1] = safe_close(errno_pipe[1]);
2548
2549 if (unshare(CLONE_NEWUSER) < 0)
2550 return log_debug_errno(errno, "Failed to unshare user namespace: %m");
2551
2552 /* Let the child know that the namespace is ready now */
2553 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
2554 return -errno;
2555
2556 /* Try to read an error code from the child */
2557 n = read(errno_pipe[0], &r, sizeof(r));
2558 if (n < 0)
2559 return -errno;
2560 if (n == sizeof(r)) { /* an error code was sent to us */
2561 if (r < 0)
2562 return r;
2563 return -EIO;
2564 }
2565 if (n != 0) /* on success we should have read 0 bytes */
2566 return -EIO;
2567
2568 r = pidref_wait_for_terminate_and_check("(sd-userns)", &pidref, 0);
2569 if (r < 0)
2570 return r;
2571 pidref_done(&pidref);
2572 if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
2573 return -EIO;
2574
2575 return 1;
2576 }
2577
2578 static int can_mount_proc(void) {
2579 _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
2580 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
2581 ssize_t n;
2582 int r;
2583
2584 /* If running via unprivileged user manager and /proc/ is masked (e.g. /proc/kmsg is over-mounted with tmpfs
2585 * like systemd-nspawn does), then mounting /proc/ will fail with EPERM. This is due to a kernel restriction
2586 * where unprivileged user namespaces cannot mount a less restrictive instance of /proc. */
2587
2588 /* Create a communication channel so that the child can tell the parent a proper error code in case it
2589 * failed. */
2590 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2591 return log_debug_errno(errno, "Failed to create pipe for communicating with child process (sd-proc-check): %m");
2592
2593 /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2594 * with FORK_MOUNTNS_SLAVE. */
2595 r = pidref_safe_fork(
2596 "(sd-proc-check)",
2597 FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS,
2598 &pidref);
2599 if (r < 0)
2600 return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
2601 if (r == 0) {
2602 errno_pipe[0] = safe_close(errno_pipe[0]);
2603
2604 /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2605 * namespace will be cleaned up once the process exits. */
2606 r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
2607 if (r < 0) {
2608 (void) write(errno_pipe[1], &r, sizeof(r));
2609 _exit(EXIT_FAILURE);
2610 }
2611
2612 _exit(EXIT_SUCCESS);
2613 }
2614
2615 errno_pipe[1] = safe_close(errno_pipe[1]);
2616
2617 /* Try to read an error code from the child */
2618 n = read(errno_pipe[0], &r, sizeof(r));
2619 if (n < 0)
2620 return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
2621 if (n == sizeof(r)) { /* an error code was sent to us */
2622 /* This is the expected case where proc cannot be mounted due to permissions. */
2623 if (ERRNO_IS_NEG_PRIVILEGE(r))
2624 return 0;
2625 if (r < 0)
2626 return r;
2627
2628 return -EIO;
2629 }
2630 if (n != 0) /* on success we should have read 0 bytes */
2631 return -EIO;
2632
2633 r = pidref_wait_for_terminate_and_check("(sd-proc-check)", &pidref, /* flags= */ 0);
2634 if (r < 0)
2635 return log_debug_errno(r, "Failed to wait for (sd-proc-check) child process to terminate: %m");
2636 pidref_done(&pidref);
2637 if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
2638 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Child process (sd-proc-check) exited with unexpected exit status '%d'.", r);
2639
2640 return 1;
2641 }
2642
2643 static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
2644 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
2645 _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
2646 ssize_t n;
2647 int r, q;
2648
2649 assert(c);
2650 assert(p);
2651 assert(p->pidref_transport_fd >= 0);
2652
2653 /* The first process created after unsharing a pid namespace becomes PID 1 in the pid namespace, so
2654 * we have to fork after unsharing the pid namespace to become PID 1. The parent sends the child
2655 * pidref to the manager and exits while the child process continues with the rest of exec_invoke()
2656 * and finally executes the actual payload. */
2657
2658 /* Create a communication channel so that the parent can tell the child a proper error code in case it
2659 * failed to send child pidref to the manager. */
2660 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2661 return log_debug_errno(errno, "Failed to create pipe for communicating with parent process: %m");
2662
2663 /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2664 r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
2665 if (r < 0)
2666 return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
2667 if (r > 0) {
2668 errno_pipe[0] = safe_close(errno_pipe[0]);
2669
2670 /* In the parent process, we send the child pidref to the manager and exit.
2671 * If PIDFD is not supported, only the child PID is sent. The server then
2672 * uses the child PID to set the new exec main process. */
2673 q = send_one_fd_iov(
2674 p->pidref_transport_fd,
2675 pidref.fd,
2676 &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
2677 /* iovlen= */ 1,
2678 /* flags= */ 0);
2679 /* Send error code to child process. */
2680 (void) write(errno_pipe[1], &q, sizeof(q));
2681 /* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
2682 * some destructors have external effects. The main codepaths continue in the child process. */
2683 _exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2684 }
2685
2686 errno_pipe[1] = safe_close(errno_pipe[1]);
2687 p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
2688
2689 /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2690 * receive an errno even on success. */
2691 n = read(errno_pipe[0], &r, sizeof(r));
2692 if (n < 0)
2693 return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
2694 if (n != sizeof(r))
2695 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
2696 if (r < 0)
2697 return log_debug_errno(r, "Failed to send child pidref to manager: %m");
2698
2699 /* NOTE! This function returns in the child process only. */
2700 return r;
2701 }
2702
2703 static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
2704 _cleanup_free_ char *src_abs = NULL;
2705 int r;
2706
2707 assert(source);
2708
2709 src_abs = path_join(root, source);
2710 if (!src_abs)
2711 return -ENOMEM;
2712
2713 STRV_FOREACH(dst, symlinks) {
2714 _cleanup_free_ char *dst_abs = NULL;
2715
2716 dst_abs = path_join(root, *dst);
2717 if (!dst_abs)
2718 return -ENOMEM;
2719
2720 r = mkdir_parents_label(dst_abs, 0755);
2721 if (r < 0)
2722 return r;
2723
2724 r = symlink_idempotent(src_abs, dst_abs, true);
2725 if (r < 0)
2726 return r;
2727 }
2728
2729 return 0;
2730 }
2731
2732 static int set_exec_storage_quota(int fd, uint32_t proj_id, const ExecQuotaLimit *ql) {
2733 int r;
2734 uint64_t block_limit = 0, inode_limit = 0;
2735
2736 assert(fd >= 0);
2737 assert(ql);
2738
2739 if (ql->quota_absolute == 0 || ql->quota_scale == 0)
2740 /* Limit of 0 means no usage is allowed. For quotactl, use 1 as the limit, since 0 means that
2741 * hard limits are disabled */
2742 block_limit = inode_limit = 1;
2743 else if (ql->quota_absolute == UINT64_MAX) {
2744 _cleanup_close_ int fd_parent = -EBADF;
2745
2746 /* Use target_dir's parent when setting quotas. If a FD for target_dir has been previously
2747 * used for quotactl_fd(SET) and is passed again for fstatvfs(), the total number of blocks is not
2748 * reported accurately (instead, the block limit is reported as total blocks). Thus, use the FD
2749 * associated with the parent, so that total blocks is accurate */
2750 fd_parent = openat(fd, "..", O_PATH|O_CLOEXEC|O_DIRECTORY);
2751 if (fd_parent < 0)
2752 return -errno;
2753
2754 uint32_t xattr_flags = 0;
2755 r = read_fs_xattr_fd(fd_parent, &xattr_flags, /* ret_projid= */ NULL);
2756 if (r < 0)
2757 return r;
2758 /* Refuse if parent has FS_XFLAG_PROJINHERIT since this will mean the total number of blocks will not
2759 * be reported accurately */
2760 if (FLAGS_SET(xattr_flags, FS_XFLAG_PROJINHERIT))
2761 return -ENOMEDIUM;
2762
2763 struct statvfs disk_st;
2764 if (fstatvfs(fd_parent, &disk_st) < 0)
2765 return -errno;
2766
2767 block_limit = (uint64_t) DIV_ROUND_UP((uint64_t)((double) (disk_st.f_frsize * disk_st.f_blocks) / UINT32_MAX * ql->quota_scale), QIF_DQBLKSIZE);
2768 inode_limit = (uint64_t) ((double) disk_st.f_files / UINT32_MAX * ql->quota_scale);
2769 } else
2770 block_limit = (uint64_t) DIV_ROUND_UP(ql->quota_absolute, QIF_DQBLKSIZE);
2771
2772 struct dqblk req = {
2773 .dqb_bhardlimit = block_limit,
2774 .dqb_ihardlimit = inode_limit,
2775 .dqb_valid = QIF_LIMITS,
2776 };
2777
2778 r = quotactl_fd_with_fallback(fd, QCMD_FIXED(Q_SETQUOTA, PRJQUOTA), proj_id, &req);
2779 if (r < 0)
2780 return r;
2781
2782 log_debug("Storage quotas set for project id %" PRIu32 ". Block limit = %" PRIu64 ", inode limit = %" PRIu64, proj_id, block_limit, inode_limit);
2783
2784 return 0;
2785 }
2786
2787 static int unset_exec_storage_quota(int fd, uint32_t proj_id, bool quota_accounting) {
2788 int r, quota_supported;
2789 struct dqblk req;
2790
2791 assert(fd >= 0);
2792
2793 quota_supported = quota_query_proj_id(fd, proj_id, &req);
2794 if (quota_supported < 0)
2795 return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
2796
2797 /* Do not enforce quotas anymore */
2798 if (quota_supported && FLAGS_SET(req.dqb_valid, QIF_BLIMITS) && (req.dqb_bhardlimit > 0 || req.dqb_ihardlimit > 0)) {
2799 req.dqb_bhardlimit = 0, req.dqb_ihardlimit = 0;
2800
2801 r = quotactl_fd_with_fallback(fd, QCMD_FIXED(Q_SETQUOTA, PRJQUOTA), proj_id, &req);
2802 if (r < 0)
2803 return log_debug_errno(r, "Failed to disable project quotas for project ID %" PRIu32 ": %m", proj_id);
2804
2805 log_debug("Storage quotas for project ID %" PRIu32 " were disabled", proj_id);
2806 }
2807
2808 /* Release project ID if no accounting needed */
2809 if (!quota_accounting) {
2810 r = set_proj_id_recursive(fd, 0);
2811 if (r < 0)
2812 log_warning_errno(r, "Failed to release project ID %" PRIu32 ", ignoring: %m", proj_id);
2813 }
2814
2815 return 0;
2816 }
2817
2818 static int apply_exec_quotas(
2819 const char *target_dir,
2820 const char *cgroup_path,
2821 ExecDirectoryType type,
2822 const ExecQuotaLimit *ql,
2823 uint32_t *exec_dt_proj_id, /* in/out */
2824 bool *already_enforced) { /* in/out */
2825
2826 _cleanup_close_ int fd = -EBADF;
2827 int r, quota_supported = 0;
2828
2829 assert(target_dir);
2830 assert(cgroup_path);
2831 assert(ql);
2832 assert(exec_dt_proj_id);
2833 assert(already_enforced);
2834
2835 /* Do not apply to the Runtime directory since tmpfs does not support project IDs yet */
2836 if (!IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_CACHE, EXEC_DIRECTORY_LOGS))
2837 return 0;
2838
2839 fd = open(target_dir, O_PATH|O_CLOEXEC|O_DIRECTORY);
2840 if (fd < 0)
2841 return log_debug_errno(errno, "Failed to open %s: %m", target_dir);
2842
2843 /* Get the project ID of the current directory */
2844 uint32_t proj_id;
2845 r = read_fs_xattr_fd(fd, /* ret_xflags= */ NULL, &proj_id);
2846 if (ERRNO_IS_NEG_IOCTL_NOT_SUPPORTED(r)) {
2847 log_debug_errno(r, "Not applying storage quotas. FS_IOC_FSGETXATTR not supported for %s: %m", target_dir);
2848 return 0;
2849 }
2850 if (r < 0)
2851 return log_debug_errno(r, "Failed to retrieve project ID for %s: %m", target_dir);
2852
2853 /* If the first directory of this ExecType already has a project ID, adopt it as the project ID for all dirs of this ExecType */
2854 bool proj_id_exists = PROJ_ID_MIN <= proj_id && proj_id <= PROJ_ID_MAX;
2855 if (proj_id_exists && *exec_dt_proj_id == 0)
2856 *exec_dt_proj_id = proj_id;
2857
2858 /* Check if enforcement should be disabled. Do not release project ID if accounting is enabled */
2859 if (!ql->quota_enforce) {
2860 if (proj_id_exists) {
2861 r = unset_exec_storage_quota(fd, proj_id, ql->quota_accounting);
2862 if (r < 0)
2863 return log_debug_errno(r, "Failed to unset project quotas for %s: %m", target_dir);
2864 }
2865
2866 if (!ql->quota_accounting)
2867 return 0;
2868 }
2869
2870 if (*exec_dt_proj_id > 0 && *exec_dt_proj_id != proj_id) {
2871 /* Set the existing project ID only if the current directory's ID does not exist or does not match */
2872 proj_id = *exec_dt_proj_id;
2873 r = quota_proj_id_set_recursive(fd, proj_id, false);
2874 if (r < 0)
2875 return log_debug_errno(r, "Failed to set project ID for %s: %m", target_dir);
2876 } else if (*exec_dt_proj_id == 0) {
2877 /* Only generate a new project ID if it's the first directory of this ExecType to be processed and does not have an existing ID */
2878 static const sd_id128_t k = SD_ID128_ARRAY(e1,4a,79,9b,64,40,41,4a,a8,46,c2,f3,f9,19,4f,01);
2879 _cleanup_free_ char *proj_id_plain = NULL;
2880
2881 /* Generate candidate project id */
2882 proj_id_plain = strjoin(cgroup_path, "|", exec_directory_type_to_string(type));
2883 if (!proj_id_plain)
2884 return log_oom_debug();
2885
2886 struct siphash state;
2887 siphash24_init(&state, k.bytes);
2888 siphash24_compress_string(proj_id_plain, &state);
2889 proj_id = PROJ_ID_CLAMP_INTO_QUOTA_RANGE(siphash24_finalize(&state));
2890
2891 #define MAX_PROJ_ID_RETRIES 10
2892 for (unsigned attempt = 0;; attempt++) {
2893 if (attempt >= MAX_PROJ_ID_RETRIES)
2894 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "Failed to generate unique project ID for '%s'.", target_dir);
2895
2896 /* Check if project quotas are supported */
2897 struct dqblk req;
2898 quota_supported = quota_query_proj_id(fd, proj_id, &req);
2899 if (quota_supported < 0)
2900 return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
2901 if (!quota_supported) {
2902 log_debug("Not applying storage quotas. Project quotas are not supported for %s", target_dir);
2903 return 0;
2904 }
2905
2906 if (!quota_dqblk_is_populated(&req)) {
2907 int proj_id_was_set = quota_proj_id_set_recursive(fd, proj_id, true);
2908 if (proj_id_was_set < 0)
2909 return log_debug_errno(proj_id_was_set, "Failed to set project ID for %s: %m", target_dir);
2910 if (proj_id_was_set) {
2911 *exec_dt_proj_id = proj_id;
2912 log_debug("Project ID %u generated for %s", proj_id, target_dir);
2913 break;
2914 }
2915 }
2916
2917 proj_id = (uint32_t) (random_u64_range(PROJ_ID_MAX - PROJ_ID_MIN + 1) + PROJ_ID_MIN);
2918 }
2919 }
2920
2921 if (ql->quota_enforce && !*already_enforced) {
2922 if (!quota_supported) {
2923 struct dqblk req;
2924 quota_supported = quota_query_proj_id(fd, proj_id, &req);
2925 if (quota_supported < 0)
2926 return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
2927 if (!quota_supported) {
2928 log_debug("Not applying storage quotas. Project quotas are not supported for %s", target_dir);
2929 return 0;
2930 }
2931 }
2932
2933 r = set_exec_storage_quota(fd, proj_id, ql);
2934 if (r < 0)
2935 return log_debug_errno(r, "Failed to set storage quotas for %s: %m", target_dir);
2936
2937 *already_enforced = true;
2938 }
2939
2940 return r;
2941 }
2942
2943 static int setup_exec_directory(
2944 const ExecContext *context,
2945 const ExecParameters *params,
2946 uid_t uid,
2947 gid_t gid,
2948 ExecDirectoryType type,
2949 bool needs_mount_namespace,
2950 int *exit_status) {
2951
2952 static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
2953 [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
2954 [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
2955 [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
2956 [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
2957 [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2958 };
2959 int r;
2960
2961 assert(context);
2962 assert(params);
2963 assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
2964 assert(exit_status);
2965
2966 if (!params->prefix[type])
2967 return 0;
2968
2969 if (params->flags & EXEC_CHOWN_DIRECTORIES) {
2970 if (!uid_is_valid(uid))
2971 uid = 0;
2972 if (!gid_is_valid(gid))
2973 gid = 0;
2974 }
2975
2976 uint32_t exec_dt_proj_id = 0;
2977 bool quota_already_enforced = false;
2978
2979 FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
2980 _cleanup_free_ char *p = NULL, *pp = NULL;
2981
2982 p = path_join(params->prefix[type], i->path);
2983 if (!p) {
2984 r = -ENOMEM;
2985 goto fail;
2986 }
2987
2988 r = mkdir_parents_label(p, 0755);
2989 if (r < 0)
2990 goto fail;
2991
2992 if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
2993
2994 /* If we are in user mode, and a configuration directory exists but a state directory
2995 * doesn't exist, then we likely are upgrading from an older systemd version that
2996 * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2997 * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2998 * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
2999 * separated. If a service has both dirs configured but only the configuration dir
3000 * exists and the state dir does not, we assume we are looking at an update
3001 * situation. Hence, create a compatibility symlink, so that all expectations are
3002 * met.
3003 *
3004 * (We also do something similar with the log directory, which still doesn't exist in
3005 * the xdg basedir spec. We'll make it a subdir of the state dir.) */
3006
3007 /* this assumes the state dir is always created before the configuration dir */
3008 assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
3009 assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
3010
3011 r = access_nofollow(p, F_OK);
3012 if (r == -ENOENT) {
3013 _cleanup_free_ char *q = NULL;
3014
3015 /* OK, we know that the state dir does not exist. Let's see if the dir exists
3016 * under the configuration hierarchy. */
3017
3018 if (type == EXEC_DIRECTORY_STATE)
3019 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3020 else if (type == EXEC_DIRECTORY_LOGS)
3021 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
3022 else
3023 assert_not_reached();
3024 if (!q) {
3025 r = -ENOMEM;
3026 goto fail;
3027 }
3028
3029 r = access_nofollow(q, F_OK);
3030 if (r >= 0) {
3031 /* It does exist! This hence looks like an update. Symlink the
3032 * configuration directory into the state directory. */
3033
3034 r = symlink_idempotent(q, p, /* make_relative= */ true);
3035 if (r < 0)
3036 goto fail;
3037
3038 log_notice("Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
3039 continue;
3040 } else if (r != -ENOENT)
3041 log_warning_errno(r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
3042
3043 } else if (r < 0)
3044 log_warning_errno(r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
3045 }
3046
3047 if (exec_directory_is_private(context, type)) {
3048 /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
3049 * case we want to avoid leaving a directory around fully accessible that is owned by
3050 * a dynamic user whose UID is later on reused. To lock this down we use the same
3051 * trick used by container managers to prohibit host users to get access to files of
3052 * the same UID in containers: we place everything inside a directory that has an
3053 * access mode of 0700 and is owned root:root, so that it acts as security boundary
3054 * for unprivileged host code. We then use fs namespacing to make this directory
3055 * permeable for the service itself.
3056 *
3057 * Specifically: for a service which wants a special directory "foo/" we first create
3058 * a directory "private/" with access mode 0700 owned by root:root. Then we place
3059 * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
3060 * "private/foo". This way, privileged host users can access "foo/" as usual, but
3061 * unprivileged host users can't look into it. Inside of the namespace of the unit
3062 * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
3063 * "private/foo/" is mounted under the same name, thus disabling the access boundary
3064 * for the service and making sure it only gets access to the dirs it needs but no
3065 * others. Tricky? Yes, absolutely, but it works!
3066 *
3067 * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
3068 * to be owned by the service itself.
3069 *
3070 * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
3071 * for sharing files or sockets with other services. */
3072
3073 pp = path_join(params->prefix[type], "private");
3074 if (!pp) {
3075 r = -ENOMEM;
3076 goto fail;
3077 }
3078
3079 /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
3080 r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
3081 if (r < 0)
3082 goto fail;
3083
3084 if (!path_extend(&pp, i->path)) {
3085 r = -ENOMEM;
3086 goto fail;
3087 }
3088
3089 /* Create all directories between the configured directory and this private root, and mark them 0755 */
3090 r = mkdir_parents_label(pp, 0755);
3091 if (r < 0)
3092 goto fail;
3093
3094 if (is_dir(p, false) > 0 &&
3095 (access_nofollow(pp, F_OK) == -ENOENT)) {
3096
3097 /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
3098 * it over. Most likely the service has been upgraded from one that didn't use
3099 * DynamicUser=1, to one that does. */
3100
3101 log_info("Found pre-existing public %s= directory %s, migrating to %s.\n"
3102 "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
3103 exec_directory_type_to_string(type), p, pp);
3104
3105 r = RET_NERRNO(rename(p, pp));
3106 if (r < 0)
3107 goto fail;
3108 } else {
3109 /* Otherwise, create the actual directory for the service */
3110
3111 r = mkdir_label(pp, context->directories[type].mode);
3112 if (r < 0 && r != -EEXIST)
3113 goto fail;
3114 }
3115
3116 if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
3117 /* And link it up from the original place.
3118 * Notes
3119 * 1) If a mount namespace is going to be used, then this symlink remains on
3120 * the host, and a new one for the child namespace will be created later.
3121 * 2) It is not necessary to create this symlink when one of its parent
3122 * directories is specified and already created. E.g.
3123 * StateDirectory=foo foo/bar
3124 * In that case, the inode points to pp and p for "foo/bar" are the same:
3125 * pp = "/var/lib/private/foo/bar"
3126 * p = "/var/lib/foo/bar"
3127 * and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
3128 * we do not need to create the symlink, but we cannot create the symlink.
3129 * See issue #24783. */
3130 r = symlink_idempotent(pp, p, true);
3131 if (r < 0)
3132 goto fail;
3133 }
3134
3135 } else {
3136 _cleanup_free_ char *target = NULL;
3137
3138 if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
3139 readlink_and_make_absolute(p, &target) >= 0) {
3140 _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
3141
3142 /* This already exists and is a symlink? Interesting. Maybe it's one created
3143 * by DynamicUser=1 (see above)?
3144 *
3145 * We do this for all directory types except for ConfigurationDirectory=,
3146 * since they all support the private/ symlink logic at least in some
3147 * configurations, see above. */
3148
3149 r = chase(target, NULL, 0, &target_resolved, NULL);
3150 if (r < 0)
3151 goto fail;
3152
3153 q = path_join(params->prefix[type], "private", i->path);
3154 if (!q) {
3155 r = -ENOMEM;
3156 goto fail;
3157 }
3158
3159 /* /var/lib or friends may be symlinks. So, let's chase them also. */
3160 r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
3161 if (r < 0)
3162 goto fail;
3163
3164 if (path_equal(q_resolved, target_resolved)) {
3165
3166 /* Hmm, apparently DynamicUser= was once turned on for this service,
3167 * but is no longer. Let's move the directory back up. */
3168
3169 log_info("Found pre-existing private %s= directory %s, migrating to %s.\n"
3170 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
3171 exec_directory_type_to_string(type), q, p);
3172
3173 r = RET_NERRNO(unlink(p));
3174 if (r < 0)
3175 goto fail;
3176
3177 r = RET_NERRNO(rename(q, p));
3178 if (r < 0)
3179 goto fail;
3180 }
3181 }
3182
3183 r = mkdir_label(p, context->directories[type].mode);
3184 if (r < 0) {
3185 if (r != -EEXIST)
3186 goto fail;
3187
3188 if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
3189 struct stat st;
3190
3191 /* Don't change the owner/access mode of the configuration directory,
3192 * as in the common case it is not written to by a service, and shall
3193 * not be writable. */
3194
3195 r = RET_NERRNO(stat(p, &st));
3196 if (r < 0)
3197 goto fail;
3198
3199 /* Still complain if the access mode doesn't match */
3200 if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
3201 log_warning("%s \'%s\' already exists but the mode is different. "
3202 "(File system: %o %sMode: %o)",
3203 exec_directory_type_to_string(type), i->path,
3204 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
3205
3206 continue;
3207 }
3208 }
3209 }
3210
3211 /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
3212 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
3213 * current UID/GID ownership.) */
3214 const char *target_dir = pp ?: p;
3215 r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
3216 if (r < 0)
3217 goto fail;
3218
3219 /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
3220 * available to user code anyway */
3221 if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3222 continue;
3223
3224 int idmapping_supported = is_idmapping_supported(target_dir);
3225 if (idmapping_supported < 0) {
3226 r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
3227 goto fail;
3228 }
3229
3230 log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
3231
3232 /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
3233 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
3234 * assignments to exist. */
3235 uid_t chown_uid = uid;
3236 gid_t chown_gid = gid;
3237 bool do_chown = false;
3238
3239 if (uid == 0 || gid == 0 || !idmapping_supported) {
3240 do_chown = true;
3241 i->idmapped = false;
3242 } else {
3243 /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
3244 * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
3245 struct stat st;
3246 r = RET_NERRNO(stat(target_dir, &st));
3247 if (r < 0)
3248 goto fail;
3249
3250 if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
3251 do_chown = false;
3252 i->idmapped = true;
3253 } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
3254 chown_uid = UID_NOBODY;
3255 chown_gid = GID_NOBODY;
3256 do_chown = true;
3257 i->idmapped = true;
3258 } else {
3259 do_chown = true;
3260 i->idmapped = false;
3261 }
3262 }
3263
3264 if (do_chown) {
3265 r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
3266 if (r < 0)
3267 goto fail;
3268 }
3269
3270 /* Apply storage quotas and accounting */
3271 r = apply_exec_quotas(target_dir, params->cgroup_path, type, &context->directories[type].exec_quota, &exec_dt_proj_id, &quota_already_enforced);
3272 if (r < 0)
3273 goto fail;
3274 }
3275
3276 /* If we are not going to run in a namespace, set up the symlinks - otherwise
3277 * they are set up later, to allow configuring empty var/run/etc. */
3278 if (!needs_mount_namespace)
3279 FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
3280 r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
3281 if (r < 0)
3282 goto fail;
3283 }
3284
3285 return 0;
3286
3287 fail:
3288 *exit_status = exit_status_table[type];
3289 return r;
3290 }
3291
3292 #if ENABLE_SMACK
3293 static int setup_smack(
3294 const ExecContext *context,
3295 const ExecParameters *params,
3296 int executable_fd) {
3297 int r;
3298
3299 assert(context);
3300 assert(params);
3301 assert(executable_fd >= 0);
3302
3303 if (context->smack_process_label) {
3304 r = mac_smack_apply_pid(0, context->smack_process_label);
3305 if (r < 0)
3306 return r;
3307 } else if (params->fallback_smack_process_label) {
3308 _cleanup_free_ char *exec_label = NULL;
3309
3310 r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
3311 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
3312 return r;
3313
3314 r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
3315 if (r < 0)
3316 return r;
3317 }
3318
3319 return 0;
3320 }
3321 #endif
3322
3323 static int compile_bind_mounts(
3324 const ExecContext *context,
3325 const ExecParameters *params,
3326 uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
3327 gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
3328 BindMount **ret_bind_mounts,
3329 size_t *ret_n_bind_mounts,
3330 char ***ret_empty_directories) {
3331
3332 _cleanup_strv_free_ char **empty_directories = NULL;
3333 BindMount *bind_mounts = NULL;
3334 size_t n, h = 0;
3335 int r;
3336
3337 assert(context);
3338 assert(params);
3339 assert(ret_bind_mounts);
3340 assert(ret_n_bind_mounts);
3341 assert(ret_empty_directories);
3342
3343 CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
3344
3345 n = context->n_bind_mounts;
3346 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
3347 if (!params->prefix[t])
3348 continue;
3349
3350 FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
3351 n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
3352 }
3353
3354 if (n <= 0) {
3355 *ret_bind_mounts = NULL;
3356 *ret_n_bind_mounts = 0;
3357 *ret_empty_directories = NULL;
3358 return 0;
3359 }
3360
3361 bind_mounts = new(BindMount, n);
3362 if (!bind_mounts)
3363 return -ENOMEM;
3364
3365 FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
3366 r = bind_mount_add(&bind_mounts, &h, item);
3367 if (r < 0)
3368 return r;
3369 }
3370
3371 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
3372 if (!params->prefix[t])
3373 continue;
3374
3375 if (context->directories[t].n_items == 0)
3376 continue;
3377
3378 if (exec_directory_is_private(context, t) &&
3379 !exec_context_with_rootfs(context)) {
3380 char *private_root;
3381
3382 /* So this is for a dynamic user, and we need to make sure the process can access its own
3383 * directory. For that we overmount the usually inaccessible "private" subdirectory with a
3384 * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
3385
3386 private_root = path_join(params->prefix[t], "private");
3387 if (!private_root)
3388 return -ENOMEM;
3389
3390 r = strv_consume(&empty_directories, private_root);
3391 if (r < 0)
3392 return r;
3393 }
3394
3395 FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items) {
3396 _cleanup_free_ char *s = NULL, *d = NULL;
3397
3398 /* When one of the parent directories is in the list, we cannot create the symlink
3399 * for the child directory. See also the comments in setup_exec_directory().
3400 * But if it needs to be read only, then we have to create a bind mount anyway to
3401 * make it so. */
3402 if (FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) && !FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
3403 continue;
3404
3405 if (exec_directory_is_private(context, t))
3406 s = path_join(params->prefix[t], "private", i->path);
3407 else
3408 s = path_join(params->prefix[t], i->path);
3409 if (!s)
3410 return -ENOMEM;
3411
3412 if (exec_directory_is_private(context, t) &&
3413 exec_context_with_rootfs(context))
3414 /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3415 * directory is not created on the root directory. So, let's bind-mount the directory
3416 * on the 'non-private' place. */
3417 d = path_join(params->prefix[t], i->path);
3418 else
3419 d = strdup(s);
3420 if (!d)
3421 return -ENOMEM;
3422
3423 bind_mounts[h++] = (BindMount) {
3424 .source = TAKE_PTR(s),
3425 .destination = TAKE_PTR(d),
3426 .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
3427 .recursive = true,
3428 .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
3429 .idmapped = i->idmapped,
3430 .uid = exec_directory_uid,
3431 .gid = exec_directory_gid,
3432 };
3433 }
3434 }
3435
3436 assert(h == n);
3437
3438 *ret_bind_mounts = TAKE_PTR(bind_mounts);
3439 *ret_n_bind_mounts = n;
3440 *ret_empty_directories = TAKE_PTR(empty_directories);
3441
3442 return (int) n;
3443 }
3444
3445 /* ret_symlinks will contain a list of pairs src:dest that describes
3446 * the symlinks to create later on. For example, the symlinks needed
3447 * to safely give private directories to DynamicUser=1 users. */
3448 static int compile_symlinks(
3449 const ExecContext *context,
3450 const ExecParameters *params,
3451 bool setup_os_release_symlink,
3452 char ***ret_symlinks) {
3453
3454 _cleanup_strv_free_ char **symlinks = NULL;
3455 int r;
3456
3457 assert(context);
3458 assert(params);
3459 assert(ret_symlinks);
3460
3461 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
3462 FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
3463 _cleanup_free_ char *private_path = NULL, *path = NULL;
3464
3465 STRV_FOREACH(symlink, i->symlinks) {
3466 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
3467
3468 src_abs = path_join(params->prefix[dt], i->path);
3469 dst_abs = path_join(params->prefix[dt], *symlink);
3470 if (!src_abs || !dst_abs)
3471 return -ENOMEM;
3472
3473 r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
3474 if (r < 0)
3475 return r;
3476 }
3477
3478 if (!exec_directory_is_private(context, dt) ||
3479 exec_context_with_rootfs(context) ||
3480 FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
3481 continue;
3482
3483 private_path = path_join(params->prefix[dt], "private", i->path);
3484 if (!private_path)
3485 return -ENOMEM;
3486
3487 path = path_join(params->prefix[dt], i->path);
3488 if (!path)
3489 return -ENOMEM;
3490
3491 r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
3492 if (r < 0)
3493 return r;
3494 }
3495
3496 /* We make the host's os-release available via a symlink, so that we can copy it atomically
3497 * and readers will never get a half-written version. Note that, while the paths specified here are
3498 * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3499 * 'os-release -> .os-release-stage/os-release' is what will be created. */
3500 if (setup_os_release_symlink) {
3501 r = strv_extend_many(
3502 &symlinks,
3503 "/run/host/.os-release-stage/os-release",
3504 "/run/host/os-release");
3505 if (r < 0)
3506 return r;
3507 }
3508
3509 *ret_symlinks = TAKE_PTR(symlinks);
3510
3511 return 0;
3512 }
3513
3514 static bool insist_on_sandboxing(
3515 const ExecContext *context,
3516 const PinnedResource *rootfs,
3517 const BindMount *bind_mounts,
3518 size_t n_bind_mounts) {
3519
3520 assert(context);
3521 assert(n_bind_mounts == 0 || bind_mounts);
3522
3523 /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
3524 * would alter the view on the file system beyond making things read-only or invisible, i.e. would
3525 * rearrange stuff in a way we cannot ignore gracefully. */
3526
3527 if (context->n_temporary_filesystems > 0)
3528 return true;
3529
3530 if (pinned_resource_is_set(rootfs))
3531 return true;
3532
3533 if (context->n_mount_images > 0)
3534 return true;
3535
3536 if (context->dynamic_user)
3537 return true;
3538
3539 if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
3540 return true;
3541
3542 /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3543 * essential. */
3544 FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
3545 if (!path_equal(i->source, i->destination))
3546 return true;
3547
3548 if (context->log_namespace)
3549 return true;
3550
3551 return false;
3552 }
3553
3554 static int setup_ephemeral(
3555 const ExecContext *context,
3556 ExecRuntime *runtime,
3557 PinnedResource *rootfs, /* both input and output! modified if ephemeral logic enabled */
3558 char **reterr_path) {
3559
3560 _cleanup_close_ int fd = -EBADF;
3561 _cleanup_free_ char *new_root = NULL;
3562 int r;
3563
3564 assert(context);
3565 assert(runtime);
3566 assert(rootfs);
3567
3568 if (!rootfs->image && !rootfs->directory)
3569 return 0;
3570
3571 if (!runtime->ephemeral_copy)
3572 return 0;
3573
3574 assert(runtime->ephemeral_storage_socket[0] >= 0);
3575 assert(runtime->ephemeral_storage_socket[1] >= 0);
3576
3577 new_root = strdup(runtime->ephemeral_copy);
3578 if (!new_root)
3579 return log_oom_debug();
3580
3581 r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
3582 if (r < 0)
3583 return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
3584
3585 CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
3586
3587 fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
3588 if (fd >= 0)
3589 /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3590 return 0;
3591 if (fd != -EAGAIN)
3592 return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
3593
3594 if (rootfs->image) {
3595 log_debug("Making ephemeral copy of %s to %s", rootfs->image, new_root);
3596
3597 fd = copy_file(rootfs->image, new_root, O_EXCL, 0600,
3598 COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3599 if (fd < 0) {
3600 *reterr_path = strdup(rootfs->image);
3601 return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
3602 rootfs->image, new_root);
3603 }
3604 } else {
3605 assert(rootfs->directory);
3606
3607 log_debug("Making ephemeral snapshot of %s to %s", rootfs->directory, new_root);
3608
3609 fd = btrfs_subvol_snapshot_at(
3610 AT_FDCWD, rootfs->directory,
3611 AT_FDCWD, new_root,
3612 BTRFS_SNAPSHOT_FALLBACK_COPY |
3613 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3614 BTRFS_SNAPSHOT_RECURSIVE |
3615 BTRFS_SNAPSHOT_LOCK_BSD);
3616 if (fd < 0) {
3617 *reterr_path = strdup(rootfs->directory);
3618 return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
3619 rootfs->directory, new_root);
3620 }
3621 }
3622
3623 r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
3624 if (r < 0)
3625 return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
3626
3627 if (rootfs->image) {
3628 free_and_replace(rootfs->image, new_root);
3629 close_and_replace(rootfs->image_fd, fd);
3630 } else {
3631 assert(rootfs->directory);
3632
3633 free_and_replace(rootfs->directory, new_root);
3634 close_and_replace(rootfs->directory_fd, fd);
3635 }
3636
3637 return 1;
3638 }
3639
3640 static int verity_settings_prepare(
3641 VeritySettings *verity,
3642 const char *root_image,
3643 const struct iovec *root_hash,
3644 const char *root_hash_path,
3645 const struct iovec *root_hash_sig,
3646 const char *root_hash_sig_path,
3647 const char *verity_data_path) {
3648
3649 int r;
3650
3651 assert(verity);
3652
3653 if (root_hash) {
3654 iovec_done(&verity->root_hash);
3655
3656 if (!iovec_memdup(root_hash, &verity->root_hash))
3657 return -ENOMEM;
3658
3659 verity->designator = PARTITION_ROOT;
3660 }
3661
3662 if (root_hash_sig) {
3663 iovec_done(&verity->root_hash_sig);
3664
3665 if (!iovec_memdup(root_hash_sig, &verity->root_hash_sig))
3666 return -ENOMEM;
3667
3668 verity->designator = PARTITION_ROOT;
3669 }
3670
3671 if (verity_data_path) {
3672 r = free_and_strdup(&verity->data_path, verity_data_path);
3673 if (r < 0)
3674 return r;
3675 }
3676
3677 r = verity_settings_load(
3678 verity,
3679 root_image,
3680 root_hash_path,
3681 root_hash_sig_path);
3682 if (r < 0)
3683 return log_debug_errno(r, "Failed to load root hash: %m");
3684
3685 return 0;
3686 }
3687
3688 static int pin_rootfs(
3689 const ExecContext *context,
3690 const ExecParameters *params,
3691 PinnedResource *ret,
3692 char **reterr_path) {
3693
3694 int r;
3695
3696 assert(context);
3697 assert(params);
3698 assert(ret);
3699
3700 if (!FLAGS_SET(params->flags, EXEC_APPLY_CHROOT)) {
3701 *ret = PINNED_RESOURCE_NULL;
3702 return 0;
3703 }
3704
3705 if (context->root_directory_as_fd) {
3706 _cleanup_close_ int fd = fcntl(params->root_directory_fd, F_DUPFD_CLOEXEC, 3);
3707 if (fd < 0)
3708 return log_debug_errno(errno, "Failed to duplicate root directory fd: %m");
3709
3710 *ret = (PinnedResource) {
3711 .directory_fd = TAKE_FD(fd),
3712 .image_fd = -EBADF,
3713 };
3714
3715 return 1;
3716 }
3717
3718 if (context->root_image) {
3719 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3720
3721 r = path_pick(/* toplevel_path= */ NULL,
3722 /* toplevel_fd= */ AT_FDCWD,
3723 context->root_image,
3724 pick_filter_image_raw,
3725 ELEMENTSOF(pick_filter_image_raw),
3726 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3727 &result);
3728 if (r < 0) {
3729 *reterr_path = strdup(context->root_image);
3730 return r;
3731 }
3732
3733 if (!result.path) {
3734 *reterr_path = strdup(context->root_image);
3735 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
3736 }
3737
3738 /* path_pick() returns us an O_PATH fd, let's turn this into a fully opened file, because
3739 * mountfsd will want this later, and it wants a fully opened fd, so that security checks
3740 * have been passed */
3741 _cleanup_close_ int reopened_fd = -EBADF;
3742 reopened_fd = fd_reopen(result.fd, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDWR);
3743 if (ERRNO_IS_NEG_FS_WRITE_REFUSED(reopened_fd))
3744 reopened_fd = fd_reopen(result.fd, O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_RDONLY);
3745 if (reopened_fd < 0) {
3746 *reterr_path = strdup(context->root_image);
3747 return log_debug_errno(reopened_fd, "Failed to open image '%s': %m", context->root_image);
3748 }
3749
3750 *ret = (PinnedResource) {
3751 .image = TAKE_PTR(result.path),
3752 .image_fd = TAKE_FD(reopened_fd),
3753 .directory_fd = -EBADF,
3754 };
3755
3756 return r;
3757 }
3758
3759 if (context->root_directory) {
3760 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3761
3762 r = path_pick(/* toplevel_path= */ NULL,
3763 /* toplevel_fd= */ AT_FDCWD,
3764 context->root_directory,
3765 pick_filter_image_dir,
3766 ELEMENTSOF(pick_filter_image_dir),
3767 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3768 &result);
3769 if (r < 0) {
3770 *reterr_path = strdup(context->root_directory);
3771 return r;
3772 }
3773
3774 if (!result.path) {
3775 *reterr_path = strdup(context->root_directory);
3776 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
3777 }
3778
3779 *ret = (PinnedResource) {
3780 .directory = TAKE_PTR(result.path),
3781 .directory_fd = TAKE_FD(result.fd),
3782 .image_fd = -EBADF,
3783 };
3784
3785 return r;
3786 }
3787
3788 if (context->root_mstack) {
3789 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3790
3791 r = path_pick(/* toplevel_path= */ NULL,
3792 /* toplevel_fd= */ AT_FDCWD,
3793 context->root_mstack,
3794 pick_filter_image_mstack,
3795 /* n_filters= */ 1,
3796 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3797 &result);
3798 if (r < 0) {
3799 *reterr_path = strdup(context->root_mstack);
3800 return r;
3801 }
3802
3803 if (!result.path) {
3804 *reterr_path = strdup(context->root_mstack);
3805 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_mstack);
3806 }
3807
3808 _cleanup_(mstack_freep) MStack *mstack = NULL;
3809 r = mstack_load(result.path, result.fd, &mstack);
3810 if (r < 0) {
3811 *reterr_path = TAKE_PTR(result.path);
3812 return r;
3813 }
3814
3815 *ret = (PinnedResource) {
3816 .mstack = TAKE_PTR(result.path),
3817 .mstack_loaded = TAKE_PTR(mstack),
3818 .image_fd = -EBADF,
3819 .directory_fd = -EBADF,
3820 };
3821
3822 return r;
3823 }
3824
3825 *ret = PINNED_RESOURCE_NULL;
3826 return 0;
3827 }
3828
3829 static int apply_mount_namespace(
3830 ExecCommandFlags command_flags,
3831 const ExecContext *context,
3832 const ExecParameters *params,
3833 const ExecRuntime *runtime,
3834 const PinnedResource *rootfs,
3835 char *const *pressure_path,
3836 bool needs_sandboxing,
3837 uid_t exec_directory_uid,
3838 gid_t exec_directory_gid,
3839 PidRef *bpffs_pidref,
3840 int bpffs_socket_fd,
3841 int bpffs_errno_pipe,
3842 sd_varlink *mountfsd_link,
3843 char **reterr_path) {
3844
3845 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3846 _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
3847 **read_write_paths_cleanup = NULL;
3848 _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
3849 *private_namespace_dir = NULL, *host_os_release_stage = NULL;
3850 const char *tmp_dir = NULL, *var_tmp_dir = NULL;
3851 char **read_write_paths;
3852 bool setup_os_release_symlink;
3853 BindMount *bind_mounts = NULL;
3854 size_t n_bind_mounts = 0;
3855 int r;
3856
3857 assert(context);
3858 assert(params);
3859 assert(runtime);
3860
3861 CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
3862
3863 r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
3864 if (r < 0)
3865 return r;
3866
3867 /* We need to make the pressure paths writable even if /sys/fs/cgroups is made read-only, as the
3868 * service will need to write to them in order to start the notifications. */
3869 bool need_pressure_rw = false;
3870 for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++)
3871 if (pressure_path[t] && !streq(pressure_path[t], "/dev/null")) {
3872 need_pressure_rw = true;
3873 break;
3874 }
3875
3876 if (exec_is_cgroup_mount_read_only(context) && need_pressure_rw) {
3877 read_write_paths_cleanup = strv_copy(context->read_write_paths);
3878 if (!read_write_paths_cleanup)
3879 return -ENOMEM;
3880
3881 for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
3882 if (!pressure_path[t] || streq(pressure_path[t], "/dev/null"))
3883 continue;
3884
3885 r = strv_extend(&read_write_paths_cleanup, pressure_path[t]);
3886 if (r < 0)
3887 return r;
3888 }
3889
3890 read_write_paths = read_write_paths_cleanup;
3891 } else
3892 read_write_paths = context->read_write_paths;
3893
3894 if (needs_sandboxing) {
3895 /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
3896 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
3897 * use here. This does not apply when we are using /run/systemd/empty as fallback. */
3898
3899 if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
3900 if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
3901 tmp_dir = runtime->shared->tmp_dir;
3902 else if (runtime->shared->tmp_dir)
3903 tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
3904 }
3905
3906 if (context->private_var_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
3907 if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
3908 var_tmp_dir = runtime->shared->var_tmp_dir;
3909 else if (runtime->shared->var_tmp_dir)
3910 var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
3911 }
3912 }
3913
3914 /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3915 setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && pinned_resource_is_set(rootfs);
3916 r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
3917 if (r < 0)
3918 return r;
3919
3920 if (context->mount_propagation_flag == MS_SHARED)
3921 log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
3922
3923 r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
3924 if (r < 0)
3925 return r;
3926
3927 if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
3928 if (!mount_new_api_supported()) {
3929 propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
3930 if (!propagate_dir)
3931 return -ENOMEM;
3932
3933 incoming_dir = strdup("/run/systemd/incoming");
3934 if (!incoming_dir)
3935 return -ENOMEM;
3936 }
3937
3938 private_namespace_dir = strdup("/run/systemd");
3939 if (!private_namespace_dir)
3940 return -ENOMEM;
3941
3942 /* If running under a different root filesystem, propagate the host's os-release. We make a
3943 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3944 if (setup_os_release_symlink) {
3945 host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
3946 if (!host_os_release_stage)
3947 return -ENOMEM;
3948 }
3949 } else {
3950 assert(params->runtime_scope == RUNTIME_SCOPE_USER);
3951
3952 if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
3953 return -ENOMEM;
3954
3955 if (setup_os_release_symlink &&
3956 asprintf(&host_os_release_stage,
3957 "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3958 geteuid()) < 0)
3959 return -ENOMEM;
3960 }
3961
3962 if (rootfs->image) {
3963 r = verity_settings_prepare(
3964 &verity,
3965 rootfs->image,
3966 &context->root_hash, context->root_hash_path,
3967 &context->root_hash_sig, context->root_hash_sig_path,
3968 context->root_verity);
3969 if (r < 0)
3970 return r;
3971 }
3972
3973 NamespaceParameters parameters = {
3974 .runtime_scope = params->runtime_scope,
3975
3976 .rootfs = rootfs,
3977 .root_image_options = context->root_image_options,
3978 .root_image_policy = context->root_image_policy ?: &image_policy_service,
3979
3980 .read_write_paths = read_write_paths,
3981 .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
3982 .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
3983
3984 .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
3985 .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
3986
3987 .empty_directories = empty_directories,
3988 .symlinks = symlinks,
3989
3990 .bind_mounts = bind_mounts,
3991 .n_bind_mounts = n_bind_mounts,
3992
3993 .temporary_filesystems = context->temporary_filesystems,
3994 .n_temporary_filesystems = context->n_temporary_filesystems,
3995
3996 .mount_images = context->mount_images,
3997 .n_mount_images = context->n_mount_images,
3998 .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
3999
4000 .tmp_dir = tmp_dir,
4001 .var_tmp_dir = var_tmp_dir,
4002
4003 .creds_path = creds_path,
4004 .log_namespace = context->log_namespace,
4005 .mount_propagation_flag = context->mount_propagation_flag,
4006
4007 .verity = &verity,
4008
4009 .extension_images = context->extension_images,
4010 .n_extension_images = context->n_extension_images,
4011 .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
4012 .extension_directories = context->extension_directories,
4013
4014 .propagate_dir = propagate_dir,
4015 .incoming_dir = incoming_dir,
4016 .private_namespace_dir = private_namespace_dir,
4017 .host_notify_socket = params->notify_socket,
4018 .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
4019 .host_os_release_stage = host_os_release_stage,
4020
4021 /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
4022 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
4023 * sandbox inside the mount namespace. */
4024 .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && pinned_resource_is_set(rootfs),
4025
4026 .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
4027 .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
4028 .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
4029 .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
4030
4031 .private_dev = needs_sandboxing && context->private_devices,
4032 .private_network = needs_sandboxing && exec_needs_network_namespace(context),
4033 .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
4034 .private_pids = needs_sandboxing && exec_needs_pid_namespace(context, params) ? context->private_pids : PRIVATE_PIDS_NO,
4035 .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
4036 .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
4037
4038 .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
4039 .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
4040
4041 /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
4042 .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
4043
4044 .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
4045 .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
4046 .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
4047 .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
4048 .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
4049 .private_bpf = needs_sandboxing ? context->private_bpf : PRIVATE_BPF_NO,
4050 .private_users = needs_sandboxing ? context->private_users : PRIVATE_USERS_NO,
4051
4052 .bpffs_pidref = bpffs_pidref,
4053 .bpffs_socket_fd = bpffs_socket_fd,
4054 .bpffs_errno_pipe = bpffs_errno_pipe,
4055
4056 .mountfsd_link = mountfsd_link,
4057 };
4058
4059 r = setup_namespace(&parameters, reterr_path);
4060 /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
4061 * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
4062 * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
4063 * completely different execution environment. */
4064 if (r == -ENOANO) {
4065 if (insist_on_sandboxing(
4066 context,
4067 rootfs,
4068 bind_mounts,
4069 n_bind_mounts))
4070 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4071 "Failed to set up namespace, and refusing to continue since "
4072 "the selected namespacing options alter mount environment non-trivially.\n"
4073 "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, root mstack: %s, dynamic user: %s",
4074 n_bind_mounts,
4075 context->n_temporary_filesystems,
4076 yes_no(rootfs->directory_fd >= 0),
4077 yes_no(rootfs->image_fd >= 0),
4078 yes_no(!!rootfs->mstack_loaded),
4079 yes_no(context->dynamic_user));
4080
4081 log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
4082 return 0;
4083 }
4084
4085 return r;
4086 }
4087
4088 static int apply_working_directory(
4089 const ExecContext *context,
4090 const ExecParameters *params,
4091 ExecRuntime *runtime,
4092 const char *pwent_home,
4093 char * const *env) {
4094
4095 const char *wd;
4096 int r;
4097
4098 assert(context);
4099 assert(params);
4100 assert(runtime);
4101
4102 if (context->working_directory_home) {
4103 /* Preferably use the data from $HOME, in case it was updated by a PAM module */
4104 wd = strv_env_get(env, "HOME");
4105 if (!wd) {
4106 /* If that's not available, use the data from the struct passwd entry: */
4107 if (!pwent_home)
4108 return -ENXIO;
4109
4110 wd = pwent_home;
4111 }
4112 } else
4113 wd = empty_to_root(context->working_directory);
4114
4115 if (params->flags & EXEC_APPLY_CHROOT)
4116 r = RET_NERRNO(chdir(wd));
4117 else {
4118 _cleanup_close_ int dfd = -EBADF;
4119
4120 r = chase(wd,
4121 runtime->ephemeral_copy ?: context->root_directory,
4122 CHASE_PREFIX_ROOT|CHASE_TRIGGER_AUTOFS,
4123 /* ret_path= */ NULL,
4124 &dfd);
4125 if (r >= 0)
4126 r = RET_NERRNO(fchdir(dfd));
4127 }
4128 return context->working_directory_missing_ok ? 0 : r;
4129 }
4130
4131 static int apply_root_directory(
4132 const ExecContext *context,
4133 const ExecParameters *params,
4134 ExecRuntime *runtime,
4135 const bool needs_mount_ns,
4136 int *exit_status) {
4137
4138 assert(context);
4139 assert(params);
4140 assert(runtime);
4141 assert(exit_status);
4142
4143 if (params->flags & EXEC_APPLY_CHROOT)
4144 if (!needs_mount_ns && context->root_directory) {
4145 if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
4146 *exit_status = EXIT_CHROOT;
4147 return -errno;
4148 }
4149
4150 /* chroot(2) changes only the process root, not cwd. Move cwd into the new root
4151 * immediately so that a subsequent apply_working_directory() failure that is
4152 * silently ignored via working_directory_missing_ok cannot leave cwd pointing
4153 * at a pre-chroot dentry outside the new root. */
4154 if (chdir("/") < 0) {
4155 *exit_status = EXIT_CHROOT;
4156 return -errno;
4157 }
4158 }
4159
4160 return 0;
4161 }
4162
4163 static int setup_keyring(
4164 const ExecContext *context,
4165 const ExecParameters *p,
4166 uid_t uid,
4167 gid_t gid) {
4168
4169 key_serial_t keyring;
4170 int r = 0;
4171 uid_t saved_uid;
4172 gid_t saved_gid;
4173
4174 assert(context);
4175 assert(p);
4176
4177 /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
4178 * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
4179 * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
4180 * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
4181 * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
4182 * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
4183
4184 if (context->keyring_mode == EXEC_KEYRING_INHERIT)
4185 return 0;
4186
4187 /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
4188 * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
4189 * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
4190 * & group is just as nasty as acquiring a reference to the user keyring. */
4191
4192 saved_uid = getuid();
4193 saved_gid = getgid();
4194
4195 if (gid_is_valid(gid) && gid != saved_gid) {
4196 if (setregid(gid, -1) < 0)
4197 return log_error_errno(errno, "Failed to change GID for user keyring: %m");
4198 }
4199
4200 if (uid_is_valid(uid) && uid != saved_uid) {
4201 if (setreuid(uid, -1) < 0) {
4202 r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
4203 goto out;
4204 }
4205 }
4206
4207 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
4208 if (keyring == -1) {
4209 if (errno == ENOSYS)
4210 log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
4211 else if (ERRNO_IS_PRIVILEGE(errno))
4212 log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
4213 else if (errno == EDQUOT)
4214 log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
4215 else
4216 r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
4217
4218 goto out;
4219 }
4220
4221 /* When requested link the user keyring into the session keyring. */
4222 if (context->keyring_mode == EXEC_KEYRING_SHARED) {
4223
4224 if (keyctl(KEYCTL_LINK,
4225 KEY_SPEC_USER_KEYRING,
4226 KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
4227 r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
4228 goto out;
4229 }
4230 }
4231
4232 /* Restore uid/gid back */
4233 if (uid_is_valid(uid) && uid != saved_uid) {
4234 if (setreuid(saved_uid, -1) < 0) {
4235 r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
4236 goto out;
4237 }
4238 }
4239
4240 if (gid_is_valid(gid) && gid != saved_gid) {
4241 if (setregid(saved_gid, -1) < 0)
4242 return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
4243 }
4244
4245 /* Populate the keyring with the invocation ID by default, as original saved_uid. */
4246 if (!sd_id128_is_null(p->invocation_id)) {
4247 key_serial_t key;
4248
4249 key = add_key("user",
4250 "invocation_id",
4251 &p->invocation_id,
4252 sizeof(p->invocation_id),
4253 KEY_SPEC_SESSION_KEYRING);
4254 if (key == -1)
4255 log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
4256 else {
4257 if (keyctl(KEYCTL_SETPERM, key,
4258 KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
4259 KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
4260 r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
4261 }
4262 }
4263
4264 out:
4265 /* Revert back uid & gid for the last time, and exit */
4266 /* no extra logging, as only the first already reported error matters */
4267 if (getuid() != saved_uid)
4268 (void) setreuid(saved_uid, -1);
4269
4270 if (getgid() != saved_gid)
4271 (void) setregid(saved_gid, -1);
4272
4273 return r;
4274 }
4275
4276 #define FD_PAIR_CONDITION(cond, pair) \
4277 (cond) ? pair[0] : -EBADF, (cond) ? pair[1] : -EBADF
4278
4279 #define FD_PAIR(pair) FD_PAIR_CONDITION(true, pair)
4280
4281 static int close_remaining_fds(
4282 const ExecParameters *params,
4283 const ExecRuntime *runtime,
4284 int socket_fd,
4285 const int fds[],
4286 size_t n_fds) {
4287
4288 assert(params);
4289 assert(runtime);
4290 assert(fds || n_fds == 0);
4291
4292 /* fds listed here shall be closed before second close_all_fds() call to avoid double close! */
4293 int static_fds[] = {
4294 params->stdin_fd, params->stdout_fd, params->stderr_fd,
4295 socket_fd,
4296 FD_PAIR(runtime->ephemeral_storage_socket),
4297 FD_PAIR_CONDITION(runtime->shared, runtime->shared->userns_storage_socket),
4298 FD_PAIR_CONDITION(runtime->shared, runtime->shared->netns_storage_socket),
4299 FD_PAIR_CONDITION(runtime->shared, runtime->shared->ipcns_storage_socket),
4300 FD_PAIR_CONDITION(runtime->dynamic_creds && runtime->dynamic_creds->user,
4301 runtime->dynamic_creds->user->storage_socket),
4302 FD_PAIR_CONDITION(runtime->dynamic_creds && runtime->dynamic_creds->group,
4303 runtime->dynamic_creds->group->storage_socket),
4304 params->user_lookup_fd,
4305 params->pidref_transport_fd,
4306 };
4307
4308 _cleanup_free_ int *accum_fds = NULL;
4309 if (n_fds > 0) {
4310 accum_fds = new(int, ELEMENTSOF(static_fds) + n_fds);
4311 if (!accum_fds)
4312 return -ENOMEM;
4313
4314 memcpy(mempcpy_typesafe(accum_fds, static_fds, ELEMENTSOF(static_fds)), fds, sizeof(int) * n_fds);
4315 }
4316
4317 return close_all_fds(accum_fds ?: static_fds, ELEMENTSOF(static_fds) + n_fds);
4318 }
4319
4320 static int send_user_lookup(
4321 const char *unit_id,
4322 int user_lookup_fd,
4323 uid_t uid,
4324 gid_t gid) {
4325
4326 assert(unit_id);
4327
4328 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
4329 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
4330 * specified. */
4331
4332 if (user_lookup_fd < 0)
4333 return 0;
4334
4335 if (!uid_is_valid(uid) && !gid_is_valid(gid))
4336 return 0;
4337
4338 if (writev(user_lookup_fd,
4339 (struct iovec[]) {
4340 IOVEC_MAKE(&uid, sizeof(uid)),
4341 IOVEC_MAKE(&gid, sizeof(gid)),
4342 IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
4343 return -errno;
4344
4345 return 0;
4346 }
4347
4348 static int acquire_home(const ExecContext *c, char **home) {
4349 assert(c);
4350 assert(home);
4351
4352 /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
4353
4354 if (*home) /* Already acquired from get_user_creds()? */
4355 return 0;
4356
4357 if (!c->working_directory_home)
4358 return 0;
4359
4360 if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
4361 return -EADDRNOTAVAIL;
4362
4363 return get_home_dir(home);
4364 }
4365
4366 static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
4367 _cleanup_strv_free_ char ** list = NULL;
4368 int r;
4369
4370 assert(c);
4371 assert(p);
4372 assert(ret);
4373
4374 assert(c->dynamic_user);
4375
4376 /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
4377 * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
4378 * directories. */
4379
4380 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
4381
4382 if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
4383 continue;
4384
4385 if (!p->prefix[t])
4386 continue;
4387
4388 for (size_t i = 0; i < c->directories[t].n_items; i++) {
4389 char *e;
4390
4391 if (exec_directory_is_private(c, t))
4392 e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
4393 else
4394 e = path_join(p->prefix[t], c->directories[t].items[i].path);
4395 if (!e)
4396 return -ENOMEM;
4397
4398 r = strv_consume(&list, e);
4399 if (r < 0)
4400 return r;
4401 }
4402 }
4403
4404 *ret = TAKE_PTR(list);
4405
4406 return 0;
4407 }
4408
4409 static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
4410 int r;
4411
4412 assert(c);
4413 assert(ret);
4414
4415 if (!c->numa_policy.nodes.set) {
4416 log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
4417 *ret = (CPUSet) {};
4418 return 0;
4419 }
4420
4421 _cleanup_(cpu_set_done) CPUSet s = {};
4422 r = numa_to_cpu_set(&c->numa_policy, &s);
4423 if (r < 0)
4424 return r;
4425
4426 *ret = TAKE_STRUCT(s);
4427 return 0;
4428 }
4429
4430 static int add_shifted_fd(int **fds, size_t *n_fds, int *fd) {
4431 int r;
4432
4433 assert(fds);
4434 assert(n_fds);
4435 assert(fd);
4436
4437 if (*fd < 0)
4438 return 0;
4439
4440 if (*fd < 3 + (int) *n_fds) {
4441 /* Let's move the fd up, so that it's outside of the fd range we will use to store
4442 * the fds we pass to the process (or which are closed only during execve). */
4443
4444 r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
4445 if (r < 0)
4446 return -errno;
4447
4448 close_and_replace(*fd, r);
4449 }
4450
4451 if (!GREEDY_REALLOC(*fds, *n_fds + 1))
4452 return -ENOMEM;
4453
4454 (*fds)[(*n_fds)++] = *fd;
4455 return 1;
4456 }
4457
4458 static int connect_unix_harder(const OpenFile *of, int ofd) {
4459 static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
4460
4461 union sockaddr_union addr = {
4462 .un.sun_family = AF_UNIX,
4463 };
4464 socklen_t sa_len;
4465 int r;
4466
4467 assert(of);
4468 assert(ofd >= 0);
4469
4470 r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
4471 if (r < 0)
4472 return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
4473 sa_len = r;
4474
4475 FOREACH_ELEMENT(i, socket_types) {
4476 _cleanup_close_ int fd = -EBADF;
4477
4478 fd = socket(AF_UNIX, *i|SOCK_CLOEXEC, 0);
4479 if (fd < 0)
4480 return log_debug_errno(errno, "Failed to create socket for '%s': %m", of->path);
4481
4482 r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
4483 if (r >= 0)
4484 return TAKE_FD(fd);
4485 if (r != -EPROTOTYPE)
4486 return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
4487 }
4488
4489 return log_debug_errno(SYNTHETIC_ERRNO(EPROTOTYPE), "No suitable socket type to connect to socket '%s'.", of->path);
4490 }
4491
4492 static int get_open_file_fd(const OpenFile *of) {
4493 _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
4494 struct stat st;
4495
4496 assert(of);
4497
4498 ofd = open(of->path, O_PATH | O_CLOEXEC);
4499 if (ofd < 0)
4500 return log_debug_errno(errno, "Failed to open '%s' as O_PATH: %m", of->path);
4501
4502 if (fstat(ofd, &st) < 0)
4503 return log_debug_errno( errno, "Failed to stat '%s': %m", of->path);
4504
4505 if (S_ISSOCK(st.st_mode)) {
4506 fd = connect_unix_harder(of, ofd);
4507 if (fd < 0)
4508 return fd;
4509
4510 if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
4511 return log_debug_errno(errno, "Failed to shutdown send for socket '%s': %m", of->path);
4512
4513 log_debug("Opened socket '%s' as fd %d.", of->path, fd);
4514 } else {
4515 int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
4516 if (FLAGS_SET(of->flags, OPENFILE_APPEND))
4517 flags |= O_APPEND;
4518 else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
4519 flags |= O_TRUNC;
4520
4521 fd = fd_reopen(ofd, flags|O_NOCTTY|O_CLOEXEC);
4522 if (fd < 0)
4523 return log_debug_errno(fd, "Failed to reopen file '%s': %m", of->path);
4524
4525 log_debug("Opened file '%s' as fd %d.", of->path, fd);
4526 }
4527
4528 return TAKE_FD(fd);
4529 }
4530
4531 static int collect_open_file_fds(ExecParameters *p) {
4532 assert(p);
4533
4534 LIST_FOREACH(open_files, of, p->open_files) {
4535 _cleanup_close_ int fd = -EBADF;
4536
4537 fd = get_open_file_fd(of);
4538 if (fd < 0) {
4539 if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
4540 log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
4541 fd,
4542 "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4543 of->path);
4544 continue;
4545 }
4546
4547 return log_error_errno(fd, "Failed to get OpenFile= file descriptor for '%s': %m", of->path);
4548 }
4549
4550 if (!GREEDY_REALLOC(p->fds, p->n_socket_fds + p->n_stashed_fds + 1))
4551 return log_oom();
4552
4553 if (strv_extend(&p->fd_names, of->fdname) < 0)
4554 return log_oom();
4555
4556 p->fds[p->n_socket_fds + p->n_stashed_fds++] = TAKE_FD(fd);
4557 }
4558
4559 return 0;
4560 }
4561
4562 static void log_command_line(
4563 const ExecContext *context,
4564 const ExecParameters *params,
4565 const char *msg,
4566 const char *executable,
4567 char **argv) {
4568
4569 assert(context);
4570 assert(params);
4571 assert(msg);
4572 assert(executable);
4573
4574 if (!DEBUG_LOGGING)
4575 return;
4576
4577 _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
4578
4579 log_struct(LOG_DEBUG,
4580 LOG_ITEM("EXECUTABLE=%s", executable),
4581 LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4582 LOG_EXEC_INVOCATION_ID(params));
4583 }
4584
4585 static bool exec_needs_cap_sys_admin(const ExecContext *context, const ExecParameters *params) {
4586 assert(context);
4587 assert(params);
4588
4589 /* We only want to ever imply PrivateUsers= for user managers, as they're not expected to setuid() to
4590 * other users, unlike the system manager which needs all users to be around. */
4591 if (params->runtime_scope != RUNTIME_SCOPE_USER)
4592 return false;
4593
4594 return context->private_users != PRIVATE_USERS_NO ||
4595 context->private_tmp != PRIVATE_TMP_NO || /* no need to check for private_var_tmp here, private_tmp is never demoted to "no" */
4596 context->private_devices ||
4597 context->private_network ||
4598 context->user_namespace_path ||
4599 context->network_namespace_path ||
4600 context->private_ipc ||
4601 context->ipc_namespace_path ||
4602 context->private_mounts > 0 ||
4603 context->mount_apivfs > 0 ||
4604 context->bind_log_sockets > 0 ||
4605 context->n_bind_mounts > 0 ||
4606 context->n_temporary_filesystems > 0 ||
4607 exec_context_with_rootfs_strict(context) ||
4608 !strv_isempty(context->extension_directories) ||
4609 context->n_mount_images > 0 ||
4610 context->n_extension_images > 0 ||
4611 context->protect_system != PROTECT_SYSTEM_NO ||
4612 context->protect_home != PROTECT_HOME_NO ||
4613 exec_needs_pid_namespace(context, params) ||
4614 context->protect_kernel_tunables ||
4615 context->protect_kernel_modules ||
4616 context->protect_kernel_logs ||
4617 exec_needs_cgroup_mount(context) ||
4618 context->protect_clock ||
4619 context->protect_hostname != PROTECT_HOSTNAME_NO ||
4620 !strv_isempty(context->read_write_paths) ||
4621 !strv_isempty(context->read_only_paths) ||
4622 !strv_isempty(context->inaccessible_paths) ||
4623 !strv_isempty(context->exec_paths) ||
4624 !strv_isempty(context->no_exec_paths) ||
4625 context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
4626 }
4627
4628 static PrivateUsers exec_context_get_effective_private_users(
4629 const ExecContext *context,
4630 const ExecParameters *params) {
4631
4632 assert(context);
4633 assert(params);
4634
4635 if (context->private_users != PRIVATE_USERS_NO)
4636 return context->private_users;
4637
4638 /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4639 if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
4640 return PRIVATE_USERS_SELF;
4641
4642 return PRIVATE_USERS_NO;
4643 }
4644
4645 static bool exec_namespace_is_delegated(
4646 const ExecContext *context,
4647 const ExecParameters *params,
4648 bool have_cap_sys_admin,
4649 unsigned long namespace) {
4650
4651 assert(context);
4652 assert(params);
4653 assert(namespace != CLONE_NEWUSER);
4654
4655 /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4656 * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4657 * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4658 if (!have_cap_sys_admin && exec_needs_cap_sys_admin(context, params))
4659 return false;
4660
4661 if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
4662 return params->runtime_scope == RUNTIME_SCOPE_USER;
4663
4664 if (FLAGS_SET(context->delegate_namespaces, namespace))
4665 return true;
4666
4667 /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4668 * those are delegated mountns must be deferred too.
4669 *
4670 * The list should stay in sync with exec_needs_mount_namespace(). */
4671 if (namespace == CLONE_NEWNS)
4672 return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4673
4674 return false;
4675 }
4676
4677 static int setup_delegated_namespaces(
4678 const ExecContext *context,
4679 ExecParameters *params,
4680 const ExecRuntime *runtime,
4681 const PinnedResource *rootfs,
4682 bool delegate,
4683 char *const *pressure_path,
4684 uid_t uid,
4685 gid_t gid,
4686 const ExecCommand *command,
4687 bool needs_sandboxing,
4688 bool have_cap_sys_admin,
4689 PidRef *bpffs_pidref,
4690 int bpffs_socket_fd,
4691 int bpffs_errno_pipe,
4692 sd_varlink *mountfsd_link,
4693 int *reterr_exit_status) {
4694
4695 int r;
4696
4697 /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4698 * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4699 * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4700 * that all namespaces that should not be delegated are unshared when this function is called the
4701 * first time and all namespaces that should be delegated are unshared when this function is called
4702 * the second time. */
4703
4704 assert(context);
4705 assert(params);
4706 assert(runtime);
4707 assert(rootfs);
4708 assert(reterr_exit_status);
4709
4710 if (exec_needs_network_namespace(context) &&
4711 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
4712 runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
4713
4714 /* Try to enable network namespacing if network namespacing is available and we have
4715 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
4716 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
4717 * the new network namespace. And if we don't have that, then we could only create a network
4718 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4719 if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
4720 r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
4721 if (ERRNO_IS_NEG_PRIVILEGE(r))
4722 log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
4723 else if (r < 0) {
4724 *reterr_exit_status = EXIT_NETWORK;
4725 return log_error_errno(r, "Failed to set up network namespacing: %m");
4726 } else
4727 log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
4728 } else if (context->network_namespace_path) {
4729 *reterr_exit_status = EXIT_NETWORK;
4730 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
4731 } else
4732 log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
4733 }
4734
4735 if (exec_needs_ipc_namespace(context) &&
4736 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
4737 runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
4738
4739 if (namespace_type_supported(NAMESPACE_IPC)) {
4740 r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
4741 if (ERRNO_IS_NEG_PRIVILEGE(r))
4742 log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
4743 else if (r < 0) {
4744 *reterr_exit_status = EXIT_NAMESPACE;
4745 return log_error_errno(r, "Failed to set up IPC namespacing: %m");
4746 } else
4747 log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
4748 } else if (context->ipc_namespace_path) {
4749 *reterr_exit_status = EXIT_NAMESPACE;
4750 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
4751 } else
4752 log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
4753 }
4754
4755 if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
4756 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
4757 if (unshare(CLONE_NEWCGROUP) < 0) {
4758 *reterr_exit_status = EXIT_NAMESPACE;
4759 return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
4760 }
4761
4762 log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
4763 }
4764
4765 /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4766 * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4767 if (needs_sandboxing && exec_needs_pid_namespace(context, params) &&
4768 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
4769 if (params->pidref_transport_fd < 0) {
4770 *reterr_exit_status = EXIT_NAMESPACE;
4771 return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up.");
4772 }
4773
4774 /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
4775 * to check if we can mount /proc/.
4776 *
4777 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
4778 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
4779 * once we unshare a mount namespace. */
4780 if (!have_cap_sys_admin || delegate) {
4781 r = can_mount_proc();
4782 if (r < 0) {
4783 *reterr_exit_status = EXIT_NAMESPACE;
4784 return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
4785 }
4786 if (r == 0) {
4787 *reterr_exit_status = EXIT_NAMESPACE;
4788 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
4789 "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
4790 }
4791 }
4792
4793 r = setup_private_pids(context, params);
4794 if (r < 0) {
4795 *reterr_exit_status = EXIT_NAMESPACE;
4796 return log_error_errno(r, "Failed to set up pid namespace: %m");
4797 }
4798
4799 log_debug("Set up %spid namespace", delegate ? "delegated " : "");
4800 }
4801
4802 /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
4803
4804 if (exec_needs_mount_namespace(context, params) &&
4805 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
4806 _cleanup_free_ char *error_path = NULL;
4807
4808 r = apply_mount_namespace(
4809 command->flags,
4810 context,
4811 params,
4812 runtime,
4813 rootfs,
4814 pressure_path,
4815 needs_sandboxing,
4816 uid,
4817 gid,
4818 bpffs_pidref,
4819 bpffs_socket_fd,
4820 bpffs_errno_pipe,
4821 mountfsd_link,
4822 &error_path);
4823 if (r < 0) {
4824 *reterr_exit_status = EXIT_NAMESPACE;
4825 return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
4826 error_path ? ": " : "", strempty(error_path));
4827 }
4828
4829 log_debug("Set up %smount namespace", delegate ? "delegated " : "");
4830 }
4831
4832 if (needs_sandboxing &&
4833 exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
4834 r = apply_protect_hostname(context, params, reterr_exit_status);
4835 if (r < 0)
4836 return r;
4837 if (r > 0)
4838 log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
4839 }
4840
4841 return 0;
4842 }
4843
4844 static int set_memory_thp(ExecMemoryTHP thp) {
4845 int r;
4846
4847 switch (thp) {
4848
4849 case EXEC_MEMORY_THP_INHERIT:
4850 return 0;
4851
4852 case EXEC_MEMORY_THP_DISABLE:
4853 r = RET_NERRNO(prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0));
4854 break;
4855
4856 case EXEC_MEMORY_THP_MADVISE:
4857 r = RET_NERRNO(prctl(PR_SET_THP_DISABLE, 1, PR_THP_DISABLE_EXCEPT_ADVISED, 0, 0));
4858 break;
4859
4860 case EXEC_MEMORY_THP_SYSTEM:
4861 r = RET_NERRNO(prctl(PR_SET_THP_DISABLE, 0, 0, 0, 0));
4862 break;
4863
4864 default:
4865 assert_not_reached();
4866 }
4867
4868 return r == -EINVAL ? -EOPNOTSUPP : r;
4869 }
4870
4871 static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
4872 assert(context);
4873
4874 if (confirm_spawn_disabled())
4875 return false;
4876
4877 /* For some reasons units remaining in the same process group
4878 * as PID 1 fail to acquire the console even if it's not used
4879 * by any process. So skip the confirmation question for them. */
4880 return !context->same_pgrp;
4881 }
4882
4883 static int exec_context_named_iofds(
4884 const ExecContext *c,
4885 const ExecParameters *p,
4886 int named_iofds[static 3]) {
4887
4888 const char *stdio_fdname[3];
4889 size_t targets;
4890
4891 assert(c);
4892 assert(p);
4893 assert(named_iofds);
4894
4895 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
4896 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
4897 (c->std_error == EXEC_OUTPUT_NAMED_FD);
4898
4899 for (size_t i = 0; i < 3; i++)
4900 stdio_fdname[i] = exec_context_fdname(c, i);
4901
4902 /* Note that socket fds are always placed at the beginning of the fds array, no need for extra
4903 * manipulation. */
4904 for (size_t i = 0; i < p->n_socket_fds && targets > 0; i++) {
4905 if (named_iofds[STDIN_FILENO] < 0 &&
4906 c->std_input == EXEC_INPUT_NAMED_FD &&
4907 streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
4908
4909 named_iofds[STDIN_FILENO] = p->fds[i];
4910 targets--;
4911 continue;
4912 }
4913
4914 /* Allow stdout and stderr to use the same named fd */
4915
4916 if (named_iofds[STDOUT_FILENO] < 0 &&
4917 c->std_output == EXEC_OUTPUT_NAMED_FD &&
4918 streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
4919
4920 named_iofds[STDOUT_FILENO] = p->fds[i];
4921 targets--;
4922 }
4923
4924 if (named_iofds[STDERR_FILENO] < 0 &&
4925 c->std_error == EXEC_OUTPUT_NAMED_FD &&
4926 streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
4927
4928 named_iofds[STDERR_FILENO] = p->fds[i];
4929 targets--;
4930 }
4931 }
4932
4933 return targets == 0 ? 0 : -ENOENT;
4934 }
4935
4936 static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
4937 if (!shared)
4938 return;
4939
4940 safe_close_pair(shared->userns_storage_socket);
4941 safe_close_pair(shared->netns_storage_socket);
4942 safe_close_pair(shared->ipcns_storage_socket);
4943 }
4944
4945 static void exec_runtime_close(ExecRuntime *rt) {
4946 if (!rt)
4947 return;
4948
4949 safe_close_pair(rt->ephemeral_storage_socket);
4950
4951 exec_shared_runtime_close(rt->shared);
4952 dynamic_creds_close(rt->dynamic_creds);
4953 }
4954
4955 static void exec_params_close(ExecParameters *p) {
4956 if (!p)
4957 return;
4958
4959 p->stdin_fd = safe_close(p->stdin_fd);
4960 p->stdout_fd = safe_close(p->stdout_fd);
4961 p->stderr_fd = safe_close(p->stderr_fd);
4962 }
4963
4964 static int exec_fd_mark_hot(
4965 const ExecContext *c,
4966 ExecParameters *p,
4967 bool hot,
4968 int *reterr_exit_status) {
4969
4970 assert(c);
4971 assert(p);
4972
4973 if (p->exec_fd < 0)
4974 return 0;
4975
4976 uint8_t x = hot;
4977
4978 if (write(p->exec_fd, &x, sizeof(x)) < 0) {
4979 if (reterr_exit_status)
4980 *reterr_exit_status = EXIT_EXEC;
4981 return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
4982 }
4983
4984 return 1;
4985 }
4986
4987 static int send_handoff_timestamp(
4988 const ExecContext *c,
4989 ExecParameters *p,
4990 int *reterr_exit_status) {
4991
4992 assert(c);
4993 assert(p);
4994
4995 if (p->handoff_timestamp_fd < 0)
4996 return 0;
4997
4998 dual_timestamp dt;
4999 dual_timestamp_now(&dt);
5000
5001 if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
5002 if (reterr_exit_status)
5003 *reterr_exit_status = EXIT_EXEC;
5004 return log_error_errno(errno, "Failed to send handoff timestamp: %m");
5005 }
5006
5007 return 1;
5008 }
5009
5010 static void prepare_terminal(
5011 const ExecContext *context,
5012 ExecParameters *p) {
5013
5014 _cleanup_close_ int lock_fd = -EBADF;
5015
5016 /* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
5017 * cleaning up things from older invocations. */
5018
5019 assert(context);
5020 assert(p);
5021
5022 /* We only try to reset things if we there's the chance our stdout points to a TTY */
5023 if (!(context->std_output == EXEC_OUTPUT_TTY ||
5024 (context->std_output == EXEC_OUTPUT_INHERIT && exec_input_is_terminal(context->std_input)) ||
5025 context->std_output == EXEC_OUTPUT_NAMED_FD ||
5026 p->stdout_fd >= 0))
5027 return;
5028
5029 /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
5030 * information into account */
5031 bool use_ansi = exec_context_shall_ansi_seq_reset(context);
5032
5033 if (context->tty_reset) {
5034 /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
5035 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
5036 * exec_context_apply_tty_size() below might interfere */
5037 lock_fd = lock_dev_console();
5038 if (lock_fd < 0)
5039 log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
5040
5041 /* We explicitly control whether to send ansi sequences or not here, since we want to consult
5042 * the env vars explicitly configured in the ExecContext, rather than our own environment
5043 * block. */
5044 (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
5045 }
5046
5047 (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
5048
5049 if (use_ansi)
5050 (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
5051 }
5052
5053 static int setup_term_environment(const ExecContext *context, char ***env) {
5054 int r;
5055
5056 assert(context);
5057 assert(env);
5058
5059 /* Already specified by user? */
5060 if (strv_env_get(*env, "TERM"))
5061 return 0;
5062
5063 /* Do we need $TERM at all? */
5064 if (!exec_context_has_tty(context))
5065 return 0;
5066
5067 const char *tty_path = exec_context_tty_path(context);
5068 if (tty_path) {
5069 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
5070 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
5071 * container manager passes to PID 1 ends up all the way in the console login shown.
5072 *
5073 * Note that if this doesn't work out we won't bother with querying systemd.tty.term.console
5074 * kernel cmdline option or DCS anymore either, because pid1 also imports $TERM based on those
5075 * and it should have showed up as our $TERM if there were anything. */
5076 if (tty_is_console(tty_path) && getppid() == 1) {
5077 const char *term = strv_find_prefix(environ, "TERM=");
5078 if (term) {
5079 r = strv_env_replace_strdup(env, term);
5080 if (r < 0)
5081 return r;
5082
5083 FOREACH_STRING(i, "COLORTERM=", "NO_COLOR=") {
5084 const char *s = strv_find_prefix(environ, i);
5085 if (!s)
5086 continue;
5087
5088 r = strv_env_replace_strdup(env, s);
5089 if (r < 0)
5090 return r;
5091 }
5092
5093 return 1;
5094 }
5095
5096 } else {
5097 if (in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
5098 _cleanup_free_ char *key = NULL, *cmdline = NULL;
5099
5100 key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
5101 if (!key)
5102 return -ENOMEM;
5103
5104 r = proc_cmdline_get_key(key, /* flags= */ 0, &cmdline);
5105 if (r > 0)
5106 return strv_env_assign(env, "TERM", cmdline);
5107 if (r < 0)
5108 log_debug_errno(r, "Failed to read '%s' from kernel cmdline, ignoring: %m", key);
5109 }
5110
5111 /* This handles real virtual terminals (returning "linux") and
5112 * any terminals which support the DCS +q query sequence. */
5113 _cleanup_free_ char *dcs_term = NULL;
5114 r = query_term_for_tty(tty_path, &dcs_term);
5115 if (r >= 0)
5116 return strv_env_assign(env, "TERM", dcs_term);
5117 }
5118 }
5119
5120 /* If $TERM is not known and we pick a fallback default, then let's also set
5121 * $COLORTERM=truecolor. That's because our fallback default is vt220, which is
5122 * generally a safe bet (as it supports PageUp/PageDown unlike vt100, and is quite
5123 * universally available in terminfo/termcap), except for the fact that real DEC
5124 * vt220 gear never actually supported color. Most tools these days generate color on
5125 * vt220 anyway, ignoring the physical capabilities of the real hardware, but some
5126 * tools actually believe in the historical truth. Which is unfortunate since *we*
5127 * *don't* care about the historical truth, we just want sane defaults if nothing
5128 * better is explicitly configured. It's 2025 after all, at the time of writing,
5129 * pretty much all terminal emulators actually *do* support color, hence if we don't
5130 * know any better let's explicitly claim color support via $COLORTERM. Or in other
5131 * words: we now explicitly claim to be connected to a franken-vt220 with true color
5132 * support. */
5133 r = strv_env_replace_strdup(env, "COLORTERM=truecolor");
5134 if (r < 0)
5135 return r;
5136
5137 return strv_env_replace_strdup(env, "TERM=" FALLBACK_TERM);
5138 }
5139
5140 static inline void free_pressure_paths(char *(*p)[_PRESSURE_RESOURCE_MAX]) {
5141 free_many_charp(*p, _PRESSURE_RESOURCE_MAX);
5142 }
5143
5144 int exec_invoke(
5145 const ExecCommand *command,
5146 const ExecContext *context,
5147 ExecParameters *params,
5148 ExecRuntime *runtime,
5149 const CGroupContext *cgroup_context,
5150 int *exit_status) {
5151
5152 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL;
5153 int r;
5154 const char *username = NULL;
5155 _cleanup_free_ char *pwent_home = NULL, *shell = NULL, *_own_user = NULL, *_username = NULL;
5156 _cleanup_(free_pressure_paths) char *pressure_path[_PRESSURE_RESOURCE_MAX] = {};
5157 dev_t journal_stream_dev = 0;
5158 ino_t journal_stream_ino = 0;
5159 bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
5160 needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */
5161 needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */
5162 have_cap_sys_admin,
5163 userns_set_up = false,
5164 keep_seccomp_privileges = false;
5165 #if HAVE_SELINUX
5166 _cleanup_free_ char *mac_selinux_context_net = NULL;
5167 bool use_selinux = false;
5168 #endif
5169 #if ENABLE_SMACK
5170 bool use_smack = false;
5171 #endif
5172 #if HAVE_APPARMOR
5173 bool use_apparmor = false;
5174 #endif
5175 #if HAVE_SECCOMP
5176 uint64_t saved_bset = 0;
5177 #endif
5178 /* saved_uid → where we started from; uid → where we ended up in; outside_uid → where we ended up in,
5179 * but seen from the outside (covers userns mappings) */
5180 uid_t uid = UID_INVALID, saved_uid = getuid(), outside_uid = UID_INVALID;
5181 gid_t gid = GID_INVALID, saved_gid = getgid(), outside_gid = GID_INVALID;
5182 int secure_bits;
5183 _cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
5184 int ngids = 0, ngids_after_pam = 0;
5185 int named_iofds[3] = EBADF_TRIPLET;
5186 _cleanup_close_ int socket_fd = -EBADF, bpffs_socket_fd = -EBADF, bpffs_errno_pipe = -EBADF;
5187 _cleanup_(pidref_done_sigkill_wait) PidRef bpffs_pidref = PIDREF_NULL;
5188
5189 assert(command);
5190 assert(context);
5191 assert(params);
5192 assert(runtime);
5193 assert(cgroup_context);
5194 assert(exit_status);
5195
5196 LOG_CONTEXT_PUSH_EXEC(context, params);
5197
5198 /* Explicitly test for CVE-2021-4034 inspired invocations */
5199 if (!command->path || strv_isempty(command->argv)) {
5200 *exit_status = EXIT_EXEC;
5201 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
5202 }
5203
5204 rename_process_from_path(command->path);
5205
5206 if (context->std_input == EXEC_INPUT_SOCKET ||
5207 context->std_output == EXEC_OUTPUT_SOCKET ||
5208 context->std_error == EXEC_OUTPUT_SOCKET) {
5209
5210 if (params->n_socket_fds != 1)
5211 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected exactly one socket, got %zu.",
5212 params->n_socket_fds);
5213
5214 socket_fd = TAKE_FD(params->fds[0]);
5215 free(params->fd_names[0]);
5216 params->n_socket_fds = 0;
5217
5218 memmove(params->fds, params->fds + 1, params->n_stashed_fds * sizeof(int));
5219 memmove(params->fd_names, params->fd_names + 1, params->n_stashed_fds * sizeof(char*));
5220 params->fd_names[params->n_stashed_fds] = NULL;
5221 }
5222
5223 r = exec_context_named_iofds(context, params, named_iofds);
5224 if (r < 0) {
5225 *exit_status = EXIT_FDS;
5226 return log_error_errno(r, "Failed to load a named file descriptor: %m");
5227 }
5228
5229 /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
5230 * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
5231 * both of which will be demoted to SIG_DFL. */
5232 (void) default_signals(SIGNALS_CRASH_HANDLER,
5233 SIGNALS_IGNORE);
5234
5235 if (context->ignore_sigpipe)
5236 (void) ignore_signals(SIGPIPE);
5237
5238 r = reset_signal_mask();
5239 if (r < 0) {
5240 *exit_status = EXIT_SIGNAL_MASK;
5241 return log_error_errno(r, "Failed to set process signal mask: %m");
5242 }
5243
5244 if (params->idle_pipe)
5245 do_idle_pipe_dance(params->idle_pipe);
5246
5247 /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
5248 * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
5249 * any fds open we don't really want open during the transition. In order to make logging work, we switch the
5250 * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
5251
5252 log_forget_fds();
5253 log_set_open_when_needed(true);
5254 log_settle_target();
5255
5256 /* In case anything used libc syslog(), close this here, too */
5257 closelog();
5258
5259 r = collect_open_file_fds(params);
5260 if (r < 0) {
5261 *exit_status = EXIT_FDS;
5262 return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
5263 }
5264
5265 size_t n_keep_fds = params->n_socket_fds + params->n_stashed_fds;
5266 _cleanup_free_ int *keep_fds = newdup(int, params->fds, n_keep_fds);
5267 if (!keep_fds) {
5268 *exit_status = EXIT_MEMORY;
5269 return log_oom();
5270 }
5271
5272 r = add_shifted_fd(&keep_fds, &n_keep_fds, &params->exec_fd);
5273 if (r < 0) {
5274 *exit_status = EXIT_FDS;
5275 return log_error_errno(r, "Failed to collect shifted fd: %m");
5276 }
5277
5278 r = add_shifted_fd(&keep_fds, &n_keep_fds, &params->handoff_timestamp_fd);
5279 if (r < 0) {
5280 *exit_status = EXIT_FDS;
5281 return log_error_errno(r, "Failed to collect shifted fd: %m");
5282 }
5283
5284 #if HAVE_LIBBPF
5285 r = add_shifted_fd(&keep_fds, &n_keep_fds, &params->bpf_restrict_fs_map_fd);
5286 if (r < 0) {
5287 *exit_status = EXIT_FDS;
5288 return log_error_errno(r, "Failed to collect shifted fd: %m");
5289 }
5290 #endif
5291
5292 r = add_shifted_fd(&keep_fds, &n_keep_fds, &params->root_directory_fd);
5293 if (r < 0) {
5294 *exit_status = EXIT_FDS;
5295 return log_error_errno(r, "Failed to collect shifted fd: %m");
5296 }
5297
5298 r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
5299 if (r < 0) {
5300 *exit_status = EXIT_FDS;
5301 return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
5302 }
5303
5304 if (!context->same_pgrp &&
5305 setsid() < 0) {
5306 *exit_status = EXIT_SETSID;
5307 return log_error_errno(errno, "Failed to create new process session: %m");
5308 }
5309
5310 /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
5311 * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
5312 * open here, hence some of the settings made here might vanish again, depending on the TTY driver
5313 * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
5314 * will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
5315 * the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
5316 * OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
5317 exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
5318
5319 if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
5320 _cleanup_free_ char *cmdline = NULL;
5321
5322 cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
5323 if (!cmdline) {
5324 *exit_status = EXIT_MEMORY;
5325 return log_oom();
5326 }
5327
5328 r = ask_for_confirmation(context, params, cmdline);
5329 if (r != CONFIRM_EXECUTE) {
5330 if (r == CONFIRM_PRETEND_SUCCESS) {
5331 *exit_status = EXIT_SUCCESS;
5332 return 0;
5333 }
5334
5335 *exit_status = EXIT_CONFIRM;
5336 return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
5337 }
5338 }
5339
5340 /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
5341 * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
5342 * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
5343 * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
5344 * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
5345 if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
5346 setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
5347 *exit_status = EXIT_MEMORY;
5348 return log_error_errno(errno, "Failed to update environment: %m");
5349 }
5350
5351 if (exec_context_get_effective_private_users(context, params) == PRIVATE_USERS_MANAGED)
5352 log_debug("Running with a managed user namespace, not initializing UIDs/GIDs.");
5353 else if (context->dynamic_user && runtime->dynamic_creds) {
5354 _cleanup_strv_free_ char **suggested_paths = NULL;
5355
5356 /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
5357 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
5358 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
5359 *exit_status = EXIT_USER;
5360 return log_error_errno(errno, "Failed to update environment: %m");
5361 }
5362
5363 r = compile_suggested_paths(context, params, &suggested_paths);
5364 if (r < 0) {
5365 *exit_status = EXIT_MEMORY;
5366 return log_oom();
5367 }
5368
5369 r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
5370 if (r < 0) {
5371 *exit_status = EXIT_USER;
5372 if (r == -EILSEQ)
5373 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
5374 "Failed to update dynamic user credentials: User or group with specified name already exists.");
5375 return log_error_errno(r, "Failed to update dynamic user credentials: %m");
5376 }
5377
5378 if (!uid_is_valid(uid)) {
5379 *exit_status = EXIT_USER;
5380 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
5381 }
5382
5383 if (!gid_is_valid(gid)) {
5384 *exit_status = EXIT_USER;
5385 return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
5386 }
5387
5388 if (runtime->dynamic_creds->user)
5389 username = runtime->dynamic_creds->user->name;
5390
5391 } else {
5392 if (context->user)
5393 username = context->user;
5394 else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
5395 /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
5396 username = _own_user = getusername_malloc();
5397 if (!username) {
5398 *exit_status = EXIT_USER;
5399 return log_oom();
5400 }
5401 }
5402
5403 if (username) {
5404 /* We can't use nss unconditionally for root without risking deadlocks if some IPC services
5405 * will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
5406 * enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
5407 * or PAM shall be invoked, let's consult NSS even for root, so that the user
5408 * gets accurate $SHELL in session(-like) contexts. */
5409 bool prefer_nss = context->set_login_environment > 0 || context->pam_name;
5410
5411 r = get_user_creds(username,
5412 USER_CREDS_CLEAN|(prefer_nss ? USER_CREDS_PREFER_NSS : 0),
5413 &_username,
5414 &uid,
5415 &gid,
5416 &pwent_home,
5417 &shell);
5418 if (r < 0) {
5419 *exit_status = EXIT_USER;
5420 log_error_errno(r, "Failed to determine credentials for user '%s': %s",
5421 username, STRERROR_USER(r));
5422 return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
5423 }
5424
5425 username = _username;
5426 }
5427
5428 if (context->group) {
5429 r = get_group_creds(context->group, /* flags= */ 0, /* ret_name= */ NULL, &gid);
5430 if (r < 0) {
5431 *exit_status = EXIT_GROUP;
5432 log_error_errno(r, "Failed to determine credentials for group '%s': %s",
5433 context->group, STRERROR_GROUP(r));
5434 return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
5435 }
5436 }
5437 }
5438
5439 if (exec_context_get_effective_private_users(context, params) != PRIVATE_USERS_MANAGED) {
5440 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
5441 ngids = get_supplementary_groups(context, username, gid, &gids);
5442 if (ngids < 0) {
5443 *exit_status = EXIT_GROUP;
5444 return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
5445 }
5446
5447 r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
5448 if (r < 0) {
5449 *exit_status = EXIT_USER;
5450 return log_error_errno(r, "Failed to send user credentials to PID1: %m");
5451 }
5452
5453 params->user_lookup_fd = safe_close(params->user_lookup_fd);
5454 }
5455
5456 r = acquire_home(context, &pwent_home);
5457 if (r < 0) {
5458 *exit_status = EXIT_CHDIR;
5459 return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
5460 }
5461
5462 /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
5463 if (socket_fd >= 0)
5464 (void) fd_nonblock(socket_fd, false);
5465
5466 /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5467 * from it. */
5468 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
5469
5470 /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
5471 * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
5472 if (params->cgroup_path) {
5473 _cleanup_free_ char *subcgroup = NULL;
5474
5475 r = exec_params_get_cgroup_path(params, cgroup_context, params->cgroup_path, &subcgroup);
5476 if (r < 0) {
5477 *exit_status = EXIT_CGROUP;
5478 return log_error_errno(r, "Failed to acquire cgroup path: %m");
5479 }
5480 if (r > 0) {
5481 /* If there is a subcgroup required, let's make sure to create it now. */
5482 r = cg_create(subcgroup);
5483 if (r < 0)
5484 return log_error_errno(r, "Failed to create subcgroup '%s': %m", subcgroup);
5485 }
5486
5487 /* If we need a cgroup namespace, we cannot yet move the service to its configured subgroup,
5488 * as unsharing the cgroup namespace later on makes the current cgroup the root of the
5489 * namespace and we want the root of the namespace to be the main service cgroup and not the
5490 * subgroup. One edge case is if we're a control process that needs to be spawned in a
5491 * subgroup, in this case, we have no choice as moving into the main service cgroup might
5492 * violate the no inner processes rule of cgroupv2. */
5493 const char *cgtarget = needs_sandboxing && exec_needs_cgroup_namespace(context) &&
5494 !exec_params_needs_control_subcgroup(params)
5495 ? params->cgroup_path : subcgroup;
5496
5497 r = cg_attach(cgtarget, 0);
5498 if (r == -EUCLEAN) {
5499 *exit_status = EXIT_CGROUP;
5500 return log_error_errno(r,
5501 "Failed to attach process to cgroup '%s', "
5502 "because the cgroup or one of its parents or "
5503 "siblings is in the threaded mode.", cgtarget);
5504 }
5505 if (r < 0) {
5506 *exit_status = EXIT_CGROUP;
5507 return log_error_errno(r, "Failed to attach to cgroup %s: %m", cgtarget);
5508 }
5509 }
5510
5511 if (context->user_namespace_path && runtime->shared && runtime->shared->userns_storage_socket[0] >= 0) {
5512 r = open_shareable_ns_path(runtime->shared->userns_storage_socket, context->user_namespace_path, CLONE_NEWUSER);
5513 if (r < 0) {
5514 *exit_status = EXIT_NAMESPACE;
5515 return log_error_errno(r, "Failed to open user namespace path %s: %m", context->user_namespace_path);
5516 }
5517 }
5518
5519 if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
5520 r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
5521 if (r < 0) {
5522 *exit_status = EXIT_NETWORK;
5523 return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
5524 }
5525 }
5526
5527 if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
5528 r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
5529 if (r < 0) {
5530 *exit_status = EXIT_NAMESPACE;
5531 return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
5532 }
5533 }
5534
5535 r = setup_input(context, params, socket_fd, named_iofds);
5536 if (r < 0) {
5537 *exit_status = EXIT_STDIN;
5538 return log_error_errno(r, "Failed to set up standard input: %m");
5539 }
5540
5541 _cleanup_free_ char *fname = NULL;
5542 r = path_extract_filename(command->path, &fname);
5543 if (r < 0) {
5544 *exit_status = EXIT_STDOUT;
5545 return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
5546 }
5547
5548 r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
5549 if (r < 0) {
5550 *exit_status = EXIT_STDOUT;
5551 return log_error_errno(r, "Failed to set up standard output: %m");
5552 }
5553
5554 r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
5555 if (r < 0) {
5556 *exit_status = EXIT_STDERR;
5557 return log_error_errno(r, "Failed to set up standard error output: %m");
5558 }
5559
5560 /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
5561 * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
5562 * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
5563 * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
5564 prepare_terminal(context, params);
5565
5566 if (context->oom_score_adjust_set) {
5567 /* When we can't make this change due to EPERM, then let's silently skip over it. User
5568 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
5569 r = set_oom_score_adjust(context->oom_score_adjust);
5570 if (ERRNO_IS_NEG_PRIVILEGE(r))
5571 log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
5572 else if (r < 0) {
5573 *exit_status = EXIT_OOM_ADJUST;
5574 return log_error_errno(r, "Failed to adjust OOM setting: %m");
5575 }
5576 }
5577
5578 if (context->coredump_filter_set) {
5579 r = set_coredump_filter(context->coredump_filter);
5580 if (ERRNO_IS_NEG_PRIVILEGE(r))
5581 log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
5582 else if (r < 0) {
5583 *exit_status = EXIT_LIMITS;
5584 return log_error_errno(r, "Failed to adjust coredump_filter: %m");
5585 }
5586 }
5587
5588 if (context->cpu_sched_set) {
5589 struct sched_attr attr = {
5590 .size = sizeof(attr),
5591 .sched_policy = context->cpu_sched_policy,
5592 .sched_priority = context->cpu_sched_priority,
5593 .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
5594 };
5595
5596 r = RET_NERRNO(sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0));
5597 if (r == -EINVAL && !sched_policy_supported(context->cpu_sched_policy)) {
5598 _cleanup_free_ char *s = NULL;
5599 (void) sched_policy_to_string_alloc(context->cpu_sched_policy, &s);
5600 log_warning_errno(r, "CPU scheduling policy %s is not supported, proceeding without.", strna(s));
5601 } else if (r < 0) {
5602 *exit_status = EXIT_SETSCHEDULER;
5603 return log_error_errno(r, "Failed to set up CPU scheduling: %m");
5604 }
5605 }
5606
5607 /*
5608 * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
5609 * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
5610 * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
5611 * It would be ideal to set both with the same call, but we cannot easily do so because of all the
5612 * extra logic in setpriority_closest().
5613 */
5614 if (context->nice_set) {
5615 r = setpriority_closest(context->nice);
5616 if (r < 0) {
5617 *exit_status = EXIT_NICE;
5618 return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
5619 }
5620 }
5621
5622 if (context->cpu_affinity_from_numa || context->cpu_set.set) {
5623 _cleanup_(cpu_set_done) CPUSet converted_cpu_set = {};
5624 const CPUSet *cpu_set;
5625
5626 if (context->cpu_affinity_from_numa) {
5627 r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
5628 if (r < 0) {
5629 *exit_status = EXIT_CPUAFFINITY;
5630 return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
5631 }
5632
5633 cpu_set = &converted_cpu_set;
5634 } else
5635 cpu_set = &context->cpu_set;
5636
5637 if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
5638 *exit_status = EXIT_CPUAFFINITY;
5639 return log_error_errno(errno, "Failed to set up CPU affinity: %m");
5640 }
5641 }
5642
5643 if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
5644 r = apply_numa_policy(&context->numa_policy);
5645 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
5646 log_debug_errno(r, "NUMA support not available, ignoring.");
5647 else if (r < 0) {
5648 *exit_status = EXIT_NUMA_POLICY;
5649 return log_error_errno(r, "Failed to set NUMA memory policy: %m");
5650 }
5651 }
5652
5653 if (context->ioprio_is_set)
5654 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
5655 *exit_status = EXIT_IOPRIO;
5656 return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
5657 }
5658
5659 if (context->timer_slack_nsec != NSEC_INFINITY)
5660 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
5661 *exit_status = EXIT_TIMERSLACK;
5662 return log_error_errno(errno, "Failed to set up timer slack: %m");
5663 }
5664
5665 if (context->personality != PERSONALITY_INVALID) {
5666 r = safe_personality(context->personality);
5667 if (r < 0) {
5668 *exit_status = EXIT_PERSONALITY;
5669 return log_error_errno(r, "Failed to set up execution domain (personality): %m");
5670 }
5671 }
5672
5673 if (context->memory_ksm >= 0)
5674 if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
5675 if (ERRNO_IS_NOT_SUPPORTED(errno))
5676 log_debug_errno(errno, "KSM support not available, ignoring.");
5677 else {
5678 *exit_status = EXIT_KSM;
5679 return log_error_errno(errno, "Failed to set KSM: %m");
5680 }
5681 }
5682
5683 r = set_memory_thp(context->memory_thp);
5684 if (r == -EOPNOTSUPP)
5685 log_debug_errno(r, "Setting MemoryTHP=%s is not supported, ignoring.",
5686 exec_memory_thp_to_string(context->memory_thp));
5687 else if (r < 0) {
5688 *exit_status = EXIT_MEMORY_THP;
5689 return log_error_errno(r, "Failed to set MemoryTHP=%s: %m",
5690 exec_memory_thp_to_string(context->memory_thp));
5691 }
5692
5693 #if ENABLE_UTMP
5694 if (context->utmp_id) {
5695 _cleanup_free_ char *username_alloc = NULL;
5696
5697 if (!username && context->utmp_mode == EXEC_UTMP_USER) {
5698 username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
5699 if (!username_alloc) {
5700 *exit_status = EXIT_USER;
5701 return log_oom();
5702 }
5703 }
5704
5705 const char *line = context->tty_path ?
5706 (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
5707 NULL;
5708 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
5709 line,
5710 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
5711 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
5712 USER_PROCESS,
5713 username ?: username_alloc);
5714 }
5715 #endif
5716
5717 if (uid_is_valid(uid)) {
5718 r = chown_terminal(STDIN_FILENO, uid);
5719 if (r < 0) {
5720 *exit_status = EXIT_STDIN;
5721 return log_error_errno(r, "Failed to change ownership of terminal: %m");
5722 }
5723 }
5724
5725 if (params->cgroup_path) {
5726 /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5727 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5728 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5729 * touch a single hierarchy too. */
5730
5731 if (params->flags & EXEC_CGROUP_DELEGATE) {
5732 _cleanup_free_ char *p = NULL;
5733
5734 r = cg_set_access(params->cgroup_path, uid, gid);
5735 if (r < 0) {
5736 *exit_status = EXIT_CGROUP;
5737 return log_error_errno(r, "Failed to adjust control group access: %m");
5738 }
5739
5740 r = exec_params_get_cgroup_path(params, cgroup_context, params->cgroup_path, &p);
5741 if (r < 0) {
5742 *exit_status = EXIT_CGROUP;
5743 return log_error_errno(r, "Failed to acquire cgroup path: %m");
5744 }
5745 if (r > 0) {
5746 r = cg_set_access_recursive(p, uid, gid);
5747 if (r < 0) {
5748 *exit_status = EXIT_CGROUP;
5749 return log_error_errno(r, "Failed to adjust control subgroup access: %m");
5750 }
5751 }
5752 }
5753
5754 if (is_pressure_supported() > 0) {
5755 for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
5756 if (cgroup_context_want_pressure(cgroup_context, t)) {
5757 _cleanup_free_ char *pressure_file = strjoin(pressure_resource_to_string(t), ".pressure");
5758 if (!pressure_file) {
5759 *exit_status = EXIT_MEMORY;
5760 return log_oom();
5761 }
5762
5763 r = cg_get_path(params->cgroup_path, pressure_file, &pressure_path[t]);
5764 if (r < 0) {
5765 *exit_status = EXIT_MEMORY;
5766 return log_oom();
5767 }
5768
5769 r = chmod_and_chown(pressure_path[t], 0644, uid, gid);
5770 if (r < 0) {
5771 log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
5772 "Failed to adjust ownership of '%s', ignoring: %m", pressure_path[t]);
5773 pressure_path[t] = mfree(pressure_path[t]);
5774 }
5775 /* First we use the current cgroup path to chmod and chown the pressure path, then pass the
5776 * path relative to the cgroup namespace to environment variables and mounts. If chown/chmod
5777 * fails, we should not pass pressure path environment variable or read-write mount to the
5778 * unit. This is why we check if pressure_path[t] != NULL in the conditional below. */
5779 if (pressure_path[t] && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
5780 pressure_path[t] = mfree(pressure_path[t]);
5781 r = cg_get_path("/", pressure_file, &pressure_path[t]);
5782 if (r < 0) {
5783 *exit_status = EXIT_MEMORY;
5784 return log_oom();
5785 }
5786 }
5787 } else if (cgroup_context->pressure[t].watch == CGROUP_PRESSURE_WATCH_NO) {
5788 pressure_path[t] = strdup("/dev/null"); /* /dev/null is explicit indicator for turning off pressure watch */
5789 if (!pressure_path[t]) {
5790 *exit_status = EXIT_MEMORY;
5791 return log_oom();
5792 }
5793 }
5794 }
5795 }
5796 }
5797
5798 _cleanup_(sd_varlink_unrefp) sd_varlink *mountfsd_link = NULL, *nsresource_link = NULL;
5799 if (needs_sandboxing &&
5800 exec_context_get_effective_private_users(context, params) == PRIVATE_USERS_MANAGED) {
5801
5802 /* In managed mode we need to allocate a userns via nsresource, and then assign mounts to
5803 * it. We must do so with our original privileges (since after creating the userns, we might
5804 * simply not have the necessary privs for the IPC calls anymore), hence do this here, ahead
5805 * of time. */
5806
5807 r = mountfsd_connect(&mountfsd_link);
5808 if (r < 0)
5809 return log_error_errno(r, "Failed to connect to mountfsd: %m");
5810
5811 r = nsresource_connect(&nsresource_link);
5812 if (r < 0)
5813 return log_error_errno(r, "Failed to connect to nsresourced: %m");
5814 }
5815
5816 needs_mount_namespace = exec_needs_mount_namespace(context, params);
5817
5818 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
5819 r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
5820 if (r < 0)
5821 return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
5822 }
5823
5824 r = exec_setup_credentials(context, cgroup_context, params, uid, gid);
5825 if (r < 0) {
5826 *exit_status = EXIT_CREDENTIALS;
5827 return log_error_errno(r, "Failed to set up credentials: %m");
5828 }
5829
5830 r = build_environment(
5831 context,
5832 params,
5833 cgroup_context,
5834 pwent_home,
5835 username,
5836 shell,
5837 journal_stream_dev,
5838 journal_stream_ino,
5839 pressure_path,
5840 needs_sandboxing,
5841 &our_env);
5842 if (r < 0) {
5843 *exit_status = EXIT_MEMORY;
5844 return log_oom();
5845 }
5846
5847 r = build_pass_environment(context, &pass_env);
5848 if (r < 0) {
5849 *exit_status = EXIT_MEMORY;
5850 return log_oom();
5851 }
5852
5853 /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5854 * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5855 * not specify PATH but the unit has ExecSearchPath. */
5856 if (!strv_isempty(context->exec_search_path)) {
5857 _cleanup_free_ char *joined = NULL;
5858
5859 joined = strv_join(context->exec_search_path, ":");
5860 if (!joined) {
5861 *exit_status = EXIT_MEMORY;
5862 return log_oom();
5863 }
5864
5865 r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
5866 if (r < 0) {
5867 *exit_status = EXIT_MEMORY;
5868 return log_oom();
5869 }
5870 }
5871
5872 accum_env = strv_env_merge(params->environment,
5873 our_env,
5874 joined_exec_search_path,
5875 pass_env,
5876 context->environment,
5877 params->files_env);
5878 if (!accum_env) {
5879 *exit_status = EXIT_MEMORY;
5880 return log_oom();
5881 }
5882 strv_env_clean(accum_env);
5883
5884 (void) umask(context->umask);
5885
5886 r = setup_term_environment(context, &accum_env);
5887 if (r < 0) {
5888 *exit_status = EXIT_MEMORY;
5889 return log_error_errno(r, "Failed to construct $TERM: %m");
5890 }
5891
5892 r = setup_keyring(context, params, uid, gid);
5893 if (r < 0) {
5894 *exit_status = EXIT_KEYRING;
5895 return log_error_errno(r, "Failed to set up kernel keyring: %m");
5896 }
5897
5898 /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5899 * excepted from either whole sandboxing or just setresuid() itself. */
5900 needs_setuid = needs_sandboxing && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_SETUID);
5901
5902 uint64_t capability_ambient_set = context->capability_ambient_set;
5903
5904 /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5905 have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
5906
5907 if (needs_sandboxing) {
5908 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5909 * /sys being present. The actual MAC context application will happen later, as late as
5910 * possible, to avoid impacting our own code paths. */
5911
5912 #if HAVE_SELINUX
5913 use_selinux = mac_selinux_use();
5914 #endif
5915 #if ENABLE_SMACK
5916 use_smack = mac_smack_use();
5917 #endif
5918 #if HAVE_APPARMOR
5919 use_apparmor = mac_apparmor_use();
5920 #endif
5921 }
5922
5923 if (needs_sandboxing) {
5924 int which_failed;
5925
5926 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5927 * is set here. (See below.) */
5928
5929 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
5930 if (r < 0) {
5931 *exit_status = EXIT_LIMITS;
5932 return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
5933 }
5934 }
5935
5936 if (needs_setuid && context->pam_name && username) {
5937 /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5938 * wins here. (See above.) */
5939
5940 /* All fds passed in the fds array will be closed in the pam child process. */
5941 r = setup_pam(context, cgroup_context, params, username, uid, gid, &accum_env,
5942 needs_sandboxing, params->exec_fd);
5943 if (r < 0) {
5944 *exit_status = EXIT_PAM;
5945 return log_error_errno(r, "Failed to set up PAM session: %m");
5946 }
5947
5948 /* PAM modules might have set some ambient caps. Query them here and merge them into
5949 * the caps we want to set in the end, so that we don't end up unsetting them. */
5950 uint64_t ambient_after_pam;
5951 r = capability_get_ambient(&ambient_after_pam);
5952 if (r < 0) {
5953 *exit_status = EXIT_CAPABILITIES;
5954 return log_error_errno(r, "Failed to query ambient caps: %m");
5955 }
5956
5957 capability_ambient_set |= ambient_after_pam;
5958
5959 ngids_after_pam = getgroups_alloc(&gids_after_pam);
5960 if (ngids_after_pam < 0) {
5961 *exit_status = EXIT_GROUP;
5962 return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
5963 }
5964 }
5965
5966 if (context->private_bpf != PRIVATE_BPF_NO) {
5967 /* To create a BPF token, the bpffs has to be mounted with the fsopen()/fsmount() API.
5968 * More specifically, fsopen() must be called within the user namespace, then all the
5969 * fsconfig() as privileged user, and finally and fsmount() and move_mount() in
5970 * the user namespace.
5971 * To do this, we split the code into a bpffs_prepare() and mount_bpffs() functions,
5972 * the first runs as privileged user the second as unprivileged one, and they coordinate
5973 * by sending messages and file descriptors via a socket pair.
5974 * The user and mount namespaces need to be unshared in this exact order and before
5975 * the fsopen() call for the fsopen() API to work as unprivileged.
5976 * This is the kernel sample doing this:
5977 * https://github.com/torvalds/linux/blob/master/tools/testing/selftests/bpf/prog_tests/token.c
5978 */
5979 r = bpffs_prepare(context, &bpffs_pidref, &bpffs_socket_fd, &bpffs_errno_pipe);
5980 if (r < 0) {
5981 *exit_status = EXIT_BPF;
5982 return log_error_errno(r, "Failed to mount bpffs in bpffs_prepare(): %m");
5983 }
5984 }
5985
5986 _cleanup_(pinned_resource_done) PinnedResource rootfs = PINNED_RESOURCE_NULL;
5987 _cleanup_free_ char *error_path = NULL;
5988 r = pin_rootfs(context, params, &rootfs, &error_path);
5989 if (r < 0) {
5990 *exit_status = EXIT_NAMESPACE;
5991 return log_error_errno(r, "Failed to open service's root fs%s%s: %m", error_path ? ": " : "", strempty(error_path));
5992 }
5993
5994 r = setup_ephemeral(context, runtime, &rootfs, &error_path);
5995 if (r < 0) {
5996 *exit_status = EXIT_NAMESPACE;
5997 return log_error_errno(r, "Failed to make ephemeral copy of service's root fs%s%s: %m", error_path ? ": " : "", strempty(error_path));
5998 }
5999
6000 /* Load a bunch of libraries we'll possibly need later, before we turn off dlopen() */
6001 (void) DLOPEN_BPF(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
6002 (void) DLOPEN_CRYPTSETUP(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
6003 (void) DLOPEN_LIBMOUNT(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
6004 (void) DLOPEN_LIBSECCOMP(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
6005
6006 /* Let's now disable further dlopen()ing of libraries, since we are about to do namespace
6007 * shenanigans, and do not want to mix resources from host and namespace */
6008 block_dlopen();
6009
6010 if (needs_sandboxing && !have_cap_sys_admin && exec_needs_cap_sys_admin(context, params)) {
6011 /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
6012 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
6013 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
6014
6015 if (context->user_namespace_path && runtime->shared->userns_storage_socket[0] >= 0)
6016 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "UserNamespacePath= is configured, but user namespace setup not permitted");
6017
6018 PrivateUsers pu = exec_context_get_effective_private_users(context, params);
6019 if (pu == PRIVATE_USERS_NO)
6020 pu = PRIVATE_USERS_SELF;
6021
6022 /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
6023 * unprivileged user namespaces. */
6024 r = setup_private_users(
6025 nsresource_link,
6026 pu,
6027 saved_uid,
6028 saved_gid,
6029 &uid,
6030 &gid,
6031 &outside_uid,
6032 &outside_gid,
6033 /* allow_setgroups= */ false);
6034 /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
6035 * the actual requested operations fail (or silently continue). */
6036 if (r < 0) {
6037 if (context->private_users != PRIVATE_USERS_NO) {
6038 *exit_status = EXIT_USER;
6039 return log_error_errno(r, "Failed to set up user namespacing for unprivileged user: %m");
6040 }
6041
6042 log_notice_errno(r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
6043 } else {
6044 assert(r > 0);
6045 userns_set_up = true;
6046 log_debug("Set up unprivileged user namespace");
6047 }
6048 }
6049
6050 /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
6051 r = setup_delegated_namespaces(
6052 context,
6053 params,
6054 runtime,
6055 &rootfs,
6056 /* delegate= */ false,
6057 pressure_path,
6058 uid,
6059 gid,
6060 command,
6061 needs_sandboxing,
6062 have_cap_sys_admin,
6063 &bpffs_pidref,
6064 bpffs_socket_fd,
6065 bpffs_errno_pipe,
6066 mountfsd_link,
6067 exit_status);
6068 if (r < 0)
6069 return r;
6070
6071 /* Drop groups as early as possible.
6072 * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
6073 * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
6074 if (needs_setuid) {
6075 _cleanup_free_ gid_t *gids_to_enforce = NULL;
6076 int ngids_to_enforce;
6077
6078 ngids_to_enforce = merge_gid_lists(gids,
6079 ngids,
6080 gids_after_pam,
6081 ngids_after_pam,
6082 &gids_to_enforce);
6083 if (ngids_to_enforce < 0) {
6084 *exit_status = EXIT_GROUP;
6085 return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
6086 }
6087
6088 r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
6089 if (r < 0) {
6090 *exit_status = EXIT_GROUP;
6091 return log_error_errno(r, "Changing group credentials failed: %m");
6092 }
6093 }
6094
6095 /* If the user namespace was not set up above, try to do it now.
6096 * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
6097 * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
6098 * case of mount namespaces being less privileged when the mount point list is copied from a
6099 * different user namespace). */
6100 if (needs_sandboxing && context->user_namespace_path && runtime->shared && runtime->shared->userns_storage_socket[0] >= 0) {
6101 if (!namespace_type_supported(NAMESPACE_USER))
6102 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "UserNamespacePath= is not supported, refusing.");
6103
6104 r = setup_shareable_ns(runtime->shared->userns_storage_socket, CLONE_NEWUSER);
6105 if (ERRNO_IS_NEG_PRIVILEGE(r))
6106 return log_notice_errno(r, "PrivateUsers= is configured, but user namespace setup not permitted, refusing.");
6107 if (r < 0) {
6108 *exit_status = EXIT_USER;
6109 return log_error_errno(r, "Failed to set up user namespacing: %m");
6110 }
6111
6112 log_debug("Set up existing user namespace");
6113 } else if (needs_sandboxing && !userns_set_up) {
6114 PrivateUsers pu = exec_context_get_effective_private_users(context, params);
6115
6116 r = setup_private_users(
6117 nsresource_link,
6118 pu,
6119 saved_uid,
6120 saved_gid,
6121 &uid,
6122 &gid,
6123 &outside_uid,
6124 &outside_gid,
6125 /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
6126 if (r < 0) {
6127 *exit_status = EXIT_USER;
6128 return log_error_errno(r, "Failed to set up user namespacing: %m");
6129 }
6130 if (r > 0)
6131 log_debug("Set up privileged user namespace");
6132 }
6133
6134 if (params->user_lookup_fd >= 0) {
6135 /* If we haven't sent the UIDs/GIDs we settled on upstream yet, let's do so now, as we
6136 * finally know our final UID/GID range */
6137
6138 r = send_user_lookup(params->unit_id, params->user_lookup_fd, outside_uid, outside_gid);
6139 if (r < 0) {
6140 *exit_status = EXIT_USER;
6141 return log_error_errno(r, "Failed to send user credentials to PID1: %m");
6142 }
6143
6144 params->user_lookup_fd = safe_close(params->user_lookup_fd);
6145 }
6146
6147 /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
6148 r = setup_delegated_namespaces(
6149 context,
6150 params,
6151 runtime,
6152 &rootfs,
6153 /* delegate= */ true,
6154 pressure_path,
6155 uid,
6156 gid,
6157 command,
6158 needs_sandboxing,
6159 have_cap_sys_admin,
6160 &bpffs_pidref,
6161 bpffs_socket_fd,
6162 bpffs_errno_pipe,
6163 mountfsd_link,
6164 exit_status);
6165 if (r < 0)
6166 return r;
6167
6168 /* We are done now with the nsresourced/mountfsd shenanigans, let's close the connections */
6169 nsresource_link = sd_varlink_unref(nsresource_link);
6170 mountfsd_link = sd_varlink_unref(mountfsd_link);
6171
6172 /* We don't need the pinned rootfs anymore at this point. Close the fds now, so that they are
6173 * definitely gone before we do our fd rearrangements below. */
6174 pinned_resource_done(&rootfs);
6175
6176 /* Kill unnecessary process, for the case that e.g. when the bpffs mount point is hidden. */
6177 pidref_done_sigkill_wait(&bpffs_pidref);
6178 bpffs_socket_fd = safe_close(bpffs_socket_fd);
6179 bpffs_errno_pipe = safe_close(bpffs_errno_pipe);
6180
6181 if (needs_sandboxing && exec_needs_cgroup_namespace(context) && params->cgroup_path) {
6182 /* Move ourselves into the subcgroup now *after* we've unshared the cgroup namespace, which
6183 * ensures the root of the cgroup namespace is the top level service cgroup and not the
6184 * subcgroup. Adjust the prefix accordingly since we're in a cgroup namespace now. */
6185 r = attach_to_subcgroup(context, cgroup_context, params, /* prefix= */ NULL);
6186 if (r < 0) {
6187 *exit_status = EXIT_CGROUP;
6188 return r;
6189 }
6190 }
6191
6192 /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
6193 * shall execute. */
6194
6195 const char *path = command->path;
6196
6197 if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
6198 if (shell_is_placeholder(shell)) {
6199 log_debug("Shell prefixing requested for user without default shell, using /bin/sh: %s",
6200 strna(username));
6201 assert(streq(path, _PATH_BSHELL));
6202 } else
6203 path = shell;
6204 }
6205
6206 _cleanup_free_ char *executable = NULL;
6207 _cleanup_close_ int executable_fd = -EBADF;
6208 r = find_executable_full(path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
6209 if (r < 0) {
6210 *exit_status = EXIT_EXEC;
6211 log_struct_errno(LOG_NOTICE, r,
6212 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
6213 LOG_EXEC_MESSAGE(params, "Unable to locate executable '%s': %m", path),
6214 LOG_ITEM("EXECUTABLE=%s", path));
6215 /* If the error will be ignored by manager, tune down the log level here. Missing executable
6216 * is very much expected in this case. */
6217 return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
6218 }
6219
6220 r = add_shifted_fd(&keep_fds, &n_keep_fds, &executable_fd);
6221 if (r < 0) {
6222 *exit_status = EXIT_FDS;
6223 return log_error_errno(r, "Failed to collect shifted fd: %m");
6224 }
6225
6226 #if HAVE_SELINUX
6227 if (needs_sandboxing && use_selinux && params->selinux_context_net) {
6228 int fd = -EBADF;
6229
6230 if (socket_fd >= 0)
6231 fd = socket_fd;
6232 else if (params->n_socket_fds == 1)
6233 /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
6234 * use context from that fd to compute the label. */
6235 fd = params->fds[0];
6236
6237 if (fd >= 0) {
6238 r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
6239 if (r < 0) {
6240 if (!context->selinux_context_ignore) {
6241 *exit_status = EXIT_SELINUX_CONTEXT;
6242 return log_error_errno(r, "Failed to determine SELinux context: %m");
6243 }
6244 log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
6245 }
6246 }
6247 }
6248 #endif
6249
6250 /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
6251 * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
6252 * more. We do keep exec_fd and handoff_timestamp_fd however, if we have it, since we need to keep
6253 * them open until the final execve(). But first, close the remaining sockets in the context
6254 * objects. */
6255
6256 socket_fd = safe_close(socket_fd);
6257 exec_runtime_close(runtime);
6258 exec_params_close(params);
6259
6260 r = close_all_fds(keep_fds, n_keep_fds);
6261 if (r >= 0)
6262 r = pack_fds(params->fds, params->n_socket_fds + params->n_stashed_fds);
6263 if (r >= 0)
6264 r = flag_fds(params->fds, params->n_socket_fds, params->n_socket_fds + params->n_stashed_fds,
6265 context->non_blocking);
6266 if (r < 0) {
6267 *exit_status = EXIT_FDS;
6268 return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
6269 }
6270
6271 /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
6272 * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
6273 * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
6274 * came this far. */
6275
6276 secure_bits = context->secure_bits;
6277
6278 if (needs_sandboxing) {
6279 uint64_t bset;
6280
6281 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
6282 * (Note this is placed after the general resource limit initialization, see above, in order
6283 * to take precedence.) */
6284 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
6285 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
6286 *exit_status = EXIT_LIMITS;
6287 return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
6288 }
6289 }
6290
6291 #if ENABLE_SMACK
6292 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
6293 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
6294 if (use_smack) {
6295 r = setup_smack(context, params, executable_fd);
6296 if (r < 0 && !context->smack_process_label_ignore) {
6297 *exit_status = EXIT_SMACK_PROCESS_LABEL;
6298 return log_error_errno(r, "Failed to set SMACK process label: %m");
6299 }
6300 }
6301 #endif
6302
6303 bset = context->capability_bounding_set;
6304
6305 #if HAVE_SECCOMP
6306 /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
6307 * keep the needed privileges to apply it even if we're not root. */
6308 if (needs_setuid &&
6309 uid_is_valid(uid) &&
6310 context_has_seccomp(context) &&
6311 seccomp_allows_drop_privileges(context)) {
6312 keep_seccomp_privileges = true;
6313
6314 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
6315 *exit_status = EXIT_USER;
6316 return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
6317 }
6318
6319 /* Save the current bounding set so we can restore it after applying the seccomp
6320 * filter */
6321 saved_bset = bset;
6322 bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
6323 (UINT64_C(1) << CAP_SETPCAP);
6324 }
6325 #endif
6326
6327 if (!cap_test_all(bset)) {
6328 r = capability_bounding_set_drop(bset, /* right_now= */ false);
6329 if (r < 0) {
6330 *exit_status = EXIT_CAPABILITIES;
6331 return log_error_errno(r, "Failed to drop capabilities: %m");
6332 }
6333 }
6334
6335 /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
6336 * keep-caps set.
6337 *
6338 * To be able to raise the ambient capabilities after setresuid() they have to be added to
6339 * the inherited set and keep caps has to be set (done in enforce_user()). After setresuid()
6340 * the ambient capabilities can be raised as they are present in the permitted and
6341 * inhertiable set. However it is possible that someone wants to set ambient capabilities
6342 * without changing the user, so we also set the ambient capabilities here.
6343 *
6344 * The requested ambient capabilities are raised in the inheritable set if the second
6345 * argument is true. */
6346 if (capability_ambient_set != 0) {
6347 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
6348 if (r < 0) {
6349 *exit_status = EXIT_CAPABILITIES;
6350 return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
6351 }
6352 }
6353 }
6354
6355 /* chroot to root directory first, before we lose the ability to chroot */
6356 r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
6357 if (r < 0)
6358 return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
6359
6360 if (needs_setuid) {
6361 if (uid_is_valid(uid)) {
6362 r = enforce_user(context, uid, capability_ambient_set);
6363 if (r < 0) {
6364 *exit_status = EXIT_USER;
6365 return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
6366 }
6367
6368 if (keep_seccomp_privileges) {
6369 if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
6370 r = drop_capability(CAP_SETUID);
6371 if (r < 0) {
6372 *exit_status = EXIT_USER;
6373 return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
6374 }
6375 }
6376
6377 r = keep_capability(CAP_SYS_ADMIN);
6378 if (r < 0) {
6379 *exit_status = EXIT_USER;
6380 return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
6381 }
6382
6383 r = keep_capability(CAP_SETPCAP);
6384 if (r < 0) {
6385 *exit_status = EXIT_USER;
6386 return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
6387 }
6388 }
6389
6390 if (capability_ambient_set != 0) {
6391
6392 /* Raise the ambient capabilities after user change. */
6393 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
6394 if (r < 0) {
6395 *exit_status = EXIT_CAPABILITIES;
6396 return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
6397 }
6398 }
6399 }
6400 }
6401
6402 /* Apply working directory here, because the working directory might be on NFS and only the user
6403 * running this service might have the correct privilege to change to the working directory. Also, it
6404 * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
6405 * the cwd cannot be used to pin directories outside of the sandbox. */
6406 r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
6407 if (r < 0) {
6408 *exit_status = EXIT_CHDIR;
6409 return log_error_errno(r, "Changing to the requested working directory failed: %m");
6410 }
6411
6412 if (needs_sandboxing) {
6413 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
6414 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
6415 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
6416 * are restricted. */
6417
6418 #if HAVE_SELINUX
6419 if (use_selinux) {
6420 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
6421
6422 if (exec_context) {
6423 r = sym_setexeccon_raw(exec_context);
6424 if (r < 0) {
6425 if (!context->selinux_context_ignore) {
6426 *exit_status = EXIT_SELINUX_CONTEXT;
6427 return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
6428 }
6429 log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
6430 }
6431 }
6432 }
6433 #endif
6434
6435 #if HAVE_APPARMOR
6436 if (use_apparmor && context->apparmor_profile) {
6437 r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
6438 if (r < 0 && !context->apparmor_profile_ignore) {
6439 *exit_status = EXIT_APPARMOR_PROFILE;
6440 return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
6441 context->apparmor_profile);
6442 }
6443 }
6444 #endif
6445
6446 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
6447 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
6448 * requires CAP_SETPCAP. */
6449 if (prctl(PR_GET_SECUREBITS) != secure_bits) {
6450 /* CAP_SETPCAP is required to set securebits. This capability is raised into the
6451 * effective set here.
6452 *
6453 * The effective set is overwritten during execve() with the following values:
6454 *
6455 * - ambient set (for non-root processes)
6456 *
6457 * - (inheritable | bounding) set for root processes)
6458 *
6459 * Hence there is no security impact to raise it in the effective set before execve
6460 */
6461 r = capability_gain_cap_setpcap();
6462 if (r < 0) {
6463 *exit_status = EXIT_CAPABILITIES;
6464 return log_error_errno(r, "Failed to gain CAP_SETPCAP for setting secure bits");
6465 }
6466 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
6467 *exit_status = EXIT_SECUREBITS;
6468 return log_error_errno(errno, "Failed to set process secure bits: %m");
6469 }
6470 }
6471
6472 if (context_has_no_new_privileges(context))
6473 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
6474 *exit_status = EXIT_NO_NEW_PRIVILEGES;
6475 return log_error_errno(errno, "Failed to disable new privileges: %m");
6476 }
6477
6478 #if HAVE_SECCOMP
6479 r = apply_address_families(context, params);
6480 if (r < 0) {
6481 *exit_status = EXIT_ADDRESS_FAMILIES;
6482 return log_error_errno(r, "Failed to restrict address families: %m");
6483 }
6484
6485 r = apply_memory_deny_write_execute(context, params);
6486 if (r < 0) {
6487 *exit_status = EXIT_SECCOMP;
6488 return log_error_errno(r, "Failed to disable writing to executable memory: %m");
6489 }
6490
6491 r = apply_restrict_realtime(context, params);
6492 if (r < 0) {
6493 *exit_status = EXIT_SECCOMP;
6494 return log_error_errno(r, "Failed to apply realtime restrictions: %m");
6495 }
6496
6497 r = apply_restrict_suid_sgid(context, params);
6498 if (r < 0) {
6499 *exit_status = EXIT_SECCOMP;
6500 return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
6501 }
6502
6503 r = apply_restrict_namespaces(context, params);
6504 if (r < 0) {
6505 *exit_status = EXIT_SECCOMP;
6506 return log_error_errno(r, "Failed to apply namespace restrictions: %m");
6507 }
6508
6509 r = apply_protect_sysctl(context, params);
6510 if (r < 0) {
6511 *exit_status = EXIT_SECCOMP;
6512 return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
6513 }
6514
6515 r = apply_protect_kernel_modules(context, params);
6516 if (r < 0) {
6517 *exit_status = EXIT_SECCOMP;
6518 return log_error_errno(r, "Failed to apply module loading restrictions: %m");
6519 }
6520
6521 r = apply_protect_kernel_logs(context, params);
6522 if (r < 0) {
6523 *exit_status = EXIT_SECCOMP;
6524 return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
6525 }
6526
6527 r = apply_protect_clock(context, params);
6528 if (r < 0) {
6529 *exit_status = EXIT_SECCOMP;
6530 return log_error_errno(r, "Failed to apply clock restrictions: %m");
6531 }
6532
6533 r = apply_private_devices(context, params);
6534 if (r < 0) {
6535 *exit_status = EXIT_SECCOMP;
6536 return log_error_errno(r, "Failed to set up private devices: %m");
6537 }
6538
6539 r = apply_syscall_archs(context, params);
6540 if (r < 0) {
6541 *exit_status = EXIT_SECCOMP;
6542 return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
6543 }
6544
6545 r = apply_lock_personality(context, params);
6546 if (r < 0) {
6547 *exit_status = EXIT_SECCOMP;
6548 return log_error_errno(r, "Failed to lock personalities: %m");
6549 }
6550
6551 r = apply_syscall_log(context, params);
6552 if (r < 0) {
6553 *exit_status = EXIT_SECCOMP;
6554 return log_error_errno(r, "Failed to apply system call log filters: %m");
6555 }
6556 #endif
6557
6558 #if HAVE_LIBBPF
6559 r = apply_restrict_filesystems(context, params);
6560 if (r < 0) {
6561 *exit_status = EXIT_BPF;
6562 return log_error_errno(r, "Failed to restrict filesystems: %m");
6563 }
6564 #endif
6565
6566 #if HAVE_SECCOMP
6567 /* This really should remain as close to the execve() as possible, to make sure our own code is affected
6568 * by the filter as little as possible. */
6569 r = apply_syscall_filter(context, params);
6570 if (r < 0) {
6571 *exit_status = EXIT_SECCOMP;
6572 return log_error_errno(r, "Failed to apply system call filters: %m");
6573 }
6574
6575 if (keep_seccomp_privileges) {
6576 /* Restore the capability bounding set with what's expected from the service + the
6577 * ambient capabilities hack */
6578 if (!cap_test_all(saved_bset)) {
6579 r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
6580 if (r < 0) {
6581 *exit_status = EXIT_CAPABILITIES;
6582 return log_error_errno(r, "Failed to drop bset capabilities: %m");
6583 }
6584 }
6585
6586 /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
6587 * applications that use it. */
6588 if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
6589 r = drop_capability(CAP_SYS_ADMIN);
6590 if (r < 0) {
6591 *exit_status = EXIT_USER;
6592 return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
6593 }
6594 }
6595
6596 /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
6597 * applications that use it. */
6598 if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
6599 r = drop_capability(CAP_SETPCAP);
6600 if (r < 0) {
6601 *exit_status = EXIT_USER;
6602 return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
6603 }
6604 }
6605
6606 if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
6607 *exit_status = EXIT_USER;
6608 return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
6609 }
6610 }
6611 #endif
6612 }
6613
6614 if (!strv_isempty(context->unset_environment)) {
6615 char **ee = NULL;
6616
6617 ee = strv_env_delete(accum_env, 1, context->unset_environment);
6618 if (!ee) {
6619 *exit_status = EXIT_MEMORY;
6620 return log_oom();
6621 }
6622
6623 strv_free_and_replace(accum_env, ee);
6624 }
6625
6626 _cleanup_strv_free_ char **replaced_argv = NULL, **argv_via_shell = NULL;
6627 char **final_argv = FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL) ? strv_skip(command->argv, 1) : command->argv;
6628
6629 if (final_argv && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
6630 _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
6631
6632 r = replace_env_argv(final_argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
6633 if (r < 0) {
6634 *exit_status = EXIT_MEMORY;
6635 return log_error_errno(r, "Failed to replace environment variables: %m");
6636 }
6637 final_argv = replaced_argv;
6638
6639 if (!strv_isempty(unset_variables)) {
6640 _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
6641 log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
6642 }
6643
6644 if (!strv_isempty(bad_variables)) {
6645 _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
6646 log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
6647 }
6648 }
6649
6650 if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
6651 r = strv_extendf(&argv_via_shell, "%s%s", command->argv[0][0] == '-' ? "-" : "", path);
6652 if (r < 0) {
6653 *exit_status = EXIT_MEMORY;
6654 return log_oom();
6655 }
6656
6657 if (!strv_isempty(final_argv)) {
6658 _cleanup_free_ char *cmdline_joined = NULL;
6659
6660 cmdline_joined = strv_join(final_argv, " ");
6661 if (!cmdline_joined) {
6662 *exit_status = EXIT_MEMORY;
6663 return log_oom();
6664 }
6665
6666 r = strv_extend_many(&argv_via_shell, "-c", cmdline_joined);
6667 if (r < 0) {
6668 *exit_status = EXIT_MEMORY;
6669 return log_oom();
6670 }
6671 }
6672
6673 final_argv = argv_via_shell;
6674 }
6675
6676 log_command_line(context, params, "Executing", executable, final_argv);
6677
6678 /* We have finished with all our initializations. Let's now let the manager know that. From this
6679 * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
6680
6681 r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
6682 if (r < 0)
6683 return r;
6684
6685 /* As last thing before the execve(), let's send the handoff timestamp */
6686 r = send_handoff_timestamp(context, params, exit_status);
6687 if (r < 0) {
6688 /* If this handoff timestamp failed, let's undo the marking as hot */
6689 (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
6690 return r;
6691 }
6692
6693 /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
6694 * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
6695 * exec_fd this is pretty much the whole raison d'etre. */
6696
6697 r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
6698
6699 /* The execve() failed, let's undo the marking as hot */
6700 (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
6701
6702 *exit_status = EXIT_EXEC;
6703 return log_error_errno(r, "Failed to execute %s: %m", executable);
6704 }