]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/exec-invoke.c
Merge pull request #30610 from YHNdnzj/logind-serialize-pidref
[thirdparty/systemd.git] / src / core / exec-invoke.c
CommitLineData
75689fb2
LB
1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3#include <sys/eventfd.h>
4#include <sys/ioctl.h>
5#include <sys/mount.h>
6#include <sys/prctl.h>
7
8#if HAVE_PAM
9#include <security/pam_appl.h>
10#include <security/pam_misc.h>
11#endif
12
13#if HAVE_APPARMOR
14#include <sys/apparmor.h>
15#endif
16
17#include "sd-messages.h"
18
19#if HAVE_APPARMOR
20#include "apparmor-util.h"
21#endif
22#include "argv-util.h"
23#include "barrier.h"
24#include "bpf-dlopen.h"
25#include "bpf-lsm.h"
26#include "btrfs-util.h"
27#include "capability-util.h"
28#include "cgroup-setup.h"
29#include "chase.h"
30#include "chattr-util.h"
31#include "chown-recursive.h"
32#include "copy.h"
33#include "data-fd-util.h"
34#include "env-util.h"
35#include "escape.h"
36#include "exec-credential.h"
37#include "exec-invoke.h"
38#include "execute.h"
39#include "exit-status.h"
40#include "fd-util.h"
41#include "hexdecoct.h"
42#include "io-util.h"
bd1ae178 43#include "iovec-util.h"
75689fb2
LB
44#include "missing_ioprio.h"
45#include "missing_prctl.h"
46#include "missing_securebits.h"
47#include "missing_syscall.h"
48#include "mkdir-label.h"
49#include "proc-cmdline.h"
50#include "process-util.h"
51#include "psi-util.h"
52#include "rlimit-util.h"
53#include "seccomp-util.h"
54#include "selinux-util.h"
55#include "signal-util.h"
56#include "smack-util.h"
57#include "socket-util.h"
58#include "string-table.h"
59#include "strv.h"
60#include "terminal-util.h"
61#include "utmp-wtmp.h"
0cb11023 62#include "vpick.h"
75689fb2
LB
63
64#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
65#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
66
67#define SNDBUF_SIZE (8*1024*1024)
68
69static int shift_fds(int fds[], size_t n_fds) {
70 if (n_fds <= 0)
71 return 0;
72
73 /* Modifies the fds array! (sorts it) */
74
75 assert(fds);
76
77 for (int start = 0;;) {
78 int restart_from = -1;
79
80 for (int i = start; i < (int) n_fds; i++) {
81 int nfd;
82
83 /* Already at right index? */
84 if (fds[i] == i+3)
85 continue;
86
87 nfd = fcntl(fds[i], F_DUPFD, i + 3);
88 if (nfd < 0)
89 return -errno;
90
91 safe_close(fds[i]);
92 fds[i] = nfd;
93
94 /* Hmm, the fd we wanted isn't free? Then
95 * let's remember that and try again from here */
96 if (nfd != i+3 && restart_from < 0)
97 restart_from = i;
98 }
99
100 if (restart_from < 0)
101 break;
102
103 start = restart_from;
104 }
105
106 return 0;
107}
108
d8da25b5 109static int flag_fds(
75689fb2
LB
110 const int fds[],
111 size_t n_socket_fds,
112 size_t n_fds,
113 bool nonblock) {
114
115 int r;
116
d8da25b5 117 assert(fds || n_fds == 0);
75689fb2
LB
118
119 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
120 * O_NONBLOCK only applies to socket activation though. */
121
122 for (size_t i = 0; i < n_fds; i++) {
123
124 if (i < n_socket_fds) {
125 r = fd_nonblock(fds[i], nonblock);
126 if (r < 0)
127 return r;
128 }
129
130 /* We unconditionally drop FD_CLOEXEC from the fds,
131 * since after all we want to pass these fds to our
132 * children */
133
134 r = fd_cloexec(fds[i], false);
135 if (r < 0)
136 return r;
137 }
138
139 return 0;
140}
141
142static bool is_terminal_input(ExecInput i) {
143 return IN_SET(i,
144 EXEC_INPUT_TTY,
145 EXEC_INPUT_TTY_FORCE,
146 EXEC_INPUT_TTY_FAIL);
147}
148
149static bool is_terminal_output(ExecOutput o) {
150 return IN_SET(o,
151 EXEC_OUTPUT_TTY,
152 EXEC_OUTPUT_KMSG_AND_CONSOLE,
153 EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
154}
155
156static bool is_kmsg_output(ExecOutput o) {
157 return IN_SET(o,
158 EXEC_OUTPUT_KMSG,
159 EXEC_OUTPUT_KMSG_AND_CONSOLE);
160}
161
162static bool exec_context_needs_term(const ExecContext *c) {
163 assert(c);
164
165 /* Return true if the execution context suggests we should set $TERM to something useful. */
166
167 if (is_terminal_input(c->std_input))
168 return true;
169
170 if (is_terminal_output(c->std_output))
171 return true;
172
173 if (is_terminal_output(c->std_error))
174 return true;
175
176 return !!c->tty_path;
177}
178
179static int open_null_as(int flags, int nfd) {
180 int fd;
181
182 assert(nfd >= 0);
183
184 fd = open("/dev/null", flags|O_NOCTTY);
185 if (fd < 0)
186 return -errno;
187
188 return move_fd(fd, nfd, false);
189}
190
191static int connect_journal_socket(
192 int fd,
193 const char *log_namespace,
194 uid_t uid,
195 gid_t gid) {
196
197 uid_t olduid = UID_INVALID;
198 gid_t oldgid = GID_INVALID;
199 const char *j;
200 int r;
201
202 j = log_namespace ?
203 strjoina("/run/systemd/journal.", log_namespace, "/stdout") :
204 "/run/systemd/journal/stdout";
205
206 if (gid_is_valid(gid)) {
207 oldgid = getgid();
208
209 if (setegid(gid) < 0)
210 return -errno;
211 }
212
213 if (uid_is_valid(uid)) {
214 olduid = getuid();
215
216 if (seteuid(uid) < 0) {
217 r = -errno;
218 goto restore_gid;
219 }
220 }
221
222 r = connect_unix_path(fd, AT_FDCWD, j);
223
224 /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
225 an LSM interferes. */
226
227 if (uid_is_valid(uid))
228 (void) seteuid(olduid);
229
230 restore_gid:
231 if (gid_is_valid(gid))
232 (void) setegid(oldgid);
233
234 return r;
235}
236
237static int connect_logger_as(
238 const ExecContext *context,
239 const ExecParameters *params,
240 ExecOutput output,
241 const char *ident,
242 int nfd,
243 uid_t uid,
244 gid_t gid) {
245
246 _cleanup_close_ int fd = -EBADF;
247 int r;
248
249 assert(context);
250 assert(params);
251 assert(output < _EXEC_OUTPUT_MAX);
252 assert(ident);
253 assert(nfd >= 0);
254
255 fd = socket(AF_UNIX, SOCK_STREAM, 0);
256 if (fd < 0)
257 return -errno;
258
259 r = connect_journal_socket(fd, context->log_namespace, uid, gid);
260 if (r < 0)
261 return r;
262
263 if (shutdown(fd, SHUT_RD) < 0)
264 return -errno;
265
266 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
267
268 if (dprintf(fd,
269 "%s\n"
270 "%s\n"
271 "%i\n"
272 "%i\n"
273 "%i\n"
274 "%i\n"
275 "%i\n",
276 context->syslog_identifier ?: ident,
277 params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
278 context->syslog_priority,
279 !!context->syslog_level_prefix,
280 false,
281 is_kmsg_output(output),
282 is_terminal_output(output)) < 0)
283 return -errno;
284
285 return move_fd(TAKE_FD(fd), nfd, false);
286}
287
288static int open_terminal_as(const char *path, int flags, int nfd) {
289 int fd;
290
291 assert(path);
292 assert(nfd >= 0);
293
294 fd = open_terminal(path, flags | O_NOCTTY);
295 if (fd < 0)
296 return fd;
297
298 return move_fd(fd, nfd, false);
299}
300
301static int acquire_path(const char *path, int flags, mode_t mode) {
302 _cleanup_close_ int fd = -EBADF;
303 int r;
304
305 assert(path);
306
307 if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
308 flags |= O_CREAT;
309
310 fd = open(path, flags|O_NOCTTY, mode);
311 if (fd >= 0)
312 return TAKE_FD(fd);
313
314 if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
315 return -errno;
316
317 /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
318
319 fd = socket(AF_UNIX, SOCK_STREAM, 0);
320 if (fd < 0)
321 return -errno;
322
323 r = connect_unix_path(fd, AT_FDCWD, path);
324 if (IN_SET(r, -ENOTSOCK, -EINVAL))
325 /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
326 * wasn't an AF_UNIX socket after all */
327 return -ENXIO;
328 if (r < 0)
329 return r;
330
331 if ((flags & O_ACCMODE) == O_RDONLY)
332 r = shutdown(fd, SHUT_WR);
333 else if ((flags & O_ACCMODE) == O_WRONLY)
334 r = shutdown(fd, SHUT_RD);
335 else
336 r = 0;
337 if (r < 0)
338 return -errno;
339
340 return TAKE_FD(fd);
341}
342
343static int fixup_input(
344 const ExecContext *context,
345 int socket_fd,
346 bool apply_tty_stdin) {
347
348 ExecInput std_input;
349
350 assert(context);
351
352 std_input = context->std_input;
353
354 if (is_terminal_input(std_input) && !apply_tty_stdin)
355 return EXEC_INPUT_NULL;
356
357 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
358 return EXEC_INPUT_NULL;
359
360 if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
361 return EXEC_INPUT_NULL;
362
363 return std_input;
364}
365
366static int fixup_output(ExecOutput output, int socket_fd) {
367
368 if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
369 return EXEC_OUTPUT_INHERIT;
370
371 return output;
372}
373
374static int setup_input(
375 const ExecContext *context,
376 const ExecParameters *params,
377 int socket_fd,
378 const int named_iofds[static 3]) {
379
380 ExecInput i;
381 int r;
382
383 assert(context);
384 assert(params);
385 assert(named_iofds);
386
387 if (params->stdin_fd >= 0) {
388 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
389 return -errno;
390
391 /* Try to make this the controlling tty, if it is a tty, and reset it */
392 if (isatty(STDIN_FILENO)) {
75689fb2 393 (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
bb2dbe7c
LP
394
395 if (context->tty_reset)
396 (void) reset_terminal_fd(STDIN_FILENO, /* switch_to_text= */ true);
397
d2b9e755 398 (void) exec_context_apply_tty_size(context, STDIN_FILENO, /* tty_path= */ NULL);
75689fb2
LB
399 }
400
401 return STDIN_FILENO;
402 }
403
404 i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
405
406 switch (i) {
407
408 case EXEC_INPUT_NULL:
409 return open_null_as(O_RDONLY, STDIN_FILENO);
410
411 case EXEC_INPUT_TTY:
412 case EXEC_INPUT_TTY_FORCE:
413 case EXEC_INPUT_TTY_FAIL: {
d2b9e755
LP
414 _cleanup_close_ int tty_fd = -EBADF;
415 const char *tty_path;
75689fb2 416
d2b9e755
LP
417 tty_path = ASSERT_PTR(exec_context_tty_path(context));
418
419 tty_fd = acquire_terminal(tty_path,
420 i == EXEC_INPUT_TTY_FAIL ? ACQUIRE_TERMINAL_TRY :
421 i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
422 ACQUIRE_TERMINAL_WAIT,
423 USEC_INFINITY);
424 if (tty_fd < 0)
425 return tty_fd;
75689fb2 426
d2b9e755 427 r = exec_context_apply_tty_size(context, tty_fd, tty_path);
75689fb2
LB
428 if (r < 0)
429 return r;
430
d2b9e755 431 r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
75689fb2
LB
432 if (r < 0)
433 return r;
434
d2b9e755
LP
435 TAKE_FD(tty_fd);
436 return r;
75689fb2
LB
437 }
438
439 case EXEC_INPUT_SOCKET:
440 assert(socket_fd >= 0);
441
442 return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
443
444 case EXEC_INPUT_NAMED_FD:
445 assert(named_iofds[STDIN_FILENO] >= 0);
446
447 (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
448 return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
449
450 case EXEC_INPUT_DATA: {
451 int fd;
452
453 fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
454 if (fd < 0)
455 return fd;
456
457 return move_fd(fd, STDIN_FILENO, false);
458 }
459
460 case EXEC_INPUT_FILE: {
461 bool rw;
462 int fd;
463
464 assert(context->stdio_file[STDIN_FILENO]);
465
466 rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
467 (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
468
469 fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
470 if (fd < 0)
471 return fd;
472
473 return move_fd(fd, STDIN_FILENO, false);
474 }
475
476 default:
477 assert_not_reached();
478 }
479}
480
481static bool can_inherit_stderr_from_stdout(
482 const ExecContext *context,
483 ExecOutput o,
484 ExecOutput e) {
485
486 assert(context);
487
488 /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
489 * stderr fd */
490
491 if (e == EXEC_OUTPUT_INHERIT)
492 return true;
493 if (e != o)
494 return false;
495
496 if (e == EXEC_OUTPUT_NAMED_FD)
497 return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
498
499 if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
500 return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
501
502 return true;
503}
504
505static int setup_output(
506 const ExecContext *context,
507 const ExecParameters *params,
508 int fileno,
509 int socket_fd,
510 const int named_iofds[static 3],
511 const char *ident,
512 uid_t uid,
513 gid_t gid,
514 dev_t *journal_stream_dev,
515 ino_t *journal_stream_ino) {
516
517 ExecOutput o;
518 ExecInput i;
519 int r;
520
521 assert(context);
522 assert(params);
523 assert(ident);
524 assert(journal_stream_dev);
525 assert(journal_stream_ino);
526
527 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
528
529 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
530 return -errno;
531
532 return STDOUT_FILENO;
533 }
534
535 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
536 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
537 return -errno;
538
539 return STDERR_FILENO;
540 }
541
542 i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
543 o = fixup_output(context->std_output, socket_fd);
544
545 if (fileno == STDERR_FILENO) {
546 ExecOutput e;
547 e = fixup_output(context->std_error, socket_fd);
548
549 /* This expects the input and output are already set up */
550
551 /* Don't change the stderr file descriptor if we inherit all
552 * the way and are not on a tty */
553 if (e == EXEC_OUTPUT_INHERIT &&
554 o == EXEC_OUTPUT_INHERIT &&
555 i == EXEC_INPUT_NULL &&
556 !is_terminal_input(context->std_input) &&
557 getppid() != 1)
558 return fileno;
559
560 /* Duplicate from stdout if possible */
561 if (can_inherit_stderr_from_stdout(context, o, e))
562 return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
563
564 o = e;
565
566 } else if (o == EXEC_OUTPUT_INHERIT) {
567 /* If input got downgraded, inherit the original value */
568 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
569 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
570
571 /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
572 if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
573 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
574
575 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
576 if (getppid() != 1)
577 return fileno;
578
579 /* We need to open /dev/null here anew, to get the right access mode. */
580 return open_null_as(O_WRONLY, fileno);
581 }
582
583 switch (o) {
584
585 case EXEC_OUTPUT_NULL:
586 return open_null_as(O_WRONLY, fileno);
587
588 case EXEC_OUTPUT_TTY:
589 if (is_terminal_input(i))
590 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
591
592 /* We don't reset the terminal if this is just about output */
593 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
594
595 case EXEC_OUTPUT_KMSG:
596 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
597 case EXEC_OUTPUT_JOURNAL:
598 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
599 r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
600 if (r < 0) {
601 log_exec_warning_errno(context,
602 params,
603 r,
604 "Failed to connect %s to the journal socket, ignoring: %m",
605 fileno == STDOUT_FILENO ? "stdout" : "stderr");
606 r = open_null_as(O_WRONLY, fileno);
607 } else {
608 struct stat st;
609
610 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
611 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
612 * services to detect whether they are connected to the journal or not.
613 *
614 * If both stdout and stderr are connected to a stream then let's make sure to store the data
615 * about STDERR as that's usually the best way to do logging. */
616
617 if (fstat(fileno, &st) >= 0 &&
618 (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
619 *journal_stream_dev = st.st_dev;
620 *journal_stream_ino = st.st_ino;
621 }
622 }
623 return r;
624
625 case EXEC_OUTPUT_SOCKET:
626 assert(socket_fd >= 0);
627
628 return RET_NERRNO(dup2(socket_fd, fileno));
629
630 case EXEC_OUTPUT_NAMED_FD:
631 assert(named_iofds[fileno] >= 0);
632
633 (void) fd_nonblock(named_iofds[fileno], false);
634 return RET_NERRNO(dup2(named_iofds[fileno], fileno));
635
636 case EXEC_OUTPUT_FILE:
637 case EXEC_OUTPUT_FILE_APPEND:
638 case EXEC_OUTPUT_FILE_TRUNCATE: {
639 bool rw;
640 int fd, flags;
641
642 assert(context->stdio_file[fileno]);
643
644 rw = context->std_input == EXEC_INPUT_FILE &&
645 streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
646
647 if (rw)
648 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
649
650 flags = O_WRONLY;
651 if (o == EXEC_OUTPUT_FILE_APPEND)
652 flags |= O_APPEND;
653 else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
654 flags |= O_TRUNC;
655
656 fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
657 if (fd < 0)
658 return fd;
659
660 return move_fd(fd, fileno, 0);
661 }
662
663 default:
664 assert_not_reached();
665 }
666}
667
668static int chown_terminal(int fd, uid_t uid) {
669 int r;
670
671 assert(fd >= 0);
672
673 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
dd9c8da8
MY
674 if (!isatty_safe(fd))
675 return 0;
75689fb2
LB
676
677 /* This might fail. What matters are the results. */
678 r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
679 if (r < 0)
680 return r;
681
682 return 1;
683}
684
685static int setup_confirm_stdio(
686 const ExecContext *context,
687 const char *vc,
688 int *ret_saved_stdin,
689 int *ret_saved_stdout) {
690
691 _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
75689fb2
LB
692 int r;
693
694 assert(ret_saved_stdin);
695 assert(ret_saved_stdout);
696
697 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
698 if (saved_stdin < 0)
699 return -errno;
700
701 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
702 if (saved_stdout < 0)
703 return -errno;
704
705 fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
706 if (fd < 0)
707 return fd;
708
709 r = chown_terminal(fd, getuid());
710 if (r < 0)
711 return r;
712
29ed1f02 713 r = reset_terminal_fd(fd, /* switch_to_text= */ true);
75689fb2
LB
714 if (r < 0)
715 return r;
716
d2b9e755 717 r = exec_context_apply_tty_size(context, fd, vc);
75689fb2
LB
718 if (r < 0)
719 return r;
720
721 r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
722 TAKE_FD(fd);
723 if (r < 0)
724 return r;
725
726 *ret_saved_stdin = TAKE_FD(saved_stdin);
727 *ret_saved_stdout = TAKE_FD(saved_stdout);
728 return 0;
729}
730
731static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
732 assert(err < 0);
733 assert(unit_id);
734
735 if (err == -ETIMEDOUT)
736 dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
737 else {
738 errno = -err;
739 dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", unit_id);
740 }
741}
742
743static void write_confirm_error(int err, const char *vc, const char *unit_id) {
744 _cleanup_close_ int fd = -EBADF;
745
746 assert(vc);
747
748 fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
749 if (fd < 0)
750 return;
751
752 write_confirm_error_fd(err, fd, unit_id);
753}
754
755static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
756 int r = 0;
757
758 assert(saved_stdin);
759 assert(saved_stdout);
760
761 release_terminal();
762
763 if (*saved_stdin >= 0)
764 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
765 r = -errno;
766
767 if (*saved_stdout >= 0)
768 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
769 r = -errno;
770
771 *saved_stdin = safe_close(*saved_stdin);
772 *saved_stdout = safe_close(*saved_stdout);
773
774 return r;
775}
776
777enum {
778 CONFIRM_PRETEND_FAILURE = -1,
779 CONFIRM_PRETEND_SUCCESS = 0,
780 CONFIRM_EXECUTE = 1,
781};
782
783static bool confirm_spawn_disabled(void) {
784 return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
785}
786
787static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
788 int saved_stdout = -1, saved_stdin = -1, r;
789 _cleanup_free_ char *e = NULL;
790 char c;
791
792 assert(context);
793 assert(params);
794
795 /* For any internal errors, assume a positive response. */
796 r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
797 if (r < 0) {
798 write_confirm_error(r, params->confirm_spawn, params->unit_id);
799 return CONFIRM_EXECUTE;
800 }
801
802 /* confirm_spawn might have been disabled while we were sleeping. */
803 if (!params->confirm_spawn || confirm_spawn_disabled()) {
804 r = 1;
805 goto restore_stdio;
806 }
807
808 e = ellipsize(cmdline, 60, 100);
809 if (!e) {
810 log_oom();
811 r = CONFIRM_EXECUTE;
812 goto restore_stdio;
813 }
814
815 for (;;) {
816 r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
817 if (r < 0) {
818 write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
819 r = CONFIRM_EXECUTE;
820 goto restore_stdio;
821 }
822
823 switch (c) {
824 case 'c':
825 printf("Resuming normal execution.\n");
826 manager_disable_confirm_spawn();
827 r = 1;
828 break;
829 case 'D':
830 printf(" Unit: %s\n",
831 params->unit_id);
832 exec_context_dump(context, stdout, " ");
833 exec_params_dump(params, stdout, " ");
834 continue; /* ask again */
835 case 'f':
836 printf("Failing execution.\n");
837 r = CONFIRM_PRETEND_FAILURE;
838 break;
839 case 'h':
840 printf(" c - continue, proceed without asking anymore\n"
841 " D - dump, show the state of the unit\n"
842 " f - fail, don't execute the command and pretend it failed\n"
843 " h - help\n"
844 " i - info, show a short summary of the unit\n"
845 " j - jobs, show jobs that are in progress\n"
846 " s - skip, don't execute the command and pretend it succeeded\n"
847 " y - yes, execute the command\n");
848 continue; /* ask again */
849 case 'i':
850 printf(" Unit: %s\n"
851 " Command: %s\n",
852 params->unit_id, cmdline);
853 continue; /* ask again */
854 case 'j':
855 if (sigqueue(getppid(),
856 SIGRTMIN+18,
857 (const union sigval) { .sival_int = MANAGER_SIGNAL_COMMAND_DUMP_JOBS }) < 0)
858 return -errno;
859
860 continue; /* ask again */
861 case 'n':
862 /* 'n' was removed in favor of 'f'. */
863 printf("Didn't understand 'n', did you mean 'f'?\n");
864 continue; /* ask again */
865 case 's':
866 printf("Skipping execution.\n");
867 r = CONFIRM_PRETEND_SUCCESS;
868 break;
869 case 'y':
870 r = CONFIRM_EXECUTE;
871 break;
872 default:
873 assert_not_reached();
874 }
875 break;
876 }
877
878restore_stdio:
879 restore_confirm_stdio(&saved_stdin, &saved_stdout);
880 return r;
881}
882
883static int get_fixed_user(
8d85efae
MY
884 const char *user_or_uid,
885 const char **ret_username,
75689fb2
LB
886 uid_t *ret_uid,
887 gid_t *ret_gid,
888 const char **ret_home,
889 const char **ret_shell) {
890
891 int r;
892
8d85efae
MY
893 assert(user_or_uid);
894 assert(ret_username);
75689fb2
LB
895
896 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
897 * (i.e. are "/" or "/bin/nologin"). */
898
8d85efae 899 r = get_user_creds(&user_or_uid, ret_uid, ret_gid, ret_home, ret_shell, USER_CREDS_CLEAN);
75689fb2
LB
900 if (r < 0)
901 return r;
902
8d85efae
MY
903 /* user_or_uid is normalized by get_user_creds to username */
904 *ret_username = user_or_uid;
905
75689fb2
LB
906 return 0;
907}
908
909static int get_fixed_group(
8d85efae
MY
910 const char *group_or_gid,
911 const char **ret_groupname,
75689fb2
LB
912 gid_t *ret_gid) {
913
914 int r;
915
8d85efae
MY
916 assert(group_or_gid);
917 assert(ret_groupname);
75689fb2 918
8d85efae 919 r = get_group_creds(&group_or_gid, ret_gid, /* flags = */ 0);
75689fb2
LB
920 if (r < 0)
921 return r;
922
8d85efae
MY
923 /* group_or_gid is normalized by get_group_creds to groupname */
924 *ret_groupname = group_or_gid;
925
75689fb2
LB
926 return 0;
927}
928
929static int get_supplementary_groups(const ExecContext *c, const char *user,
930 const char *group, gid_t gid,
931 gid_t **supplementary_gids, int *ngids) {
932 int r, k = 0;
933 int ngroups_max;
934 bool keep_groups = false;
935 gid_t *groups = NULL;
936 _cleanup_free_ gid_t *l_gids = NULL;
937
938 assert(c);
939
940 /*
941 * If user is given, then lookup GID and supplementary groups list.
942 * We avoid NSS lookups for gid=0. Also we have to initialize groups
943 * here and as early as possible so we keep the list of supplementary
944 * groups of the caller.
945 */
946 if (user && gid_is_valid(gid) && gid != 0) {
947 /* First step, initialize groups from /etc/groups */
948 if (initgroups(user, gid) < 0)
949 return -errno;
950
951 keep_groups = true;
952 }
953
954 if (strv_isempty(c->supplementary_groups))
955 return 0;
956
957 /*
958 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
959 * be positive, otherwise fail.
960 */
961 errno = 0;
962 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
963 if (ngroups_max <= 0)
964 return errno_or_else(EOPNOTSUPP);
965
966 l_gids = new(gid_t, ngroups_max);
967 if (!l_gids)
968 return -ENOMEM;
969
970 if (keep_groups) {
971 /*
972 * Lookup the list of groups that the user belongs to, we
973 * avoid NSS lookups here too for gid=0.
974 */
975 k = ngroups_max;
976 if (getgrouplist(user, gid, l_gids, &k) < 0)
977 return -EINVAL;
978 } else
979 k = 0;
980
981 STRV_FOREACH(i, c->supplementary_groups) {
982 const char *g;
983
984 if (k >= ngroups_max)
985 return -E2BIG;
986
987 g = *i;
988 r = get_group_creds(&g, l_gids+k, 0);
989 if (r < 0)
990 return r;
991
992 k++;
993 }
994
995 /*
996 * Sets ngids to zero to drop all supplementary groups, happens
997 * when we are under root and SupplementaryGroups= is empty.
998 */
999 if (k == 0) {
1000 *ngids = 0;
1001 return 0;
1002 }
1003
1004 /* Otherwise get the final list of supplementary groups */
1005 groups = memdup(l_gids, sizeof(gid_t) * k);
1006 if (!groups)
1007 return -ENOMEM;
1008
1009 *supplementary_gids = groups;
1010 *ngids = k;
1011
1012 groups = NULL;
1013
1014 return 0;
1015}
1016
1017static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
1018 int r;
1019
1020 /* Handle SupplementaryGroups= if it is not empty */
1021 if (ngids > 0) {
1022 r = maybe_setgroups(ngids, supplementary_gids);
1023 if (r < 0)
1024 return r;
1025 }
1026
1027 if (gid_is_valid(gid)) {
1028 /* Then set our gids */
1029 if (setresgid(gid, gid, gid) < 0)
1030 return -errno;
1031 }
1032
1033 return 0;
1034}
1035
1036static int set_securebits(unsigned bits, unsigned mask) {
1037 unsigned applied;
1038 int current;
1039
1040 current = prctl(PR_GET_SECUREBITS);
1041 if (current < 0)
1042 return -errno;
1043
1044 /* Clear all securebits defined in mask and set bits */
1045 applied = ((unsigned) current & ~mask) | bits;
1046 if ((unsigned) current == applied)
1047 return 0;
1048
1049 if (prctl(PR_SET_SECUREBITS, applied) < 0)
1050 return -errno;
1051
1052 return 1;
1053}
1054
1055static int enforce_user(
1056 const ExecContext *context,
1057 uid_t uid,
1058 uint64_t capability_ambient_set) {
1059 assert(context);
1060 int r;
1061
1062 if (!uid_is_valid(uid))
1063 return 0;
1064
1065 /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
1066 * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
1067 * case. */
1068
1069 if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
1070
1071 /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1072 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1073 r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
1074 if (r < 0)
1075 return r;
1076 }
1077
1078 /* Second step: actually set the uids */
1079 if (setresuid(uid, uid, uid) < 0)
1080 return -errno;
1081
1082 /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1083 * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1084 * outside of this call. */
1085 return 0;
1086}
1087
1088#if HAVE_PAM
1089
1090static int null_conv(
1091 int num_msg,
1092 const struct pam_message **msg,
1093 struct pam_response **resp,
1094 void *appdata_ptr) {
1095
1096 /* We don't support conversations */
1097
1098 return PAM_CONV_ERR;
1099}
1100
1101#endif
1102
1103static int setup_pam(
1104 const char *name,
1105 const char *user,
1106 uid_t uid,
1107 gid_t gid,
1108 const char *tty,
1109 char ***env, /* updated on success */
5863f1da
LP
1110 const int fds[], size_t n_fds,
1111 int exec_fd) {
75689fb2
LB
1112
1113#if HAVE_PAM
1114
1115 static const struct pam_conv conv = {
1116 .conv = null_conv,
1117 .appdata_ptr = NULL
1118 };
1119
1120 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
1121 _cleanup_strv_free_ char **e = NULL;
1122 pam_handle_t *handle = NULL;
1123 sigset_t old_ss;
1124 int pam_code = PAM_SUCCESS, r;
1125 bool close_session = false;
1126 pid_t pam_pid = 0, parent_pid;
1127 int flags = 0;
1128
1129 assert(name);
1130 assert(user);
1131 assert(env);
1132
1133 /* We set up PAM in the parent process, then fork. The child
1134 * will then stay around until killed via PR_GET_PDEATHSIG or
1135 * systemd via the cgroup logic. It will then remove the PAM
1136 * session again. The parent process will exec() the actual
1137 * daemon. We do things this way to ensure that the main PID
1138 * of the daemon is the one we initially fork()ed. */
1139
1140 r = barrier_create(&barrier);
1141 if (r < 0)
1142 goto fail;
1143
1144 if (log_get_max_level() < LOG_DEBUG)
1145 flags |= PAM_SILENT;
1146
1147 pam_code = pam_start(name, user, &conv, &handle);
1148 if (pam_code != PAM_SUCCESS) {
1149 handle = NULL;
1150 goto fail;
1151 }
1152
1153 if (!tty) {
1154 _cleanup_free_ char *q = NULL;
1155
1156 /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
1157 * out if that's the case, and read the TTY off it. */
1158
1159 if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
1160 tty = strjoina("/dev/", q);
1161 }
1162
1163 if (tty) {
1164 pam_code = pam_set_item(handle, PAM_TTY, tty);
1165 if (pam_code != PAM_SUCCESS)
1166 goto fail;
1167 }
1168
1169 STRV_FOREACH(nv, *env) {
1170 pam_code = pam_putenv(handle, *nv);
1171 if (pam_code != PAM_SUCCESS)
1172 goto fail;
1173 }
1174
1175 pam_code = pam_acct_mgmt(handle, flags);
1176 if (pam_code != PAM_SUCCESS)
1177 goto fail;
1178
1179 pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
1180 if (pam_code != PAM_SUCCESS)
1181 log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code));
1182
1183 pam_code = pam_open_session(handle, flags);
1184 if (pam_code != PAM_SUCCESS)
1185 goto fail;
1186
1187 close_session = true;
1188
1189 e = pam_getenvlist(handle);
1190 if (!e) {
1191 pam_code = PAM_BUF_ERR;
1192 goto fail;
1193 }
1194
1195 /* Block SIGTERM, so that we know that it won't get lost in the child */
1196
1197 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
1198
1199 parent_pid = getpid_cached();
1200
1201 r = safe_fork("(sd-pam)", 0, &pam_pid);
1202 if (r < 0)
1203 goto fail;
1204 if (r == 0) {
c8f7c9a1 1205 int ret = EXIT_PAM;
75689fb2
LB
1206
1207 /* The child's job is to reset the PAM session on termination */
1208 barrier_set_role(&barrier, BARRIER_CHILD);
1209
1210 /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1211 * those fds are open here that have been opened by PAM. */
1212 (void) close_many(fds, n_fds);
1213
5863f1da
LP
1214 /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1215 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1216 * we'd never signal completion. */
1217 exec_fd = safe_close(exec_fd);
1218
75689fb2
LB
1219 /* Drop privileges - we don't need any to pam_close_session and this will make
1220 * PR_SET_PDEATHSIG work in most cases. If this fails, ignore the error - but expect sd-pam
1221 * threads to fail to exit normally */
1222
6498a0c2 1223 r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
75689fb2 1224 if (r < 0)
6498a0c2 1225 log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
75689fb2
LB
1226
1227 (void) ignore_signals(SIGPIPE);
1228
1229 /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1230 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1231 * this way. We rely on the control groups kill logic to do the rest for us. */
1232 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
1233 goto child_finish;
1234
1235 /* Tell the parent that our setup is done. This is especially important regarding dropping
1236 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1237 *
1238 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1239 (void) barrier_place(&barrier);
1240
1241 /* Check if our parent process might already have died? */
1242 if (getppid() == parent_pid) {
1243 sigset_t ss;
c8f7c9a1 1244 int sig;
75689fb2
LB
1245
1246 assert_se(sigemptyset(&ss) >= 0);
1247 assert_se(sigaddset(&ss, SIGTERM) >= 0);
1248
c8f7c9a1
MY
1249 assert_se(sigwait(&ss, &sig) == 0);
1250 assert(sig == SIGTERM);
75689fb2
LB
1251 }
1252
1253 pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags);
1254 if (pam_code != PAM_SUCCESS)
1255 goto child_finish;
1256
1257 /* If our parent died we'll end the session */
1258 if (getppid() != parent_pid) {
1259 pam_code = pam_close_session(handle, flags);
1260 if (pam_code != PAM_SUCCESS)
1261 goto child_finish;
1262 }
1263
1264 ret = 0;
1265
1266 child_finish:
1267 /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1268 * know about this. See pam_end(3) */
1269 (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
1270 _exit(ret);
1271 }
1272
1273 barrier_set_role(&barrier, BARRIER_PARENT);
1274
1275 /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1276 * here. */
1277 handle = NULL;
1278
1279 /* Unblock SIGTERM again in the parent */
1280 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
1281
1282 /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1283 * this fd around. */
1284 closelog();
1285
1286 /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1287 * recover. However, warn loudly if it happens. */
1288 if (!barrier_place_and_sync(&barrier))
1289 log_error("PAM initialization failed");
1290
1291 return strv_free_and_replace(*env, e);
1292
1293fail:
1294 if (pam_code != PAM_SUCCESS) {
1295 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
1296 r = -EPERM; /* PAM errors do not map to errno */
1297 } else
1298 log_error_errno(r, "PAM failed: %m");
1299
1300 if (handle) {
1301 if (close_session)
1302 pam_code = pam_close_session(handle, flags);
1303
1304 (void) pam_end(handle, pam_code | flags);
1305 }
1306
1307 closelog();
1308 return r;
1309#else
1310 return 0;
1311#endif
1312}
1313
1314static void rename_process_from_path(const char *path) {
1315 _cleanup_free_ char *buf = NULL;
1316 const char *p;
1317
1318 assert(path);
1319
1320 /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
1321 * /bin/ps */
1322
1323 if (path_extract_filename(path, &buf) < 0) {
1324 rename_process("(...)");
1325 return;
1326 }
1327
1328 size_t l = strlen(buf);
1329 if (l > 8) {
1330 /* The end of the process name is usually more interesting, since the first bit might just be
1331 * "systemd-" */
1332 p = buf + l - 8;
1333 l = 8;
1334 } else
1335 p = buf;
1336
1337 char process_name[11];
1338 process_name[0] = '(';
1339 memcpy(process_name+1, p, l);
1340 process_name[1+l] = ')';
1341 process_name[1+l+1] = 0;
1342
c0e82e3a 1343 (void) rename_process(process_name);
75689fb2
LB
1344}
1345
1346static bool context_has_address_families(const ExecContext *c) {
1347 assert(c);
1348
1349 return c->address_families_allow_list ||
1350 !set_isempty(c->address_families);
1351}
1352
1353static bool context_has_syscall_filters(const ExecContext *c) {
1354 assert(c);
1355
1356 return c->syscall_allow_list ||
1357 !hashmap_isempty(c->syscall_filter);
1358}
1359
1360static bool context_has_syscall_logs(const ExecContext *c) {
1361 assert(c);
1362
1363 return c->syscall_log_allow_list ||
1364 !hashmap_isempty(c->syscall_log);
1365}
1366
24832d10 1367static bool context_has_seccomp(const ExecContext *c) {
75689fb2
LB
1368 /* We need NNP if we have any form of seccomp and are unprivileged */
1369 return c->lock_personality ||
1370 c->memory_deny_write_execute ||
1371 c->private_devices ||
1372 c->protect_clock ||
1373 c->protect_hostname ||
1374 c->protect_kernel_tunables ||
1375 c->protect_kernel_modules ||
1376 c->protect_kernel_logs ||
1377 context_has_address_families(c) ||
1378 exec_context_restrict_namespaces_set(c) ||
1379 c->restrict_realtime ||
1380 c->restrict_suid_sgid ||
1381 !set_isempty(c->syscall_archs) ||
1382 context_has_syscall_filters(c) ||
1383 context_has_syscall_logs(c);
1384}
1385
24832d10
ILG
1386static bool context_has_no_new_privileges(const ExecContext *c) {
1387 assert(c);
1388
1389 if (c->no_new_privileges)
1390 return true;
1391
1392 if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
1393 return false;
1394
1395 return context_has_seccomp(c);
1396}
1397
75689fb2
LB
1398#if HAVE_SECCOMP
1399
24832d10
ILG
1400static bool seccomp_allows_drop_privileges(const ExecContext *c) {
1401 void *id, *val;
1402 bool has_capget = false, has_capset = false, has_prctl = false;
1403
1404 assert(c);
1405
1406 /* No syscall filter, we are allowed to drop privileges */
1407 if (hashmap_isempty(c->syscall_filter))
1408 return true;
1409
1410 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
1411 _cleanup_free_ char *name = NULL;
1412
1413 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
1414
1415 if (streq(name, "capget"))
1416 has_capget = true;
1417 else if (streq(name, "capset"))
1418 has_capset = true;
1419 else if (streq(name, "prctl"))
1420 has_prctl = true;
1421 }
1422
1423 if (c->syscall_allow_list)
1424 return has_capget && has_capset && has_prctl;
1425 else
1426 return !(has_capget || has_capset || has_prctl);
1427}
1428
75689fb2
LB
1429static bool skip_seccomp_unavailable(const ExecContext *c, const ExecParameters *p, const char* msg) {
1430
1431 if (is_seccomp_available())
1432 return false;
1433
1434 log_exec_debug(c, p, "SECCOMP features not detected in the kernel, skipping %s", msg);
1435 return true;
1436}
1437
1438static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p, bool needs_ambient_hack) {
1439 uint32_t negative_action, default_action, action;
1440 int r;
1441
1442 assert(c);
1443 assert(p);
1444
1445 if (!context_has_syscall_filters(c))
1446 return 0;
1447
1448 if (skip_seccomp_unavailable(c, p, "SystemCallFilter="))
1449 return 0;
1450
1451 negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
1452
1453 if (c->syscall_allow_list) {
1454 default_action = negative_action;
1455 action = SCMP_ACT_ALLOW;
1456 } else {
1457 default_action = SCMP_ACT_ALLOW;
1458 action = negative_action;
1459 }
1460
1461 if (needs_ambient_hack) {
1462 r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
1463 if (r < 0)
1464 return r;
1465 }
1466
1467 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1468}
1469
1470static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
1471#ifdef SCMP_ACT_LOG
1472 uint32_t default_action, action;
1473#endif
1474
1475 assert(c);
1476 assert(p);
1477
1478 if (!context_has_syscall_logs(c))
1479 return 0;
1480
1481#ifdef SCMP_ACT_LOG
1482 if (skip_seccomp_unavailable(c, p, "SystemCallLog="))
1483 return 0;
1484
1485 if (c->syscall_log_allow_list) {
1486 /* Log nothing but the ones listed */
1487 default_action = SCMP_ACT_ALLOW;
1488 action = SCMP_ACT_LOG;
1489 } else {
1490 /* Log everything but the ones listed */
1491 default_action = SCMP_ACT_LOG;
1492 action = SCMP_ACT_ALLOW;
1493 }
1494
1495 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
1496#else
1497 /* old libseccomp */
1498 log_exec_debug(c, p, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1499 return 0;
1500#endif
1501}
1502
1503static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
1504 assert(c);
1505 assert(p);
1506
1507 if (set_isempty(c->syscall_archs))
1508 return 0;
1509
1510 if (skip_seccomp_unavailable(c, p, "SystemCallArchitectures="))
1511 return 0;
1512
1513 return seccomp_restrict_archs(c->syscall_archs);
1514}
1515
1516static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
1517 assert(c);
1518 assert(p);
1519
1520 if (!context_has_address_families(c))
1521 return 0;
1522
1523 if (skip_seccomp_unavailable(c, p, "RestrictAddressFamilies="))
1524 return 0;
1525
1526 return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
1527}
1528
1529static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
1530 int r;
1531
1532 assert(c);
1533 assert(p);
1534
1535 if (!c->memory_deny_write_execute)
1536 return 0;
1537
1538 /* use prctl() if kernel supports it (6.3) */
1539 r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1540 if (r == 0) {
1541 log_exec_debug(c, p, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1542 return 0;
1543 }
1544 if (r < 0 && errno != EINVAL)
1545 return log_exec_debug_errno(c,
1546 p,
1547 errno,
1548 "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
1549 /* else use seccomp */
1550 log_exec_debug(c, p, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
1551
1552 if (skip_seccomp_unavailable(c, p, "MemoryDenyWriteExecute="))
1553 return 0;
1554
1555 return seccomp_memory_deny_write_execute();
1556}
1557
1558static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
1559 assert(c);
1560 assert(p);
1561
1562 if (!c->restrict_realtime)
1563 return 0;
1564
1565 if (skip_seccomp_unavailable(c, p, "RestrictRealtime="))
1566 return 0;
1567
1568 return seccomp_restrict_realtime();
1569}
1570
1571static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
1572 assert(c);
1573 assert(p);
1574
1575 if (!c->restrict_suid_sgid)
1576 return 0;
1577
1578 if (skip_seccomp_unavailable(c, p, "RestrictSUIDSGID="))
1579 return 0;
1580
1581 return seccomp_restrict_suid_sgid();
1582}
1583
1584static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
1585 assert(c);
1586 assert(p);
1587
1588 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1589 * let's protect even those systems where this is left on in the kernel. */
1590
1591 if (!c->protect_kernel_tunables)
1592 return 0;
1593
1594 if (skip_seccomp_unavailable(c, p, "ProtectKernelTunables="))
1595 return 0;
1596
1597 return seccomp_protect_sysctl();
1598}
1599
1600static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
1601 assert(c);
1602 assert(p);
1603
1604 /* Turn off module syscalls on ProtectKernelModules=yes */
1605
1606 if (!c->protect_kernel_modules)
1607 return 0;
1608
1609 if (skip_seccomp_unavailable(c, p, "ProtectKernelModules="))
1610 return 0;
1611
1612 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1613}
1614
1615static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
1616 assert(c);
1617 assert(p);
1618
1619 if (!c->protect_kernel_logs)
1620 return 0;
1621
1622 if (skip_seccomp_unavailable(c, p, "ProtectKernelLogs="))
1623 return 0;
1624
1625 return seccomp_protect_syslog();
1626}
1627
1628static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
1629 assert(c);
1630 assert(p);
1631
1632 if (!c->protect_clock)
1633 return 0;
1634
1635 if (skip_seccomp_unavailable(c, p, "ProtectClock="))
1636 return 0;
1637
1638 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
1639}
1640
1641static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
1642 assert(c);
1643 assert(p);
1644
1645 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1646
1647 if (!c->private_devices)
1648 return 0;
1649
1650 if (skip_seccomp_unavailable(c, p, "PrivateDevices="))
1651 return 0;
1652
1653 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
1654}
1655
1656static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
1657 assert(c);
1658 assert(p);
1659
1660 if (!exec_context_restrict_namespaces_set(c))
1661 return 0;
1662
1663 if (skip_seccomp_unavailable(c, p, "RestrictNamespaces="))
1664 return 0;
1665
1666 return seccomp_restrict_namespaces(c->restrict_namespaces);
1667}
1668
1669static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
1670 unsigned long personality;
1671 int r;
1672
1673 assert(c);
1674 assert(p);
1675
1676 if (!c->lock_personality)
1677 return 0;
1678
1679 if (skip_seccomp_unavailable(c, p, "LockPersonality="))
1680 return 0;
1681
1682 personality = c->personality;
1683
1684 /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1685 if (personality == PERSONALITY_INVALID) {
1686
1687 r = opinionated_personality(&personality);
1688 if (r < 0)
1689 return r;
1690 }
1691
1692 return seccomp_lock_personality(personality);
1693}
1694
1695#endif
1696
1697#if HAVE_LIBBPF
1698static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
1699 int r;
1700
1701 assert(c);
1702 assert(p);
1703
1704 if (!exec_context_restrict_filesystems_set(c))
1705 return 0;
1706
1707 if (p->bpf_outer_map_fd < 0) {
1708 /* LSM BPF is unsupported or lsm_bpf_setup failed */
1709 log_exec_debug(c, p, "LSM BPF not supported, skipping RestrictFileSystems=");
1710 return 0;
1711 }
1712
1713 /* We are in a new binary, so dl-open again */
1714 r = dlopen_bpf();
1715 if (r < 0)
1716 return r;
1717
1718 return lsm_bpf_restrict_filesystems(c->restrict_filesystems, p->cgroup_id, p->bpf_outer_map_fd, c->restrict_filesystems_allow_list);
1719}
1720#endif
1721
1722static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
1723 assert(c);
1724 assert(p);
1725
1726 if (!c->protect_hostname)
1727 return 0;
1728
1729 if (ns_type_supported(NAMESPACE_UTS)) {
1730 if (unshare(CLONE_NEWUTS) < 0) {
1731 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
1732 *ret_exit_status = EXIT_NAMESPACE;
1733 return log_exec_error_errno(c,
1734 p,
1735 errno,
1736 "Failed to set up UTS namespacing: %m");
1737 }
1738
1739 log_exec_warning(c,
1740 p,
1741 "ProtectHostname=yes is configured, but UTS namespace setup is "
1742 "prohibited (container manager?), ignoring namespace setup.");
1743 }
1744 } else
1745 log_exec_warning(c,
1746 p,
1747 "ProtectHostname=yes is configured, but the kernel does not "
1748 "support UTS namespaces, ignoring namespace setup.");
1749
1750#if HAVE_SECCOMP
1751 int r;
1752
1753 if (skip_seccomp_unavailable(c, p, "ProtectHostname="))
1754 return 0;
1755
1756 r = seccomp_protect_hostname();
1757 if (r < 0) {
1758 *ret_exit_status = EXIT_SECCOMP;
1759 return log_exec_error_errno(c, p, r, "Failed to apply hostname restrictions: %m");
1760 }
1761#endif
1762
1763 return 0;
1764}
1765
1766static void do_idle_pipe_dance(int idle_pipe[static 4]) {
1767 assert(idle_pipe);
1768
1769 idle_pipe[1] = safe_close(idle_pipe[1]);
1770 idle_pipe[2] = safe_close(idle_pipe[2]);
1771
1772 if (idle_pipe[0] >= 0) {
1773 int r;
1774
1775 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1776
1777 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
1778 ssize_t n;
1779
1780 /* Signal systemd that we are bored and want to continue. */
1781 n = write(idle_pipe[3], "x", 1);
1782 if (n > 0)
1783 /* Wait for systemd to react to the signal above. */
1784 (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
1785 }
1786
1787 idle_pipe[0] = safe_close(idle_pipe[0]);
1788
1789 }
1790
1791 idle_pipe[3] = safe_close(idle_pipe[3]);
1792}
1793
1794static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1795
1796/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1797 * the service payload in. */
1798static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1799 [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
1800 [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
1801 [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
1802 [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
1803 [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1804};
1805
1806DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
1807
1808static int build_environment(
1809 const ExecContext *c,
1810 const ExecParameters *p,
1811 const CGroupContext *cgroup_context,
1812 size_t n_fds,
75689fb2
LB
1813 const char *home,
1814 const char *username,
1815 const char *shell,
1816 dev_t journal_stream_dev,
1817 ino_t journal_stream_ino,
1818 const char *memory_pressure_path,
1819 char ***ret) {
1820
1821 _cleanup_strv_free_ char **our_env = NULL;
1822 size_t n_env = 0;
1823 char *x;
1824 int r;
1825
1826 assert(c);
1827 assert(p);
1828 assert(ret);
1829
1830#define N_ENV_VARS 19
1831 our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
1832 if (!our_env)
1833 return -ENOMEM;
1834
1835 if (n_fds > 0) {
1836 _cleanup_free_ char *joined = NULL;
1837
1838 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1839 return -ENOMEM;
1840 our_env[n_env++] = x;
1841
1842 if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1843 return -ENOMEM;
1844 our_env[n_env++] = x;
1845
1eeaa93d 1846 joined = strv_join(p->fd_names, ":");
75689fb2
LB
1847 if (!joined)
1848 return -ENOMEM;
1849
1850 x = strjoin("LISTEN_FDNAMES=", joined);
1851 if (!x)
1852 return -ENOMEM;
1853 our_env[n_env++] = x;
1854 }
1855
1856 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
1857 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
1858 return -ENOMEM;
1859 our_env[n_env++] = x;
1860
1861 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
1862 return -ENOMEM;
1863 our_env[n_env++] = x;
1864 }
1865
1866 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
1867 * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
1868 * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
1869 if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
1870 x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
1871 if (!x)
1872 return -ENOMEM;
1873 our_env[n_env++] = x;
1874 }
1875
1876 /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
1877 * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL don't
1878 * really make much sense since we're not logged in. Hence we conditionalize the three based on
1879 * SetLoginEnvironment= switch. */
1880 if (!c->user && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
1881 r = get_fixed_user("root", &username, NULL, NULL, &home, &shell);
1882 if (r < 0)
1883 return log_exec_debug_errno(c,
1884 p,
1885 r,
1886 "Failed to determine user credentials for root: %m");
1887 }
1888
d1a5be82 1889 bool set_user_login_env = exec_context_get_set_login_environment(c);
75689fb2
LB
1890
1891 if (username) {
1892 x = strjoin("USER=", username);
1893 if (!x)
1894 return -ENOMEM;
1895 our_env[n_env++] = x;
1896
1897 if (set_user_login_env) {
1898 x = strjoin("LOGNAME=", username);
1899 if (!x)
1900 return -ENOMEM;
1901 our_env[n_env++] = x;
1902 }
1903 }
1904
1905 if (home && set_user_login_env) {
1906 x = strjoin("HOME=", home);
1907 if (!x)
1908 return -ENOMEM;
1909
1910 path_simplify(x + 5);
1911 our_env[n_env++] = x;
1912 }
1913
1914 if (shell && set_user_login_env) {
1915 x = strjoin("SHELL=", shell);
1916 if (!x)
1917 return -ENOMEM;
1918
1919 path_simplify(x + 6);
1920 our_env[n_env++] = x;
1921 }
1922
1923 if (!sd_id128_is_null(p->invocation_id)) {
1924 assert(p->invocation_id_string);
1925
1926 x = strjoin("INVOCATION_ID=", p->invocation_id_string);
1927 if (!x)
1928 return -ENOMEM;
1929
1930 our_env[n_env++] = x;
1931 }
1932
1933 if (exec_context_needs_term(c)) {
1934 _cleanup_free_ char *cmdline = NULL;
1935 const char *tty_path, *term = NULL;
1936
1937 tty_path = exec_context_tty_path(c);
1938
1939 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
1940 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
1941 * container manager passes to PID 1 ends up all the way in the console login shown. */
1942
1943 if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1)
1944 term = getenv("TERM");
1945 else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
1946 _cleanup_free_ char *key = NULL;
1947
1948 key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
1949 if (!key)
1950 return -ENOMEM;
1951
1952 r = proc_cmdline_get_key(key, 0, &cmdline);
1953 if (r < 0)
1954 log_exec_debug_errno(c,
1955 p,
1956 r,
1957 "Failed to read %s from kernel cmdline, ignoring: %m",
1958 key);
1959 else if (r > 0)
1960 term = cmdline;
1961 }
1962
1963 if (!term)
1964 term = default_term_for_tty(tty_path);
1965
1966 x = strjoin("TERM=", term);
1967 if (!x)
1968 return -ENOMEM;
1969 our_env[n_env++] = x;
1970 }
1971
1972 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1973 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1974 return -ENOMEM;
1975
1976 our_env[n_env++] = x;
1977 }
1978
1979 if (c->log_namespace) {
1980 x = strjoin("LOG_NAMESPACE=", c->log_namespace);
1981 if (!x)
1982 return -ENOMEM;
1983
1984 our_env[n_env++] = x;
1985 }
1986
1987 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
1988 _cleanup_free_ char *joined = NULL;
1989 const char *n;
1990
1991 if (!p->prefix[t])
1992 continue;
1993
1994 if (c->directories[t].n_items == 0)
1995 continue;
1996
1997 n = exec_directory_env_name_to_string(t);
1998 if (!n)
1999 continue;
2000
2001 for (size_t i = 0; i < c->directories[t].n_items; i++) {
2002 _cleanup_free_ char *prefixed = NULL;
2003
2004 prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2005 if (!prefixed)
2006 return -ENOMEM;
2007
2008 if (!strextend_with_separator(&joined, ":", prefixed))
2009 return -ENOMEM;
2010 }
2011
2012 x = strjoin(n, "=", joined);
2013 if (!x)
2014 return -ENOMEM;
2015
2016 our_env[n_env++] = x;
2017 }
2018
2019 _cleanup_free_ char *creds_dir = NULL;
2020 r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
2021 if (r < 0)
2022 return r;
2023 if (r > 0) {
2024 x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
2025 if (!x)
2026 return -ENOMEM;
2027
2028 our_env[n_env++] = x;
2029 }
2030
2031 if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
2032 return -ENOMEM;
2033
2034 our_env[n_env++] = x;
2035
2036 if (memory_pressure_path) {
2037 x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
2038 if (!x)
2039 return -ENOMEM;
2040
2041 our_env[n_env++] = x;
2042
2043 if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
2044 _cleanup_free_ char *b = NULL, *e = NULL;
2045
2046 if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
2047 MEMORY_PRESSURE_DEFAULT_TYPE,
2048 cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
2049 CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
2050 MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2051 return -ENOMEM;
2052
2053 if (base64mem(b, strlen(b) + 1, &e) < 0)
2054 return -ENOMEM;
2055
2056 x = strjoin("MEMORY_PRESSURE_WRITE=", e);
2057 if (!x)
2058 return -ENOMEM;
2059
2060 our_env[n_env++] = x;
2061 }
2062 }
2063
2064 assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
2065#undef N_ENV_VARS
2066
2067 *ret = TAKE_PTR(our_env);
2068
2069 return 0;
2070}
2071
2072static int build_pass_environment(const ExecContext *c, char ***ret) {
2073 _cleanup_strv_free_ char **pass_env = NULL;
2074 size_t n_env = 0;
2075
2076 STRV_FOREACH(i, c->pass_environment) {
2077 _cleanup_free_ char *x = NULL;
2078 char *v;
2079
2080 v = getenv(*i);
2081 if (!v)
2082 continue;
2083 x = strjoin(*i, "=", v);
2084 if (!x)
2085 return -ENOMEM;
2086
2087 if (!GREEDY_REALLOC(pass_env, n_env + 2))
2088 return -ENOMEM;
2089
2090 pass_env[n_env++] = TAKE_PTR(x);
2091 pass_env[n_env] = NULL;
2092 }
2093
2094 *ret = TAKE_PTR(pass_env);
2095
2096 return 0;
2097}
2098
2099static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) {
2100 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
71136404 2101 _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
75689fb2
LB
2102 _cleanup_close_ int unshare_ready_fd = -EBADF;
2103 _cleanup_(sigkill_waitp) pid_t pid = 0;
2104 uint64_t c = 1;
2105 ssize_t n;
2106 int r;
2107
2108 /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
2109 * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
2110 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
2111 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
2112 * which waits for the parent to create the new user namespace while staying in the original namespace. The
2113 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
2114 * continues execution normally.
2115 * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
2116 * does not need CAP_SETUID to write the single line mapping to itself. */
2117
2118 /* Can only set up multiple mappings with CAP_SETUID. */
2119 if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid))
2120 r = asprintf(&uid_map,
2121 UID_FMT " " UID_FMT " 1\n" /* Map $OUID → $OUID */
2122 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
2123 ouid, ouid, uid, uid);
2124 else
2125 r = asprintf(&uid_map,
2126 UID_FMT " " UID_FMT " 1\n", /* Map $OUID → $OUID */
2127 ouid, ouid);
2128
2129 if (r < 0)
2130 return -ENOMEM;
2131
2132 /* Can only set up multiple mappings with CAP_SETGID. */
2133 if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid))
2134 r = asprintf(&gid_map,
2135 GID_FMT " " GID_FMT " 1\n" /* Map $OGID → $OGID */
2136 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
2137 ogid, ogid, gid, gid);
2138 else
2139 r = asprintf(&gid_map,
2140 GID_FMT " " GID_FMT " 1\n", /* Map $OGID -> $OGID */
2141 ogid, ogid);
2142
2143 if (r < 0)
2144 return -ENOMEM;
2145
2146 /* Create a communication channel so that the parent can tell the child when it finished creating the user
2147 * namespace. */
2148 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
2149 if (unshare_ready_fd < 0)
2150 return -errno;
2151
2152 /* Create a communication channel so that the child can tell the parent a proper error code in case it
2153 * failed. */
2154 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2155 return -errno;
2156
e9ccae31 2157 r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
75689fb2
LB
2158 if (r < 0)
2159 return r;
2160 if (r == 0) {
2161 _cleanup_close_ int fd = -EBADF;
2162 const char *a;
2163 pid_t ppid;
2164
2165 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
2166 * here, after the parent opened its own user namespace. */
2167
2168 ppid = getppid();
2169 errno_pipe[0] = safe_close(errno_pipe[0]);
2170
2171 /* Wait until the parent unshared the user namespace */
2172 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
2173 r = -errno;
2174 goto child_fail;
2175 }
2176
2177 /* Disable the setgroups() system call in the child user namespace, for good. */
2178 a = procfs_file_alloca(ppid, "setgroups");
2179 fd = open(a, O_WRONLY|O_CLOEXEC);
2180 if (fd < 0) {
2181 if (errno != ENOENT) {
2182 r = -errno;
2183 goto child_fail;
2184 }
2185
2186 /* If the file is missing the kernel is too old, let's continue anyway. */
2187 } else {
2188 if (write(fd, "deny\n", 5) < 0) {
2189 r = -errno;
2190 goto child_fail;
2191 }
2192
2193 fd = safe_close(fd);
2194 }
2195
2196 /* First write the GID map */
2197 a = procfs_file_alloca(ppid, "gid_map");
2198 fd = open(a, O_WRONLY|O_CLOEXEC);
2199 if (fd < 0) {
2200 r = -errno;
2201 goto child_fail;
2202 }
2203 if (write(fd, gid_map, strlen(gid_map)) < 0) {
2204 r = -errno;
2205 goto child_fail;
2206 }
2207 fd = safe_close(fd);
2208
2209 /* The write the UID map */
2210 a = procfs_file_alloca(ppid, "uid_map");
2211 fd = open(a, O_WRONLY|O_CLOEXEC);
2212 if (fd < 0) {
2213 r = -errno;
2214 goto child_fail;
2215 }
2216 if (write(fd, uid_map, strlen(uid_map)) < 0) {
2217 r = -errno;
2218 goto child_fail;
2219 }
2220
2221 _exit(EXIT_SUCCESS);
2222
2223 child_fail:
2224 (void) write(errno_pipe[1], &r, sizeof(r));
2225 _exit(EXIT_FAILURE);
2226 }
2227
2228 errno_pipe[1] = safe_close(errno_pipe[1]);
2229
2230 if (unshare(CLONE_NEWUSER) < 0)
2231 return -errno;
2232
2233 /* Let the child know that the namespace is ready now */
2234 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
2235 return -errno;
2236
2237 /* Try to read an error code from the child */
2238 n = read(errno_pipe[0], &r, sizeof(r));
2239 if (n < 0)
2240 return -errno;
2241 if (n == sizeof(r)) { /* an error code was sent to us */
2242 if (r < 0)
2243 return r;
2244 return -EIO;
2245 }
2246 if (n != 0) /* on success we should have read 0 bytes */
2247 return -EIO;
2248
2249 r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
2250 if (r < 0)
2251 return r;
2252 if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
2253 return -EIO;
2254
2255 return 0;
2256}
2257
2258static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
2259 _cleanup_free_ char *src_abs = NULL;
2260 int r;
2261
2262 assert(source);
2263
2264 src_abs = path_join(root, source);
2265 if (!src_abs)
2266 return -ENOMEM;
2267
2268 STRV_FOREACH(dst, symlinks) {
2269 _cleanup_free_ char *dst_abs = NULL;
2270
2271 dst_abs = path_join(root, *dst);
2272 if (!dst_abs)
2273 return -ENOMEM;
2274
2275 r = mkdir_parents_label(dst_abs, 0755);
2276 if (r < 0)
2277 return r;
2278
2279 r = symlink_idempotent(src_abs, dst_abs, true);
2280 if (r < 0)
2281 return r;
2282 }
2283
2284 return 0;
2285}
2286
2287static int setup_exec_directory(
2288 const ExecContext *context,
2289 const ExecParameters *params,
2290 uid_t uid,
2291 gid_t gid,
2292 ExecDirectoryType type,
2293 bool needs_mount_namespace,
2294 int *exit_status) {
2295
2296 static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
2297 [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
2298 [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
2299 [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
2300 [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
2301 [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2302 };
2303 int r;
2304
2305 assert(context);
2306 assert(params);
2307 assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
2308 assert(exit_status);
2309
2310 if (!params->prefix[type])
2311 return 0;
2312
2313 if (params->flags & EXEC_CHOWN_DIRECTORIES) {
2314 if (!uid_is_valid(uid))
2315 uid = 0;
2316 if (!gid_is_valid(gid))
2317 gid = 0;
2318 }
2319
2320 for (size_t i = 0; i < context->directories[type].n_items; i++) {
2321 _cleanup_free_ char *p = NULL, *pp = NULL;
2322
2323 p = path_join(params->prefix[type], context->directories[type].items[i].path);
2324 if (!p) {
2325 r = -ENOMEM;
2326 goto fail;
2327 }
2328
2329 r = mkdir_parents_label(p, 0755);
2330 if (r < 0)
2331 goto fail;
2332
2333 if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
2334
2335 /* If we are in user mode, and a configuration directory exists but a state directory
2336 * doesn't exist, then we likely are upgrading from an older systemd version that
2337 * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2338 * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2339 * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME is is now
2340 * separated. If a service has both dirs configured but only the configuration dir
2341 * exists and the state dir does not, we assume we are looking at an update
2342 * situation. Hence, create a compatibility symlink, so that all expectations are
2343 * met.
2344 *
2345 * (We also do something similar with the log directory, which still doesn't exist in
2346 * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2347
2348 /* this assumes the state dir is always created before the configuration dir */
2349 assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
2350 assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
2351
2352 r = laccess(p, F_OK);
2353 if (r == -ENOENT) {
2354 _cleanup_free_ char *q = NULL;
2355
2356 /* OK, we know that the state dir does not exist. Let's see if the dir exists
2357 * under the configuration hierarchy. */
2358
2359 if (type == EXEC_DIRECTORY_STATE)
2360 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], context->directories[type].items[i].path);
2361 else if (type == EXEC_DIRECTORY_LOGS)
2362 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", context->directories[type].items[i].path);
2363 else
2364 assert_not_reached();
2365 if (!q) {
2366 r = -ENOMEM;
2367 goto fail;
2368 }
2369
2370 r = laccess(q, F_OK);
2371 if (r >= 0) {
2372 /* It does exist! This hence looks like an update. Symlink the
2373 * configuration directory into the state directory. */
2374
2375 r = symlink_idempotent(q, p, /* make_relative= */ true);
2376 if (r < 0)
2377 goto fail;
2378
2379 log_exec_notice(context, params, "Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
2380 continue;
2381 } else if (r != -ENOENT)
2382 log_exec_warning_errno(context, params, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
2383
2384 } else if (r < 0)
2385 log_exec_warning_errno(context, params, r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
2386 }
2387
2388 if (exec_directory_is_private(context, type)) {
2389 /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2390 * case we want to avoid leaving a directory around fully accessible that is owned by
2391 * a dynamic user whose UID is later on reused. To lock this down we use the same
2392 * trick used by container managers to prohibit host users to get access to files of
2393 * the same UID in containers: we place everything inside a directory that has an
2394 * access mode of 0700 and is owned root:root, so that it acts as security boundary
2395 * for unprivileged host code. We then use fs namespacing to make this directory
2396 * permeable for the service itself.
2397 *
2398 * Specifically: for a service which wants a special directory "foo/" we first create
2399 * a directory "private/" with access mode 0700 owned by root:root. Then we place
2400 * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2401 * "private/foo". This way, privileged host users can access "foo/" as usual, but
2402 * unprivileged host users can't look into it. Inside of the namespace of the unit
2403 * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2404 * "private/foo/" is mounted under the same name, thus disabling the access boundary
2405 * for the service and making sure it only gets access to the dirs it needs but no
2406 * others. Tricky? Yes, absolutely, but it works!
2407 *
2408 * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2409 * to be owned by the service itself.
2410 *
2411 * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2412 * for sharing files or sockets with other services. */
2413
2414 pp = path_join(params->prefix[type], "private");
2415 if (!pp) {
2416 r = -ENOMEM;
2417 goto fail;
2418 }
2419
2420 /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2421 r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
2422 if (r < 0)
2423 goto fail;
2424
2425 if (!path_extend(&pp, context->directories[type].items[i].path)) {
2426 r = -ENOMEM;
2427 goto fail;
2428 }
2429
2430 /* Create all directories between the configured directory and this private root, and mark them 0755 */
2431 r = mkdir_parents_label(pp, 0755);
2432 if (r < 0)
2433 goto fail;
2434
2435 if (is_dir(p, false) > 0 &&
2436 (laccess(pp, F_OK) == -ENOENT)) {
2437
2438 /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
2439 * it over. Most likely the service has been upgraded from one that didn't use
2440 * DynamicUser=1, to one that does. */
2441
2442 log_exec_info(context,
2443 params,
2444 "Found pre-existing public %s= directory %s, migrating to %s.\n"
2445 "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
2446 exec_directory_type_to_string(type), p, pp);
2447
2448 r = RET_NERRNO(rename(p, pp));
2449 if (r < 0)
2450 goto fail;
2451 } else {
2452 /* Otherwise, create the actual directory for the service */
2453
2454 r = mkdir_label(pp, context->directories[type].mode);
2455 if (r < 0 && r != -EEXIST)
2456 goto fail;
2457 }
2458
2459 if (!context->directories[type].items[i].only_create) {
2460 /* And link it up from the original place.
2461 * Notes
2462 * 1) If a mount namespace is going to be used, then this symlink remains on
2463 * the host, and a new one for the child namespace will be created later.
2464 * 2) It is not necessary to create this symlink when one of its parent
2465 * directories is specified and already created. E.g.
2466 * StateDirectory=foo foo/bar
2467 * In that case, the inode points to pp and p for "foo/bar" are the same:
2468 * pp = "/var/lib/private/foo/bar"
2469 * p = "/var/lib/foo/bar"
2470 * and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2471 * we do not need to create the symlink, but we cannot create the symlink.
2472 * See issue #24783. */
2473 r = symlink_idempotent(pp, p, true);
2474 if (r < 0)
2475 goto fail;
2476 }
2477
2478 } else {
2479 _cleanup_free_ char *target = NULL;
2480
2481 if (type != EXEC_DIRECTORY_CONFIGURATION &&
2482 readlink_and_make_absolute(p, &target) >= 0) {
2483 _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
2484
2485 /* This already exists and is a symlink? Interesting. Maybe it's one created
2486 * by DynamicUser=1 (see above)?
2487 *
2488 * We do this for all directory types except for ConfigurationDirectory=,
2489 * since they all support the private/ symlink logic at least in some
2490 * configurations, see above. */
2491
2492 r = chase(target, NULL, 0, &target_resolved, NULL);
2493 if (r < 0)
2494 goto fail;
2495
2496 q = path_join(params->prefix[type], "private", context->directories[type].items[i].path);
2497 if (!q) {
2498 r = -ENOMEM;
2499 goto fail;
2500 }
2501
2502 /* /var/lib or friends may be symlinks. So, let's chase them also. */
2503 r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
2504 if (r < 0)
2505 goto fail;
2506
2507 if (path_equal(q_resolved, target_resolved)) {
2508
2509 /* Hmm, apparently DynamicUser= was once turned on for this service,
2510 * but is no longer. Let's move the directory back up. */
2511
2512 log_exec_info(context,
2513 params,
2514 "Found pre-existing private %s= directory %s, migrating to %s.\n"
2515 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
2516 exec_directory_type_to_string(type), q, p);
2517
2518 r = RET_NERRNO(unlink(p));
2519 if (r < 0)
2520 goto fail;
2521
2522 r = RET_NERRNO(rename(q, p));
2523 if (r < 0)
2524 goto fail;
2525 }
2526 }
2527
2528 r = mkdir_label(p, context->directories[type].mode);
2529 if (r < 0) {
2530 if (r != -EEXIST)
2531 goto fail;
2532
2533 if (type == EXEC_DIRECTORY_CONFIGURATION) {
2534 struct stat st;
2535
2536 /* Don't change the owner/access mode of the configuration directory,
2537 * as in the common case it is not written to by a service, and shall
2538 * not be writable. */
2539
2540 r = RET_NERRNO(stat(p, &st));
2541 if (r < 0)
2542 goto fail;
2543
2544 /* Still complain if the access mode doesn't match */
2545 if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
2546 log_exec_warning(context,
2547 params,
2548 "%s \'%s\' already exists but the mode is different. "
2549 "(File system: %o %sMode: %o)",
2550 exec_directory_type_to_string(type), context->directories[type].items[i].path,
2551 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2552
2553 continue;
2554 }
2555 }
2556 }
2557
2558 /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2559 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2560 * current UID/GID ownership.) */
2561 r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
2562 if (r < 0)
2563 goto fail;
2564
2565 /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2566 * available to user code anyway */
2567 if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
2568 continue;
2569
2570 /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
2571 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2572 * assignments to exist. */
2573 r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
2574 if (r < 0)
2575 goto fail;
2576 }
2577
2578 /* If we are not going to run in a namespace, set up the symlinks - otherwise
2579 * they are set up later, to allow configuring empty var/run/etc. */
2580 if (!needs_mount_namespace)
2581 for (size_t i = 0; i < context->directories[type].n_items; i++) {
2582 r = create_many_symlinks(params->prefix[type],
2583 context->directories[type].items[i].path,
2584 context->directories[type].items[i].symlinks);
2585 if (r < 0)
2586 goto fail;
2587 }
2588
2589 return 0;
2590
2591fail:
2592 *exit_status = exit_status_table[type];
2593 return r;
2594}
2595
2596#if ENABLE_SMACK
2597static int setup_smack(
2598 const ExecParameters *params,
2599 const ExecContext *context,
2600 int executable_fd) {
2601 int r;
2602
2603 assert(params);
2604 assert(executable_fd >= 0);
2605
2606 if (context->smack_process_label) {
2607 r = mac_smack_apply_pid(0, context->smack_process_label);
2608 if (r < 0)
2609 return r;
2610 } else if (params->fallback_smack_process_label) {
2611 _cleanup_free_ char *exec_label = NULL;
2612
2613 r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
2614 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
2615 return r;
2616
2617 r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
2618 if (r < 0)
2619 return r;
2620 }
2621
2622 return 0;
2623}
2624#endif
2625
2626static int compile_bind_mounts(
2627 const ExecContext *context,
2628 const ExecParameters *params,
2629 BindMount **ret_bind_mounts,
2630 size_t *ret_n_bind_mounts,
2631 char ***ret_empty_directories) {
2632
2633 _cleanup_strv_free_ char **empty_directories = NULL;
2634 BindMount *bind_mounts = NULL;
2635 size_t n, h = 0;
2636 int r;
2637
2638 assert(context);
2639 assert(params);
2640 assert(ret_bind_mounts);
2641 assert(ret_n_bind_mounts);
2642 assert(ret_empty_directories);
2643
2644 CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2645
2646 n = context->n_bind_mounts;
2647 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2648 if (!params->prefix[t])
2649 continue;
2650
2651 for (size_t i = 0; i < context->directories[t].n_items; i++)
2652 n += !context->directories[t].items[i].only_create;
2653 }
2654
2655 if (n <= 0) {
2656 *ret_bind_mounts = NULL;
2657 *ret_n_bind_mounts = 0;
2658 *ret_empty_directories = NULL;
2659 return 0;
2660 }
2661
2662 bind_mounts = new(BindMount, n);
2663 if (!bind_mounts)
2664 return -ENOMEM;
2665
2666 for (size_t i = 0; i < context->n_bind_mounts; i++) {
2667 BindMount *item = context->bind_mounts + i;
2668 _cleanup_free_ char *s = NULL, *d = NULL;
2669
2670 s = strdup(item->source);
2671 if (!s)
2672 return -ENOMEM;
2673
2674 d = strdup(item->destination);
2675 if (!d)
2676 return -ENOMEM;
2677
2678 bind_mounts[h++] = (BindMount) {
2679 .source = TAKE_PTR(s),
2680 .destination = TAKE_PTR(d),
2681 .read_only = item->read_only,
2682 .recursive = item->recursive,
2683 .ignore_enoent = item->ignore_enoent,
2684 };
2685 }
2686
2687 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
2688 if (!params->prefix[t])
2689 continue;
2690
2691 if (context->directories[t].n_items == 0)
2692 continue;
2693
2694 if (exec_directory_is_private(context, t) &&
2695 !exec_context_with_rootfs(context)) {
2696 char *private_root;
2697
2698 /* So this is for a dynamic user, and we need to make sure the process can access its own
2699 * directory. For that we overmount the usually inaccessible "private" subdirectory with a
2700 * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
2701
2702 private_root = path_join(params->prefix[t], "private");
2703 if (!private_root)
2704 return -ENOMEM;
2705
2706 r = strv_consume(&empty_directories, private_root);
2707 if (r < 0)
2708 return r;
2709 }
2710
2711 for (size_t i = 0; i < context->directories[t].n_items; i++) {
2712 _cleanup_free_ char *s = NULL, *d = NULL;
2713
2714 /* When one of the parent directories is in the list, we cannot create the symlink
2715 * for the child directory. See also the comments in setup_exec_directory(). */
2716 if (context->directories[t].items[i].only_create)
2717 continue;
2718
2719 if (exec_directory_is_private(context, t))
2720 s = path_join(params->prefix[t], "private", context->directories[t].items[i].path);
2721 else
2722 s = path_join(params->prefix[t], context->directories[t].items[i].path);
2723 if (!s)
2724 return -ENOMEM;
2725
2726 if (exec_directory_is_private(context, t) &&
2727 exec_context_with_rootfs(context))
2728 /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
2729 * directory is not created on the root directory. So, let's bind-mount the directory
2730 * on the 'non-private' place. */
2731 d = path_join(params->prefix[t], context->directories[t].items[i].path);
2732 else
2733 d = strdup(s);
2734 if (!d)
2735 return -ENOMEM;
2736
2737 bind_mounts[h++] = (BindMount) {
2738 .source = TAKE_PTR(s),
2739 .destination = TAKE_PTR(d),
2740 .read_only = false,
2741 .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
2742 .recursive = true,
2743 .ignore_enoent = false,
2744 };
2745 }
2746 }
2747
2748 assert(h == n);
2749
2750 *ret_bind_mounts = TAKE_PTR(bind_mounts);
2751 *ret_n_bind_mounts = n;
2752 *ret_empty_directories = TAKE_PTR(empty_directories);
2753
2754 return (int) n;
2755}
2756
2757/* ret_symlinks will contain a list of pairs src:dest that describes
2758 * the symlinks to create later on. For example, the symlinks needed
2759 * to safely give private directories to DynamicUser=1 users. */
2760static int compile_symlinks(
2761 const ExecContext *context,
2762 const ExecParameters *params,
2763 bool setup_os_release_symlink,
2764 char ***ret_symlinks) {
2765
2766 _cleanup_strv_free_ char **symlinks = NULL;
2767 int r;
2768
2769 assert(context);
2770 assert(params);
2771 assert(ret_symlinks);
2772
2773 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
2774 for (size_t i = 0; i < context->directories[dt].n_items; i++) {
2775 _cleanup_free_ char *private_path = NULL, *path = NULL;
2776
2777 STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) {
2778 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
2779
2780 src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path);
2781 dst_abs = path_join(params->prefix[dt], *symlink);
2782 if (!src_abs || !dst_abs)
2783 return -ENOMEM;
2784
2785 r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
2786 if (r < 0)
2787 return r;
2788 }
2789
2790 if (!exec_directory_is_private(context, dt) ||
2791 exec_context_with_rootfs(context) ||
2792 context->directories[dt].items[i].only_create)
2793 continue;
2794
2795 private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path);
2796 if (!private_path)
2797 return -ENOMEM;
2798
2799 path = path_join(params->prefix[dt], context->directories[dt].items[i].path);
2800 if (!path)
2801 return -ENOMEM;
2802
2803 r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
2804 if (r < 0)
2805 return r;
2806 }
2807 }
2808
2809 /* We make the host's os-release available via a symlink, so that we can copy it atomically
2810 * and readers will never get a half-written version. Note that, while the paths specified here are
2811 * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
2812 * 'os-release -> .os-release-stage/os-release' is what will be created. */
2813 if (setup_os_release_symlink) {
2814 r = strv_extend(&symlinks, "/run/host/.os-release-stage/os-release");
2815 if (r < 0)
2816 return r;
2817
2818 r = strv_extend(&symlinks, "/run/host/os-release");
2819 if (r < 0)
2820 return r;
2821 }
2822
2823 *ret_symlinks = TAKE_PTR(symlinks);
2824
2825 return 0;
2826}
2827
2828static bool insist_on_sandboxing(
2829 const ExecContext *context,
2830 const char *root_dir,
2831 const char *root_image,
2832 const BindMount *bind_mounts,
2833 size_t n_bind_mounts) {
2834
2835 assert(context);
2836 assert(n_bind_mounts == 0 || bind_mounts);
2837
2838 /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
2839 * would alter the view on the file system beyond making things read-only or invisible, i.e. would
2840 * rearrange stuff in a way we cannot ignore gracefully. */
2841
2842 if (context->n_temporary_filesystems > 0)
2843 return true;
2844
2845 if (root_dir || root_image)
2846 return true;
2847
2848 if (context->n_mount_images > 0)
2849 return true;
2850
2851 if (context->dynamic_user)
2852 return true;
2853
2854 if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
2855 return true;
2856
2857 /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
2858 * essential. */
2859 for (size_t i = 0; i < n_bind_mounts; i++)
2860 if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
2861 return true;
2862
2863 if (context->log_namespace)
2864 return true;
2865
2866 return false;
2867}
2868
0cb11023
LP
2869static int setup_ephemeral(
2870 const ExecContext *context,
2871 ExecRuntime *runtime,
2872 char **root_image, /* both input and output! modified if ephemeral logic enabled */
2873 char **root_directory) { /* ditto */
2874
75689fb2 2875 _cleanup_close_ int fd = -EBADF;
0cb11023 2876 _cleanup_free_ char *new_root = NULL;
75689fb2
LB
2877 int r;
2878
0cb11023
LP
2879 assert(context);
2880 assert(root_image);
2881 assert(root_directory);
2882
2883 if (!*root_image && !*root_directory)
2884 return 0;
2885
75689fb2
LB
2886 if (!runtime || !runtime->ephemeral_copy)
2887 return 0;
2888
0cb11023
LP
2889 assert(runtime->ephemeral_storage_socket[0] >= 0);
2890 assert(runtime->ephemeral_storage_socket[1] >= 0);
2891
2892 new_root = strdup(runtime->ephemeral_copy);
2893 if (!new_root)
2894 return log_oom_debug();
2895
75689fb2
LB
2896 r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
2897 if (r < 0)
2898 return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
2899
2900 CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
2901
2902 fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2903 if (fd >= 0)
2904 /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
2905 return 0;
75689fb2
LB
2906 if (fd != -EAGAIN)
2907 return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
2908
0cb11023
LP
2909 if (*root_image) {
2910 log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
75689fb2 2911
0cb11023
LP
2912 fd = copy_file(*root_image,
2913 new_root,
2914 O_EXCL,
2915 0600,
2916 COPY_LOCK_BSD|
2917 COPY_REFLINK|
2918 COPY_CRTIME);
2919 if (fd < 0)
2920 return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
2921 *root_image, new_root);
75689fb2 2922
75689fb2
LB
2923 /* A root image might be subject to lots of random writes so let's try to disable COW on it
2924 * which tends to not perform well in combination with lots of random writes.
2925 *
2926 * Note: btrfs actually isn't impressed by us setting the flag after making the reflink'ed
2927 * copy, but we at least want to make the intention clear.
2928 */
2929 r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL, NULL);
2930 if (r < 0)
0cb11023
LP
2931 log_debug_errno(fd, "Failed to disable copy-on-write for %s, ignoring: %m", new_root);
2932 } else {
2933 assert(*root_directory);
2934
2935 log_debug("Making ephemeral snapshot of %s to %s", *root_directory, new_root);
2936
2937 fd = btrfs_subvol_snapshot_at(
2938 AT_FDCWD, *root_directory,
2939 AT_FDCWD, new_root,
2940 BTRFS_SNAPSHOT_FALLBACK_COPY |
2941 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
2942 BTRFS_SNAPSHOT_RECURSIVE |
2943 BTRFS_SNAPSHOT_LOCK_BSD);
2944 if (fd < 0)
2945 return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
2946 *root_directory, new_root);
75689fb2
LB
2947 }
2948
2949 r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
2950 if (r < 0)
2951 return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
2952
0cb11023
LP
2953 if (*root_image)
2954 free_and_replace(*root_image, new_root);
2955 else {
2956 assert(*root_directory);
2957 free_and_replace(*root_directory, new_root);
2958 }
2959
75689fb2
LB
2960 return 1;
2961}
2962
2963static int verity_settings_prepare(
2964 VeritySettings *verity,
2965 const char *root_image,
2966 const void *root_hash,
2967 size_t root_hash_size,
2968 const char *root_hash_path,
2969 const void *root_hash_sig,
2970 size_t root_hash_sig_size,
2971 const char *root_hash_sig_path,
2972 const char *verity_data_path) {
2973
2974 int r;
2975
2976 assert(verity);
2977
2978 if (root_hash) {
2979 void *d;
2980
2981 d = memdup(root_hash, root_hash_size);
2982 if (!d)
2983 return -ENOMEM;
2984
2985 free_and_replace(verity->root_hash, d);
2986 verity->root_hash_size = root_hash_size;
2987 verity->designator = PARTITION_ROOT;
2988 }
2989
2990 if (root_hash_sig) {
2991 void *d;
2992
2993 d = memdup(root_hash_sig, root_hash_sig_size);
2994 if (!d)
2995 return -ENOMEM;
2996
2997 free_and_replace(verity->root_hash_sig, d);
2998 verity->root_hash_sig_size = root_hash_sig_size;
2999 verity->designator = PARTITION_ROOT;
3000 }
3001
3002 if (verity_data_path) {
3003 r = free_and_strdup(&verity->data_path, verity_data_path);
3004 if (r < 0)
3005 return r;
3006 }
3007
3008 r = verity_settings_load(
3009 verity,
3010 root_image,
3011 root_hash_path,
3012 root_hash_sig_path);
3013 if (r < 0)
3014 return log_debug_errno(r, "Failed to load root hash: %m");
3015
3016 return 0;
3017}
3018
0cb11023
LP
3019static int pick_versions(
3020 const ExecContext *context,
3021 const ExecParameters *params,
3022 char **ret_root_image,
3023 char **ret_root_directory) {
3024
3025 int r;
3026
3027 assert(context);
3028 assert(params);
3029 assert(ret_root_image);
3030 assert(ret_root_directory);
3031
3032 if (context->root_image) {
3033 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3034
3035 r = path_pick(/* toplevel_path= */ NULL,
3036 /* toplevel_fd= */ AT_FDCWD,
3037 context->root_image,
3038 &pick_filter_image_raw,
3039 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3040 &result);
3041 if (r < 0)
3042 return r;
3043
3044 if (!result.path)
3045 return log_exec_debug_errno(context, params, SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
3046
3047 *ret_root_image = TAKE_PTR(result.path);
3048 *ret_root_directory = NULL;
3049 return r;
3050 }
3051
3052 if (context->root_directory) {
3053 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
3054
3055 r = path_pick(/* toplevel_path= */ NULL,
3056 /* toplevel_fd= */ AT_FDCWD,
3057 context->root_directory,
3058 &pick_filter_image_dir,
3059 PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3060 &result);
3061 if (r < 0)
3062 return r;
3063
3064 if (!result.path)
3065 return log_exec_debug_errno(context, params, SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
3066
3067 *ret_root_image = NULL;
3068 *ret_root_directory = TAKE_PTR(result.path);
3069 return r;
3070 }
3071
3072 *ret_root_image = *ret_root_directory = NULL;
3073 return 0;
3074}
3075
75689fb2
LB
3076static int apply_mount_namespace(
3077 ExecCommandFlags command_flags,
3078 const ExecContext *context,
3079 const ExecParameters *params,
3080 ExecRuntime *runtime,
3081 const char *memory_pressure_path,
3082 char **error_path) {
3083
3084 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3085 _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
3086 **read_write_paths_cleanup = NULL;
3087 _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
0cb11023
LP
3088 *extension_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
3089 const char *tmp_dir = NULL, *var_tmp_dir = NULL;
75689fb2
LB
3090 char **read_write_paths;
3091 bool needs_sandboxing, setup_os_release_symlink;
3092 BindMount *bind_mounts = NULL;
3093 size_t n_bind_mounts = 0;
3094 int r;
3095
3096 assert(context);
3097
3098 CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
3099
3100 if (params->flags & EXEC_APPLY_CHROOT) {
0cb11023
LP
3101 r = pick_versions(
3102 context,
3103 params,
3104 &root_image,
3105 &root_dir);
75689fb2
LB
3106 if (r < 0)
3107 return r;
3108
0cb11023
LP
3109 r = setup_ephemeral(
3110 context,
3111 runtime,
3112 &root_image,
3113 &root_dir);
3114 if (r < 0)
3115 return r;
75689fb2
LB
3116 }
3117
3118 r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
3119 if (r < 0)
3120 return r;
3121
3122 /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3123 * service will need to write to it in order to start the notifications. */
3124 if (context->protect_control_groups && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
3125 read_write_paths_cleanup = strv_copy(context->read_write_paths);
3126 if (!read_write_paths_cleanup)
3127 return -ENOMEM;
3128
3129 r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
3130 if (r < 0)
3131 return r;
3132
3133 read_write_paths = read_write_paths_cleanup;
3134 } else
3135 read_write_paths = context->read_write_paths;
3136
3137 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
3138 if (needs_sandboxing) {
3139 /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
3140 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
3141 * use here. This does not apply when we are using /run/systemd/empty as fallback. */
3142
3143 if (context->private_tmp && runtime && runtime->shared) {
3144 if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
3145 tmp_dir = runtime->shared->tmp_dir;
3146 else if (runtime->shared->tmp_dir)
3147 tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
3148
3149 if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
3150 var_tmp_dir = runtime->shared->var_tmp_dir;
3151 else if (runtime->shared->var_tmp_dir)
3152 var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
3153 }
3154 }
3155
3156 /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3157 setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
3158 r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
3159 if (r < 0)
3160 return r;
3161
3162 if (context->mount_propagation_flag == MS_SHARED)
3163 log_exec_debug(context,
3164 params,
3165 "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
3166
3167 if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
3168 r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
3169 if (r < 0)
3170 return r;
3171 }
3172
3173 if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
3174 propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
3175 if (!propagate_dir)
3176 return -ENOMEM;
3177
3178 incoming_dir = strdup("/run/systemd/incoming");
3179 if (!incoming_dir)
3180 return -ENOMEM;
3181
3182 extension_dir = strdup("/run/systemd/unit-extensions");
3183 if (!extension_dir)
3184 return -ENOMEM;
3185
3186 /* If running under a different root filesystem, propagate the host's os-release. We make a
3187 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3188 if (setup_os_release_symlink) {
3189 host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
3190 if (!host_os_release_stage)
3191 return -ENOMEM;
3192 }
3193 } else {
3194 assert(params->runtime_scope == RUNTIME_SCOPE_USER);
3195
3196 if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0)
3197 return -ENOMEM;
3198
3199 if (setup_os_release_symlink) {
3200 if (asprintf(&host_os_release_stage,
3201 "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3202 geteuid()) < 0)
3203 return -ENOMEM;
3204 }
3205 }
3206
3207 if (root_image) {
3208 r = verity_settings_prepare(
3209 &verity,
3210 root_image,
3211 context->root_hash, context->root_hash_size, context->root_hash_path,
3212 context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
3213 context->root_verity);
3214 if (r < 0)
3215 return r;
3216 }
3217
3218 NamespaceParameters parameters = {
3219 .runtime_scope = params->runtime_scope,
3220
3221 .root_directory = root_dir,
3222 .root_image = root_image,
3223 .root_image_options = context->root_image_options,
3224 .root_image_policy = context->root_image_policy ?: &image_policy_service,
3225
3226 .read_write_paths = read_write_paths,
3227 .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
3228 .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
3229
3230 .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
3231 .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
3232
3233 .empty_directories = empty_directories,
3234 .symlinks = symlinks,
3235
3236 .bind_mounts = bind_mounts,
3237 .n_bind_mounts = n_bind_mounts,
3238
3239 .temporary_filesystems = context->temporary_filesystems,
3240 .n_temporary_filesystems = context->n_temporary_filesystems,
3241
3242 .mount_images = context->mount_images,
3243 .n_mount_images = context->n_mount_images,
3244 .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
3245
3246 .tmp_dir = tmp_dir,
3247 .var_tmp_dir = var_tmp_dir,
3248
3249 .creds_path = creds_path,
3250 .log_namespace = context->log_namespace,
3251 .mount_propagation_flag = context->mount_propagation_flag,
3252
3253 .verity = &verity,
3254
3255 .extension_images = context->extension_images,
3256 .n_extension_images = context->n_extension_images,
3257 .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
3258 .extension_directories = context->extension_directories,
3259
3260 .propagate_dir = propagate_dir,
3261 .incoming_dir = incoming_dir,
3262 .extension_dir = extension_dir,
3263 .notify_socket = root_dir || root_image ? params->notify_socket : NULL,
3264 .host_os_release_stage = host_os_release_stage,
3265
3266 /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
3267 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
3268 * sandbox inside the mount namespace. */
3269 .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && root_dir,
3270
3271 .protect_control_groups = needs_sandboxing && context->protect_control_groups,
3272 .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
3273 .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
3274 .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
3275 .protect_hostname = needs_sandboxing && context->protect_hostname,
3276
3277 .private_dev = needs_sandboxing && context->private_devices,
3278 .private_network = needs_sandboxing && exec_needs_network_namespace(context),
3279 .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
3280
3281 .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
3282
3283 /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
3284 .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
3285
abcf5997
FS
3286 .protect_home = needs_sandboxing ? context->protect_home : false,
3287 .protect_system = needs_sandboxing ? context->protect_system : false,
3288 .protect_proc = needs_sandboxing ? context->protect_proc : false,
3289 .proc_subset = needs_sandboxing ? context->proc_subset : false,
75689fb2
LB
3290 };
3291
3292 r = setup_namespace(&parameters, error_path);
3293 /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
3294 * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
3295 * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3296 * completely different execution environment. */
3297 if (r == -ENOANO) {
3298 if (insist_on_sandboxing(
3299 context,
3300 root_dir, root_image,
3301 bind_mounts,
3302 n_bind_mounts))
3303 return log_exec_debug_errno(context,
3304 params,
3305 SYNTHETIC_ERRNO(EOPNOTSUPP),
3306 "Failed to set up namespace, and refusing to continue since "
3307 "the selected namespacing options alter mount environment non-trivially.\n"
3308 "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3309 n_bind_mounts,
3310 context->n_temporary_filesystems,
3311 yes_no(root_dir),
3312 yes_no(root_image),
3313 yes_no(context->dynamic_user));
3314
3315 log_exec_debug(context, params, "Failed to set up namespace, assuming containerized execution and ignoring.");
3316 return 0;
3317 }
3318
3319 return r;
3320}
3321
3322static int apply_working_directory(
3323 const ExecContext *context,
3324 const ExecParameters *params,
3325 ExecRuntime *runtime,
3326 const char *home,
3327 int *exit_status) {
3328
3329 const char *d, *wd;
3330
3331 assert(context);
3332 assert(exit_status);
3333
3334 if (context->working_directory_home) {
3335
3336 if (!home) {
3337 *exit_status = EXIT_CHDIR;
3338 return -ENXIO;
3339 }
3340
3341 wd = home;
3342
3343 } else
3344 wd = empty_to_root(context->working_directory);
3345
3346 if (params->flags & EXEC_APPLY_CHROOT)
3347 d = wd;
3348 else
3349 d = prefix_roota((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory, wd);
3350
3351 if (chdir(d) < 0 && !context->working_directory_missing_ok) {
3352 *exit_status = EXIT_CHDIR;
3353 return -errno;
3354 }
3355
3356 return 0;
3357}
3358
3359static int apply_root_directory(
3360 const ExecContext *context,
3361 const ExecParameters *params,
3362 ExecRuntime *runtime,
3363 const bool needs_mount_ns,
3364 int *exit_status) {
3365
3366 assert(context);
3367 assert(exit_status);
3368
3369 if (params->flags & EXEC_APPLY_CHROOT)
3370 if (!needs_mount_ns && context->root_directory)
3371 if (chroot((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory) < 0) {
3372 *exit_status = EXIT_CHROOT;
3373 return -errno;
3374 }
3375
3376 return 0;
3377}
3378
3379static int setup_keyring(
3380 const ExecContext *context,
3381 const ExecParameters *p,
3382 uid_t uid, gid_t gid) {
3383
3384 key_serial_t keyring;
3385 int r = 0;
3386 uid_t saved_uid;
3387 gid_t saved_gid;
3388
3389 assert(context);
3390 assert(p);
3391
3392 /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
3393 * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
3394 * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
3395 * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
3396 * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
3397 * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
3398
3399 if (context->keyring_mode == EXEC_KEYRING_INHERIT)
3400 return 0;
3401
3402 /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
3403 * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
3404 * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
3405 * & group is just as nasty as acquiring a reference to the user keyring. */
3406
3407 saved_uid = getuid();
3408 saved_gid = getgid();
3409
3410 if (gid_is_valid(gid) && gid != saved_gid) {
3411 if (setregid(gid, -1) < 0)
3412 return log_exec_error_errno(context,
3413 p,
3414 errno,
3415 "Failed to change GID for user keyring: %m");
3416 }
3417
3418 if (uid_is_valid(uid) && uid != saved_uid) {
3419 if (setreuid(uid, -1) < 0) {
3420 r = log_exec_error_errno(context,
3421 p,
3422 errno,
3423 "Failed to change UID for user keyring: %m");
3424 goto out;
3425 }
3426 }
3427
3428 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
3429 if (keyring == -1) {
3430 if (errno == ENOSYS)
3431 log_exec_debug_errno(context,
3432 p,
3433 errno,
3434 "Kernel keyring not supported, ignoring.");
3435 else if (ERRNO_IS_PRIVILEGE(errno))
3436 log_exec_debug_errno(context,
3437 p,
3438 errno,
3439 "Kernel keyring access prohibited, ignoring.");
3440 else if (errno == EDQUOT)
3441 log_exec_debug_errno(context,
3442 p,
3443 errno,
3444 "Out of kernel keyrings to allocate, ignoring.");
3445 else
3446 r = log_exec_error_errno(context,
3447 p,
3448 errno,
3449 "Setting up kernel keyring failed: %m");
3450
3451 goto out;
3452 }
3453
3454 /* When requested link the user keyring into the session keyring. */
3455 if (context->keyring_mode == EXEC_KEYRING_SHARED) {
3456
3457 if (keyctl(KEYCTL_LINK,
3458 KEY_SPEC_USER_KEYRING,
3459 KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3460 r = log_exec_error_errno(context,
3461 p,
3462 errno,
3463 "Failed to link user keyring into session keyring: %m");
3464 goto out;
3465 }
3466 }
3467
3468 /* Restore uid/gid back */
3469 if (uid_is_valid(uid) && uid != saved_uid) {
3470 if (setreuid(saved_uid, -1) < 0) {
3471 r = log_exec_error_errno(context,
3472 p,
3473 errno,
3474 "Failed to change UID back for user keyring: %m");
3475 goto out;
3476 }
3477 }
3478
3479 if (gid_is_valid(gid) && gid != saved_gid) {
3480 if (setregid(saved_gid, -1) < 0)
3481 return log_exec_error_errno(context,
3482 p,
3483 errno,
3484 "Failed to change GID back for user keyring: %m");
3485 }
3486
3487 /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3488 if (!sd_id128_is_null(p->invocation_id)) {
3489 key_serial_t key;
3490
3491 key = add_key("user",
3492 "invocation_id",
3493 &p->invocation_id,
3494 sizeof(p->invocation_id),
3495 KEY_SPEC_SESSION_KEYRING);
3496 if (key == -1)
3497 log_exec_debug_errno(context,
3498 p,
3499 errno,
3500 "Failed to add invocation ID to keyring, ignoring: %m");
3501 else {
3502 if (keyctl(KEYCTL_SETPERM, key,
3503 KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3504 KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3505 r = log_exec_error_errno(context,
3506 p,
3507 errno,
3508 "Failed to restrict invocation ID permission: %m");
3509 }
3510 }
3511
3512out:
3513 /* Revert back uid & gid for the last time, and exit */
3514 /* no extra logging, as only the first already reported error matters */
3515 if (getuid() != saved_uid)
3516 (void) setreuid(saved_uid, -1);
3517
3518 if (getgid() != saved_gid)
3519 (void) setregid(saved_gid, -1);
3520
3521 return r;
3522}
3523
3524static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
3525 assert(array);
3526 assert(n);
3527 assert(pair);
3528
3529 if (pair[0] >= 0)
3530 array[(*n)++] = pair[0];
3531 if (pair[1] >= 0)
3532 array[(*n)++] = pair[1];
3533}
3534
3535static int close_remaining_fds(
3536 const ExecParameters *params,
3537 const ExecRuntime *runtime,
3538 int socket_fd,
3539 const int *fds, size_t n_fds) {
3540
3541 size_t n_dont_close = 0;
3542 int dont_close[n_fds + 14];
3543
3544 assert(params);
3545
3546 if (params->stdin_fd >= 0)
3547 dont_close[n_dont_close++] = params->stdin_fd;
3548 if (params->stdout_fd >= 0)
3549 dont_close[n_dont_close++] = params->stdout_fd;
3550 if (params->stderr_fd >= 0)
3551 dont_close[n_dont_close++] = params->stderr_fd;
3552
3553 if (socket_fd >= 0)
3554 dont_close[n_dont_close++] = socket_fd;
3555 if (n_fds > 0) {
3556 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
3557 n_dont_close += n_fds;
3558 }
3559
3560 if (runtime)
3561 append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
3562
3563 if (runtime && runtime->shared) {
3564 append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
3565 append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
3566 }
3567
3568 if (runtime && runtime->dynamic_creds) {
3569 if (runtime->dynamic_creds->user)
3570 append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
3571 if (runtime->dynamic_creds->group)
3572 append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
3573 }
3574
3575 if (params->user_lookup_fd >= 0)
3576 dont_close[n_dont_close++] = params->user_lookup_fd;
3577
3578 return close_all_fds(dont_close, n_dont_close);
3579}
3580
3581static int send_user_lookup(
3582 const char *unit_id,
3583 int user_lookup_fd,
3584 uid_t uid,
3585 gid_t gid) {
3586
3587 assert(unit_id);
3588
3589 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
3590 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
3591 * specified. */
3592
3593 if (user_lookup_fd < 0)
3594 return 0;
3595
3596 if (!uid_is_valid(uid) && !gid_is_valid(gid))
3597 return 0;
3598
3599 if (writev(user_lookup_fd,
3600 (struct iovec[]) {
3601 IOVEC_MAKE(&uid, sizeof(uid)),
3602 IOVEC_MAKE(&gid, sizeof(gid)),
3603 IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
3604 return -errno;
3605
3606 return 0;
3607}
3608
3609static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
3610 int r;
3611
3612 assert(c);
3613 assert(home);
3614 assert(buf);
3615
3616 /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
3617
3618 if (*home)
3619 return 0;
3620
3621 if (!c->working_directory_home)
3622 return 0;
3623
3624 r = get_home_dir(buf);
3625 if (r < 0)
3626 return r;
3627
3628 *home = *buf;
3629 return 1;
3630}
3631
3632static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
3633 _cleanup_strv_free_ char ** list = NULL;
3634 int r;
3635
3636 assert(c);
3637 assert(p);
3638 assert(ret);
3639
3640 assert(c->dynamic_user);
3641
3642 /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
3643 * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
3644 * directories. */
3645
3646 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
3647 if (t == EXEC_DIRECTORY_CONFIGURATION)
3648 continue;
3649
3650 if (!p->prefix[t])
3651 continue;
3652
3653 for (size_t i = 0; i < c->directories[t].n_items; i++) {
3654 char *e;
3655
3656 if (exec_directory_is_private(c, t))
3657 e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
3658 else
3659 e = path_join(p->prefix[t], c->directories[t].items[i].path);
3660 if (!e)
3661 return -ENOMEM;
3662
3663 r = strv_consume(&list, e);
3664 if (r < 0)
3665 return r;
3666 }
3667 }
3668
3669 *ret = TAKE_PTR(list);
3670
3671 return 0;
3672}
3673
3674static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
3675 _cleanup_(cpu_set_reset) CPUSet s = {};
3676 int r;
3677
3678 assert(c);
3679 assert(ret);
3680
3681 if (!c->numa_policy.nodes.set) {
3682 log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
3683 return 0;
3684 }
3685
3686 r = numa_to_cpu_set(&c->numa_policy, &s);
3687 if (r < 0)
3688 return r;
3689
3690 cpu_set_reset(ret);
3691
3692 return cpu_set_add_all(ret, &s);
3693}
3694
5a5fdfe3 3695static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
75689fb2
LB
3696 int r;
3697
3698 assert(fds);
3699 assert(n_fds);
3700 assert(*n_fds < fds_size);
5a5fdfe3 3701 assert(fd);
75689fb2 3702
5a5fdfe3
MY
3703 if (*fd < 0)
3704 return 0;
75689fb2 3705
5a5fdfe3 3706 if (*fd < 3 + (int) *n_fds) {
75689fb2
LB
3707 /* Let's move the fd up, so that it's outside of the fd range we will use to store
3708 * the fds we pass to the process (or which are closed only during execve). */
3709
5a5fdfe3 3710 r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
75689fb2
LB
3711 if (r < 0)
3712 return -errno;
3713
5a5fdfe3 3714 close_and_replace(*fd, r);
75689fb2
LB
3715 }
3716
5a5fdfe3 3717 fds[(*n_fds)++] = *fd;
75689fb2
LB
3718 return 1;
3719}
3720
3721static int connect_unix_harder(const ExecContext *c, const ExecParameters *p, const OpenFile *of, int ofd) {
3722 union sockaddr_union addr = {
3723 .un.sun_family = AF_UNIX,
3724 };
3725 socklen_t sa_len;
3726 static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
3727 int r;
3728
3729 assert(c);
3730 assert(p);
3731 assert(of);
3732 assert(ofd >= 0);
3733
3734 r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
3735 if (r < 0)
3736 return log_exec_error_errno(c, p, r, "Failed to set sockaddr for %s: %m", of->path);
3737
3738 sa_len = r;
3739
3740 for (size_t i = 0; i < ELEMENTSOF(socket_types); i++) {
3741 _cleanup_close_ int fd = -EBADF;
3742
3743 fd = socket(AF_UNIX, socket_types[i] | SOCK_CLOEXEC, 0);
3744 if (fd < 0)
3745 return log_exec_error_errno(c,
3746 p,
3747 errno,
3748 "Failed to create socket for %s: %m",
3749 of->path);
3750
3751 r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
3752 if (r == -EPROTOTYPE)
3753 continue;
3754 if (r < 0)
3755 return log_exec_error_errno(c,
3756 p,
3757 r,
3758 "Failed to connect socket for %s: %m",
3759 of->path);
3760
3761 return TAKE_FD(fd);
3762 }
3763
3764 return log_exec_error_errno(c,
3765 p,
3766 SYNTHETIC_ERRNO(EPROTOTYPE), "Failed to connect socket for \"%s\".",
3767 of->path);
3768}
3769
3770static int get_open_file_fd(const ExecContext *c, const ExecParameters *p, const OpenFile *of) {
3771 struct stat st;
3772 _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
3773
3774 assert(c);
3775 assert(p);
3776 assert(of);
3777
3778 ofd = open(of->path, O_PATH | O_CLOEXEC);
3779 if (ofd < 0)
3780 return log_exec_error_errno(c, p, errno, "Could not open \"%s\": %m", of->path);
3781
3782 if (fstat(ofd, &st) < 0)
3783 return log_exec_error_errno(c, p, errno, "Failed to stat %s: %m", of->path);
3784
3785 if (S_ISSOCK(st.st_mode)) {
3786 fd = connect_unix_harder(c, p, of, ofd);
3787 if (fd < 0)
3788 return fd;
3789
3790 if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
3791 return log_exec_error_errno(c, p, errno, "Failed to shutdown send for socket %s: %m",
3792 of->path);
3793
3794 log_exec_debug(c, p, "socket %s opened (fd=%d)", of->path, fd);
3795 } else {
3796 int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
3797 if (FLAGS_SET(of->flags, OPENFILE_APPEND))
3798 flags |= O_APPEND;
3799 else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
3800 flags |= O_TRUNC;
3801
3802 fd = fd_reopen(ofd, flags | O_CLOEXEC);
3803 if (fd < 0)
3804 return log_exec_error_errno(c, p, fd, "Failed to open file %s: %m", of->path);
3805
3806 log_exec_debug(c, p, "file %s opened (fd=%d)", of->path, fd);
3807 }
3808
3809 return TAKE_FD(fd);
3810}
3811
1eeaa93d 3812static int collect_open_file_fds(const ExecContext *c, ExecParameters *p, size_t *n_fds) {
75689fb2
LB
3813 int r;
3814
3815 assert(c);
3816 assert(p);
75689fb2
LB
3817 assert(n_fds);
3818
3819 LIST_FOREACH(open_files, of, p->open_files) {
3820 _cleanup_close_ int fd = -EBADF;
3821
3822 fd = get_open_file_fd(c, p, of);
3823 if (fd < 0) {
3824 if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
3825 log_exec_debug_errno(c, p, fd, "Failed to get OpenFile= file descriptor for %s, ignoring: %m", of->path);
3826 continue;
3827 }
3828
3829 return fd;
3830 }
3831
1eeaa93d 3832 if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
75689fb2
LB
3833 return -ENOMEM;
3834
1eeaa93d 3835 r = strv_extend(&p->fd_names, of->fdname);
75689fb2
LB
3836 if (r < 0)
3837 return r;
3838
1eeaa93d 3839 p->fds[*n_fds] = TAKE_FD(fd);
75689fb2
LB
3840
3841 (*n_fds)++;
3842 }
3843
3844 return 0;
3845}
3846
3847static void log_command_line(
3848 const ExecContext *context,
3849 const ExecParameters *params,
3850 const char *msg,
3851 const char *executable,
3852 char **argv) {
3853
3854 assert(context);
3855 assert(params);
3856 assert(msg);
3857 assert(executable);
3858
3859 if (!DEBUG_LOGGING)
3860 return;
3861
3862 _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
3863
3864 log_exec_struct(context, params, LOG_DEBUG,
3865 "EXECUTABLE=%s", executable,
3866 LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
3867 LOG_EXEC_INVOCATION_ID(params));
3868}
3869
3870static bool exec_context_need_unprivileged_private_users(
3871 const ExecContext *context,
3872 const ExecParameters *params) {
3873
3874 assert(context);
3875 assert(params);
3876
3877 /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
3878 * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
3879 * (system manager) then we have privileges and don't need this. */
3880 if (params->runtime_scope != RUNTIME_SCOPE_USER)
3881 return false;
3882
3883 return context->private_users ||
3884 context->private_tmp ||
3885 context->private_devices ||
3886 context->private_network ||
3887 context->network_namespace_path ||
3888 context->private_ipc ||
3889 context->ipc_namespace_path ||
3890 context->private_mounts > 0 ||
3891 context->mount_apivfs ||
3892 context->n_bind_mounts > 0 ||
3893 context->n_temporary_filesystems > 0 ||
3894 context->root_directory ||
3895 !strv_isempty(context->extension_directories) ||
3896 context->protect_system != PROTECT_SYSTEM_NO ||
3897 context->protect_home != PROTECT_HOME_NO ||
3898 context->protect_kernel_tunables ||
3899 context->protect_kernel_modules ||
3900 context->protect_kernel_logs ||
3901 context->protect_control_groups ||
3902 context->protect_clock ||
3903 context->protect_hostname ||
3904 !strv_isempty(context->read_write_paths) ||
3905 !strv_isempty(context->read_only_paths) ||
3906 !strv_isempty(context->inaccessible_paths) ||
3907 !strv_isempty(context->exec_paths) ||
3908 !strv_isempty(context->no_exec_paths);
3909}
3910
3911static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
3912 assert(context);
3913
3914 if (confirm_spawn_disabled())
3915 return false;
3916
3917 /* For some reasons units remaining in the same process group
3918 * as PID 1 fail to acquire the console even if it's not used
3919 * by any process. So skip the confirmation question for them. */
3920 return !context->same_pgrp;
3921}
3922
3923static int exec_context_named_iofds(
3924 const ExecContext *c,
3925 const ExecParameters *p,
3926 int named_iofds[static 3]) {
3927
3928 size_t targets;
3929 const char* stdio_fdname[3];
3930 size_t n_fds;
3931
3932 assert(c);
3933 assert(p);
3934 assert(named_iofds);
3935
3936 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
3937 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
3938 (c->std_error == EXEC_OUTPUT_NAMED_FD);
3939
3940 for (size_t i = 0; i < 3; i++)
3941 stdio_fdname[i] = exec_context_fdname(c, i);
3942
3943 n_fds = p->n_storage_fds + p->n_socket_fds;
3944
3945 for (size_t i = 0; i < n_fds && targets > 0; i++)
3946 if (named_iofds[STDIN_FILENO] < 0 &&
3947 c->std_input == EXEC_INPUT_NAMED_FD &&
3948 stdio_fdname[STDIN_FILENO] &&
3949 streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
3950
3951 named_iofds[STDIN_FILENO] = p->fds[i];
3952 targets--;
3953
3954 } else if (named_iofds[STDOUT_FILENO] < 0 &&
3955 c->std_output == EXEC_OUTPUT_NAMED_FD &&
3956 stdio_fdname[STDOUT_FILENO] &&
3957 streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
3958
3959 named_iofds[STDOUT_FILENO] = p->fds[i];
3960 targets--;
3961
3962 } else if (named_iofds[STDERR_FILENO] < 0 &&
3963 c->std_error == EXEC_OUTPUT_NAMED_FD &&
3964 stdio_fdname[STDERR_FILENO] &&
3965 streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
3966
3967 named_iofds[STDERR_FILENO] = p->fds[i];
3968 targets--;
3969 }
3970
3971 return targets == 0 ? 0 : -ENOENT;
3972}
3973
7b6d3dcd
LB
3974static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
3975 if (!shared)
3976 return;
3977
3978 safe_close_pair(shared->netns_storage_socket);
3979 safe_close_pair(shared->ipcns_storage_socket);
3980}
3981
3982static void exec_runtime_close(ExecRuntime *rt) {
3983 if (!rt)
3984 return;
3985
3986 safe_close_pair(rt->ephemeral_storage_socket);
3987
3988 exec_shared_runtime_close(rt->shared);
3989 dynamic_creds_close(rt->dynamic_creds);
3990}
3991
3992static void exec_params_close(ExecParameters *p) {
3993 if (!p)
3994 return;
3995
3996 p->stdin_fd = safe_close(p->stdin_fd);
3997 p->stdout_fd = safe_close(p->stdout_fd);
3998 p->stderr_fd = safe_close(p->stderr_fd);
3999}
4000
75689fb2
LB
4001int exec_invoke(
4002 const ExecCommand *command,
4003 const ExecContext *context,
4004 ExecParameters *params,
4005 ExecRuntime *runtime,
4006 const CGroupContext *cgroup_context,
4007 int *exit_status) {
4008
4009 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
5a5fdfe3 4010 int r, ngids = 0;
75689fb2
LB
4011 _cleanup_free_ gid_t *supplementary_gids = NULL;
4012 const char *username = NULL, *groupname = NULL;
4013 _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL;
4014 const char *home = NULL, *shell = NULL;
4015 char **final_argv = NULL;
4016 dev_t journal_stream_dev = 0;
4017 ino_t journal_stream_ino = 0;
4018 bool userns_set_up = false;
4019 bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
4020 needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */
4021 needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */
4022 needs_ambient_hack; /* Do we need to apply the ambient capabilities hack? */
24832d10 4023 bool keep_seccomp_privileges = false;
75689fb2
LB
4024#if HAVE_SELINUX
4025 _cleanup_free_ char *mac_selinux_context_net = NULL;
4026 bool use_selinux = false;
4027#endif
4028#if ENABLE_SMACK
4029 bool use_smack = false;
4030#endif
4031#if HAVE_APPARMOR
4032 bool use_apparmor = false;
24832d10
ILG
4033#endif
4034#if HAVE_SECCOMP
4035 uint64_t saved_bset = 0;
75689fb2
LB
4036#endif
4037 uid_t saved_uid = getuid();
4038 gid_t saved_gid = getgid();
4039 uid_t uid = UID_INVALID;
4040 gid_t gid = GID_INVALID;
4041 size_t n_fds, /* fds to pass to the child */
4042 n_keep_fds; /* total number of fds not to close */
4043 int secure_bits;
4044 _cleanup_free_ gid_t *gids_after_pam = NULL;
4045 int ngids_after_pam = 0;
75689fb2 4046
1eeaa93d
LB
4047 int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
4048 size_t n_storage_fds, n_socket_fds;
75689fb2
LB
4049
4050 assert(command);
4051 assert(context);
4052 assert(params);
4053 assert(exit_status);
4054
36013380
YW
4055 /* This should be mostly redundant, as the log level is also passed as an argument of the executor,
4056 * and is already applied earlier. Just for safety. */
cc9f4cad
LB
4057 if (context->log_level_max >= 0)
4058 log_set_max_level(context->log_level_max);
4059
75689fb2 4060 /* Explicitly test for CVE-2021-4034 inspired invocations */
856bed0a
LB
4061 if (!command->path || strv_isempty(command->argv)) {
4062 *exit_status = EXIT_EXEC;
4063 return log_exec_error_errno(
4064 context,
4065 params,
4066 SYNTHETIC_ERRNO(EINVAL),
4067 "Invalid command line arguments.");
4068 }
75689fb2
LB
4069
4070 LOG_CONTEXT_PUSH_EXEC(context, params);
4071
4072 if (context->std_input == EXEC_INPUT_SOCKET ||
4073 context->std_output == EXEC_OUTPUT_SOCKET ||
4074 context->std_error == EXEC_OUTPUT_SOCKET) {
4075
4076 if (params->n_socket_fds > 1)
4077 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
4078
4079 if (params->n_socket_fds == 0)
4080 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
4081
4082 socket_fd = params->fds[0];
1eeaa93d 4083 n_storage_fds = n_socket_fds = 0;
75689fb2 4084 } else {
75689fb2
LB
4085 n_socket_fds = params->n_socket_fds;
4086 n_storage_fds = params->n_storage_fds;
4087 }
4088 n_fds = n_socket_fds + n_storage_fds;
4089
4090 r = exec_context_named_iofds(context, params, named_iofds);
4091 if (r < 0)
4092 return log_exec_error_errno(context, params, r, "Failed to load a named file descriptor: %m");
4093
4094 rename_process_from_path(command->path);
4095
4096 /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4097 * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4098 * both of which will be demoted to SIG_DFL. */
4099 (void) default_signals(SIGNALS_CRASH_HANDLER,
4100 SIGNALS_IGNORE);
4101
4102 if (context->ignore_sigpipe)
4103 (void) ignore_signals(SIGPIPE);
4104
4105 r = reset_signal_mask();
4106 if (r < 0) {
4107 *exit_status = EXIT_SIGNAL_MASK;
4108 return log_exec_error_errno(context, params, r, "Failed to set process signal mask: %m");
4109 }
4110
4111 if (params->idle_pipe)
4112 do_idle_pipe_dance(params->idle_pipe);
4113
4114 /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4115 * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4116 * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4117 * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
4118
4119 log_forget_fds();
4120 log_set_open_when_needed(true);
4121 log_settle_target();
75689fb2
LB
4122
4123 /* In case anything used libc syslog(), close this here, too */
4124 closelog();
4125
1eeaa93d 4126 r = collect_open_file_fds(context, params, &n_fds);
75689fb2
LB
4127 if (r < 0) {
4128 *exit_status = EXIT_FDS;
4129 return log_exec_error_errno(context, params, r, "Failed to get OpenFile= file descriptors: %m");
4130 }
4131
4132 int keep_fds[n_fds + 3];
1eeaa93d 4133 memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
75689fb2
LB
4134 n_keep_fds = n_fds;
4135
5a5fdfe3 4136 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
75689fb2
LB
4137 if (r < 0) {
4138 *exit_status = EXIT_FDS;
5a5fdfe3 4139 return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
75689fb2
LB
4140 }
4141
4142#if HAVE_LIBBPF
5a5fdfe3
MY
4143 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_outer_map_fd);
4144 if (r < 0) {
4145 *exit_status = EXIT_FDS;
4146 return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
75689fb2
LB
4147 }
4148#endif
4149
4150 r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
4151 if (r < 0) {
4152 *exit_status = EXIT_FDS;
4153 return log_exec_error_errno(context, params, r, "Failed to close unwanted file descriptors: %m");
4154 }
4155
4156 if (!context->same_pgrp &&
4157 setsid() < 0) {
4158 *exit_status = EXIT_SETSID;
4159 return log_exec_error_errno(context, params, errno, "Failed to create new process session: %m");
4160 }
4161
4162 exec_context_tty_reset(context, params);
4163
4164 if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
4165 _cleanup_free_ char *cmdline = NULL;
4166
4167 cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
4168 if (!cmdline) {
4169 *exit_status = EXIT_MEMORY;
4170 return log_oom();
4171 }
4172
4173 r = ask_for_confirmation(context, params, cmdline);
4174 if (r != CONFIRM_EXECUTE) {
4175 if (r == CONFIRM_PRETEND_SUCCESS) {
4176 *exit_status = EXIT_SUCCESS;
4177 return 0;
4178 }
4179
4180 *exit_status = EXIT_CONFIRM;
4181 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ECANCELED),
4182 "Execution cancelled by the user");
4183 }
4184 }
4185
4186 /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4187 * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4188 * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4189 * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4190 * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4191 if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
4192 setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
4193 *exit_status = EXIT_MEMORY;
4194 return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
4195 }
4196
4197 if (context->dynamic_user && runtime && runtime->dynamic_creds) {
4198 _cleanup_strv_free_ char **suggested_paths = NULL;
4199
4200 /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4201 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4202 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
4203 *exit_status = EXIT_USER;
4204 return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
4205 }
4206
4207 r = compile_suggested_paths(context, params, &suggested_paths);
4208 if (r < 0) {
4209 *exit_status = EXIT_MEMORY;
4210 return log_oom();
4211 }
4212
4213 r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
4214 if (r < 0) {
4215 *exit_status = EXIT_USER;
4216 if (r == -EILSEQ)
4217 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
4218 "Failed to update dynamic user credentials: User or group with specified name already exists.");
4219 return log_exec_error_errno(context, params, r, "Failed to update dynamic user credentials: %m");
4220 }
4221
4222 if (!uid_is_valid(uid)) {
4223 *exit_status = EXIT_USER;
4224 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
4225 }
4226
4227 if (!gid_is_valid(gid)) {
4228 *exit_status = EXIT_USER;
4229 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
4230 }
4231
4232 if (runtime->dynamic_creds->user)
4233 username = runtime->dynamic_creds->user->name;
4234
4235 } else {
4236 if (context->user) {
4237 r = get_fixed_user(context->user, &username, &uid, &gid, &home, &shell);
4238 if (r < 0) {
4239 *exit_status = EXIT_USER;
4240 return log_exec_error_errno(context, params, r, "Failed to determine user credentials: %m");
4241 }
4242 }
4243
4244 if (context->group) {
4245 r = get_fixed_group(context->group, &groupname, &gid);
4246 if (r < 0) {
4247 *exit_status = EXIT_GROUP;
4248 return log_exec_error_errno(context, params, r, "Failed to determine group credentials: %m");
4249 }
4250 }
4251 }
4252
4253 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4254 r = get_supplementary_groups(context, username, groupname, gid,
4255 &supplementary_gids, &ngids);
4256 if (r < 0) {
4257 *exit_status = EXIT_GROUP;
4258 return log_exec_error_errno(context, params, r, "Failed to determine supplementary groups: %m");
4259 }
4260
4261 r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
4262 if (r < 0) {
4263 *exit_status = EXIT_USER;
4264 return log_exec_error_errno(context, params, r, "Failed to send user credentials to PID1: %m");
4265 }
4266
4267 params->user_lookup_fd = safe_close(params->user_lookup_fd);
4268
4269 r = acquire_home(context, uid, &home, &home_buffer);
4270 if (r < 0) {
4271 *exit_status = EXIT_CHDIR;
4272 return log_exec_error_errno(context, params, r, "Failed to determine $HOME for user: %m");
4273 }
4274
4275 /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4276 if (socket_fd >= 0)
4277 (void) fd_nonblock(socket_fd, false);
4278
4279 /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4280 * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4281 if (params->cgroup_path) {
4282 _cleanup_free_ char *p = NULL;
4283
4284 r = exec_params_get_cgroup_path(params, cgroup_context, &p);
4285 if (r < 0) {
4286 *exit_status = EXIT_CGROUP;
4287 return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
4288 }
4289
4290 r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
4291 if (r == -EUCLEAN) {
4292 *exit_status = EXIT_CGROUP;
4293 return log_exec_error_errno(context, params, r, "Failed to attach process to cgroup %s "
4294 "because the cgroup or one of its parents or "
4295 "siblings is in the threaded mode: %m", p);
4296 }
4297 if (r < 0) {
4298 *exit_status = EXIT_CGROUP;
4299 return log_exec_error_errno(context, params, r, "Failed to attach to cgroup %s: %m", p);
4300 }
4301 }
4302
4303 if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
4304 r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
4305 if (r < 0) {
4306 *exit_status = EXIT_NETWORK;
4307 return log_exec_error_errno(context, params, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
4308 }
4309 }
4310
4311 if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
4312 r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
4313 if (r < 0) {
4314 *exit_status = EXIT_NAMESPACE;
4315 return log_exec_error_errno(context, params, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
4316 }
4317 }
4318
4319 r = setup_input(context, params, socket_fd, named_iofds);
4320 if (r < 0) {
4321 *exit_status = EXIT_STDIN;
4322 return log_exec_error_errno(context, params, r, "Failed to set up standard input: %m");
4323 }
4324
4325 r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
4326 if (r < 0) {
4327 *exit_status = EXIT_STDOUT;
4328 return log_exec_error_errno(context, params, r, "Failed to set up standard output: %m");
4329 }
4330
4331 r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
4332 if (r < 0) {
4333 *exit_status = EXIT_STDERR;
4334 return log_exec_error_errno(context, params, r, "Failed to set up standard error output: %m");
4335 }
4336
4337 if (context->oom_score_adjust_set) {
4338 /* When we can't make this change due to EPERM, then let's silently skip over it. User
4339 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4340 r = set_oom_score_adjust(context->oom_score_adjust);
4341 if (ERRNO_IS_NEG_PRIVILEGE(r))
4342 log_exec_debug_errno(context, params, r,
4343 "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
4344 else if (r < 0) {
4345 *exit_status = EXIT_OOM_ADJUST;
4346 return log_exec_error_errno(context, params, r, "Failed to adjust OOM setting: %m");
4347 }
4348 }
4349
4350 if (context->coredump_filter_set) {
4351 r = set_coredump_filter(context->coredump_filter);
4352 if (ERRNO_IS_NEG_PRIVILEGE(r))
4353 log_exec_debug_errno(context, params, r, "Failed to adjust coredump_filter, ignoring: %m");
4354 else if (r < 0) {
4355 *exit_status = EXIT_LIMITS;
4356 return log_exec_error_errno(context, params, r, "Failed to adjust coredump_filter: %m");
4357 }
4358 }
4359
4360 if (context->nice_set) {
4361 r = setpriority_closest(context->nice);
4362 if (r < 0) {
4363 *exit_status = EXIT_NICE;
4364 return log_exec_error_errno(context, params, r, "Failed to set up process scheduling priority (nice level): %m");
4365 }
4366 }
4367
4368 if (context->cpu_sched_set) {
4369 struct sched_param param = {
4370 .sched_priority = context->cpu_sched_priority,
4371 };
4372
4373 r = sched_setscheduler(0,
4374 context->cpu_sched_policy |
4375 (context->cpu_sched_reset_on_fork ?
4376 SCHED_RESET_ON_FORK : 0),
4377 &param);
4378 if (r < 0) {
4379 *exit_status = EXIT_SETSCHEDULER;
4380 return log_exec_error_errno(context, params, errno, "Failed to set up CPU scheduling: %m");
4381 }
4382 }
4383
4384 if (context->cpu_affinity_from_numa || context->cpu_set.set) {
4385 _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
4386 const CPUSet *cpu_set;
4387
4388 if (context->cpu_affinity_from_numa) {
4389 r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
4390 if (r < 0) {
4391 *exit_status = EXIT_CPUAFFINITY;
4392 return log_exec_error_errno(context, params, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
4393 }
4394
4395 cpu_set = &converted_cpu_set;
4396 } else
4397 cpu_set = &context->cpu_set;
4398
4399 if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
4400 *exit_status = EXIT_CPUAFFINITY;
4401 return log_exec_error_errno(context, params, errno, "Failed to set up CPU affinity: %m");
4402 }
4403 }
4404
4405 if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
4406 r = apply_numa_policy(&context->numa_policy);
4407 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
4408 log_exec_debug_errno(context, params, r, "NUMA support not available, ignoring.");
4409 else if (r < 0) {
4410 *exit_status = EXIT_NUMA_POLICY;
4411 return log_exec_error_errno(context, params, r, "Failed to set NUMA memory policy: %m");
4412 }
4413 }
4414
4415 if (context->ioprio_set)
4416 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
4417 *exit_status = EXIT_IOPRIO;
4418 return log_exec_error_errno(context, params, errno, "Failed to set up IO scheduling priority: %m");
4419 }
4420
4421 if (context->timer_slack_nsec != NSEC_INFINITY)
4422 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
4423 *exit_status = EXIT_TIMERSLACK;
4424 return log_exec_error_errno(context, params, errno, "Failed to set up timer slack: %m");
4425 }
4426
4427 if (context->personality != PERSONALITY_INVALID) {
4428 r = safe_personality(context->personality);
4429 if (r < 0) {
4430 *exit_status = EXIT_PERSONALITY;
4431 return log_exec_error_errno(context, params, r, "Failed to set up execution domain (personality): %m");
4432 }
4433 }
4434
de3612db 4435#if ENABLE_UTMP
75689fb2
LB
4436 if (context->utmp_id) {
4437 const char *line = context->tty_path ?
4438 (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
4439 NULL;
4440 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
4441 line,
4442 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
4443 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
4444 USER_PROCESS,
4445 username);
4446 }
de3612db 4447#endif
75689fb2
LB
4448
4449 if (uid_is_valid(uid)) {
4450 r = chown_terminal(STDIN_FILENO, uid);
4451 if (r < 0) {
4452 *exit_status = EXIT_STDIN;
4453 return log_exec_error_errno(context, params, r, "Failed to change ownership of terminal: %m");
4454 }
4455 }
4456
4457 if (params->cgroup_path) {
4458 /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
4459 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
4460 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
4461 * touch a single hierarchy too. */
4462
4463 if (params->flags & EXEC_CGROUP_DELEGATE) {
4464 _cleanup_free_ char *p = NULL;
4465
4466 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
4467 if (r < 0) {
4468 *exit_status = EXIT_CGROUP;
4469 return log_exec_error_errno(context, params, r, "Failed to adjust control group access: %m");
4470 }
4471
4472 r = exec_params_get_cgroup_path(params, cgroup_context, &p);
4473 if (r < 0) {
4474 *exit_status = EXIT_CGROUP;
4475 return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
4476 }
4477 if (r > 0) {
4478 r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
4479 if (r < 0) {
4480 *exit_status = EXIT_CGROUP;
4481 return log_exec_error_errno(context, params, r, "Failed to adjust control subgroup access: %m");
4482 }
4483 }
4484 }
4485
4486 if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
4487 if (cgroup_context_want_memory_pressure(cgroup_context)) {
4488 r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
4489 if (r < 0) {
4490 *exit_status = EXIT_MEMORY;
4491 return log_oom();
4492 }
4493
4494 r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
4495 if (r < 0) {
4496 log_exec_full_errno(context, params, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
4497 "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
4498 memory_pressure_path = mfree(memory_pressure_path);
4499 }
4500 } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_OFF) {
4501 memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
4502 if (!memory_pressure_path) {
4503 *exit_status = EXIT_MEMORY;
4504 return log_oom();
4505 }
4506 }
4507 }
4508 }
4509
4510 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
4511
4512 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
4513 r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
4514 if (r < 0)
4515 return log_exec_error_errno(context, params, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
4516 }
4517
4518 if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
4519 r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
4520 if (r < 0) {
4521 *exit_status = EXIT_CREDENTIALS;
4522 return log_exec_error_errno(context, params, r, "Failed to set up credentials: %m");
4523 }
4524 }
4525
4526 r = build_environment(
4527 context,
4528 params,
4529 cgroup_context,
4530 n_fds,
75689fb2
LB
4531 home,
4532 username,
4533 shell,
4534 journal_stream_dev,
4535 journal_stream_ino,
4536 memory_pressure_path,
4537 &our_env);
4538 if (r < 0) {
4539 *exit_status = EXIT_MEMORY;
4540 return log_oom();
4541 }
4542
4543 r = build_pass_environment(context, &pass_env);
4544 if (r < 0) {
4545 *exit_status = EXIT_MEMORY;
4546 return log_oom();
4547 }
4548
4549 /* The $PATH variable is set to the default path in params->environment. However, this is overridden
4550 * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
4551 * not specify PATH but the unit has ExecSearchPath. */
4552 if (!strv_isempty(context->exec_search_path)) {
4553 _cleanup_free_ char *joined = NULL;
4554
4555 joined = strv_join(context->exec_search_path, ":");
4556 if (!joined) {
4557 *exit_status = EXIT_MEMORY;
4558 return log_oom();
4559 }
4560
4561 r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
4562 if (r < 0) {
4563 *exit_status = EXIT_MEMORY;
4564 return log_oom();
4565 }
4566 }
4567
4568 accum_env = strv_env_merge(params->environment,
4569 our_env,
4570 joined_exec_search_path,
4571 pass_env,
4572 context->environment,
4573 params->files_env);
4574 if (!accum_env) {
4575 *exit_status = EXIT_MEMORY;
4576 return log_oom();
4577 }
4578 accum_env = strv_env_clean(accum_env);
4579
4580 (void) umask(context->umask);
4581
4582 r = setup_keyring(context, params, uid, gid);
4583 if (r < 0) {
4584 *exit_status = EXIT_KEYRING;
4585 return log_exec_error_errno(context, params, r, "Failed to set up kernel keyring: %m");
4586 }
4587
4588 /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
4589 * from it. */
4590 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
4591
4592 /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked
4593 * for it, and the kernel doesn't actually support ambient caps. */
4594 needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
4595
4596 /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
4597 * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not
4598 * desired. */
4599 if (needs_ambient_hack)
4600 needs_setuid = false;
4601 else
4602 needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
4603
4604 uint64_t capability_ambient_set = context->capability_ambient_set;
4605
4606 if (needs_sandboxing) {
4607 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
4608 * /sys being present. The actual MAC context application will happen later, as late as
4609 * possible, to avoid impacting our own code paths. */
4610
4611#if HAVE_SELINUX
4612 use_selinux = mac_selinux_use();
4613#endif
4614#if ENABLE_SMACK
4615 use_smack = mac_smack_use();
4616#endif
4617#if HAVE_APPARMOR
4618 use_apparmor = mac_apparmor_use();
4619#endif
4620 }
4621
4622 if (needs_sandboxing) {
4623 int which_failed;
4624
4625 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
4626 * is set here. (See below.) */
4627
4628 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
4629 if (r < 0) {
4630 *exit_status = EXIT_LIMITS;
4631 return log_exec_error_errno(context, params, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
4632 }
4633 }
4634
4635 if (needs_setuid && context->pam_name && username) {
6634e66d 4636 /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
75689fb2
LB
4637 * wins here. (See above.) */
4638
4639 /* All fds passed in the fds array will be closed in the pam child process. */
5863f1da 4640 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, params->fds, n_fds, params->exec_fd);
75689fb2
LB
4641 if (r < 0) {
4642 *exit_status = EXIT_PAM;
4643 return log_exec_error_errno(context, params, r, "Failed to set up PAM session: %m");
4644 }
4645
4646 if (ambient_capabilities_supported()) {
4647 uint64_t ambient_after_pam;
4648
4649 /* PAM modules might have set some ambient caps. Query them here and merge them into
4650 * the caps we want to set in the end, so that we don't end up unsetting them. */
4651 r = capability_get_ambient(&ambient_after_pam);
4652 if (r < 0) {
4653 *exit_status = EXIT_CAPABILITIES;
4654 return log_exec_error_errno(context, params, r, "Failed to query ambient caps: %m");
4655 }
4656
4657 capability_ambient_set |= ambient_after_pam;
4658 }
4659
4660 ngids_after_pam = getgroups_alloc(&gids_after_pam);
4661 if (ngids_after_pam < 0) {
dbc0342e 4662 *exit_status = EXIT_GROUP;
75689fb2
LB
4663 return log_exec_error_errno(context, params, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
4664 }
4665 }
4666
4667 if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
4668 /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
4669 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
6634e66d 4670 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
75689fb2
LB
4671
4672 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4673 /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
4674 * the actual requested operations fail (or silently continue). */
4675 if (r < 0 && context->private_users) {
4676 *exit_status = EXIT_USER;
4677 return log_exec_error_errno(context, params, r, "Failed to set up user namespacing for unprivileged user: %m");
4678 }
4679 if (r < 0)
4680 log_exec_info_errno(context, params, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
4681 else
4682 userns_set_up = true;
4683 }
4684
4685 if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
4686
4687 /* Try to enable network namespacing if network namespacing is available and we have
4688 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
4689 * new network namespace. And if we don't have that, then we could only create a network
4690 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4691 if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
4692 r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
4693 if (ERRNO_IS_NEG_PRIVILEGE(r))
4694 log_exec_notice_errno(context, params, r,
4695 "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
4696 else if (r < 0) {
4697 *exit_status = EXIT_NETWORK;
4698 return log_exec_error_errno(context, params, r, "Failed to set up network namespacing: %m");
4699 }
4700 } else if (context->network_namespace_path) {
4701 *exit_status = EXIT_NETWORK;
4702 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
4703 "NetworkNamespacePath= is not supported, refusing.");
4704 } else
4705 log_exec_notice(context, params, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
4706 }
4707
4708 if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
4709
4710 if (ns_type_supported(NAMESPACE_IPC)) {
4711 r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
4712 if (r == -EPERM)
4713 log_exec_warning_errno(context, params, r,
4714 "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
4715 else if (r < 0) {
4716 *exit_status = EXIT_NAMESPACE;
4717 return log_exec_error_errno(context, params, r, "Failed to set up IPC namespacing: %m");
4718 }
4719 } else if (context->ipc_namespace_path) {
4720 *exit_status = EXIT_NAMESPACE;
4721 return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
4722 "IPCNamespacePath= is not supported, refusing.");
4723 } else
4724 log_exec_warning(context, params, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
4725 }
4726
4727 if (needs_mount_namespace) {
4728 _cleanup_free_ char *error_path = NULL;
4729
4730 r = apply_mount_namespace(command->flags, context, params, runtime, memory_pressure_path, &error_path);
4731 if (r < 0) {
4732 *exit_status = EXIT_NAMESPACE;
4733 return log_exec_error_errno(context, params, r, "Failed to set up mount namespacing%s%s: %m",
4734 error_path ? ": " : "", strempty(error_path));
4735 }
4736 }
4737
4738 if (needs_sandboxing) {
4739 r = apply_protect_hostname(context, params, exit_status);
4740 if (r < 0)
4741 return r;
4742 }
4743
4744 if (context->memory_ksm >= 0)
4745 if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm) < 0) {
4746 if (ERRNO_IS_NOT_SUPPORTED(errno))
4747 log_exec_debug_errno(context,
4748 params,
4749 errno,
4750 "KSM support not available, ignoring.");
4751 else {
4752 *exit_status = EXIT_KSM;
4753 return log_exec_error_errno(context, params, errno, "Failed to set KSM: %m");
4754 }
4755 }
4756
4757 /* Drop groups as early as possible.
6634e66d 4758 * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
75689fb2
LB
4759 * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
4760 if (needs_setuid) {
4761 _cleanup_free_ gid_t *gids_to_enforce = NULL;
4762 int ngids_to_enforce = 0;
4763
4764 ngids_to_enforce = merge_gid_lists(supplementary_gids,
4765 ngids,
4766 gids_after_pam,
4767 ngids_after_pam,
4768 &gids_to_enforce);
4769 if (ngids_to_enforce < 0) {
dbc0342e 4770 *exit_status = EXIT_GROUP;
75689fb2
LB
4771 return log_exec_error_errno(context, params,
4772 ngids_to_enforce,
4773 "Failed to merge group lists. Group membership might be incorrect: %m");
4774 }
4775
4776 r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
4777 if (r < 0) {
4778 *exit_status = EXIT_GROUP;
4779 return log_exec_error_errno(context, params, r, "Changing group credentials failed: %m");
4780 }
4781 }
4782
4783 /* If the user namespace was not set up above, try to do it now.
4784 * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
4785 * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
4786 * case of mount namespaces being less privileged when the mount point list is copied from a
4787 * different user namespace). */
4788
4789 if (needs_sandboxing && context->private_users && !userns_set_up) {
4790 r = setup_private_users(saved_uid, saved_gid, uid, gid);
4791 if (r < 0) {
4792 *exit_status = EXIT_USER;
4793 return log_exec_error_errno(context, params, r, "Failed to set up user namespacing: %m");
4794 }
4795 }
4796
4797 /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
4798 * shall execute. */
4799
4800 _cleanup_free_ char *executable = NULL;
4801 _cleanup_close_ int executable_fd = -EBADF;
4802 r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
4803 if (r < 0) {
4804 if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
4805 log_exec_struct_errno(context, params, LOG_INFO, r,
4806 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4807 LOG_EXEC_INVOCATION_ID(params),
4808 LOG_EXEC_MESSAGE(params,
4809 "Executable %s missing, skipping: %m",
4810 command->path),
4811 "EXECUTABLE=%s", command->path);
4812 *exit_status = EXIT_SUCCESS;
4813 return 0;
4814 }
4815
4816 *exit_status = EXIT_EXEC;
4817 return log_exec_struct_errno(context, params, LOG_INFO, r,
4818 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
4819 LOG_EXEC_INVOCATION_ID(params),
4820 LOG_EXEC_MESSAGE(params,
4821 "Failed to locate executable %s: %m",
4822 command->path),
4823 "EXECUTABLE=%s", command->path);
4824 }
4825
5a5fdfe3 4826 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
75689fb2
LB
4827 if (r < 0) {
4828 *exit_status = EXIT_FDS;
5a5fdfe3 4829 return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
75689fb2
LB
4830 }
4831
4832#if HAVE_SELINUX
4833 if (needs_sandboxing && use_selinux && params->selinux_context_net) {
4834 int fd = -EBADF;
4835
4836 if (socket_fd >= 0)
4837 fd = socket_fd;
4838 else if (params->n_socket_fds == 1)
4839 /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
4840 * use context from that fd to compute the label. */
4841 fd = params->fds[0];
4842
4843 if (fd >= 0) {
4844 r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
4845 if (r < 0) {
4846 if (!context->selinux_context_ignore) {
4847 *exit_status = EXIT_SELINUX_CONTEXT;
4848 return log_exec_error_errno(context,
4849 params,
4850 r,
4851 "Failed to determine SELinux context: %m");
4852 }
4853 log_exec_debug_errno(context,
4854 params,
4855 r,
4856 "Failed to determine SELinux context, ignoring: %m");
4857 }
4858 }
4859 }
4860#endif
4861
4862 /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
4863 * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
4864 * more. We do keep exec_fd however, if we have it, since we need to keep it open until the final
7b6d3dcd
LB
4865 * execve(). But first, close the remaining sockets in the context objects. */
4866
4867 exec_runtime_close(runtime);
4868 exec_params_close(params);
75689fb2
LB
4869
4870 r = close_all_fds(keep_fds, n_keep_fds);
4871 if (r >= 0)
1eeaa93d 4872 r = shift_fds(params->fds, n_fds);
75689fb2 4873 if (r >= 0)
1eeaa93d 4874 r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
75689fb2
LB
4875 if (r < 0) {
4876 *exit_status = EXIT_FDS;
4877 return log_exec_error_errno(context, params, r, "Failed to adjust passed file descriptors: %m");
4878 }
4879
4880 /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
4881 * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
4882 * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
4883 * came this far. */
4884
4885 secure_bits = context->secure_bits;
4886
4887 if (needs_sandboxing) {
4888 uint64_t bset;
4889
4890 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
4891 * (Note this is placed after the general resource limit initialization, see above, in order
4892 * to take precedence.) */
4893 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
4894 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
4895 *exit_status = EXIT_LIMITS;
4896 return log_exec_error_errno(context, params, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
4897 }
4898 }
4899
4900#if ENABLE_SMACK
4901 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
4902 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
4903 if (use_smack && context->smack_process_label) {
4904 r = setup_smack(params, context, executable_fd);
4905 if (r < 0 && !context->smack_process_label_ignore) {
4906 *exit_status = EXIT_SMACK_PROCESS_LABEL;
4907 return log_exec_error_errno(context, params, r, "Failed to set SMACK process label: %m");
4908 }
4909 }
4910#endif
4911
4912 bset = context->capability_bounding_set;
4913 /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
4914 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
4915 * instead of us doing that */
4916 if (needs_ambient_hack)
4917 bset |= (UINT64_C(1) << CAP_SETPCAP) |
4918 (UINT64_C(1) << CAP_SETUID) |
4919 (UINT64_C(1) << CAP_SETGID);
4920
24832d10
ILG
4921#if HAVE_SECCOMP
4922 /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
4923 * keep the needed privileges to apply it even if we're not root. */
4924 if (needs_setuid &&
4925 uid_is_valid(uid) &&
4926 context_has_seccomp(context) &&
4927 seccomp_allows_drop_privileges(context)) {
4928 keep_seccomp_privileges = true;
4929
4930 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
4931 *exit_status = EXIT_USER;
4932 return log_exec_error_errno(context, params, errno, "Failed to enable keep capabilities flag: %m");
4933 }
4934
4935 /* Save the current bounding set so we can restore it after applying the seccomp
4936 * filter */
4937 saved_bset = bset;
4938 bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
4939 (UINT64_C(1) << CAP_SETPCAP);
4940 }
4941#endif
4942
75689fb2
LB
4943 if (!cap_test_all(bset)) {
4944 r = capability_bounding_set_drop(bset, /* right_now= */ false);
4945 if (r < 0) {
4946 *exit_status = EXIT_CAPABILITIES;
4947 return log_exec_error_errno(context, params, r, "Failed to drop capabilities: %m");
4948 }
4949 }
4950
4951 /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
4952 * keep-caps set.
4953 *
4954 * To be able to raise the ambient capabilities after setresuid() they have to be added to
4955 * the inherited set and keep caps has to be set (done in enforce_user()). After setresuid()
4956 * the ambient capabilities can be raised as they are present in the permitted and
4957 * inhertiable set. However it is possible that someone wants to set ambient capabilities
4958 * without changing the user, so we also set the ambient capabilities here.
4959 *
4960 * The requested ambient capabilities are raised in the inheritable set if the second
4961 * argument is true. */
4962 if (!needs_ambient_hack) {
4963 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
4964 if (r < 0) {
4965 *exit_status = EXIT_CAPABILITIES;
4966 return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (before UID change): %m");
4967 }
4968 }
4969 }
4970
4971 /* chroot to root directory first, before we lose the ability to chroot */
4972 r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
4973 if (r < 0)
4974 return log_exec_error_errno(context, params, r, "Chrooting to the requested root directory failed: %m");
4975
4976 if (needs_setuid) {
4977 if (uid_is_valid(uid)) {
4978 r = enforce_user(context, uid, capability_ambient_set);
4979 if (r < 0) {
4980 *exit_status = EXIT_USER;
4981 return log_exec_error_errno(context, params, r, "Failed to change UID to " UID_FMT ": %m", uid);
4982 }
4983
24832d10 4984 if (keep_seccomp_privileges) {
f4a35f2a
LB
4985 if (!FLAGS_SET(capability_ambient_set, (UINT64_C(1) << CAP_SETUID))) {
4986 r = drop_capability(CAP_SETUID);
4987 if (r < 0) {
4988 *exit_status = EXIT_USER;
4989 return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETUID: %m");
4990 }
24832d10
ILG
4991 }
4992
4993 r = keep_capability(CAP_SYS_ADMIN);
4994 if (r < 0) {
4995 *exit_status = EXIT_USER;
4996 return log_exec_error_errno(context, params, r, "Failed to keep CAP_SYS_ADMIN: %m");
4997 }
4998
4999 r = keep_capability(CAP_SETPCAP);
5000 if (r < 0) {
5001 *exit_status = EXIT_USER;
5002 return log_exec_error_errno(context, params, r, "Failed to keep CAP_SETPCAP: %m");
5003 }
5004 }
5005
75689fb2
LB
5006 if (!needs_ambient_hack && capability_ambient_set != 0) {
5007
5008 /* Raise the ambient capabilities after user change. */
5009 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
5010 if (r < 0) {
5011 *exit_status = EXIT_CAPABILITIES;
5012 return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (after UID change): %m");
5013 }
5014 }
5015 }
5016 }
5017
5018 /* Apply working directory here, because the working directory might be on NFS and only the user running
5019 * this service might have the correct privilege to change to the working directory */
5020 r = apply_working_directory(context, params, runtime, home, exit_status);
5021 if (r < 0)
5022 return log_exec_error_errno(context, params, r, "Changing to the requested working directory failed: %m");
5023
5024 if (needs_sandboxing) {
5025 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5026 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5027 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5028 * are restricted. */
5029
5030#if HAVE_SELINUX
5031 if (use_selinux) {
5032 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5033
5034 if (exec_context) {
5035 r = setexeccon(exec_context);
5036 if (r < 0) {
5037 if (!context->selinux_context_ignore) {
5038 *exit_status = EXIT_SELINUX_CONTEXT;
5039 return log_exec_error_errno(context, params, r, "Failed to change SELinux context to %s: %m", exec_context);
5040 }
5041 log_exec_debug_errno(context,
5042 params,
5043 r,
5044 "Failed to change SELinux context to %s, ignoring: %m",
5045 exec_context);
5046 }
5047 }
5048 }
5049#endif
5050
5051#if HAVE_APPARMOR
5052 if (use_apparmor && context->apparmor_profile) {
5053 r = aa_change_onexec(context->apparmor_profile);
5054 if (r < 0 && !context->apparmor_profile_ignore) {
5055 *exit_status = EXIT_APPARMOR_PROFILE;
5056 return log_exec_error_errno(context,
5057 params,
5058 errno,
5059 "Failed to prepare AppArmor profile change to %s: %m",
5060 context->apparmor_profile);
5061 }
5062 }
5063#endif
5064
5065 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5066 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5067 * requires CAP_SETPCAP. */
5068 if (prctl(PR_GET_SECUREBITS) != secure_bits) {
5069 /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5070 * effective set here.
5071 *
5072 * The effective set is overwritten during execve() with the following values:
5073 *
5074 * - ambient set (for non-root processes)
5075 *
5076 * - (inheritable | bounding) set for root processes)
5077 *
5078 * Hence there is no security impact to raise it in the effective set before execve
5079 */
5080 r = capability_gain_cap_setpcap(/* return_caps= */ NULL);
5081 if (r < 0) {
5082 *exit_status = EXIT_CAPABILITIES;
5083 return log_exec_error_errno(context, params, r, "Failed to gain CAP_SETPCAP for setting secure bits");
5084 }
5085 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
5086 *exit_status = EXIT_SECUREBITS;
5087 return log_exec_error_errno(context, params, errno, "Failed to set process secure bits: %m");
5088 }
5089 }
5090
5091 if (context_has_no_new_privileges(context))
5092 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
5093 *exit_status = EXIT_NO_NEW_PRIVILEGES;
5094 return log_exec_error_errno(context, params, errno, "Failed to disable new privileges: %m");
5095 }
5096
5097#if HAVE_SECCOMP
5098 r = apply_address_families(context, params);
5099 if (r < 0) {
5100 *exit_status = EXIT_ADDRESS_FAMILIES;
5101 return log_exec_error_errno(context, params, r, "Failed to restrict address families: %m");
5102 }
5103
5104 r = apply_memory_deny_write_execute(context, params);
5105 if (r < 0) {
5106 *exit_status = EXIT_SECCOMP;
5107 return log_exec_error_errno(context, params, r, "Failed to disable writing to executable memory: %m");
5108 }
5109
5110 r = apply_restrict_realtime(context, params);
5111 if (r < 0) {
5112 *exit_status = EXIT_SECCOMP;
5113 return log_exec_error_errno(context, params, r, "Failed to apply realtime restrictions: %m");
5114 }
5115
5116 r = apply_restrict_suid_sgid(context, params);
5117 if (r < 0) {
5118 *exit_status = EXIT_SECCOMP;
5119 return log_exec_error_errno(context, params, r, "Failed to apply SUID/SGID restrictions: %m");
5120 }
5121
5122 r = apply_restrict_namespaces(context, params);
5123 if (r < 0) {
5124 *exit_status = EXIT_SECCOMP;
5125 return log_exec_error_errno(context, params, r, "Failed to apply namespace restrictions: %m");
5126 }
5127
5128 r = apply_protect_sysctl(context, params);
5129 if (r < 0) {
5130 *exit_status = EXIT_SECCOMP;
5131 return log_exec_error_errno(context, params, r, "Failed to apply sysctl restrictions: %m");
5132 }
5133
5134 r = apply_protect_kernel_modules(context, params);
5135 if (r < 0) {
5136 *exit_status = EXIT_SECCOMP;
5137 return log_exec_error_errno(context, params, r, "Failed to apply module loading restrictions: %m");
5138 }
5139
5140 r = apply_protect_kernel_logs(context, params);
5141 if (r < 0) {
5142 *exit_status = EXIT_SECCOMP;
5143 return log_exec_error_errno(context, params, r, "Failed to apply kernel log restrictions: %m");
5144 }
5145
5146 r = apply_protect_clock(context, params);
5147 if (r < 0) {
5148 *exit_status = EXIT_SECCOMP;
5149 return log_exec_error_errno(context, params, r, "Failed to apply clock restrictions: %m");
5150 }
5151
5152 r = apply_private_devices(context, params);
5153 if (r < 0) {
5154 *exit_status = EXIT_SECCOMP;
5155 return log_exec_error_errno(context, params, r, "Failed to set up private devices: %m");
5156 }
5157
5158 r = apply_syscall_archs(context, params);
5159 if (r < 0) {
5160 *exit_status = EXIT_SECCOMP;
5161 return log_exec_error_errno(context, params, r, "Failed to apply syscall architecture restrictions: %m");
5162 }
5163
5164 r = apply_lock_personality(context, params);
5165 if (r < 0) {
5166 *exit_status = EXIT_SECCOMP;
5167 return log_exec_error_errno(context, params, r, "Failed to lock personalities: %m");
5168 }
5169
5170 r = apply_syscall_log(context, params);
5171 if (r < 0) {
5172 *exit_status = EXIT_SECCOMP;
5173 return log_exec_error_errno(context, params, r, "Failed to apply system call log filters: %m");
5174 }
24832d10 5175#endif
75689fb2 5176
24832d10
ILG
5177#if HAVE_LIBBPF
5178 r = apply_restrict_filesystems(context, params);
5179 if (r < 0) {
5180 *exit_status = EXIT_BPF;
5181 return log_exec_error_errno(context, params, r, "Failed to restrict filesystems: %m");
5182 }
5183#endif
5184
5185#if HAVE_SECCOMP
86a1ee93 5186 /* This really should remain as close to the execve() as possible, to make sure our own code is affected
75689fb2
LB
5187 * by the filter as little as possible. */
5188 r = apply_syscall_filter(context, params, needs_ambient_hack);
5189 if (r < 0) {
5190 *exit_status = EXIT_SECCOMP;
5191 return log_exec_error_errno(context, params, r, "Failed to apply system call filters: %m");
5192 }
75689fb2 5193
24832d10
ILG
5194 if (keep_seccomp_privileges) {
5195 /* Restore the capability bounding set with what's expected from the service + the
5196 * ambient capabilities hack */
5197 if (!cap_test_all(saved_bset)) {
5198 r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
5199 if (r < 0) {
5200 *exit_status = EXIT_CAPABILITIES;
5201 return log_exec_error_errno(context, params, r, "Failed to drop bset capabilities: %m");
5202 }
5203 }
5204
5205 /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5206 * applications that use it. */
5207 if (!FLAGS_SET(saved_bset, (UINT64_C(1) << CAP_SYS_ADMIN))) {
5208 r = drop_capability(CAP_SYS_ADMIN);
5209 if (r < 0) {
5210 *exit_status = EXIT_USER;
5211 return log_exec_error_errno(context, params, r, "Failed to drop CAP_SYS_ADMIN: %m");
5212 }
5213 }
5214
5215 /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5216 * applications that use it. */
5217 if (!FLAGS_SET(saved_bset, (UINT64_C(1) << CAP_SETPCAP))) {
5218 r = drop_capability(CAP_SETPCAP);
5219 if (r < 0) {
5220 *exit_status = EXIT_USER;
5221 return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETPCAP: %m");
5222 }
5223 }
5224
5225 if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
5226 *exit_status = EXIT_USER;
5227 return log_exec_error_errno(context, params, errno, "Failed to drop keep capabilities flag: %m");
5228 }
75689fb2
LB
5229 }
5230#endif
5231
5232 }
5233
5234 if (!strv_isempty(context->unset_environment)) {
5235 char **ee = NULL;
5236
5237 ee = strv_env_delete(accum_env, 1, context->unset_environment);
5238 if (!ee) {
5239 *exit_status = EXIT_MEMORY;
5240 return log_oom();
5241 }
5242
5243 strv_free_and_replace(accum_env, ee);
5244 }
5245
5246 if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
5247 _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
5248
5249 r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
5250 if (r < 0) {
5251 *exit_status = EXIT_MEMORY;
5252 return log_exec_error_errno(context,
5253 params,
5254 r,
5255 "Failed to replace environment variables: %m");
5256 }
5257 final_argv = replaced_argv;
5258
5259 if (!strv_isempty(unset_variables)) {
5260 _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
5261 log_exec_warning(context,
5262 params,
5263 "Referenced but unset environment variable evaluates to an empty string: %s",
5264 strna(ju));
5265 }
5266
5267 if (!strv_isempty(bad_variables)) {
5268 _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
5269 log_exec_warning(context,
5270 params,
5271 "Invalid environment variable name evaluates to an empty string: %s",
5272 strna(jb));
5273 }
5274 } else
5275 final_argv = command->argv;
5276
5277 log_command_line(context, params, "Executing", executable, final_argv);
5278
5a5fdfe3 5279 if (params->exec_fd >= 0) {
75689fb2
LB
5280 uint8_t hot = 1;
5281
5282 /* We have finished with all our initializations. Let's now let the manager know that. From this point
5283 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5284
5a5fdfe3 5285 if (write(params->exec_fd, &hot, sizeof(hot)) < 0) {
75689fb2
LB
5286 *exit_status = EXIT_EXEC;
5287 return log_exec_error_errno(context, params, errno, "Failed to enable exec_fd: %m");
5288 }
5289 }
5290
5291 r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
5292
5a5fdfe3 5293 if (params->exec_fd >= 0) {
75689fb2
LB
5294 uint8_t hot = 0;
5295
5296 /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
5297 * that POLLHUP on it no longer means execve() succeeded. */
5298
5a5fdfe3 5299 if (write(params->exec_fd, &hot, sizeof(hot)) < 0) {
75689fb2
LB
5300 *exit_status = EXIT_EXEC;
5301 return log_exec_error_errno(context, params, errno, "Failed to disable exec_fd: %m");
5302 }
5303 }
5304
5305 *exit_status = EXIT_EXEC;
5306 return log_exec_error_errno(context, params, r, "Failed to execute %s: %m", executable);
5307}