]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
various: use _NEG_ macros to reduce indentation
[thirdparty/systemd.git] / src / core / execute.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
034c6ed7
LP
3#include <errno.h>
4#include <fcntl.h>
8dd4c05b 5#include <poll.h>
d251207d 6#include <sys/eventfd.h>
ac8db36c 7#include <sys/file.h>
f5947a5e 8#include <sys/ioctl.h>
f3e43635 9#include <sys/mman.h>
bb0c0d6f 10#include <sys/mount.h>
8dd4c05b 11#include <sys/personality.h>
94f04347 12#include <sys/prctl.h>
d2ffa389 13#include <sys/shm.h>
d2ffa389 14#include <sys/types.h>
8dd4c05b
LP
15#include <sys/un.h>
16#include <unistd.h>
023a4f67 17#include <utmpx.h>
5cb5a6ff 18
9c0c6701
DDM
19#include <linux/fs.h> /* Must be included after <sys/mount.h> */
20
349cc4a5 21#if HAVE_PAM
5b6319dc
LP
22#include <security/pam_appl.h>
23#endif
24
349cc4a5 25#if HAVE_SELINUX
7b52a628
MS
26#include <selinux/selinux.h>
27#endif
28
349cc4a5 29#if HAVE_SECCOMP
17df7223
LP
30#include <seccomp.h>
31#endif
32
349cc4a5 33#if HAVE_APPARMOR
eef65bf3
MS
34#include <sys/apparmor.h>
35#endif
36
24882e06 37#include "sd-messages.h"
8dd4c05b 38
bb0c0d6f 39#include "acl-util.h"
8dd4c05b 40#include "af-list.h"
b5efdb8a 41#include "alloc-util.h"
349cc4a5 42#if HAVE_APPARMOR
3ffd4af2
LP
43#include "apparmor-util.h"
44#endif
ee617a4e 45#include "argv-util.h"
8dd4c05b
LP
46#include "async.h"
47#include "barrier.h"
b1994387 48#include "bpf-lsm.h"
9c0c6701 49#include "btrfs-util.h"
8dd4c05b 50#include "cap-list.h"
430f0182 51#include "capability-util.h"
9c0c6701 52#include "chattr-util.h"
fdb3deca 53#include "cgroup-setup.h"
f461a28d 54#include "chase.h"
bb0c0d6f 55#include "chown-recursive.h"
28db6fbf 56#include "constants.h"
da681e1b 57#include "cpu-set-util.h"
43144be4 58#include "creds-util.h"
6a818c3c 59#include "data-fd-util.h"
686d13b9 60#include "env-file.h"
4d1a6904 61#include "env-util.h"
17df7223 62#include "errno-list.h"
8a62620e 63#include "escape.h"
3ffd4af2 64#include "execute.h"
8dd4c05b 65#include "exit-status.h"
3ffd4af2 66#include "fd-util.h"
bb0c0d6f 67#include "fileio.h"
f97b34a6 68#include "format-util.h"
7d50b32a 69#include "glob-util.h"
0389f4fa 70#include "hexdecoct.h"
c004493c 71#include "io-util.h"
032b3afb 72#include "ioprio-util.h"
0690160e 73#include "label-util.h"
9c0c6701 74#include "lock-util.h"
8dd4c05b
LP
75#include "log.h"
76#include "macro.h"
e8a565cb 77#include "manager.h"
2a341bb9 78#include "manager-dump.h"
0a970718 79#include "memory-util.h"
f5947a5e 80#include "missing_fs.h"
5bead76e 81#include "missing_ioprio.h"
7a114ed4 82#include "missing_prctl.h"
35cd0ba5 83#include "mkdir-label.h"
21935150 84#include "mount-util.h"
bb0c0d6f 85#include "mountpoint-util.h"
8dd4c05b 86#include "namespace.h"
6bedfcbb 87#include "parse-util.h"
8dd4c05b 88#include "path-util.h"
4d62ee55 89#include "proc-cmdline.h"
0b452006 90#include "process-util.h"
6bb00842 91#include "psi-util.h"
d3dcf4e3 92#include "random-util.h"
3989bdc1 93#include "recurse-dir.h"
78f22b97 94#include "rlimit-util.h"
8dd4c05b 95#include "rm-rf.h"
349cc4a5 96#if HAVE_SECCOMP
3ffd4af2
LP
97#include "seccomp-util.h"
98#endif
07d46372 99#include "securebits-util.h"
8dd4c05b 100#include "selinux-util.h"
24882e06 101#include "signal-util.h"
8dd4c05b 102#include "smack-util.h"
57b7a260 103#include "socket-util.h"
a2ab603c 104#include "sort-util.h"
fd63e712 105#include "special.h"
949befd3 106#include "stat-util.h"
8b43440b 107#include "string-table.h"
07630cea 108#include "string-util.h"
8dd4c05b 109#include "strv.h"
7ccbd1ae 110#include "syslog-util.h"
8dd4c05b 111#include "terminal-util.h"
bb0c0d6f 112#include "tmpfile-util.h"
566b7d23 113#include "umask-util.h"
2d3b784d 114#include "unit-serialize.h"
b1d4f8e1 115#include "user-util.h"
8dd4c05b 116#include "utmp-wtmp.h"
5cb5a6ff 117
e056b01d 118#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
31a7eb86 119#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
e6a26745 120
531dca78
LP
121#define SNDBUF_SIZE (8*1024*1024)
122
da6053d0 123static int shift_fds(int fds[], size_t n_fds) {
034c6ed7
LP
124 if (n_fds <= 0)
125 return 0;
126
a0d40ac5
LP
127 /* Modifies the fds array! (sorts it) */
128
034c6ed7
LP
129 assert(fds);
130
5b10116e
ZJS
131 for (int start = 0;;) {
132 int restart_from = -1;
034c6ed7 133
5b10116e 134 for (int i = start; i < (int) n_fds; i++) {
034c6ed7
LP
135 int nfd;
136
137 /* Already at right index? */
138 if (fds[i] == i+3)
139 continue;
140
3cc2aff1
LP
141 nfd = fcntl(fds[i], F_DUPFD, i + 3);
142 if (nfd < 0)
034c6ed7
LP
143 return -errno;
144
03e334a1 145 safe_close(fds[i]);
034c6ed7
LP
146 fds[i] = nfd;
147
148 /* Hmm, the fd we wanted isn't free? Then
ee33e53a 149 * let's remember that and try again from here */
034c6ed7
LP
150 if (nfd != i+3 && restart_from < 0)
151 restart_from = i;
152 }
153
154 if (restart_from < 0)
155 break;
156
157 start = restart_from;
158 }
159
160 return 0;
161}
162
cd48e23f
RP
163static int flags_fds(
164 const int fds[],
165 size_t n_socket_fds,
166 size_t n_fds,
167 bool nonblock) {
168
e2c76839 169 int r;
47a71eed
LP
170
171 if (n_fds <= 0)
172 return 0;
173
174 assert(fds);
175
9b141911
FB
176 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
177 * O_NONBLOCK only applies to socket activation though. */
47a71eed 178
5b10116e 179 for (size_t i = 0; i < n_fds; i++) {
47a71eed 180
9b141911
FB
181 if (i < n_socket_fds) {
182 r = fd_nonblock(fds[i], nonblock);
183 if (r < 0)
184 return r;
185 }
47a71eed 186
451a074f
LP
187 /* We unconditionally drop FD_CLOEXEC from the fds,
188 * since after all we want to pass these fds to our
189 * children */
47a71eed 190
3cc2aff1
LP
191 r = fd_cloexec(fds[i], false);
192 if (r < 0)
e2c76839 193 return r;
47a71eed
LP
194 }
195
196 return 0;
197}
198
1e22b5cd 199static const char *exec_context_tty_path(const ExecContext *context) {
80876c20
LP
200 assert(context);
201
1e22b5cd
LP
202 if (context->stdio_as_fds)
203 return NULL;
204
80876c20
LP
205 if (context->tty_path)
206 return context->tty_path;
207
208 return "/dev/console";
209}
210
4d62ee55 211static int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows, unsigned *ret_cols) {
4d62ee55
DDM
212 unsigned rows, cols;
213 const char *tty;
4d62ee55
DDM
214
215 assert(context);
216 assert(ret_rows);
217 assert(ret_cols);
218
219 rows = context->tty_rows;
220 cols = context->tty_cols;
221
222 tty = exec_context_tty_path(context);
29f5a5ae
DDM
223 if (tty)
224 (void) proc_cmdline_tty_size(tty, rows == UINT_MAX ? &rows : NULL, cols == UINT_MAX ? &cols : NULL);
4d62ee55
DDM
225
226 *ret_rows = rows;
227 *ret_cols = cols;
228
229 return 0;
230}
231
1e22b5cd 232static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
a0043bfa
ZJS
233 _cleanup_close_ int fd = -EBADF;
234 const char *path = exec_context_tty_path(ASSERT_PTR(context));
1e22b5cd 235
a0043bfa
ZJS
236 /* Take a lock around the device for the duration of the setup that we do here.
237 * systemd-vconsole-setup.service also takes the lock to avoid being interrupted.
238 * We open a new fd that will be closed automatically, and operate on it for convenience.
239 */
6ea832a2 240
a0043bfa
ZJS
241 if (p && p->stdin_fd >= 0) {
242 fd = xopenat_lock(p->stdin_fd, NULL,
243 O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY, 0, 0, LOCK_BSD, LOCK_EX);
244 if (fd < 0)
245 return;
246 } else if (path) {
247 fd = open_terminal(path, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
248 if (fd < 0)
249 return;
6ea832a2 250
a0043bfa
ZJS
251 if (lock_generic(fd, LOCK_BSD, LOCK_EX) < 0)
252 return;
253 } else
254 return; /* nothing to do */
6ea832a2 255
a0043bfa
ZJS
256 if (context->tty_vhangup)
257 (void) terminal_vhangup_fd(fd);
258
259 if (context->tty_reset)
260 (void) reset_terminal_fd(fd, true);
1e22b5cd 261
4d62ee55
DDM
262 if (p && p->stdin_fd >= 0) {
263 unsigned rows = context->tty_rows, cols = context->tty_cols;
264
265 (void) exec_context_tty_size(context, &rows, &cols);
266 (void) terminal_set_size_fd(p->stdin_fd, path, rows, cols);
267 }
51462135 268
1e22b5cd
LP
269 if (context->tty_vt_disallocate && path)
270 (void) vt_disallocate(path);
6ea832a2
LP
271}
272
6af760f3
LP
273static bool is_terminal_input(ExecInput i) {
274 return IN_SET(i,
275 EXEC_INPUT_TTY,
276 EXEC_INPUT_TTY_FORCE,
277 EXEC_INPUT_TTY_FAIL);
278}
279
3a1286b6 280static bool is_terminal_output(ExecOutput o) {
6af760f3
LP
281 return IN_SET(o,
282 EXEC_OUTPUT_TTY,
6af760f3
LP
283 EXEC_OUTPUT_KMSG_AND_CONSOLE,
284 EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
285}
286
aac8c0c3
LP
287static bool is_kmsg_output(ExecOutput o) {
288 return IN_SET(o,
289 EXEC_OUTPUT_KMSG,
290 EXEC_OUTPUT_KMSG_AND_CONSOLE);
291}
292
6af760f3
LP
293static bool exec_context_needs_term(const ExecContext *c) {
294 assert(c);
295
296 /* Return true if the execution context suggests we should set $TERM to something useful. */
297
298 if (is_terminal_input(c->std_input))
299 return true;
300
301 if (is_terminal_output(c->std_output))
302 return true;
303
304 if (is_terminal_output(c->std_error))
305 return true;
306
307 return !!c->tty_path;
3a1286b6
MS
308}
309
80876c20 310static int open_null_as(int flags, int nfd) {
046a82c1 311 int fd;
071830ff 312
80876c20 313 assert(nfd >= 0);
071830ff 314
613b411c
LP
315 fd = open("/dev/null", flags|O_NOCTTY);
316 if (fd < 0)
071830ff
LP
317 return -errno;
318
046a82c1 319 return move_fd(fd, nfd, false);
071830ff
LP
320}
321
91dd5f7c
LP
322static int connect_journal_socket(
323 int fd,
324 const char *log_namespace,
325 uid_t uid,
326 gid_t gid) {
327
524daa8c
ZJS
328 uid_t olduid = UID_INVALID;
329 gid_t oldgid = GID_INVALID;
91dd5f7c 330 const char *j;
524daa8c
ZJS
331 int r;
332
91dd5f7c
LP
333 j = log_namespace ?
334 strjoina("/run/systemd/journal.", log_namespace, "/stdout") :
335 "/run/systemd/journal/stdout";
91dd5f7c 336
cad93f29 337 if (gid_is_valid(gid)) {
524daa8c
ZJS
338 oldgid = getgid();
339
92a17af9 340 if (setegid(gid) < 0)
524daa8c
ZJS
341 return -errno;
342 }
343
cad93f29 344 if (uid_is_valid(uid)) {
524daa8c
ZJS
345 olduid = getuid();
346
92a17af9 347 if (seteuid(uid) < 0) {
524daa8c
ZJS
348 r = -errno;
349 goto restore_gid;
350 }
351 }
352
1861986a 353 r = connect_unix_path(fd, AT_FDCWD, j);
524daa8c 354
1861986a
LP
355 /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
356 an LSM interferes. */
524daa8c 357
cad93f29 358 if (uid_is_valid(uid))
524daa8c
ZJS
359 (void) seteuid(olduid);
360
361 restore_gid:
cad93f29 362 if (gid_is_valid(gid))
524daa8c
ZJS
363 (void) setegid(oldgid);
364
365 return r;
366}
367
fd1f9c89 368static int connect_logger_as(
34cf6c43 369 const Unit *unit,
fd1f9c89 370 const ExecContext *context,
af635cf3 371 const ExecParameters *params,
fd1f9c89
LP
372 ExecOutput output,
373 const char *ident,
fd1f9c89
LP
374 int nfd,
375 uid_t uid,
376 gid_t gid) {
377
254d1313 378 _cleanup_close_ int fd = -EBADF;
2ac1ff68 379 int r;
071830ff
LP
380
381 assert(context);
af635cf3 382 assert(params);
80876c20
LP
383 assert(output < _EXEC_OUTPUT_MAX);
384 assert(ident);
385 assert(nfd >= 0);
071830ff 386
54fe0cdb
LP
387 fd = socket(AF_UNIX, SOCK_STREAM, 0);
388 if (fd < 0)
80876c20 389 return -errno;
071830ff 390
91dd5f7c 391 r = connect_journal_socket(fd, context->log_namespace, uid, gid);
524daa8c
ZJS
392 if (r < 0)
393 return r;
071830ff 394
2ac1ff68 395 if (shutdown(fd, SHUT_RD) < 0)
80876c20 396 return -errno;
071830ff 397
fd1f9c89 398 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
531dca78 399
2ac1ff68 400 if (dprintf(fd,
62bca2c6 401 "%s\n"
80876c20
LP
402 "%s\n"
403 "%i\n"
54fe0cdb
LP
404 "%i\n"
405 "%i\n"
406 "%i\n"
4f4a1dbf 407 "%i\n",
c867611e 408 context->syslog_identifier ?: ident,
af635cf3 409 params->flags & EXEC_PASS_LOG_UNIT ? unit->id : "",
54fe0cdb
LP
410 context->syslog_priority,
411 !!context->syslog_level_prefix,
f3dc6af2 412 false,
aac8c0c3 413 is_kmsg_output(output),
2ac1ff68
EV
414 is_terminal_output(output)) < 0)
415 return -errno;
80876c20 416
2ac1ff68 417 return move_fd(TAKE_FD(fd), nfd, false);
80876c20 418}
2ac1ff68 419
3a274a21 420static int open_terminal_as(const char *path, int flags, int nfd) {
046a82c1 421 int fd;
071830ff 422
80876c20
LP
423 assert(path);
424 assert(nfd >= 0);
fd1f9c89 425
3a274a21 426 fd = open_terminal(path, flags | O_NOCTTY);
3cc2aff1 427 if (fd < 0)
80876c20 428 return fd;
071830ff 429
046a82c1 430 return move_fd(fd, nfd, false);
80876c20 431}
071830ff 432
2038c3f5 433static int acquire_path(const char *path, int flags, mode_t mode) {
254d1313 434 _cleanup_close_ int fd = -EBADF;
86fca584 435 int r;
071830ff 436
80876c20 437 assert(path);
071830ff 438
2038c3f5
LP
439 if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
440 flags |= O_CREAT;
441
442 fd = open(path, flags|O_NOCTTY, mode);
443 if (fd >= 0)
15a3e96f 444 return TAKE_FD(fd);
071830ff 445
2038c3f5
LP
446 if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
447 return -errno;
2038c3f5
LP
448
449 /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
450
451 fd = socket(AF_UNIX, SOCK_STREAM, 0);
452 if (fd < 0)
453 return -errno;
454
1861986a
LP
455 r = connect_unix_path(fd, AT_FDCWD, path);
456 if (IN_SET(r, -ENOTSOCK, -EINVAL))
457 /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
458 * wasn't an AF_UNIX socket after all */
459 return -ENXIO;
460 if (r < 0)
461 return r;
071830ff 462
2038c3f5
LP
463 if ((flags & O_ACCMODE) == O_RDONLY)
464 r = shutdown(fd, SHUT_WR);
465 else if ((flags & O_ACCMODE) == O_WRONLY)
466 r = shutdown(fd, SHUT_RD);
467 else
86fca584 468 r = 0;
15a3e96f 469 if (r < 0)
2038c3f5 470 return -errno;
2038c3f5 471
15a3e96f 472 return TAKE_FD(fd);
80876c20 473}
071830ff 474
08f3be7a
LP
475static int fixup_input(
476 const ExecContext *context,
477 int socket_fd,
478 bool apply_tty_stdin) {
479
480 ExecInput std_input;
481
482 assert(context);
483
484 std_input = context->std_input;
1e3ad081
LP
485
486 if (is_terminal_input(std_input) && !apply_tty_stdin)
487 return EXEC_INPUT_NULL;
071830ff 488
03fd9c49 489 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
490 return EXEC_INPUT_NULL;
491
08f3be7a
LP
492 if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
493 return EXEC_INPUT_NULL;
494
03fd9c49 495 return std_input;
4f2d528d
LP
496}
497
7966a916 498static int fixup_output(ExecOutput output, int socket_fd) {
4f2d528d 499
7966a916 500 if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
501 return EXEC_OUTPUT_INHERIT;
502
7966a916 503 return output;
4f2d528d
LP
504}
505
a34ceba6
LP
506static int setup_input(
507 const ExecContext *context,
508 const ExecParameters *params,
52c239d7 509 int socket_fd,
2caa38e9 510 const int named_iofds[static 3]) {
a34ceba6 511
4f2d528d 512 ExecInput i;
51462135 513 int r;
4f2d528d
LP
514
515 assert(context);
a34ceba6 516 assert(params);
2caa38e9 517 assert(named_iofds);
a34ceba6
LP
518
519 if (params->stdin_fd >= 0) {
520 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
521 return -errno;
522
523 /* Try to make this the controlling tty, if it is a tty, and reset it */
1fb0682e 524 if (isatty(STDIN_FILENO)) {
4d62ee55
DDM
525 unsigned rows = context->tty_rows, cols = context->tty_cols;
526
527 (void) exec_context_tty_size(context, &rows, &cols);
1fb0682e
LP
528 (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
529 (void) reset_terminal_fd(STDIN_FILENO, true);
4d62ee55 530 (void) terminal_set_size_fd(STDIN_FILENO, NULL, rows, cols);
1fb0682e 531 }
a34ceba6
LP
532
533 return STDIN_FILENO;
534 }
4f2d528d 535
08f3be7a 536 i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
4f2d528d
LP
537
538 switch (i) {
071830ff 539
80876c20
LP
540 case EXEC_INPUT_NULL:
541 return open_null_as(O_RDONLY, STDIN_FILENO);
542
543 case EXEC_INPUT_TTY:
544 case EXEC_INPUT_TTY_FORCE:
545 case EXEC_INPUT_TTY_FAIL: {
4d62ee55 546 unsigned rows, cols;
046a82c1 547 int fd;
071830ff 548
1e22b5cd 549 fd = acquire_terminal(exec_context_tty_path(context),
8854d795
LP
550 i == EXEC_INPUT_TTY_FAIL ? ACQUIRE_TERMINAL_TRY :
551 i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
552 ACQUIRE_TERMINAL_WAIT,
3a43da28 553 USEC_INFINITY);
970edce6 554 if (fd < 0)
80876c20
LP
555 return fd;
556
4d62ee55
DDM
557 r = exec_context_tty_size(context, &rows, &cols);
558 if (r < 0)
559 return r;
560
561 r = terminal_set_size_fd(fd, exec_context_tty_path(context), rows, cols);
51462135
DDM
562 if (r < 0)
563 return r;
564
046a82c1 565 return move_fd(fd, STDIN_FILENO, false);
80876c20
LP
566 }
567
4f2d528d 568 case EXEC_INPUT_SOCKET:
e75a9ed1
LP
569 assert(socket_fd >= 0);
570
7c248223 571 return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
4f2d528d 572
52c239d7 573 case EXEC_INPUT_NAMED_FD:
e75a9ed1
LP
574 assert(named_iofds[STDIN_FILENO] >= 0);
575
52c239d7 576 (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
7c248223 577 return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
52c239d7 578
08f3be7a
LP
579 case EXEC_INPUT_DATA: {
580 int fd;
581
582 fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
583 if (fd < 0)
584 return fd;
585
586 return move_fd(fd, STDIN_FILENO, false);
587 }
588
2038c3f5
LP
589 case EXEC_INPUT_FILE: {
590 bool rw;
591 int fd;
592
593 assert(context->stdio_file[STDIN_FILENO]);
594
595 rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
596 (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
597
598 fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
599 if (fd < 0)
600 return fd;
601
602 return move_fd(fd, STDIN_FILENO, false);
603 }
604
80876c20 605 default:
04499a70 606 assert_not_reached();
80876c20
LP
607 }
608}
609
41fc585a
LP
610static bool can_inherit_stderr_from_stdout(
611 const ExecContext *context,
612 ExecOutput o,
613 ExecOutput e) {
614
615 assert(context);
616
617 /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
618 * stderr fd */
619
620 if (e == EXEC_OUTPUT_INHERIT)
621 return true;
622 if (e != o)
623 return false;
624
625 if (e == EXEC_OUTPUT_NAMED_FD)
626 return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
627
8d7dab1f 628 if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
41fc585a
LP
629 return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
630
631 return true;
632}
633
a34ceba6 634static int setup_output(
34cf6c43 635 const Unit *unit,
a34ceba6
LP
636 const ExecContext *context,
637 const ExecParameters *params,
638 int fileno,
639 int socket_fd,
2caa38e9 640 const int named_iofds[static 3],
a34ceba6 641 const char *ident,
7bce046b
LP
642 uid_t uid,
643 gid_t gid,
644 dev_t *journal_stream_dev,
645 ino_t *journal_stream_ino) {
a34ceba6 646
4f2d528d
LP
647 ExecOutput o;
648 ExecInput i;
47c1d80d 649 int r;
4f2d528d 650
f2341e0a 651 assert(unit);
80876c20 652 assert(context);
a34ceba6 653 assert(params);
80876c20 654 assert(ident);
7bce046b
LP
655 assert(journal_stream_dev);
656 assert(journal_stream_ino);
80876c20 657
a34ceba6
LP
658 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
659
660 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
661 return -errno;
662
663 return STDOUT_FILENO;
664 }
665
666 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
667 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
668 return -errno;
669
670 return STDERR_FILENO;
671 }
672
08f3be7a 673 i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
03fd9c49 674 o = fixup_output(context->std_output, socket_fd);
4f2d528d 675
eb17e935
MS
676 if (fileno == STDERR_FILENO) {
677 ExecOutput e;
678 e = fixup_output(context->std_error, socket_fd);
80876c20 679
eb17e935
MS
680 /* This expects the input and output are already set up */
681
682 /* Don't change the stderr file descriptor if we inherit all
683 * the way and are not on a tty */
684 if (e == EXEC_OUTPUT_INHERIT &&
685 o == EXEC_OUTPUT_INHERIT &&
686 i == EXEC_INPUT_NULL &&
687 !is_terminal_input(context->std_input) &&
7966a916 688 getppid() != 1)
eb17e935
MS
689 return fileno;
690
691 /* Duplicate from stdout if possible */
41fc585a 692 if (can_inherit_stderr_from_stdout(context, o, e))
7c248223 693 return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
071830ff 694
eb17e935 695 o = e;
80876c20 696
eb17e935 697 } else if (o == EXEC_OUTPUT_INHERIT) {
21d21ea4
LP
698 /* If input got downgraded, inherit the original value */
699 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
1e22b5cd 700 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
21d21ea4 701
08f3be7a
LP
702 /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
703 if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
7c248223 704 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
071830ff 705
acb591e4
LP
706 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
707 if (getppid() != 1)
eb17e935 708 return fileno;
94f04347 709
eb17e935
MS
710 /* We need to open /dev/null here anew, to get the right access mode. */
711 return open_null_as(O_WRONLY, fileno);
071830ff 712 }
94f04347 713
eb17e935 714 switch (o) {
80876c20
LP
715
716 case EXEC_OUTPUT_NULL:
eb17e935 717 return open_null_as(O_WRONLY, fileno);
80876c20
LP
718
719 case EXEC_OUTPUT_TTY:
4f2d528d 720 if (is_terminal_input(i))
7c248223 721 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
80876c20
LP
722
723 /* We don't reset the terminal if this is just about output */
1e22b5cd 724 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
80876c20 725
9a6bca7a 726 case EXEC_OUTPUT_KMSG:
28dbc1e8 727 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
706343f4
LP
728 case EXEC_OUTPUT_JOURNAL:
729 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
af635cf3 730 r = connect_logger_as(unit, context, params, o, ident, fileno, uid, gid);
47c1d80d 731 if (r < 0) {
7966a916
ZJS
732 log_unit_warning_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m",
733 fileno == STDOUT_FILENO ? "stdout" : "stderr");
eb17e935 734 r = open_null_as(O_WRONLY, fileno);
7bce046b
LP
735 } else {
736 struct stat st;
737
738 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
739 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
ab2116b1
LP
740 * services to detect whether they are connected to the journal or not.
741 *
742 * If both stdout and stderr are connected to a stream then let's make sure to store the data
743 * about STDERR as that's usually the best way to do logging. */
7bce046b 744
ab2116b1
LP
745 if (fstat(fileno, &st) >= 0 &&
746 (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
7bce046b
LP
747 *journal_stream_dev = st.st_dev;
748 *journal_stream_ino = st.st_ino;
749 }
47c1d80d
MS
750 }
751 return r;
4f2d528d
LP
752
753 case EXEC_OUTPUT_SOCKET:
754 assert(socket_fd >= 0);
e75a9ed1 755
7c248223 756 return RET_NERRNO(dup2(socket_fd, fileno));
94f04347 757
52c239d7 758 case EXEC_OUTPUT_NAMED_FD:
e75a9ed1
LP
759 assert(named_iofds[fileno] >= 0);
760
52c239d7 761 (void) fd_nonblock(named_iofds[fileno], false);
7c248223 762 return RET_NERRNO(dup2(named_iofds[fileno], fileno));
52c239d7 763
566b7d23 764 case EXEC_OUTPUT_FILE:
8d7dab1f
LW
765 case EXEC_OUTPUT_FILE_APPEND:
766 case EXEC_OUTPUT_FILE_TRUNCATE: {
2038c3f5 767 bool rw;
566b7d23 768 int fd, flags;
2038c3f5
LP
769
770 assert(context->stdio_file[fileno]);
771
772 rw = context->std_input == EXEC_INPUT_FILE &&
773 streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
774
775 if (rw)
7c248223 776 return RET_NERRNO(dup2(STDIN_FILENO, fileno));
2038c3f5 777
566b7d23
ZD
778 flags = O_WRONLY;
779 if (o == EXEC_OUTPUT_FILE_APPEND)
780 flags |= O_APPEND;
8d7dab1f
LW
781 else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
782 flags |= O_TRUNC;
566b7d23
ZD
783
784 fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
2038c3f5
LP
785 if (fd < 0)
786 return fd;
787
566b7d23 788 return move_fd(fd, fileno, 0);
2038c3f5
LP
789 }
790
94f04347 791 default:
04499a70 792 assert_not_reached();
94f04347 793 }
071830ff
LP
794}
795
02a51aba 796static int chown_terminal(int fd, uid_t uid) {
4b3b5bc7 797 int r;
02a51aba
LP
798
799 assert(fd >= 0);
02a51aba 800
1ff74fb6 801 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
4b3b5bc7
LP
802 if (isatty(fd) < 1) {
803 if (IN_SET(errno, EINVAL, ENOTTY))
804 return 0; /* not a tty */
1ff74fb6 805
02a51aba 806 return -errno;
4b3b5bc7 807 }
02a51aba 808
4b3b5bc7 809 /* This might fail. What matters are the results. */
f2df231f 810 r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
4b3b5bc7
LP
811 if (r < 0)
812 return r;
02a51aba 813
4b3b5bc7 814 return 1;
02a51aba
LP
815}
816
aedec452 817static int setup_confirm_stdio(
51462135 818 const ExecContext *context,
aedec452
LP
819 const char *vc,
820 int *ret_saved_stdin,
821 int *ret_saved_stdout) {
822
254d1313 823 _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
4d62ee55 824 unsigned rows, cols;
3d18b167 825 int r;
80876c20 826
aedec452
LP
827 assert(ret_saved_stdin);
828 assert(ret_saved_stdout);
80876c20 829
af6da548
LP
830 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
831 if (saved_stdin < 0)
832 return -errno;
80876c20 833
af6da548 834 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
3d18b167
LP
835 if (saved_stdout < 0)
836 return -errno;
80876c20 837
8854d795 838 fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
3d18b167
LP
839 if (fd < 0)
840 return fd;
80876c20 841
af6da548
LP
842 r = chown_terminal(fd, getuid());
843 if (r < 0)
3d18b167 844 return r;
02a51aba 845
3d18b167
LP
846 r = reset_terminal_fd(fd, true);
847 if (r < 0)
848 return r;
80876c20 849
4d62ee55
DDM
850 r = exec_context_tty_size(context, &rows, &cols);
851 if (r < 0)
852 return r;
853
854 r = terminal_set_size_fd(fd, vc, rows, cols);
51462135
DDM
855 if (r < 0)
856 return r;
857
aedec452
LP
858 r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
859 TAKE_FD(fd);
2b33ab09
LP
860 if (r < 0)
861 return r;
80876c20 862
aedec452
LP
863 *ret_saved_stdin = TAKE_FD(saved_stdin);
864 *ret_saved_stdout = TAKE_FD(saved_stdout);
3d18b167 865 return 0;
80876c20
LP
866}
867
63d77c92 868static void write_confirm_error_fd(int err, int fd, const Unit *u) {
3b20f877
FB
869 assert(err < 0);
870
871 if (err == -ETIMEDOUT)
63d77c92 872 dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", u->id);
3b20f877
FB
873 else {
874 errno = -err;
63d77c92 875 dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", u->id);
3b20f877
FB
876 }
877}
878
63d77c92 879static void write_confirm_error(int err, const char *vc, const Unit *u) {
254d1313 880 _cleanup_close_ int fd = -EBADF;
80876c20 881
3b20f877 882 assert(vc);
80876c20 883
7d5ceb64 884 fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
af6da548 885 if (fd < 0)
3b20f877 886 return;
80876c20 887
63d77c92 888 write_confirm_error_fd(err, fd, u);
af6da548 889}
80876c20 890
3d18b167 891static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
af6da548 892 int r = 0;
80876c20 893
af6da548
LP
894 assert(saved_stdin);
895 assert(saved_stdout);
896
897 release_terminal();
898
899 if (*saved_stdin >= 0)
80876c20 900 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
af6da548 901 r = -errno;
80876c20 902
af6da548 903 if (*saved_stdout >= 0)
80876c20 904 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
af6da548 905 r = -errno;
80876c20 906
3d18b167
LP
907 *saved_stdin = safe_close(*saved_stdin);
908 *saved_stdout = safe_close(*saved_stdout);
af6da548
LP
909
910 return r;
911}
912
3b20f877
FB
913enum {
914 CONFIRM_PRETEND_FAILURE = -1,
915 CONFIRM_PRETEND_SUCCESS = 0,
916 CONFIRM_EXECUTE = 1,
917};
918
51462135 919static int ask_for_confirmation(const ExecContext *context, const char *vc, Unit *u, const char *cmdline) {
af6da548 920 int saved_stdout = -1, saved_stdin = -1, r;
2bcd3c26 921 _cleanup_free_ char *e = NULL;
3b20f877 922 char c;
af6da548 923
3b20f877 924 /* For any internal errors, assume a positive response. */
51462135 925 r = setup_confirm_stdio(context, vc, &saved_stdin, &saved_stdout);
3b20f877 926 if (r < 0) {
63d77c92 927 write_confirm_error(r, vc, u);
3b20f877
FB
928 return CONFIRM_EXECUTE;
929 }
af6da548 930
b0eb2944
FB
931 /* confirm_spawn might have been disabled while we were sleeping. */
932 if (manager_is_confirm_spawn_disabled(u->manager)) {
933 r = 1;
934 goto restore_stdio;
935 }
af6da548 936
2bcd3c26
FB
937 e = ellipsize(cmdline, 60, 100);
938 if (!e) {
939 log_oom();
940 r = CONFIRM_EXECUTE;
941 goto restore_stdio;
942 }
af6da548 943
d172b175 944 for (;;) {
539622bd 945 r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
d172b175 946 if (r < 0) {
63d77c92 947 write_confirm_error_fd(r, STDOUT_FILENO, u);
d172b175
FB
948 r = CONFIRM_EXECUTE;
949 goto restore_stdio;
950 }
af6da548 951
d172b175 952 switch (c) {
b0eb2944
FB
953 case 'c':
954 printf("Resuming normal execution.\n");
955 manager_disable_confirm_spawn();
956 r = 1;
957 break;
dd6f9ac0
FB
958 case 'D':
959 unit_dump(u, stdout, " ");
960 continue; /* ask again */
d172b175
FB
961 case 'f':
962 printf("Failing execution.\n");
963 r = CONFIRM_PRETEND_FAILURE;
964 break;
965 case 'h':
b0eb2944
FB
966 printf(" c - continue, proceed without asking anymore\n"
967 " D - dump, show the state of the unit\n"
dd6f9ac0 968 " f - fail, don't execute the command and pretend it failed\n"
d172b175 969 " h - help\n"
eedf223a 970 " i - info, show a short summary of the unit\n"
56fde33a 971 " j - jobs, show jobs that are in progress\n"
d172b175
FB
972 " s - skip, don't execute the command and pretend it succeeded\n"
973 " y - yes, execute the command\n");
dd6f9ac0 974 continue; /* ask again */
eedf223a
FB
975 case 'i':
976 printf(" Description: %s\n"
977 " Unit: %s\n"
978 " Command: %s\n",
979 u->id, u->description, cmdline);
980 continue; /* ask again */
56fde33a 981 case 'j':
d1d8786c 982 manager_dump_jobs(u->manager, stdout, /* patterns= */ NULL, " ");
56fde33a 983 continue; /* ask again */
539622bd
FB
984 case 'n':
985 /* 'n' was removed in favor of 'f'. */
986 printf("Didn't understand 'n', did you mean 'f'?\n");
987 continue; /* ask again */
d172b175
FB
988 case 's':
989 printf("Skipping execution.\n");
990 r = CONFIRM_PRETEND_SUCCESS;
991 break;
992 case 'y':
993 r = CONFIRM_EXECUTE;
994 break;
995 default:
04499a70 996 assert_not_reached();
d172b175 997 }
3b20f877 998 break;
3b20f877 999 }
af6da548 1000
3b20f877 1001restore_stdio:
af6da548 1002 restore_confirm_stdio(&saved_stdin, &saved_stdout);
af6da548 1003 return r;
80876c20
LP
1004}
1005
4d885bd3
DH
1006static int get_fixed_user(const ExecContext *c, const char **user,
1007 uid_t *uid, gid_t *gid,
1008 const char **home, const char **shell) {
81a2b7ce 1009 int r;
4d885bd3 1010 const char *name;
81a2b7ce 1011
4d885bd3 1012 assert(c);
81a2b7ce 1013
23deef88
LP
1014 if (!c->user)
1015 return 0;
1016
4d885bd3
DH
1017 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
1018 * (i.e. are "/" or "/bin/nologin"). */
81a2b7ce 1019
23deef88 1020 name = c->user;
fafff8f1 1021 r = get_user_creds(&name, uid, gid, home, shell, USER_CREDS_CLEAN);
4d885bd3
DH
1022 if (r < 0)
1023 return r;
81a2b7ce 1024
4d885bd3
DH
1025 *user = name;
1026 return 0;
1027}
1028
1029static int get_fixed_group(const ExecContext *c, const char **group, gid_t *gid) {
1030 int r;
1031 const char *name;
1032
1033 assert(c);
1034
1035 if (!c->group)
1036 return 0;
1037
1038 name = c->group;
fafff8f1 1039 r = get_group_creds(&name, gid, 0);
4d885bd3
DH
1040 if (r < 0)
1041 return r;
1042
1043 *group = name;
1044 return 0;
1045}
1046
cdc5d5c5
DH
1047static int get_supplementary_groups(const ExecContext *c, const char *user,
1048 const char *group, gid_t gid,
1049 gid_t **supplementary_gids, int *ngids) {
4d885bd3
DH
1050 int r, k = 0;
1051 int ngroups_max;
1052 bool keep_groups = false;
1053 gid_t *groups = NULL;
1054 _cleanup_free_ gid_t *l_gids = NULL;
1055
1056 assert(c);
1057
bbeea271
DH
1058 /*
1059 * If user is given, then lookup GID and supplementary groups list.
1060 * We avoid NSS lookups for gid=0. Also we have to initialize groups
cdc5d5c5
DH
1061 * here and as early as possible so we keep the list of supplementary
1062 * groups of the caller.
bbeea271
DH
1063 */
1064 if (user && gid_is_valid(gid) && gid != 0) {
1065 /* First step, initialize groups from /etc/groups */
1066 if (initgroups(user, gid) < 0)
1067 return -errno;
1068
1069 keep_groups = true;
1070 }
1071
ac6e8be6 1072 if (strv_isempty(c->supplementary_groups))
4d885bd3
DH
1073 return 0;
1074
366ddd25
DH
1075 /*
1076 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
1077 * be positive, otherwise fail.
1078 */
1079 errno = 0;
1080 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
66855de7
LP
1081 if (ngroups_max <= 0)
1082 return errno_or_else(EOPNOTSUPP);
366ddd25 1083
4d885bd3
DH
1084 l_gids = new(gid_t, ngroups_max);
1085 if (!l_gids)
1086 return -ENOMEM;
81a2b7ce 1087
4d885bd3
DH
1088 if (keep_groups) {
1089 /*
1090 * Lookup the list of groups that the user belongs to, we
1091 * avoid NSS lookups here too for gid=0.
1092 */
1093 k = ngroups_max;
1094 if (getgrouplist(user, gid, l_gids, &k) < 0)
1095 return -EINVAL;
1096 } else
1097 k = 0;
81a2b7ce 1098
4d885bd3
DH
1099 STRV_FOREACH(i, c->supplementary_groups) {
1100 const char *g;
81a2b7ce 1101
4d885bd3
DH
1102 if (k >= ngroups_max)
1103 return -E2BIG;
81a2b7ce 1104
4d885bd3 1105 g = *i;
fafff8f1 1106 r = get_group_creds(&g, l_gids+k, 0);
4d885bd3
DH
1107 if (r < 0)
1108 return r;
81a2b7ce 1109
4d885bd3
DH
1110 k++;
1111 }
81a2b7ce 1112
4d885bd3
DH
1113 /*
1114 * Sets ngids to zero to drop all supplementary groups, happens
1115 * when we are under root and SupplementaryGroups= is empty.
1116 */
1117 if (k == 0) {
1118 *ngids = 0;
1119 return 0;
1120 }
81a2b7ce 1121
4d885bd3
DH
1122 /* Otherwise get the final list of supplementary groups */
1123 groups = memdup(l_gids, sizeof(gid_t) * k);
1124 if (!groups)
1125 return -ENOMEM;
1126
1127 *supplementary_gids = groups;
1128 *ngids = k;
1129
1130 groups = NULL;
1131
1132 return 0;
1133}
1134
34cf6c43 1135static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
4d885bd3
DH
1136 int r;
1137
709dbeac
YW
1138 /* Handle SupplementaryGroups= if it is not empty */
1139 if (ngids > 0) {
4d885bd3
DH
1140 r = maybe_setgroups(ngids, supplementary_gids);
1141 if (r < 0)
97f0e76f 1142 return r;
4d885bd3 1143 }
81a2b7ce 1144
4d885bd3
DH
1145 if (gid_is_valid(gid)) {
1146 /* Then set our gids */
1147 if (setresgid(gid, gid, gid) < 0)
1148 return -errno;
81a2b7ce
LP
1149 }
1150
1151 return 0;
1152}
1153
a954b249
LP
1154static int set_securebits(unsigned bits, unsigned mask) {
1155 unsigned applied;
1156 int current;
1157
dbdc4098
TK
1158 current = prctl(PR_GET_SECUREBITS);
1159 if (current < 0)
1160 return -errno;
a954b249 1161
dbdc4098 1162 /* Clear all securebits defined in mask and set bits */
a954b249
LP
1163 applied = ((unsigned) current & ~mask) | bits;
1164 if ((unsigned) current == applied)
dbdc4098 1165 return 0;
a954b249 1166
dbdc4098
TK
1167 if (prctl(PR_SET_SECUREBITS, applied) < 0)
1168 return -errno;
a954b249 1169
dbdc4098
TK
1170 return 1;
1171}
1172
638fd8cc
LP
1173static int enforce_user(
1174 const ExecContext *context,
1175 uid_t uid,
1176 uint64_t capability_ambient_set) {
81a2b7ce 1177 assert(context);
dbdc4098 1178 int r;
81a2b7ce 1179
4d885bd3
DH
1180 if (!uid_is_valid(uid))
1181 return 0;
1182
a954b249
LP
1183 /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
1184 * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
1185 * case. */
81a2b7ce 1186
638fd8cc 1187 if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
81a2b7ce 1188
a954b249
LP
1189 /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1190 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1191 r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
1192 if (r < 0)
1193 return r;
81a2b7ce
LP
1194 }
1195
479050b3 1196 /* Second step: actually set the uids */
81a2b7ce
LP
1197 if (setresuid(uid, uid, uid) < 0)
1198 return -errno;
1199
a954b249
LP
1200 /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1201 * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1202 * outside of this call. */
81a2b7ce
LP
1203 return 0;
1204}
1205
349cc4a5 1206#if HAVE_PAM
5b6319dc
LP
1207
1208static int null_conv(
1209 int num_msg,
1210 const struct pam_message **msg,
1211 struct pam_response **resp,
1212 void *appdata_ptr) {
1213
1214 /* We don't support conversations */
1215
1216 return PAM_CONV_ERR;
1217}
1218
cefc33ae
LP
1219#endif
1220
5b6319dc
LP
1221static int setup_pam(
1222 const char *name,
1223 const char *user,
940c5210 1224 uid_t uid,
2d6fce8d 1225 gid_t gid,
5b6319dc 1226 const char *tty,
421bb42d 1227 char ***env, /* updated on success */
5b8d1f6b 1228 const int fds[], size_t n_fds) {
5b6319dc 1229
349cc4a5 1230#if HAVE_PAM
cefc33ae 1231
5b6319dc
LP
1232 static const struct pam_conv conv = {
1233 .conv = null_conv,
1234 .appdata_ptr = NULL
1235 };
1236
2d7c6aa2 1237 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
46e5bbab 1238 _cleanup_strv_free_ char **e = NULL;
5b6319dc 1239 pam_handle_t *handle = NULL;
d6e5f3ad 1240 sigset_t old_ss;
7bb70b6e 1241 int pam_code = PAM_SUCCESS, r;
5b6319dc
LP
1242 bool close_session = false;
1243 pid_t pam_pid = 0, parent_pid;
970edce6 1244 int flags = 0;
5b6319dc
LP
1245
1246 assert(name);
1247 assert(user);
2065ca69 1248 assert(env);
5b6319dc
LP
1249
1250 /* We set up PAM in the parent process, then fork. The child
35b8ca3a 1251 * will then stay around until killed via PR_GET_PDEATHSIG or
5b6319dc
LP
1252 * systemd via the cgroup logic. It will then remove the PAM
1253 * session again. The parent process will exec() the actual
1254 * daemon. We do things this way to ensure that the main PID
1255 * of the daemon is the one we initially fork()ed. */
1256
7bb70b6e
LP
1257 r = barrier_create(&barrier);
1258 if (r < 0)
2d7c6aa2
DH
1259 goto fail;
1260
553d2243 1261 if (log_get_max_level() < LOG_DEBUG)
970edce6
ZJS
1262 flags |= PAM_SILENT;
1263
f546241b
ZJS
1264 pam_code = pam_start(name, user, &conv, &handle);
1265 if (pam_code != PAM_SUCCESS) {
5b6319dc
LP
1266 handle = NULL;
1267 goto fail;
1268 }
1269
3cd24c1a
LP
1270 if (!tty) {
1271 _cleanup_free_ char *q = NULL;
1272
1273 /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
1274 * out if that's the case, and read the TTY off it. */
1275
1276 if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
1277 tty = strjoina("/dev/", q);
1278 }
1279
513cf7da
MS
1280 if (tty) {
1281 pam_code = pam_set_item(handle, PAM_TTY, tty);
1282 if (pam_code != PAM_SUCCESS)
1283 goto fail;
1284 }
5b6319dc 1285
84eada2f
JW
1286 STRV_FOREACH(nv, *env) {
1287 pam_code = pam_putenv(handle, *nv);
2065ca69
JW
1288 if (pam_code != PAM_SUCCESS)
1289 goto fail;
1290 }
1291
970edce6 1292 pam_code = pam_acct_mgmt(handle, flags);
f546241b 1293 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
1294 goto fail;
1295
3bb39ea9
DG
1296 pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
1297 if (pam_code != PAM_SUCCESS)
46d7c6af 1298 log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code));
3bb39ea9 1299
970edce6 1300 pam_code = pam_open_session(handle, flags);
f546241b 1301 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
1302 goto fail;
1303
1304 close_session = true;
1305
f546241b
ZJS
1306 e = pam_getenvlist(handle);
1307 if (!e) {
5b6319dc
LP
1308 pam_code = PAM_BUF_ERR;
1309 goto fail;
1310 }
1311
cafc5ca1 1312 /* Block SIGTERM, so that we know that it won't get lost in the child */
ce30c8dc 1313
72c0a2c2 1314 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
5b6319dc 1315
df0ff127 1316 parent_pid = getpid_cached();
5b6319dc 1317
4c253ed1
LP
1318 r = safe_fork("(sd-pam)", 0, &pam_pid);
1319 if (r < 0)
5b6319dc 1320 goto fail;
4c253ed1 1321 if (r == 0) {
7bb70b6e 1322 int sig, ret = EXIT_PAM;
5b6319dc 1323
cafc5ca1 1324 /* The child's job is to reset the PAM session on termination */
2d7c6aa2 1325 barrier_set_role(&barrier, BARRIER_CHILD);
5b6319dc 1326
1da37e58
ZJS
1327 /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1328 * those fds are open here that have been opened by PAM. */
4c253ed1 1329 (void) close_many(fds, n_fds);
5b6319dc 1330
cafc5ca1
LP
1331 /* Drop privileges - we don't need any to pam_close_session and this will make
1332 * PR_SET_PDEATHSIG work in most cases. If this fails, ignore the error - but expect sd-pam
1333 * threads to fail to exit normally */
2d6fce8d 1334
97f0e76f
LP
1335 r = maybe_setgroups(0, NULL);
1336 if (r < 0)
1337 log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
2d6fce8d
LP
1338 if (setresgid(gid, gid, gid) < 0)
1339 log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
940c5210 1340 if (setresuid(uid, uid, uid) < 0)
2d6fce8d 1341 log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
940c5210 1342
9c274488 1343 (void) ignore_signals(SIGPIPE);
ce30c8dc 1344
cafc5ca1
LP
1345 /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1346 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1347 * this way. We rely on the control groups kill logic to do the rest for us. */
5b6319dc
LP
1348 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
1349 goto child_finish;
1350
cafc5ca1
LP
1351 /* Tell the parent that our setup is done. This is especially important regarding dropping
1352 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
643f4706 1353 *
cafc5ca1 1354 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
643f4706 1355 (void) barrier_place(&barrier);
2d7c6aa2 1356
643f4706 1357 /* Check if our parent process might already have died? */
5b6319dc 1358 if (getppid() == parent_pid) {
d6e5f3ad
DM
1359 sigset_t ss;
1360
1361 assert_se(sigemptyset(&ss) >= 0);
1362 assert_se(sigaddset(&ss, SIGTERM) >= 0);
1363
3dead8d9
LP
1364 for (;;) {
1365 if (sigwait(&ss, &sig) < 0) {
1366 if (errno == EINTR)
1367 continue;
1368
1369 goto child_finish;
1370 }
5b6319dc 1371
3dead8d9
LP
1372 assert(sig == SIGTERM);
1373 break;
1374 }
5b6319dc
LP
1375 }
1376
3bb39ea9
DG
1377 pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags);
1378 if (pam_code != PAM_SUCCESS)
1379 goto child_finish;
1380
3dead8d9 1381 /* If our parent died we'll end the session */
f546241b 1382 if (getppid() != parent_pid) {
970edce6 1383 pam_code = pam_close_session(handle, flags);
f546241b 1384 if (pam_code != PAM_SUCCESS)
5b6319dc 1385 goto child_finish;
f546241b 1386 }
5b6319dc 1387
7bb70b6e 1388 ret = 0;
5b6319dc
LP
1389
1390 child_finish:
7feb2b57
LP
1391 /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1392 * know about this. See pam_end(3) */
1393 (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
7bb70b6e 1394 _exit(ret);
5b6319dc
LP
1395 }
1396
2d7c6aa2
DH
1397 barrier_set_role(&barrier, BARRIER_PARENT);
1398
cafc5ca1
LP
1399 /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1400 * here. */
5b6319dc
LP
1401 handle = NULL;
1402
3b8bddde 1403 /* Unblock SIGTERM again in the parent */
72c0a2c2 1404 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
5b6319dc 1405
cafc5ca1
LP
1406 /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1407 * this fd around. */
5b6319dc
LP
1408 closelog();
1409
cafc5ca1
LP
1410 /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1411 * recover. However, warn loudly if it happens. */
2d7c6aa2
DH
1412 if (!barrier_place_and_sync(&barrier))
1413 log_error("PAM initialization failed");
1414
130d3d22 1415 return strv_free_and_replace(*env, e);
5b6319dc
LP
1416
1417fail:
970edce6
ZJS
1418 if (pam_code != PAM_SUCCESS) {
1419 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
7bb70b6e
LP
1420 r = -EPERM; /* PAM errors do not map to errno */
1421 } else
1422 log_error_errno(r, "PAM failed: %m");
9ba35398 1423
5b6319dc
LP
1424 if (handle) {
1425 if (close_session)
970edce6 1426 pam_code = pam_close_session(handle, flags);
5b6319dc 1427
7feb2b57 1428 (void) pam_end(handle, pam_code | flags);
5b6319dc
LP
1429 }
1430
5b6319dc 1431 closelog();
7bb70b6e 1432 return r;
cefc33ae
LP
1433#else
1434 return 0;
5b6319dc 1435#endif
cefc33ae 1436}
5b6319dc 1437
5d6b1584 1438static void rename_process_from_path(const char *path) {
a99626c1 1439 _cleanup_free_ char *buf = NULL;
5d6b1584 1440 const char *p;
5d6b1584 1441
a99626c1
LP
1442 assert(path);
1443
1444 /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
1445 * /bin/ps */
5d6b1584 1446
a99626c1 1447 if (path_extract_filename(path, &buf) < 0) {
5d6b1584
LP
1448 rename_process("(...)");
1449 return;
1450 }
1451
a99626c1 1452 size_t l = strlen(buf);
5d6b1584 1453 if (l > 8) {
a99626c1 1454 /* The end of the process name is usually more interesting, since the first bit might just be
5d6b1584 1455 * "systemd-" */
a99626c1 1456 p = buf + l - 8;
5d6b1584 1457 l = 8;
a99626c1
LP
1458 } else
1459 p = buf;
5d6b1584 1460
a99626c1 1461 char process_name[11];
5d6b1584
LP
1462 process_name[0] = '(';
1463 memcpy(process_name+1, p, l);
1464 process_name[1+l] = ')';
1465 process_name[1+l+1] = 0;
1466
1467 rename_process(process_name);
1468}
1469
469830d1
LP
1470static bool context_has_address_families(const ExecContext *c) {
1471 assert(c);
1472
6b000af4 1473 return c->address_families_allow_list ||
469830d1
LP
1474 !set_isempty(c->address_families);
1475}
1476
1477static bool context_has_syscall_filters(const ExecContext *c) {
1478 assert(c);
1479
6b000af4 1480 return c->syscall_allow_list ||
8cfa775f 1481 !hashmap_isempty(c->syscall_filter);
469830d1
LP
1482}
1483
9df2cdd8
TM
1484static bool context_has_syscall_logs(const ExecContext *c) {
1485 assert(c);
1486
1487 return c->syscall_log_allow_list ||
1488 !hashmap_isempty(c->syscall_log);
1489}
1490
469830d1
LP
1491static bool context_has_no_new_privileges(const ExecContext *c) {
1492 assert(c);
1493
1494 if (c->no_new_privileges)
1495 return true;
1496
26c45a6c 1497 if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
469830d1
LP
1498 return false;
1499
1500 /* We need NNP if we have any form of seccomp and are unprivileged */
0538d2a8 1501 return c->lock_personality ||
469830d1 1502 c->memory_deny_write_execute ||
0538d2a8 1503 c->private_devices ||
fc64760d 1504 c->protect_clock ||
0538d2a8 1505 c->protect_hostname ||
469830d1
LP
1506 c->protect_kernel_tunables ||
1507 c->protect_kernel_modules ||
84703040 1508 c->protect_kernel_logs ||
0538d2a8
YW
1509 context_has_address_families(c) ||
1510 exec_context_restrict_namespaces_set(c) ||
1511 c->restrict_realtime ||
1512 c->restrict_suid_sgid ||
78e864e5 1513 !set_isempty(c->syscall_archs) ||
0538d2a8
YW
1514 context_has_syscall_filters(c) ||
1515 context_has_syscall_logs(c);
469830d1
LP
1516}
1517
ce18c396 1518bool exec_context_has_credentials(const ExecContext *context) {
bb0c0d6f
LP
1519
1520 assert(context);
1521
1522 return !hashmap_isempty(context->set_credentials) ||
bbfb25f4
DDM
1523 !hashmap_isempty(context->load_credentials) ||
1524 !set_isempty(context->import_credentials);
bb0c0d6f
LP
1525}
1526
349cc4a5 1527#if HAVE_SECCOMP
17df7223 1528
83f12b27 1529static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {
f673b62d
LP
1530
1531 if (is_seccomp_available())
1532 return false;
1533
f673b62d 1534 log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
f673b62d 1535 return true;
83f12b27
FS
1536}
1537
165a31c0 1538static int apply_syscall_filter(const Unit* u, const ExecContext *c, bool needs_ambient_hack) {
469830d1 1539 uint32_t negative_action, default_action, action;
165a31c0 1540 int r;
8351ceae 1541
469830d1 1542 assert(u);
c0467cf3 1543 assert(c);
8351ceae 1544
469830d1 1545 if (!context_has_syscall_filters(c))
83f12b27
FS
1546 return 0;
1547
469830d1
LP
1548 if (skip_seccomp_unavailable(u, "SystemCallFilter="))
1549 return 0;
e9642be2 1550
005bfaf1 1551 negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
e9642be2 1552
6b000af4 1553 if (c->syscall_allow_list) {
469830d1
LP
1554 default_action = negative_action;
1555 action = SCMP_ACT_ALLOW;
7c66bae2 1556 } else {
469830d1
LP
1557 default_action = SCMP_ACT_ALLOW;
1558 action = negative_action;
57183d11 1559 }
8351ceae 1560
165a31c0 1561 if (needs_ambient_hack) {
6b000af4 1562 r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
165a31c0
LP
1563 if (r < 0)
1564 return r;
1565 }
1566
b54f36c6 1567 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
4298d0b5
LP
1568}
1569
9df2cdd8
TM
1570static int apply_syscall_log(const Unit* u, const ExecContext *c) {
1571#ifdef SCMP_ACT_LOG
1572 uint32_t default_action, action;
1573#endif
1574
1575 assert(u);
1576 assert(c);
1577
1578 if (!context_has_syscall_logs(c))
1579 return 0;
1580
1581#ifdef SCMP_ACT_LOG
1582 if (skip_seccomp_unavailable(u, "SystemCallLog="))
1583 return 0;
1584
1585 if (c->syscall_log_allow_list) {
1586 /* Log nothing but the ones listed */
1587 default_action = SCMP_ACT_ALLOW;
1588 action = SCMP_ACT_LOG;
1589 } else {
1590 /* Log everything but the ones listed */
1591 default_action = SCMP_ACT_LOG;
1592 action = SCMP_ACT_ALLOW;
1593 }
1594
1595 return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
1596#else
1597 /* old libseccomp */
1598 log_unit_debug(u, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1599 return 0;
1600#endif
1601}
1602
469830d1
LP
1603static int apply_syscall_archs(const Unit *u, const ExecContext *c) {
1604 assert(u);
4298d0b5
LP
1605 assert(c);
1606
469830d1 1607 if (set_isempty(c->syscall_archs))
83f12b27
FS
1608 return 0;
1609
469830d1
LP
1610 if (skip_seccomp_unavailable(u, "SystemCallArchitectures="))
1611 return 0;
4298d0b5 1612
469830d1
LP
1613 return seccomp_restrict_archs(c->syscall_archs);
1614}
4298d0b5 1615
469830d1
LP
1616static int apply_address_families(const Unit* u, const ExecContext *c) {
1617 assert(u);
1618 assert(c);
4298d0b5 1619
469830d1
LP
1620 if (!context_has_address_families(c))
1621 return 0;
4298d0b5 1622
469830d1
LP
1623 if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
1624 return 0;
4298d0b5 1625
6b000af4 1626 return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
8351ceae 1627}
4298d0b5 1628
83f12b27 1629static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
7a114ed4
TM
1630 int r;
1631
469830d1 1632 assert(u);
f3e43635
TM
1633 assert(c);
1634
469830d1 1635 if (!c->memory_deny_write_execute)
83f12b27
FS
1636 return 0;
1637
7a114ed4
TM
1638 /* use prctl() if kernel supports it (6.3) */
1639 r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1640 if (r == 0) {
1641 log_unit_debug(u, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1642 return 0;
1643 }
1644 if (r < 0 && errno != EINVAL)
1645 return log_unit_debug_errno(u, errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
1646 /* else use seccomp */
1647 log_unit_debug(u, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
1648
469830d1
LP
1649 if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
1650 return 0;
f3e43635 1651
469830d1 1652 return seccomp_memory_deny_write_execute();
f3e43635
TM
1653}
1654
83f12b27 1655static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
469830d1 1656 assert(u);
f4170c67
LP
1657 assert(c);
1658
469830d1 1659 if (!c->restrict_realtime)
83f12b27
FS
1660 return 0;
1661
469830d1
LP
1662 if (skip_seccomp_unavailable(u, "RestrictRealtime="))
1663 return 0;
f4170c67 1664
469830d1 1665 return seccomp_restrict_realtime();
f4170c67
LP
1666}
1667
f69567cb
LP
1668static int apply_restrict_suid_sgid(const Unit* u, const ExecContext *c) {
1669 assert(u);
1670 assert(c);
1671
1672 if (!c->restrict_suid_sgid)
1673 return 0;
1674
1675 if (skip_seccomp_unavailable(u, "RestrictSUIDSGID="))
1676 return 0;
1677
1678 return seccomp_restrict_suid_sgid();
1679}
1680
59e856c7 1681static int apply_protect_sysctl(const Unit *u, const ExecContext *c) {
469830d1 1682 assert(u);
59eeb84b
LP
1683 assert(c);
1684
1685 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1686 * let's protect even those systems where this is left on in the kernel. */
1687
469830d1 1688 if (!c->protect_kernel_tunables)
59eeb84b
LP
1689 return 0;
1690
469830d1
LP
1691 if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
1692 return 0;
59eeb84b 1693
469830d1 1694 return seccomp_protect_sysctl();
59eeb84b
LP
1695}
1696
59e856c7 1697static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) {
469830d1 1698 assert(u);
502d704e
DH
1699 assert(c);
1700
25a8d8a0 1701 /* Turn off module syscalls on ProtectKernelModules=yes */
502d704e 1702
469830d1
LP
1703 if (!c->protect_kernel_modules)
1704 return 0;
1705
502d704e
DH
1706 if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
1707 return 0;
1708
b54f36c6 1709 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
502d704e
DH
1710}
1711
84703040
KK
1712static int apply_protect_kernel_logs(const Unit *u, const ExecContext *c) {
1713 assert(u);
1714 assert(c);
1715
1716 if (!c->protect_kernel_logs)
1717 return 0;
1718
1719 if (skip_seccomp_unavailable(u, "ProtectKernelLogs="))
1720 return 0;
1721
1722 return seccomp_protect_syslog();
1723}
1724
daf8f72b 1725static int apply_protect_clock(const Unit *u, const ExecContext *c) {
fc64760d
KK
1726 assert(u);
1727 assert(c);
1728
1729 if (!c->protect_clock)
1730 return 0;
1731
1732 if (skip_seccomp_unavailable(u, "ProtectClock="))
1733 return 0;
1734
1735 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
1736}
1737
59e856c7 1738static int apply_private_devices(const Unit *u, const ExecContext *c) {
469830d1 1739 assert(u);
ba128bb8
LP
1740 assert(c);
1741
8f81a5f6 1742 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
ba128bb8 1743
469830d1
LP
1744 if (!c->private_devices)
1745 return 0;
1746
ba128bb8
LP
1747 if (skip_seccomp_unavailable(u, "PrivateDevices="))
1748 return 0;
1749
b54f36c6 1750 return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
ba128bb8
LP
1751}
1752
34cf6c43 1753static int apply_restrict_namespaces(const Unit *u, const ExecContext *c) {
469830d1 1754 assert(u);
add00535
LP
1755 assert(c);
1756
1757 if (!exec_context_restrict_namespaces_set(c))
1758 return 0;
1759
1760 if (skip_seccomp_unavailable(u, "RestrictNamespaces="))
1761 return 0;
1762
1763 return seccomp_restrict_namespaces(c->restrict_namespaces);
1764}
1765
78e864e5 1766static int apply_lock_personality(const Unit* u, const ExecContext *c) {
e8132d63
LP
1767 unsigned long personality;
1768 int r;
78e864e5
TM
1769
1770 assert(u);
1771 assert(c);
1772
1773 if (!c->lock_personality)
1774 return 0;
1775
1776 if (skip_seccomp_unavailable(u, "LockPersonality="))
1777 return 0;
1778
e8132d63
LP
1779 personality = c->personality;
1780
1781 /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1782 if (personality == PERSONALITY_INVALID) {
1783
1784 r = opinionated_personality(&personality);
1785 if (r < 0)
1786 return r;
1787 }
78e864e5
TM
1788
1789 return seccomp_lock_personality(personality);
1790}
1791
c0467cf3 1792#endif
8351ceae 1793
7a8288f6 1794#if HAVE_LIBBPF
7a8288f6
DM
1795static int apply_restrict_filesystems(Unit *u, const ExecContext *c) {
1796 assert(u);
1797 assert(c);
1798
1799 if (!exec_context_restrict_filesystems_set(c))
1800 return 0;
1801
46004616
ZJS
1802 if (!u->manager->restrict_fs) {
1803 /* LSM BPF is unsupported or lsm_bpf_setup failed */
1804 log_unit_debug(u, "LSM BPF not supported, skipping RestrictFileSystems=");
7a8288f6 1805 return 0;
46004616 1806 }
7a8288f6
DM
1807
1808 return lsm_bpf_unit_restrict_filesystems(u, c->restrict_filesystems, c->restrict_filesystems_allow_list);
1809}
1810#endif
1811
daf8f72b 1812static int apply_protect_hostname(const Unit *u, const ExecContext *c, int *ret_exit_status) {
daf8f72b
LP
1813 assert(u);
1814 assert(c);
1815
1816 if (!c->protect_hostname)
1817 return 0;
1818
1819 if (ns_type_supported(NAMESPACE_UTS)) {
1820 if (unshare(CLONE_NEWUTS) < 0) {
1821 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
1822 *ret_exit_status = EXIT_NAMESPACE;
1823 return log_unit_error_errno(u, errno, "Failed to set up UTS namespacing: %m");
1824 }
1825
1826 log_unit_warning(u, "ProtectHostname=yes is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.");
1827 }
1828 } else
1829 log_unit_warning(u, "ProtectHostname=yes is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.");
1830
1831#if HAVE_SECCOMP
8f3e342f
ZJS
1832 int r;
1833
daf8f72b
LP
1834 if (skip_seccomp_unavailable(u, "ProtectHostname="))
1835 return 0;
1836
1837 r = seccomp_protect_hostname();
1838 if (r < 0) {
1839 *ret_exit_status = EXIT_SECCOMP;
1840 return log_unit_error_errno(u, r, "Failed to apply hostname restrictions: %m");
1841 }
1842#endif
1843
1844 return 0;
1845}
1846
3042bbeb 1847static void do_idle_pipe_dance(int idle_pipe[static 4]) {
31a7eb86
ZJS
1848 assert(idle_pipe);
1849
54eb2300
LP
1850 idle_pipe[1] = safe_close(idle_pipe[1]);
1851 idle_pipe[2] = safe_close(idle_pipe[2]);
31a7eb86
ZJS
1852
1853 if (idle_pipe[0] >= 0) {
1854 int r;
1855
1856 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1857
1858 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
c7cc737f
LP
1859 ssize_t n;
1860
31a7eb86 1861 /* Signal systemd that we are bored and want to continue. */
c7cc737f
LP
1862 n = write(idle_pipe[3], "x", 1);
1863 if (n > 0)
cd972d69 1864 /* Wait for systemd to react to the signal above. */
54756dce 1865 (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
31a7eb86
ZJS
1866 }
1867
54eb2300 1868 idle_pipe[0] = safe_close(idle_pipe[0]);
31a7eb86
ZJS
1869
1870 }
1871
54eb2300 1872 idle_pipe[3] = safe_close(idle_pipe[3]);
31a7eb86
ZJS
1873}
1874
fb2042dd
YW
1875static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1876
7cae38c4 1877static int build_environment(
34cf6c43 1878 const Unit *u,
9fa95f85 1879 const ExecContext *c,
1e22b5cd 1880 const ExecParameters *p,
6bb00842 1881 const CGroupContext *cgroup_context,
da6053d0 1882 size_t n_fds,
cd48e23f 1883 char **fdnames,
7cae38c4
LP
1884 const char *home,
1885 const char *username,
1886 const char *shell,
7bce046b
LP
1887 dev_t journal_stream_dev,
1888 ino_t journal_stream_ino,
6bb00842 1889 const char *memory_pressure_path,
7cae38c4
LP
1890 char ***ret) {
1891
1892 _cleanup_strv_free_ char **our_env = NULL;
da6053d0 1893 size_t n_env = 0;
7cae38c4 1894 char *x;
4d62ee55 1895 int r;
7cae38c4 1896
4b58153d 1897 assert(u);
7cae38c4 1898 assert(c);
7c1cb6f1 1899 assert(p);
7cae38c4
LP
1900 assert(ret);
1901
6bb00842 1902#define N_ENV_VARS 19
8d5bb13d 1903 our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
7cae38c4
LP
1904 if (!our_env)
1905 return -ENOMEM;
1906
1907 if (n_fds > 0) {
8dd4c05b
LP
1908 _cleanup_free_ char *joined = NULL;
1909
df0ff127 1910 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
7cae38c4
LP
1911 return -ENOMEM;
1912 our_env[n_env++] = x;
1913
da6053d0 1914 if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
7cae38c4
LP
1915 return -ENOMEM;
1916 our_env[n_env++] = x;
8dd4c05b 1917
cd48e23f 1918 joined = strv_join(fdnames, ":");
8dd4c05b
LP
1919 if (!joined)
1920 return -ENOMEM;
1921
605405c6 1922 x = strjoin("LISTEN_FDNAMES=", joined);
8dd4c05b
LP
1923 if (!x)
1924 return -ENOMEM;
1925 our_env[n_env++] = x;
7cae38c4
LP
1926 }
1927
b08af3b1 1928 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
df0ff127 1929 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
09812eb7
LP
1930 return -ENOMEM;
1931 our_env[n_env++] = x;
1932
1e22b5cd 1933 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
09812eb7
LP
1934 return -ENOMEM;
1935 our_env[n_env++] = x;
1936 }
1937
de90700f
LP
1938 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
1939 * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
1940 * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
1941 if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
1942 x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
fd63e712
LP
1943 if (!x)
1944 return -ENOMEM;
1945 our_env[n_env++] = x;
1946 }
1947
7cae38c4 1948 if (home) {
b910cc72 1949 x = strjoin("HOME=", home);
7cae38c4
LP
1950 if (!x)
1951 return -ENOMEM;
7bbead1d 1952
4ff361cc 1953 path_simplify(x + 5);
7cae38c4
LP
1954 our_env[n_env++] = x;
1955 }
1956
1957 if (username) {
b910cc72 1958 x = strjoin("LOGNAME=", username);
7cae38c4
LP
1959 if (!x)
1960 return -ENOMEM;
1961 our_env[n_env++] = x;
1962
b910cc72 1963 x = strjoin("USER=", username);
7cae38c4
LP
1964 if (!x)
1965 return -ENOMEM;
1966 our_env[n_env++] = x;
1967 }
1968
1969 if (shell) {
b910cc72 1970 x = strjoin("SHELL=", shell);
7cae38c4
LP
1971 if (!x)
1972 return -ENOMEM;
7bbead1d 1973
4ff361cc 1974 path_simplify(x + 6);
7cae38c4
LP
1975 our_env[n_env++] = x;
1976 }
1977
4b58153d
LP
1978 if (!sd_id128_is_null(u->invocation_id)) {
1979 if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
1980 return -ENOMEM;
1981
1982 our_env[n_env++] = x;
1983 }
1984
6af760f3 1985 if (exec_context_needs_term(c)) {
4d62ee55 1986 _cleanup_free_ char *cmdline = NULL;
6af760f3
LP
1987 const char *tty_path, *term = NULL;
1988
1989 tty_path = exec_context_tty_path(c);
1990
e8cf09b2
LP
1991 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
1992 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
1993 * container manager passes to PID 1 ends up all the way in the console login shown. */
6af760f3 1994
e8cf09b2 1995 if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1)
6af760f3 1996 term = getenv("TERM");
4d62ee55
DDM
1997 else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
1998 _cleanup_free_ char *key = NULL;
1999
2000 key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
2001 if (!key)
2002 return -ENOMEM;
2003
2004 r = proc_cmdline_get_key(key, 0, &cmdline);
2005 if (r < 0)
2006 log_debug_errno(r, "Failed to read %s from kernel cmdline, ignoring: %m", key);
2007 else if (r > 0)
2008 term = cmdline;
2009 }
e8cf09b2 2010
6af760f3
LP
2011 if (!term)
2012 term = default_term_for_tty(tty_path);
7cae38c4 2013
b910cc72 2014 x = strjoin("TERM=", term);
7cae38c4
LP
2015 if (!x)
2016 return -ENOMEM;
2017 our_env[n_env++] = x;
2018 }
2019
7bce046b
LP
2020 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
2021 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
2022 return -ENOMEM;
2023
2024 our_env[n_env++] = x;
2025 }
2026
91dd5f7c
LP
2027 if (c->log_namespace) {
2028 x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2029 if (!x)
2030 return -ENOMEM;
2031
2032 our_env[n_env++] = x;
2033 }
2034
5b10116e 2035 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
211a3d87 2036 _cleanup_free_ char *joined = NULL;
fb2042dd
YW
2037 const char *n;
2038
2039 if (!p->prefix[t])
2040 continue;
2041
211a3d87 2042 if (c->directories[t].n_items == 0)
fb2042dd
YW
2043 continue;
2044
2045 n = exec_directory_env_name_to_string(t);
2046 if (!n)
2047 continue;
2048
211a3d87
LB
2049 for (size_t i = 0; i < c->directories[t].n_items; i++) {
2050 _cleanup_free_ char *prefixed = NULL;
fb2042dd 2051
211a3d87
LB
2052 prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2053 if (!prefixed)
2054 return -ENOMEM;
2055
2056 if (!strextend_with_separator(&joined, ":", prefixed))
2057 return -ENOMEM;
2058 }
fb2042dd
YW
2059
2060 x = strjoin(n, "=", joined);
2061 if (!x)
2062 return -ENOMEM;
2063
2064 our_env[n_env++] = x;
2065 }
2066
bb0c0d6f
LP
2067 if (exec_context_has_credentials(c) && p->prefix[EXEC_DIRECTORY_RUNTIME]) {
2068 x = strjoin("CREDENTIALS_DIRECTORY=", p->prefix[EXEC_DIRECTORY_RUNTIME], "/credentials/", u->id);
2069 if (!x)
2070 return -ENOMEM;
2071
2072 our_env[n_env++] = x;
2073 }
2074
dc4e2940
YW
2075 if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
2076 return -ENOMEM;
2077
2078 our_env[n_env++] = x;
2079
6bb00842
LP
2080 if (memory_pressure_path) {
2081 x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
2082 if (!x)
2083 return -ENOMEM;
2084
2085 our_env[n_env++] = x;
2086
2087 if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
2088 _cleanup_free_ char *b = NULL, *e = NULL;
2089
2090 if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
2091 MEMORY_PRESSURE_DEFAULT_TYPE,
2092 cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
2093 CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
2094 MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2095 return -ENOMEM;
2096
2097 if (base64mem(b, strlen(b) + 1, &e) < 0)
2098 return -ENOMEM;
2099
2100 x = strjoin("MEMORY_PRESSURE_WRITE=", e);
2101 if (!x)
2102 return -ENOMEM;
2103
2104 our_env[n_env++] = x;
2105 }
2106 }
2107
2108 assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
8d5bb13d 2109#undef N_ENV_VARS
7cae38c4 2110
ae2a15bc 2111 *ret = TAKE_PTR(our_env);
7cae38c4
LP
2112
2113 return 0;
2114}
2115
b4c14404
FB
2116static int build_pass_environment(const ExecContext *c, char ***ret) {
2117 _cleanup_strv_free_ char **pass_env = NULL;
319a4f4b 2118 size_t n_env = 0;
b4c14404
FB
2119
2120 STRV_FOREACH(i, c->pass_environment) {
2121 _cleanup_free_ char *x = NULL;
2122 char *v;
2123
2124 v = getenv(*i);
2125 if (!v)
2126 continue;
605405c6 2127 x = strjoin(*i, "=", v);
b4c14404
FB
2128 if (!x)
2129 return -ENOMEM;
00819cc1 2130
319a4f4b 2131 if (!GREEDY_REALLOC(pass_env, n_env + 2))
b4c14404 2132 return -ENOMEM;
00819cc1 2133
1cc6c93a 2134 pass_env[n_env++] = TAKE_PTR(x);
b4c14404 2135 pass_env[n_env] = NULL;
b4c14404
FB
2136 }
2137
ae2a15bc 2138 *ret = TAKE_PTR(pass_env);
b4c14404
FB
2139
2140 return 0;
2141}
2142
fbbb9697
YW
2143bool exec_needs_network_namespace(const ExecContext *context) {
2144 assert(context);
2145
2146 return context->private_network || context->network_namespace_path;
2147}
2148
9c0c6701
DDM
2149static bool exec_needs_ephemeral(const ExecContext *context) {
2150 return (context->root_image || context->root_directory) && context->root_ephemeral;
2151}
2152
fde36d25
YW
2153static bool exec_needs_ipc_namespace(const ExecContext *context) {
2154 assert(context);
2155
2156 return context->private_ipc || context->ipc_namespace_path;
2157}
2158
5e8deb94 2159bool exec_needs_mount_namespace(
8b44a3d2
LP
2160 const ExecContext *context,
2161 const ExecParameters *params,
28135da3 2162 const ExecRuntime *runtime) {
8b44a3d2
LP
2163
2164 assert(context);
8b44a3d2 2165
915e6d16
LP
2166 if (context->root_image)
2167 return true;
2168
2a624c36
AP
2169 if (!strv_isempty(context->read_write_paths) ||
2170 !strv_isempty(context->read_only_paths) ||
ddc155b2
TM
2171 !strv_isempty(context->inaccessible_paths) ||
2172 !strv_isempty(context->exec_paths) ||
2173 !strv_isempty(context->no_exec_paths))
8b44a3d2
LP
2174 return true;
2175
42b1d8e0 2176 if (context->n_bind_mounts > 0)
d2d6c096
LP
2177 return true;
2178
2abd4e38
YW
2179 if (context->n_temporary_filesystems > 0)
2180 return true;
2181
b3d13314
LB
2182 if (context->n_mount_images > 0)
2183 return true;
2184
93f59701
LB
2185 if (context->n_extension_images > 0)
2186 return true;
2187
a07b9926
LB
2188 if (!strv_isempty(context->extension_directories))
2189 return true;
2190
874cdcbc 2191 if (!IN_SET(context->mount_propagation_flag, 0, MS_SHARED))
8b44a3d2
LP
2192 return true;
2193
28135da3 2194 if (context->private_tmp && runtime && runtime->shared && (runtime->shared->tmp_dir || runtime->shared->var_tmp_dir))
8b44a3d2
LP
2195 return true;
2196
8b44a3d2 2197 if (context->private_devices ||
24002121 2198 context->private_mounts > 0 ||
c2da3bf2 2199 (context->private_mounts < 0 && exec_needs_network_namespace(context)) ||
8b44a3d2 2200 context->protect_system != PROTECT_SYSTEM_NO ||
59eeb84b
LP
2201 context->protect_home != PROTECT_HOME_NO ||
2202 context->protect_kernel_tunables ||
c575770b 2203 context->protect_kernel_modules ||
94a7b275 2204 context->protect_kernel_logs ||
4e399953
LP
2205 context->protect_control_groups ||
2206 context->protect_proc != PROTECT_PROC_DEFAULT ||
80271a44 2207 context->proc_subset != PROC_SUBSET_ALL ||
fde36d25 2208 exec_needs_ipc_namespace(context))
8b44a3d2
LP
2209 return true;
2210
37c56f89 2211 if (context->root_directory) {
5e98086d 2212 if (exec_context_get_effective_mount_apivfs(context))
37c56f89
YW
2213 return true;
2214
5b10116e 2215 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5e8deb94 2216 if (params && !params->prefix[t])
37c56f89
YW
2217 continue;
2218
211a3d87 2219 if (context->directories[t].n_items > 0)
37c56f89
YW
2220 return true;
2221 }
2222 }
5d997827 2223
42b1d8e0 2224 if (context->dynamic_user &&
211a3d87
LB
2225 (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
2226 context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
2227 context->directories[EXEC_DIRECTORY_LOGS].n_items > 0))
42b1d8e0
YW
2228 return true;
2229
91dd5f7c
LP
2230 if (context->log_namespace)
2231 return true;
2232
8b44a3d2
LP
2233 return false;
2234}
2235
5749f855 2236static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) {
d251207d 2237 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
19ee48a6 2238 _cleanup_close_pair_ int errno_pipe[2] = PIPE_EBADF;
254d1313 2239 _cleanup_close_ int unshare_ready_fd = -EBADF;
d251207d
LP
2240 _cleanup_(sigkill_waitp) pid_t pid = 0;
2241 uint64_t c = 1;
d251207d
LP
2242 ssize_t n;
2243 int r;
2244
5749f855
AZ
2245 /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
2246 * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
d251207d
LP
2247 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
2248 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
2249 * which waits for the parent to create the new user namespace while staying in the original namespace. The
2250 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
5749f855
AZ
2251 * continues execution normally.
2252 * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
2253 * does not need CAP_SETUID to write the single line mapping to itself. */
d251207d 2254
5749f855 2255 /* Can only set up multiple mappings with CAP_SETUID. */
26c45a6c 2256 if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid))
587ab01b 2257 r = asprintf(&uid_map,
5749f855 2258 UID_FMT " " UID_FMT " 1\n" /* Map $OUID → $OUID */
587ab01b 2259 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
5749f855
AZ
2260 ouid, ouid, uid, uid);
2261 else
2262 r = asprintf(&uid_map,
2263 UID_FMT " " UID_FMT " 1\n", /* Map $OUID → $OUID */
2264 ouid, ouid);
d251207d 2265
5749f855
AZ
2266 if (r < 0)
2267 return -ENOMEM;
2268
2269 /* Can only set up multiple mappings with CAP_SETGID. */
26c45a6c 2270 if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid))
587ab01b 2271 r = asprintf(&gid_map,
5749f855 2272 GID_FMT " " GID_FMT " 1\n" /* Map $OGID → $OGID */
587ab01b 2273 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
5749f855
AZ
2274 ogid, ogid, gid, gid);
2275 else
2276 r = asprintf(&gid_map,
2277 GID_FMT " " GID_FMT " 1\n", /* Map $OGID -> $OGID */
2278 ogid, ogid);
2279
2280 if (r < 0)
2281 return -ENOMEM;
d251207d
LP
2282
2283 /* Create a communication channel so that the parent can tell the child when it finished creating the user
2284 * namespace. */
2285 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
2286 if (unshare_ready_fd < 0)
2287 return -errno;
2288
2289 /* Create a communication channel so that the child can tell the parent a proper error code in case it
2290 * failed. */
2291 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
2292 return -errno;
2293
4c253ed1
LP
2294 r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
2295 if (r < 0)
2296 return r;
2297 if (r == 0) {
254d1313 2298 _cleanup_close_ int fd = -EBADF;
d251207d
LP
2299 const char *a;
2300 pid_t ppid;
2301
2302 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
2303 * here, after the parent opened its own user namespace. */
2304
2305 ppid = getppid();
2306 errno_pipe[0] = safe_close(errno_pipe[0]);
2307
2308 /* Wait until the parent unshared the user namespace */
2309 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
2310 r = -errno;
2311 goto child_fail;
2312 }
2313
2314 /* Disable the setgroups() system call in the child user namespace, for good. */
2315 a = procfs_file_alloca(ppid, "setgroups");
2316 fd = open(a, O_WRONLY|O_CLOEXEC);
2317 if (fd < 0) {
2318 if (errno != ENOENT) {
2319 r = -errno;
2320 goto child_fail;
2321 }
2322
2323 /* If the file is missing the kernel is too old, let's continue anyway. */
2324 } else {
2325 if (write(fd, "deny\n", 5) < 0) {
2326 r = -errno;
2327 goto child_fail;
2328 }
2329
2330 fd = safe_close(fd);
2331 }
2332
2333 /* First write the GID map */
2334 a = procfs_file_alloca(ppid, "gid_map");
2335 fd = open(a, O_WRONLY|O_CLOEXEC);
2336 if (fd < 0) {
2337 r = -errno;
2338 goto child_fail;
2339 }
2340 if (write(fd, gid_map, strlen(gid_map)) < 0) {
2341 r = -errno;
2342 goto child_fail;
2343 }
2344 fd = safe_close(fd);
2345
2346 /* The write the UID map */
2347 a = procfs_file_alloca(ppid, "uid_map");
2348 fd = open(a, O_WRONLY|O_CLOEXEC);
2349 if (fd < 0) {
2350 r = -errno;
2351 goto child_fail;
2352 }
2353 if (write(fd, uid_map, strlen(uid_map)) < 0) {
2354 r = -errno;
2355 goto child_fail;
2356 }
2357
2358 _exit(EXIT_SUCCESS);
2359
2360 child_fail:
2361 (void) write(errno_pipe[1], &r, sizeof(r));
2362 _exit(EXIT_FAILURE);
2363 }
2364
2365 errno_pipe[1] = safe_close(errno_pipe[1]);
2366
2367 if (unshare(CLONE_NEWUSER) < 0)
2368 return -errno;
2369
2370 /* Let the child know that the namespace is ready now */
2371 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
2372 return -errno;
2373
2374 /* Try to read an error code from the child */
2375 n = read(errno_pipe[0], &r, sizeof(r));
2376 if (n < 0)
2377 return -errno;
2378 if (n == sizeof(r)) { /* an error code was sent to us */
2379 if (r < 0)
2380 return r;
2381 return -EIO;
2382 }
2383 if (n != 0) /* on success we should have read 0 bytes */
2384 return -EIO;
2385
8f03de53 2386 r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
d251207d
LP
2387 if (r < 0)
2388 return r;
2e87a1fd 2389 if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
d251207d
LP
2390 return -EIO;
2391
2392 return 0;
2393}
2394
494d0247 2395static bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
e43911a7
LP
2396 assert(context);
2397
494d0247
YW
2398 if (!context->dynamic_user)
2399 return false;
2400
2401 if (type == EXEC_DIRECTORY_CONFIGURATION)
2402 return false;
2403
2404 if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
2405 return false;
2406
2407 return true;
2408}
2409
211a3d87
LB
2410static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
2411 _cleanup_free_ char *src_abs = NULL;
211a3d87
LB
2412 int r;
2413
2414 assert(source);
2415
2416 src_abs = path_join(root, source);
2417 if (!src_abs)
2418 return -ENOMEM;
2419
2420 STRV_FOREACH(dst, symlinks) {
2421 _cleanup_free_ char *dst_abs = NULL;
2422
2423 dst_abs = path_join(root, *dst);
2424 if (!dst_abs)
2425 return -ENOMEM;
2426
2427 r = mkdir_parents_label(dst_abs, 0755);
2428 if (r < 0)
2429 return r;
2430
2431 r = symlink_idempotent(src_abs, dst_abs, true);
2432 if (r < 0)
2433 return r;
2434 }
2435
2436 return 0;
2437}
2438
3536f49e 2439static int setup_exec_directory(
59dd2bbb 2440 Unit *u,
07689d5d
LP
2441 const ExecContext *context,
2442 const ExecParameters *params,
2443 uid_t uid,
3536f49e 2444 gid_t gid,
3536f49e 2445 ExecDirectoryType type,
211a3d87 2446 bool needs_mount_namespace,
3536f49e 2447 int *exit_status) {
07689d5d 2448
72fd1768 2449 static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
2450 [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
2451 [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
2452 [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
2453 [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
2454 [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2455 };
07689d5d
LP
2456 int r;
2457
2458 assert(context);
2459 assert(params);
72fd1768 2460 assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
3536f49e 2461 assert(exit_status);
07689d5d 2462
3536f49e
YW
2463 if (!params->prefix[type])
2464 return 0;
2465
8679efde 2466 if (params->flags & EXEC_CHOWN_DIRECTORIES) {
3536f49e
YW
2467 if (!uid_is_valid(uid))
2468 uid = 0;
2469 if (!gid_is_valid(gid))
2470 gid = 0;
2471 }
2472
211a3d87 2473 for (size_t i = 0; i < context->directories[type].n_items; i++) {
6c47cd7d 2474 _cleanup_free_ char *p = NULL, *pp = NULL;
07689d5d 2475
211a3d87 2476 p = path_join(params->prefix[type], context->directories[type].items[i].path);
3536f49e
YW
2477 if (!p) {
2478 r = -ENOMEM;
2479 goto fail;
2480 }
07689d5d 2481
23a7448e
YW
2482 r = mkdir_parents_label(p, 0755);
2483 if (r < 0)
3536f49e 2484 goto fail;
23a7448e 2485
f9c91932
LP
2486 if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
2487
2488 /* If we are in user mode, and a configuration directory exists but a state directory
2489 * doesn't exist, then we likely are upgrading from an older systemd version that
2490 * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2491 * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2492 * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME is is now
627cdcc7 2493 * separated. If a service has both dirs configured but only the configuration dir
f9c91932
LP
2494 * exists and the state dir does not, we assume we are looking at an update
2495 * situation. Hence, create a compatibility symlink, so that all expectations are
2496 * met.
2497 *
2498 * (We also do something similar with the log directory, which still doesn't exist in
2499 * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2500
2501 /* this assumes the state dir is always created before the configuration dir */
2502 assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
2503 assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
2504
2505 r = laccess(p, F_OK);
2506 if (r == -ENOENT) {
2507 _cleanup_free_ char *q = NULL;
2508
2509 /* OK, we know that the state dir does not exist. Let's see if the dir exists
2510 * under the configuration hierarchy. */
2511
2512 if (type == EXEC_DIRECTORY_STATE)
2513 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], context->directories[type].items[i].path);
2514 else if (type == EXEC_DIRECTORY_LOGS)
2515 q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", context->directories[type].items[i].path);
2516 else
2517 assert_not_reached();
2518 if (!q) {
2519 r = -ENOMEM;
2520 goto fail;
2521 }
2522
2523 r = laccess(q, F_OK);
2524 if (r >= 0) {
2525 /* It does exist! This hence looks like an update. Symlink the
2526 * configuration directory into the state directory. */
2527
2528 r = symlink_idempotent(q, p, /* make_relative= */ true);
2529 if (r < 0)
2530 goto fail;
2531
59dd2bbb 2532 log_unit_notice(u, "Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
f9c91932
LP
2533 continue;
2534 } else if (r != -ENOENT)
59dd2bbb 2535 log_unit_warning_errno(u, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
f9c91932
LP
2536
2537 } else if (r < 0)
59dd2bbb 2538 log_unit_warning_errno(u, r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
f9c91932
LP
2539 }
2540
494d0247 2541 if (exec_directory_is_private(context, type)) {
3f5b1508
LP
2542 /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2543 * case we want to avoid leaving a directory around fully accessible that is owned by
2544 * a dynamic user whose UID is later on reused. To lock this down we use the same
2545 * trick used by container managers to prohibit host users to get access to files of
2546 * the same UID in containers: we place everything inside a directory that has an
2547 * access mode of 0700 and is owned root:root, so that it acts as security boundary
2548 * for unprivileged host code. We then use fs namespacing to make this directory
2549 * permeable for the service itself.
6c47cd7d 2550 *
3f5b1508
LP
2551 * Specifically: for a service which wants a special directory "foo/" we first create
2552 * a directory "private/" with access mode 0700 owned by root:root. Then we place
2553 * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2554 * "private/foo". This way, privileged host users can access "foo/" as usual, but
2555 * unprivileged host users can't look into it. Inside of the namespace of the unit
2556 * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2557 * "private/foo/" is mounted under the same name, thus disabling the access boundary
2558 * for the service and making sure it only gets access to the dirs it needs but no
2559 * others. Tricky? Yes, absolutely, but it works!
6c47cd7d 2560 *
3f5b1508
LP
2561 * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2562 * to be owned by the service itself.
2563 *
2564 * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2565 * for sharing files or sockets with other services. */
6c47cd7d 2566
4ede9802
LP
2567 pp = path_join(params->prefix[type], "private");
2568 if (!pp) {
6c47cd7d
LP
2569 r = -ENOMEM;
2570 goto fail;
2571 }
2572
2573 /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
4ede9802 2574 r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
6c47cd7d
LP
2575 if (r < 0)
2576 goto fail;
2577
211a3d87 2578 if (!path_extend(&pp, context->directories[type].items[i].path)) {
6c47cd7d
LP
2579 r = -ENOMEM;
2580 goto fail;
2581 }
2582
2583 /* Create all directories between the configured directory and this private root, and mark them 0755 */
2584 r = mkdir_parents_label(pp, 0755);
2585 if (r < 0)
2586 goto fail;
2587
949befd3 2588 if (is_dir(p, false) > 0 &&
b93d24e0 2589 (laccess(pp, F_OK) == -ENOENT)) {
949befd3
LP
2590
2591 /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
2592 * it over. Most likely the service has been upgraded from one that didn't use
2593 * DynamicUser=1, to one that does. */
2594
59dd2bbb
LP
2595 log_unit_info(u, "Found pre-existing public %s= directory %s, migrating to %s.\n"
2596 "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
2597 exec_directory_type_to_string(type), p, pp);
cf52c45d 2598
db58f5de
LP
2599 r = RET_NERRNO(rename(p, pp));
2600 if (r < 0)
949befd3 2601 goto fail;
949befd3
LP
2602 } else {
2603 /* Otherwise, create the actual directory for the service */
2604
2605 r = mkdir_label(pp, context->directories[type].mode);
2606 if (r < 0 && r != -EEXIST)
2607 goto fail;
2608 }
6c47cd7d 2609
a2ab603c
YW
2610 if (!context->directories[type].items[i].only_create) {
2611 /* And link it up from the original place.
2612 * Notes
2613 * 1) If a mount namespace is going to be used, then this symlink remains on
2614 * the host, and a new one for the child namespace will be created later.
2615 * 2) It is not necessary to create this symlink when one of its parent
2616 * directories is specified and already created. E.g.
2617 * StateDirectory=foo foo/bar
2618 * In that case, the inode points to pp and p for "foo/bar" are the same:
2619 * pp = "/var/lib/private/foo/bar"
2620 * p = "/var/lib/foo/bar"
2621 * and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2622 * we do not need to create the symlink, but we cannot create the symlink.
2623 * See issue #24783. */
2624 r = symlink_idempotent(pp, p, true);
2625 if (r < 0)
2626 goto fail;
2627 }
6c47cd7d 2628
6c47cd7d 2629 } else {
5c6d40d1
LP
2630 _cleanup_free_ char *target = NULL;
2631
2632 if (type != EXEC_DIRECTORY_CONFIGURATION &&
2633 readlink_and_make_absolute(p, &target) >= 0) {
578dc69f 2634 _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
5c6d40d1
LP
2635
2636 /* This already exists and is a symlink? Interesting. Maybe it's one created
2193f17c
LP
2637 * by DynamicUser=1 (see above)?
2638 *
2639 * We do this for all directory types except for ConfigurationDirectory=,
2640 * since they all support the private/ symlink logic at least in some
2641 * configurations, see above. */
5c6d40d1 2642
f461a28d 2643 r = chase(target, NULL, 0, &target_resolved, NULL);
578dc69f
YW
2644 if (r < 0)
2645 goto fail;
2646
211a3d87 2647 q = path_join(params->prefix[type], "private", context->directories[type].items[i].path);
5c6d40d1
LP
2648 if (!q) {
2649 r = -ENOMEM;
2650 goto fail;
2651 }
2652
578dc69f 2653 /* /var/lib or friends may be symlinks. So, let's chase them also. */
f461a28d 2654 r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
578dc69f
YW
2655 if (r < 0)
2656 goto fail;
2657
2658 if (path_equal(q_resolved, target_resolved)) {
5c6d40d1
LP
2659
2660 /* Hmm, apparently DynamicUser= was once turned on for this service,
2661 * but is no longer. Let's move the directory back up. */
2662
59dd2bbb
LP
2663 log_unit_info(u, "Found pre-existing private %s= directory %s, migrating to %s.\n"
2664 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
2665 exec_directory_type_to_string(type), q, p);
cf52c45d 2666
db58f5de
LP
2667 r = RET_NERRNO(unlink(p));
2668 if (r < 0)
5c6d40d1 2669 goto fail;
5c6d40d1 2670
db58f5de
LP
2671 r = RET_NERRNO(rename(q, p));
2672 if (r < 0)
5c6d40d1 2673 goto fail;
5c6d40d1
LP
2674 }
2675 }
2676
6c47cd7d 2677 r = mkdir_label(p, context->directories[type].mode);
d484580c 2678 if (r < 0) {
d484580c
LP
2679 if (r != -EEXIST)
2680 goto fail;
2681
206e9864
LP
2682 if (type == EXEC_DIRECTORY_CONFIGURATION) {
2683 struct stat st;
2684
2685 /* Don't change the owner/access mode of the configuration directory,
2686 * as in the common case it is not written to by a service, and shall
2687 * not be writable. */
2688
db58f5de
LP
2689 r = RET_NERRNO(stat(p, &st));
2690 if (r < 0)
206e9864 2691 goto fail;
206e9864
LP
2692
2693 /* Still complain if the access mode doesn't match */
2694 if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
59dd2bbb
LP
2695 log_unit_warning(u, "%s \'%s\' already exists but the mode is different. "
2696 "(File system: %o %sMode: %o)",
2697 exec_directory_type_to_string(type), context->directories[type].items[i].path,
2698 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
206e9864 2699
6cff72eb 2700 continue;
206e9864 2701 }
6cff72eb 2702 }
a1164ae3 2703 }
07689d5d 2704
206e9864 2705 /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
5238e957 2706 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
206e9864
LP
2707 * current UID/GID ownership.) */
2708 r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
2709 if (r < 0)
2710 goto fail;
c71b2eb7 2711
f5bb36dc
LP
2712 /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2713 * available to user code anyway */
2714 if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
2715 continue;
2716
607b358e
LP
2717 /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
2718 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
7802194a 2719 * assignments to exist. */
d5602c16 2720 r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
07689d5d 2721 if (r < 0)
3536f49e 2722 goto fail;
07689d5d
LP
2723 }
2724
211a3d87
LB
2725 /* If we are not going to run in a namespace, set up the symlinks - otherwise
2726 * they are set up later, to allow configuring empty var/run/etc. */
2727 if (!needs_mount_namespace)
2728 for (size_t i = 0; i < context->directories[type].n_items; i++) {
2729 r = create_many_symlinks(params->prefix[type],
2730 context->directories[type].items[i].path,
2731 context->directories[type].items[i].symlinks);
2732 if (r < 0)
2733 goto fail;
2734 }
2735
07689d5d 2736 return 0;
3536f49e
YW
2737
2738fail:
2739 *exit_status = exit_status_table[type];
3536f49e 2740 return r;
07689d5d
LP
2741}
2742
bb0c0d6f
LP
2743static int write_credential(
2744 int dfd,
2745 const char *id,
2746 const void *data,
2747 size_t size,
2748 uid_t uid,
3a78b0e9 2749 gid_t gid,
bb0c0d6f
LP
2750 bool ownership_ok) {
2751
2752 _cleanup_(unlink_and_freep) char *tmp = NULL;
254d1313 2753 _cleanup_close_ int fd = -EBADF;
bb0c0d6f
LP
2754 int r;
2755
2756 r = tempfn_random_child("", "cred", &tmp);
2757 if (r < 0)
2758 return r;
2759
2760 fd = openat(dfd, tmp, O_CREAT|O_RDWR|O_CLOEXEC|O_EXCL|O_NOFOLLOW|O_NOCTTY, 0600);
2761 if (fd < 0) {
2762 tmp = mfree(tmp);
2763 return -errno;
2764 }
2765
43144be4 2766 r = loop_write(fd, data, size, /* do_poll = */ false);
bb0c0d6f
LP
2767 if (r < 0)
2768 return r;
2769
2770 if (fchmod(fd, 0400) < 0) /* Take away "w" bit */
2771 return -errno;
2772
2773 if (uid_is_valid(uid) && uid != getuid()) {
567aeb58 2774 r = fd_add_uid_acl_permission(fd, uid, ACL_READ);
bb0c0d6f
LP
2775 if (r < 0) {
2776 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
2777 return r;
2778
2779 if (!ownership_ok) /* Ideally we use ACLs, since we can neatly express what we want
2780 * to express: that the user gets read access and nothing
2781 * else. But if the backing fs can't support that (e.g. ramfs)
2782 * then we can use file ownership instead. But that's only safe if
2783 * we can then re-mount the whole thing read-only, so that the
2784 * user can no longer chmod() the file to gain write access. */
2785 return r;
2786
3a78b0e9 2787 if (fchown(fd, uid, gid) < 0)
bb0c0d6f
LP
2788 return -errno;
2789 }
2790 }
2791
2792 if (renameat(dfd, tmp, dfd, id) < 0)
2793 return -errno;
2794
2795 tmp = mfree(tmp);
2796 return 0;
2797}
2798
96df2bd8
DDM
2799typedef enum CredentialSearchPath {
2800 CREDENTIAL_SEARCH_PATH_TRUSTED,
2801 CREDENTIAL_SEARCH_PATH_ENCRYPTED,
2802 CREDENTIAL_SEARCH_PATH_ALL,
2803 _CREDENTIAL_SEARCH_PATH_MAX,
2804 _CREDENTIAL_SEARCH_PATH_INVALID = -EINVAL,
2805} CredentialSearchPath;
2806
2807static char **credential_search_path(const ExecParameters *params, CredentialSearchPath path) {
2ad591a3
LP
2808
2809 _cleanup_strv_free_ char **l = NULL;
2810
2811 assert(params);
96df2bd8 2812 assert(path >= 0 && path < _CREDENTIAL_SEARCH_PATH_MAX);
2ad591a3 2813
96df2bd8
DDM
2814 /* Assemble a search path to find credentials in. For non-encrypted credentials, We'll look in
2815 * /etc/credstore/ (and similar directories in /usr/lib/ + /run/). If we're looking for encrypted
2816 * credentials, we'll look in /etc/credstore.encrypted/ (and similar dirs). */
2ad591a3 2817
96df2bd8 2818 if (IN_SET(path, CREDENTIAL_SEARCH_PATH_ENCRYPTED, CREDENTIAL_SEARCH_PATH_ALL)) {
2ad591a3
LP
2819 if (strv_extend(&l, params->received_encrypted_credentials_directory) < 0)
2820 return NULL;
2821
2822 if (strv_extend_strv(&l, CONF_PATHS_STRV("credstore.encrypted"), /* filter_duplicates= */ true) < 0)
2823 return NULL;
2824 }
2825
96df2bd8
DDM
2826 if (IN_SET(path, CREDENTIAL_SEARCH_PATH_TRUSTED, CREDENTIAL_SEARCH_PATH_ALL)) {
2827 if (params->received_credentials_directory)
2828 if (strv_extend(&l, params->received_credentials_directory) < 0)
2829 return NULL;
2ad591a3 2830
96df2bd8
DDM
2831 if (strv_extend_strv(&l, CONF_PATHS_STRV("credstore"), /* filter_duplicates= */ true) < 0)
2832 return NULL;
2833 }
2ad591a3
LP
2834
2835 if (DEBUG_LOGGING) {
2836 _cleanup_free_ char *t = strv_join(l, ":");
2837
00078fb3 2838 log_debug("Credential search path is: %s", strempty(t));
2ad591a3
LP
2839 }
2840
2841 return TAKE_PTR(l);
2842}
2843
bbfb25f4
DDM
2844static int maybe_decrypt_and_write_credential(
2845 int dir_fd,
2846 const char *id,
2847 bool encrypted,
2848 uid_t uid,
3a78b0e9 2849 gid_t gid,
bbfb25f4
DDM
2850 bool ownership_ok,
2851 const char *data,
2852 size_t size,
2853 uint64_t *left) {
2854
2855 _cleanup_free_ void *plaintext = NULL;
2856 size_t add;
2857 int r;
2858
2859 if (encrypted) {
2860 size_t plaintext_size = 0;
2861
2862 r = decrypt_credential_and_warn(id, now(CLOCK_REALTIME), NULL, NULL, data, size,
2863 &plaintext, &plaintext_size);
2864 if (r < 0)
2865 return r;
2866
2867 data = plaintext;
2868 size = plaintext_size;
2869 }
2870
2871 add = strlen(id) + size;
2872 if (add > *left)
2873 return -E2BIG;
2874
3a78b0e9 2875 r = write_credential(dir_fd, id, data, size, uid, gid, ownership_ok);
bbfb25f4
DDM
2876 if (r < 0)
2877 return log_debug_errno(r, "Failed to write credential '%s': %m", id);
2878
2879 *left -= add;
2880 return 0;
2881}
2882
2883static int load_credential_glob(
2884 const char *path,
2885 bool encrypted,
2886 char **search_path,
2887 ReadFullFileFlags flags,
2888 int write_dfd,
2889 uid_t uid,
3a78b0e9 2890 gid_t gid,
bbfb25f4
DDM
2891 bool ownership_ok,
2892 uint64_t *left) {
2893
2894 int r;
2895
2896 STRV_FOREACH(d, search_path) {
2897 _cleanup_globfree_ glob_t pglob = {};
2898 _cleanup_free_ char *j = NULL;
2899
2900 j = path_join(*d, path);
2901 if (!j)
2902 return -ENOMEM;
2903
2904 r = safe_glob(j, 0, &pglob);
2905 if (r == -ENOENT)
2906 continue;
2907 if (r < 0)
2908 return r;
2909
fcc06682 2910 for (size_t n = 0; n < pglob.gl_pathc; n++) {
bbfb25f4
DDM
2911 _cleanup_free_ char *fn = NULL;
2912 _cleanup_(erase_and_freep) char *data = NULL;
2913 size_t size;
2914
2915 /* path is absolute, hence pass AT_FDCWD as nop dir fd here */
2916 r = read_full_file_full(
2917 AT_FDCWD,
2918 pglob.gl_pathv[n],
2919 UINT64_MAX,
2920 encrypted ? CREDENTIAL_ENCRYPTED_SIZE_MAX : CREDENTIAL_SIZE_MAX,
2921 flags,
2922 NULL,
2923 &data, &size);
2924 if (r < 0)
2925 return log_debug_errno(r, "Failed to read credential '%s': %m",
2926 pglob.gl_pathv[n]);
2927
2928 r = path_extract_filename(pglob.gl_pathv[n], &fn);
2929 if (r < 0)
2930 return log_debug_errno(r, "Failed to extract filename from '%s': %m",
2931 pglob.gl_pathv[n]);
2932
2933 r = maybe_decrypt_and_write_credential(
2934 write_dfd,
2935 fn,
2936 encrypted,
2937 uid,
3a78b0e9 2938 gid,
bbfb25f4
DDM
2939 ownership_ok,
2940 data, size,
2941 left);
2942 if (r == -EEXIST)
2943 continue;
2944 if (r < 0)
2945 return r;
2946 }
2947 }
2948
2949 return 0;
2950}
2951
3989bdc1
AB
2952static int load_credential(
2953 const ExecContext *context,
2954 const ExecParameters *params,
10b44e1d
LP
2955 const char *id,
2956 const char *path,
2957 bool encrypted,
3989bdc1
AB
2958 const char *unit,
2959 int read_dfd,
2960 int write_dfd,
2961 uid_t uid,
3a78b0e9 2962 gid_t gid,
3989bdc1
AB
2963 bool ownership_ok,
2964 uint64_t *left) {
2965
3989bdc1 2966 ReadFullFileFlags flags = READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER;
2ad591a3 2967 _cleanup_strv_free_ char **search_path = NULL;
3989bdc1 2968 _cleanup_(erase_and_freep) char *data = NULL;
2ad591a3
LP
2969 _cleanup_free_ char *bindname = NULL;
2970 const char *source = NULL;
3989bdc1 2971 bool missing_ok = true;
bbfb25f4 2972 size_t size, maxsz;
3989bdc1
AB
2973 int r;
2974
10b44e1d
LP
2975 assert(context);
2976 assert(params);
2977 assert(id);
2978 assert(path);
2979 assert(unit);
661e4251 2980 assert(read_dfd >= 0 || read_dfd == AT_FDCWD);
10b44e1d
LP
2981 assert(write_dfd >= 0);
2982 assert(left);
2983
2ad591a3
LP
2984 if (read_dfd >= 0) {
2985 /* If a directory fd is specified, then read the file directly from that dir. In this case we
2986 * won't do AF_UNIX stuff (we simply don't want to recursively iterate down a tree of AF_UNIX
2987 * IPC sockets). It's OK if a file vanishes here in the time we enumerate it and intend to
2988 * open it. */
2989
2990 if (!filename_is_valid(path)) /* safety check */
2991 return -EINVAL;
2992
2993 missing_ok = true;
10b44e1d 2994 source = path;
2ad591a3
LP
2995
2996 } else if (path_is_absolute(path)) {
2997 /* If this is an absolute path, read the data directly from it, and support AF_UNIX
2998 * sockets */
2999
3000 if (!path_is_valid(path)) /* safety check */
3001 return -EINVAL;
3002
3989bdc1
AB
3003 flags |= READ_FULL_FILE_CONNECT_SOCKET;
3004
3005 /* Pass some minimal info about the unit and the credential name we are looking to acquire
3006 * via the source socket address in case we read off an AF_UNIX socket. */
10b44e1d 3007 if (asprintf(&bindname, "@%" PRIx64"/unit/%s/%s", random_u64(), unit, id) < 0)
3989bdc1
AB
3008 return -ENOMEM;
3009
3010 missing_ok = false;
2ad591a3 3011 source = path;
3989bdc1 3012
2ad591a3
LP
3013 } else if (credential_name_valid(path)) {
3014 /* If this is a relative path, take it as credential name relative to the credentials
3015 * directory we received ourselves. We don't support the AF_UNIX stuff in this mode, since we
3016 * are operating on a credential store, i.e. this is guaranteed to be regular files. */
3017
96df2bd8 3018 search_path = credential_search_path(params, CREDENTIAL_SEARCH_PATH_ALL);
2ad591a3 3019 if (!search_path)
3989bdc1
AB
3020 return -ENOMEM;
3021
2ad591a3 3022 missing_ok = true;
3989bdc1
AB
3023 } else
3024 source = NULL;
3025
2ad591a3
LP
3026 if (encrypted)
3027 flags |= READ_FULL_FILE_UNBASE64;
3028
3029 maxsz = encrypted ? CREDENTIAL_ENCRYPTED_SIZE_MAX : CREDENTIAL_SIZE_MAX;
3030
3031 if (search_path) {
3032 STRV_FOREACH(d, search_path) {
3033 _cleanup_free_ char *j = NULL;
3034
3035 j = path_join(*d, path);
3036 if (!j)
3037 return -ENOMEM;
3038
3039 r = read_full_file_full(
3040 AT_FDCWD, j, /* path is absolute, hence pass AT_FDCWD as nop dir fd here */
3041 UINT64_MAX,
3042 maxsz,
3043 flags,
3044 NULL,
3045 &data, &size);
3046 if (r != -ENOENT)
3047 break;
3048 }
3049 } else if (source)
3989bdc1
AB
3050 r = read_full_file_full(
3051 read_dfd, source,
3052 UINT64_MAX,
2ad591a3
LP
3053 maxsz,
3054 flags,
3989bdc1
AB
3055 bindname,
3056 &data, &size);
3057 else
3058 r = -ENOENT;
3059
10b44e1d 3060 if (r == -ENOENT && (missing_ok || hashmap_contains(context->set_credentials, id))) {
3989bdc1
AB
3061 /* Make a missing inherited credential non-fatal, let's just continue. After all apps
3062 * will get clear errors if we don't pass such a missing credential on as they
3063 * themselves will get ENOENT when trying to read them, which should not be much
3064 * worse than when we handle the error here and make it fatal.
3065 *
3066 * Also, if the source file doesn't exist, but a fallback is set via SetCredentials=
3067 * we are fine, too. */
10b44e1d 3068 log_debug_errno(r, "Couldn't read inherited credential '%s', skipping: %m", path);
3989bdc1
AB
3069 return 0;
3070 }
3071 if (r < 0)
10b44e1d 3072 return log_debug_errno(r, "Failed to read credential '%s': %m", path);
3989bdc1 3073
3a78b0e9 3074 return maybe_decrypt_and_write_credential(write_dfd, id, encrypted, uid, gid, ownership_ok, data, size, left);
3989bdc1
AB
3075}
3076
3077struct load_cred_args {
3989bdc1
AB
3078 const ExecContext *context;
3079 const ExecParameters *params;
461345a1 3080 bool encrypted;
3989bdc1
AB
3081 const char *unit;
3082 int dfd;
3083 uid_t uid;
3a78b0e9 3084 gid_t gid;
3989bdc1
AB
3085 bool ownership_ok;
3086 uint64_t *left;
3087};
3088
3089static int load_cred_recurse_dir_cb(
3090 RecurseDirEvent event,
3091 const char *path,
3092 int dir_fd,
3093 int inode_fd,
3094 const struct dirent *de,
3095 const struct statx *sx,
3096 void *userdata) {
3097
6394e5cd 3098 struct load_cred_args *args = ASSERT_PTR(userdata);
11348386 3099 _cleanup_free_ char *sub_id = NULL;
3989bdc1
AB
3100 int r;
3101
3102 if (event != RECURSE_DIR_ENTRY)
3103 return RECURSE_DIR_CONTINUE;
3104
3105 if (!IN_SET(de->d_type, DT_REG, DT_SOCK))
3106 return RECURSE_DIR_CONTINUE;
3107
11348386 3108 sub_id = strreplace(path, "/", "_");
3989bdc1
AB
3109 if (!sub_id)
3110 return -ENOMEM;
3111
3112 if (!credential_name_valid(sub_id))
1451435c 3113 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Credential would get ID %s, which is not valid, refusing", sub_id);
3989bdc1 3114
5bec447a 3115 if (faccessat(args->dfd, sub_id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0) {
3989bdc1
AB
3116 log_debug("Skipping credential with duplicated ID %s at %s", sub_id, path);
3117 return RECURSE_DIR_CONTINUE;
3118 }
5bec447a
LP
3119 if (errno != ENOENT)
3120 return log_debug_errno(errno, "Failed to test if credential %s exists: %m", sub_id);
3989bdc1 3121
10b44e1d
LP
3122 r = load_credential(
3123 args->context,
3124 args->params,
3125 sub_id,
3126 de->d_name,
461345a1 3127 args->encrypted,
10b44e1d
LP
3128 args->unit,
3129 dir_fd,
3130 args->dfd,
3131 args->uid,
3a78b0e9 3132 args->gid,
10b44e1d
LP
3133 args->ownership_ok,
3134 args->left);
3989bdc1
AB
3135 if (r < 0)
3136 return r;
3137
3138 return RECURSE_DIR_CONTINUE;
3139}
3140
bb0c0d6f
LP
3141static int acquire_credentials(
3142 const ExecContext *context,
3143 const ExecParameters *params,
d3dcf4e3 3144 const char *unit,
bb0c0d6f
LP
3145 const char *p,
3146 uid_t uid,
3a78b0e9 3147 gid_t gid,
bb0c0d6f
LP
3148 bool ownership_ok) {
3149
43144be4 3150 uint64_t left = CREDENTIALS_TOTAL_SIZE_MAX;
254d1313 3151 _cleanup_close_ int dfd = -EBADF;
bbfb25f4 3152 const char *ic;
43144be4 3153 ExecLoadCredential *lc;
bb0c0d6f 3154 ExecSetCredential *sc;
bb0c0d6f
LP
3155 int r;
3156
3157 assert(context);
3158 assert(p);
3159
3160 dfd = open(p, O_DIRECTORY|O_CLOEXEC);
3161 if (dfd < 0)
3162 return -errno;
3163
f76ce81b
LP
3164 r = fd_acl_make_writable(dfd); /* Add the "w" bit, if we are reusing an already set up credentials dir where it was unset */
3165 if (r < 0)
3166 return r;
3167
43144be4
LP
3168 /* First, load credentials off disk (or acquire via AF_UNIX socket) */
3169 HASHMAP_FOREACH(lc, context->load_credentials) {
254d1313 3170 _cleanup_close_ int sub_fd = -EBADF;
d3dcf4e3 3171
f344f7fd
LP
3172 /* If this is an absolute path, then try to open it as a directory. If that works, then we'll
3173 * recurse into it. If it is an absolute path but it isn't a directory, then we'll open it as
3174 * a regular file. Finally, if it's a relative path we will use it as a credential name to
3175 * propagate a credential passed to us from further up. */
43144be4 3176
f344f7fd
LP
3177 if (path_is_absolute(lc->path)) {
3178 sub_fd = open(lc->path, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
1d68a2e1
LP
3179 if (sub_fd < 0 && !IN_SET(errno,
3180 ENOTDIR, /* Not a directory */
3181 ENOENT)) /* Doesn't exist? */
3182 return log_debug_errno(errno, "Failed to open '%s': %m", lc->path);
f344f7fd 3183 }
43144be4 3184
61c5a49e 3185 if (sub_fd < 0)
f344f7fd 3186 /* Regular file (incl. a credential passed in from higher up) */
10b44e1d
LP
3187 r = load_credential(
3188 context,
3189 params,
3190 lc->id,
3191 lc->path,
3192 lc->encrypted,
3193 unit,
661e4251 3194 AT_FDCWD,
10b44e1d
LP
3195 dfd,
3196 uid,
3a78b0e9 3197 gid,
10b44e1d
LP
3198 ownership_ok,
3199 &left);
61c5a49e 3200 else
10b44e1d 3201 /* Directory */
3989bdc1
AB
3202 r = recurse_dir(
3203 sub_fd,
11348386 3204 /* path= */ lc->id, /* recurse_dir() will suffix the subdir paths from here to the top-level id */
3989bdc1
AB
3205 /* statx_mask= */ 0,
3206 /* n_depth_max= */ UINT_MAX,
9883cbb2 3207 RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE,
3989bdc1
AB
3208 load_cred_recurse_dir_cb,
3209 &(struct load_cred_args) {
3989bdc1
AB
3210 .context = context,
3211 .params = params,
461345a1 3212 .encrypted = lc->encrypted,
3989bdc1
AB
3213 .unit = unit,
3214 .dfd = dfd,
3215 .uid = uid,
3a78b0e9 3216 .gid = gid,
3989bdc1
AB
3217 .ownership_ok = ownership_ok,
3218 .left = &left,
3219 });
61c5a49e
LP
3220 if (r < 0)
3221 return r;
bb0c0d6f
LP
3222 }
3223
bbfb25f4
DDM
3224 /* Next, look for system credentials and credentials in the credentials store. Note that these do not
3225 * override any credentials found earlier. */
3226 SET_FOREACH(ic, context->import_credentials) {
3227 _cleanup_free_ char **search_path = NULL;
3228
3229 search_path = credential_search_path(params, CREDENTIAL_SEARCH_PATH_TRUSTED);
3230 if (!search_path)
3231 return -ENOMEM;
3232
3233 r = load_credential_glob(
3234 ic,
3235 /* encrypted = */ false,
3236 search_path,
3237 READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER,
3238 dfd,
3239 uid,
3a78b0e9 3240 gid,
bbfb25f4
DDM
3241 ownership_ok,
3242 &left);
3243 if (r < 0)
3244 return r;
3245
3246 search_path = strv_free(search_path);
3247 search_path = credential_search_path(params, CREDENTIAL_SEARCH_PATH_ENCRYPTED);
3248 if (!search_path)
3249 return -ENOMEM;
3250
3251 r = load_credential_glob(
3252 ic,
3253 /* encrypted = */ true,
3254 search_path,
3255 READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER|READ_FULL_FILE_UNBASE64,
3256 dfd,
3257 uid,
3a78b0e9 3258 gid,
bbfb25f4
DDM
3259 ownership_ok,
3260 &left);
3261 if (r < 0)
3262 return r;
3263 }
3264
3265 /* Finally, we add in literally specified credentials. If the credentials already exist, we'll not
3266 * add them, so that they can act as a "default" if the same credential is specified multiple times. */
43144be4
LP
3267 HASHMAP_FOREACH(sc, context->set_credentials) {
3268 _cleanup_(erase_and_freep) void *plaintext = NULL;
3269 const char *data;
3270 size_t size, add;
3271
9e6e9d61
LP
3272 /* Note that we check ahead of time here instead of relying on O_EXCL|O_CREAT later to return
3273 * EEXIST if the credential already exists. That's because the TPM2-based decryption is kinda
3274 * slow and involved, hence it's nice to be able to skip that if the credential already
3275 * exists anyway. */
43144be4
LP
3276 if (faccessat(dfd, sc->id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
3277 continue;
3278 if (errno != ENOENT)
3279 return log_debug_errno(errno, "Failed to test if credential %s exists: %m", sc->id);
3280
3281 if (sc->encrypted) {
6a0779cb 3282 r = decrypt_credential_and_warn(sc->id, now(CLOCK_REALTIME), NULL, NULL, sc->data, sc->size, &plaintext, &size);
43144be4
LP
3283 if (r < 0)
3284 return r;
3285
3286 data = plaintext;
3287 } else {
3288 data = sc->data;
3289 size = sc->size;
3290 }
3291
3292 add = strlen(sc->id) + size;
3293 if (add > left)
3294 return -E2BIG;
3295
3a78b0e9 3296 r = write_credential(dfd, sc->id, data, size, uid, gid, ownership_ok);
43144be4
LP
3297 if (r < 0)
3298 return r;
3299
43144be4
LP
3300 left -= add;
3301 }
3302
f76ce81b
LP
3303 r = fd_acl_make_read_only(dfd); /* Now take away the "w" bit */
3304 if (r < 0)
3305 return r;
bb0c0d6f
LP
3306
3307 /* After we created all keys with the right perms, also make sure the credential store as a whole is
3308 * accessible */
3309
3310 if (uid_is_valid(uid) && uid != getuid()) {
567aeb58 3311 r = fd_add_uid_acl_permission(dfd, uid, ACL_READ | ACL_EXECUTE);
bb0c0d6f
LP
3312 if (r < 0) {
3313 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
3314 return r;
3315
3316 if (!ownership_ok)
3317 return r;
3318
3a78b0e9 3319 if (fchown(dfd, uid, gid) < 0)
bb0c0d6f
LP
3320 return -errno;
3321 }
3322 }
3323
3324 return 0;
3325}
3326
3327static int setup_credentials_internal(
3328 const ExecContext *context,
3329 const ExecParameters *params,
d3dcf4e3 3330 const char *unit,
bb0c0d6f
LP
3331 const char *final, /* This is where the credential store shall eventually end up at */
3332 const char *workspace, /* This is where we can prepare it before moving it to the final place */
3333 bool reuse_workspace, /* Whether to reuse any existing workspace mount if it already is a mount */
3334 bool must_mount, /* Whether to require that we mount something, it's not OK to use the plain directory fall back */
3a78b0e9
DDM
3335 uid_t uid,
3336 gid_t gid) {
bb0c0d6f
LP
3337
3338 int r, workspace_mounted; /* negative if we don't know yet whether we have/can mount something; true
3339 * if we mounted something; false if we definitely can't mount anything */
3340 bool final_mounted;
3341 const char *where;
3342
3343 assert(context);
3344 assert(final);
3345 assert(workspace);
3346
3347 if (reuse_workspace) {
3348 r = path_is_mount_point(workspace, NULL, 0);
3349 if (r < 0)
3350 return r;
3351 if (r > 0)
3352 workspace_mounted = true; /* If this is already a mount, and we are supposed to reuse it, let's keep this in mind */
3353 else
3354 workspace_mounted = -1; /* We need to figure out if we can mount something to the workspace */
3355 } else
3356 workspace_mounted = -1; /* ditto */
3357
3358 r = path_is_mount_point(final, NULL, 0);
3359 if (r < 0)
3360 return r;
3361 if (r > 0) {
3362 /* If the final place already has something mounted, we use that. If the workspace also has
3363 * something mounted we assume it's actually the same mount (but with MS_RDONLY
3364 * different). */
3365 final_mounted = true;
3366
3367 if (workspace_mounted < 0) {
f0353cf2 3368 /* If the final place is mounted, but the workspace isn't, then let's bind mount
bb0c0d6f
LP
3369 * the final version to the workspace, and make it writable, so that we can make
3370 * changes */
3371
21935150
LP
3372 r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
3373 if (r < 0)
3374 return r;
bb0c0d6f 3375
1155f44f 3376 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|credentials_fs_mount_flags(/* ro= */ false), NULL);
21935150
LP
3377 if (r < 0)
3378 return r;
bb0c0d6f
LP
3379
3380 workspace_mounted = true;
3381 }
3382 } else
3383 final_mounted = false;
3384
3385 if (workspace_mounted < 0) {
3386 /* Nothing is mounted on the workspace yet, let's try to mount something now */
bb0c0d6f 3387
1155f44f
LP
3388 r = mount_credentials_fs(workspace, CREDENTIALS_TOTAL_SIZE_MAX, /* ro= */ false);
3389 if (r < 0) {
3390 /* If that didn't work, try to make a bind mount from the final to the workspace, so that we can make it writable there. */
3391 r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
3392 if (r < 0) {
3393 if (!ERRNO_IS_PRIVILEGE(r)) /* Propagate anything that isn't a permission problem */
3394 return r;
bb0c0d6f 3395
1155f44f
LP
3396 if (must_mount) /* If we it's not OK to use the plain directory
3397 * fallback, propagate all errors too */
3398 return r;
bb0c0d6f 3399
1155f44f
LP
3400 /* If we lack privileges to bind mount stuff, then let's gracefully
3401 * proceed for compat with container envs, and just use the final dir
3402 * as is. */
bb0c0d6f 3403
1155f44f 3404 workspace_mounted = false;
bb0c0d6f 3405 } else {
bb0c0d6f 3406 /* Make the new bind mount writable (i.e. drop MS_RDONLY) */
1155f44f 3407 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|credentials_fs_mount_flags(/* ro= */ false), NULL);
21935150
LP
3408 if (r < 0)
3409 return r;
bb0c0d6f
LP
3410
3411 workspace_mounted = true;
bb0c0d6f 3412 }
1155f44f
LP
3413 } else
3414 workspace_mounted = true;
bb0c0d6f
LP
3415 }
3416
3417 assert(!must_mount || workspace_mounted > 0);
3418 where = workspace_mounted ? workspace : final;
3419
03bc11d1 3420 (void) label_fix_full(AT_FDCWD, where, final, 0);
e3a0a862 3421
3a78b0e9 3422 r = acquire_credentials(context, params, unit, where, uid, gid, workspace_mounted);
bb0c0d6f
LP
3423 if (r < 0)
3424 return r;
3425
3426 if (workspace_mounted) {
21dd1de6 3427 bool install;
bb0c0d6f 3428
21dd1de6
LP
3429 /* Determine if we should actually install the prepared mount in the final location by bind
3430 * mounting it there. We do so only if the mount is not established there already, and if the
3431 * mount is actually non-empty (i.e. carries at least one credential). Not that in the best
fa18faf1 3432 * case we are doing all this in a mount namespace, thus no one else will see that we
21dd1de6 3433 * allocated a file system we are getting rid of again here. */
21935150 3434 if (final_mounted)
21dd1de6
LP
3435 install = false; /* already installed */
3436 else {
3437 r = dir_is_empty(where, /* ignore_hidden_or_backup= */ false);
3438 if (r < 0)
3439 return r;
3440
3441 install = r == 0; /* install only if non-empty */
3442 }
3443
3444 if (install) {
3445 /* Make workspace read-only now, so that any bind mount we make from it defaults to read-only too */
1155f44f 3446 r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|credentials_fs_mount_flags(/* ro= */ true), NULL);
21dd1de6
LP
3447 if (r < 0)
3448 return r;
3449
3450 /* And mount it to the final place, read-only */
21935150 3451 r = mount_nofollow_verbose(LOG_DEBUG, workspace, final, NULL, MS_MOVE, NULL);
21dd1de6
LP
3452 } else
3453 /* Otherwise get rid of it */
3454 r = umount_verbose(LOG_DEBUG, workspace, MNT_DETACH|UMOUNT_NOFOLLOW);
21935150
LP
3455 if (r < 0)
3456 return r;
bb0c0d6f
LP
3457 } else {
3458 _cleanup_free_ char *parent = NULL;
3459
3460 /* If we do not have our own mount put used the plain directory fallback, then we need to
3461 * open access to the top-level credential directory and the per-service directory now */
3462
45519d13
LP
3463 r = path_extract_directory(final, &parent);
3464 if (r < 0)
3465 return r;
bb0c0d6f
LP
3466 if (chmod(parent, 0755) < 0)
3467 return -errno;
3468 }
3469
3470 return 0;
3471}
3472
3473static int setup_credentials(
3474 const ExecContext *context,
3475 const ExecParameters *params,
3476 const char *unit,
3a78b0e9
DDM
3477 uid_t uid,
3478 gid_t gid) {
bb0c0d6f
LP
3479
3480 _cleanup_free_ char *p = NULL, *q = NULL;
bb0c0d6f
LP
3481 int r;
3482
3483 assert(context);
3484 assert(params);
3485
3486 if (!exec_context_has_credentials(context))
3487 return 0;
3488
3489 if (!params->prefix[EXEC_DIRECTORY_RUNTIME])
3490 return -EINVAL;
3491
3492 /* This where we'll place stuff when we are done; this main credentials directory is world-readable,
3493 * and the subdir we mount over with a read-only file system readable by the service's user */
3494 q = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials");
3495 if (!q)
3496 return -ENOMEM;
3497
3498 r = mkdir_label(q, 0755); /* top-level dir: world readable/searchable */
3499 if (r < 0 && r != -EEXIST)
3500 return r;
3501
3502 p = path_join(q, unit);
3503 if (!p)
3504 return -ENOMEM;
3505
3506 r = mkdir_label(p, 0700); /* per-unit dir: private to user */
3507 if (r < 0 && r != -EEXIST)
3508 return r;
3509
3510 r = safe_fork("(sd-mkdcreds)", FORK_DEATHSIG|FORK_WAIT|FORK_NEW_MOUNTNS, NULL);
3511 if (r < 0) {
3512 _cleanup_free_ char *t = NULL, *u = NULL;
3513
3514 /* If this is not a privilege or support issue then propagate the error */
3515 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
3516 return r;
3517
3518 /* Temporary workspace, that remains inaccessible all the time. We prepare stuff there before moving
3519 * it into place, so that users can't access half-initialized credential stores. */
3520 t = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/temporary-credentials");
3521 if (!t)
3522 return -ENOMEM;
3523
3524 /* We can't set up a mount namespace. In that case operate on a fixed, inaccessible per-unit
3525 * directory outside of /run/credentials/ first, and then move it over to /run/credentials/
3526 * after it is fully set up */
3527 u = path_join(t, unit);
3528 if (!u)
3529 return -ENOMEM;
3530
3531 FOREACH_STRING(i, t, u) {
3532 r = mkdir_label(i, 0700);
3533 if (r < 0 && r != -EEXIST)
3534 return r;
3535 }
3536
3537 r = setup_credentials_internal(
3538 context,
3539 params,
d3dcf4e3 3540 unit,
bb0c0d6f
LP
3541 p, /* final mount point */
3542 u, /* temporary workspace to overmount */
3543 true, /* reuse the workspace if it is already a mount */
3544 false, /* it's OK to fall back to a plain directory if we can't mount anything */
3a78b0e9
DDM
3545 uid,
3546 gid);
bb0c0d6f
LP
3547
3548 (void) rmdir(u); /* remove the workspace again if we can. */
3549
3550 if (r < 0)
3551 return r;
3552
3553 } else if (r == 0) {
3554
3555 /* We managed to set up a mount namespace, and are now in a child. That's great. In this case
3556 * we can use the same directory for all cases, after turning off propagation. Question
3557 * though is: where do we turn off propagation exactly, and where do we place the workspace
3558 * directory? We need some place that is guaranteed to be a mount point in the host, and
3559 * which is guaranteed to have a subdir we can mount over. /run/ is not suitable for this,
3560 * since we ultimately want to move the resulting file system there, i.e. we need propagation
3561 * for /run/ eventually. We could use our own /run/systemd/bind mount on itself, but that
3562 * would be visible in the host mount table all the time, which we want to avoid. Hence, what
3563 * we do here instead we use /dev/ and /dev/shm/ for our purposes. We know for sure that
3564 * /dev/ is a mount point and we now for sure that /dev/shm/ exists. Hence we can turn off
3565 * propagation on the former, and then overmount the latter.
3566 *
3567 * Yes it's nasty playing games with /dev/ and /dev/shm/ like this, since it does not exist
3568 * for this purpose, but there are few other candidates that work equally well for us, and
3569 * given that the we do this in a privately namespaced short-lived single-threaded process
7802194a 3570 * that no one else sees this should be OK to do. */
bb0c0d6f 3571
21935150
LP
3572 r = mount_nofollow_verbose(LOG_DEBUG, NULL, "/dev", NULL, MS_SLAVE|MS_REC, NULL); /* Turn off propagation from our namespace to host */
3573 if (r < 0)
bb0c0d6f
LP
3574 goto child_fail;
3575
3576 r = setup_credentials_internal(
3577 context,
3578 params,
d3dcf4e3 3579 unit,
bb0c0d6f
LP
3580 p, /* final mount point */
3581 "/dev/shm", /* temporary workspace to overmount */
3582 false, /* do not reuse /dev/shm if it is already a mount, under no circumstances */
3583 true, /* insist that something is mounted, do not allow fallback to plain directory */
3a78b0e9
DDM
3584 uid,
3585 gid);
bb0c0d6f
LP
3586 if (r < 0)
3587 goto child_fail;
3588
3589 _exit(EXIT_SUCCESS);
3590
3591 child_fail:
3592 _exit(EXIT_FAILURE);
3593 }
3594
3aaa3763
LP
3595 /* If the credentials dir is empty and not a mount point, then there's no point in having it. Let's
3596 * try to remove it. This matters in particular if we created the dir as mount point but then didn't
3597 * actually end up mounting anything on it. In that case we'd rather have ENOENT than EACCESS being
3598 * seen by users when trying access this inode. */
3599 (void) rmdir(p);
bb0c0d6f
LP
3600 return 0;
3601}
3602
92b423b9 3603#if ENABLE_SMACK
cefc33ae 3604static int setup_smack(
aa5ae971 3605 const Manager *manager,
cefc33ae 3606 const ExecContext *context,
b83d5050 3607 int executable_fd) {
cefc33ae
LP
3608 int r;
3609
3610 assert(context);
b83d5050 3611 assert(executable_fd >= 0);
cefc33ae 3612
cefc33ae
LP
3613 if (context->smack_process_label) {
3614 r = mac_smack_apply_pid(0, context->smack_process_label);
3615 if (r < 0)
3616 return r;
aa5ae971 3617 } else if (manager->default_smack_process_label) {
cefc33ae
LP
3618 _cleanup_free_ char *exec_label = NULL;
3619
b83d5050 3620 r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
00675c36 3621 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
cefc33ae
LP
3622 return r;
3623
1da3cb81 3624 r = mac_smack_apply_pid(0, exec_label ?: manager->default_smack_process_label);
cefc33ae
LP
3625 if (r < 0)
3626 return r;
3627 }
cefc33ae
LP
3628
3629 return 0;
3630}
92b423b9 3631#endif
cefc33ae 3632
6c47cd7d
LP
3633static int compile_bind_mounts(
3634 const ExecContext *context,
3635 const ExecParameters *params,
3636 BindMount **ret_bind_mounts,
da6053d0 3637 size_t *ret_n_bind_mounts,
6c47cd7d
LP
3638 char ***ret_empty_directories) {
3639
3640 _cleanup_strv_free_ char **empty_directories = NULL;
ed8267c7 3641 BindMount *bind_mounts = NULL;
5b10116e 3642 size_t n, h = 0;
6c47cd7d
LP
3643 int r;
3644
3645 assert(context);
3646 assert(params);
3647 assert(ret_bind_mounts);
3648 assert(ret_n_bind_mounts);
3649 assert(ret_empty_directories);
3650
ed8267c7
DT
3651 CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
3652
6c47cd7d 3653 n = context->n_bind_mounts;
5b10116e 3654 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
6c47cd7d
LP
3655 if (!params->prefix[t])
3656 continue;
3657
a2ab603c
YW
3658 for (size_t i = 0; i < context->directories[t].n_items; i++)
3659 n += !context->directories[t].items[i].only_create;
6c47cd7d
LP
3660 }
3661
3662 if (n <= 0) {
3663 *ret_bind_mounts = NULL;
3664 *ret_n_bind_mounts = 0;
3665 *ret_empty_directories = NULL;
3666 return 0;
3667 }
3668
3669 bind_mounts = new(BindMount, n);
3670 if (!bind_mounts)
3671 return -ENOMEM;
3672
5b10116e 3673 for (size_t i = 0; i < context->n_bind_mounts; i++) {
6c47cd7d 3674 BindMount *item = context->bind_mounts + i;
93404d34 3675 _cleanup_free_ char *s = NULL, *d = NULL;
6c47cd7d
LP
3676
3677 s = strdup(item->source);
ed8267c7
DT
3678 if (!s)
3679 return -ENOMEM;
6c47cd7d
LP
3680
3681 d = strdup(item->destination);
93404d34 3682 if (!d)
ed8267c7 3683 return -ENOMEM;
6c47cd7d
LP
3684
3685 bind_mounts[h++] = (BindMount) {
93404d34
DT
3686 .source = TAKE_PTR(s),
3687 .destination = TAKE_PTR(d),
6c47cd7d
LP
3688 .read_only = item->read_only,
3689 .recursive = item->recursive,
3690 .ignore_enoent = item->ignore_enoent,
3691 };
3692 }
3693
5b10116e 3694 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
6c47cd7d
LP
3695 if (!params->prefix[t])
3696 continue;
3697
211a3d87 3698 if (context->directories[t].n_items == 0)
6c47cd7d
LP
3699 continue;
3700
494d0247 3701 if (exec_directory_is_private(context, t) &&
74e12520 3702 !exec_context_with_rootfs(context)) {
6c47cd7d
LP
3703 char *private_root;
3704
3705 /* So this is for a dynamic user, and we need to make sure the process can access its own
3706 * directory. For that we overmount the usually inaccessible "private" subdirectory with a
3707 * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
3708
657ee2d8 3709 private_root = path_join(params->prefix[t], "private");
ed8267c7
DT
3710 if (!private_root)
3711 return -ENOMEM;
6c47cd7d
LP
3712
3713 r = strv_consume(&empty_directories, private_root);
a635a7ae 3714 if (r < 0)
ed8267c7 3715 return r;
6c47cd7d
LP
3716 }
3717
211a3d87 3718 for (size_t i = 0; i < context->directories[t].n_items; i++) {
93404d34 3719 _cleanup_free_ char *s = NULL, *d = NULL;
6c47cd7d 3720
a2ab603c
YW
3721 /* When one of the parent directories is in the list, we cannot create the symlink
3722 * for the child directory. See also the comments in setup_exec_directory(). */
3723 if (context->directories[t].items[i].only_create)
3724 continue;
3725
494d0247 3726 if (exec_directory_is_private(context, t))
211a3d87 3727 s = path_join(params->prefix[t], "private", context->directories[t].items[i].path);
6c47cd7d 3728 else
211a3d87 3729 s = path_join(params->prefix[t], context->directories[t].items[i].path);
ed8267c7
DT
3730 if (!s)
3731 return -ENOMEM;
6c47cd7d 3732
494d0247 3733 if (exec_directory_is_private(context, t) &&
74e12520 3734 exec_context_with_rootfs(context))
5609f688
YW
3735 /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3736 * directory is not created on the root directory. So, let's bind-mount the directory
3737 * on the 'non-private' place. */
211a3d87 3738 d = path_join(params->prefix[t], context->directories[t].items[i].path);
5609f688
YW
3739 else
3740 d = strdup(s);
93404d34 3741 if (!d)
ed8267c7 3742 return -ENOMEM;
6c47cd7d
LP
3743
3744 bind_mounts[h++] = (BindMount) {
93404d34
DT
3745 .source = TAKE_PTR(s),
3746 .destination = TAKE_PTR(d),
6c47cd7d 3747 .read_only = false,
9ce4e4b0 3748 .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
6c47cd7d
LP
3749 .recursive = true,
3750 .ignore_enoent = false,
3751 };
3752 }
3753 }
3754
3755 assert(h == n);
3756
ed8267c7 3757 *ret_bind_mounts = TAKE_PTR(bind_mounts);
6c47cd7d 3758 *ret_n_bind_mounts = n;
ae2a15bc 3759 *ret_empty_directories = TAKE_PTR(empty_directories);
6c47cd7d
LP
3760
3761 return (int) n;
6c47cd7d
LP
3762}
3763
df61e79a
LB
3764/* ret_symlinks will contain a list of pairs src:dest that describes
3765 * the symlinks to create later on. For example, the symlinks needed
3766 * to safely give private directories to DynamicUser=1 users. */
3767static int compile_symlinks(
3768 const ExecContext *context,
3769 const ExecParameters *params,
3770 char ***ret_symlinks) {
3771
3772 _cleanup_strv_free_ char **symlinks = NULL;
3773 int r;
3774
3775 assert(context);
3776 assert(params);
3777 assert(ret_symlinks);
3778
3779 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
211a3d87
LB
3780 for (size_t i = 0; i < context->directories[dt].n_items; i++) {
3781 _cleanup_free_ char *private_path = NULL, *path = NULL;
df61e79a 3782
211a3d87
LB
3783 STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) {
3784 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
df61e79a 3785
211a3d87
LB
3786 src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path);
3787 dst_abs = path_join(params->prefix[dt], *symlink);
3788 if (!src_abs || !dst_abs)
3789 return -ENOMEM;
df61e79a 3790
211a3d87
LB
3791 r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
3792 if (r < 0)
3793 return r;
3794 }
3795
a2ab603c
YW
3796 if (!exec_directory_is_private(context, dt) ||
3797 exec_context_with_rootfs(context) ||
3798 context->directories[dt].items[i].only_create)
211a3d87
LB
3799 continue;
3800
3801 private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path);
df61e79a
LB
3802 if (!private_path)
3803 return -ENOMEM;
3804
211a3d87 3805 path = path_join(params->prefix[dt], context->directories[dt].items[i].path);
df61e79a
LB
3806 if (!path)
3807 return -ENOMEM;
3808
3809 r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
3810 if (r < 0)
3811 return r;
3812 }
3813 }
3814
3815 *ret_symlinks = TAKE_PTR(symlinks);
3816
3817 return 0;
3818}
3819
4e677599
LP
3820static bool insist_on_sandboxing(
3821 const ExecContext *context,
3822 const char *root_dir,
3823 const char *root_image,
3824 const BindMount *bind_mounts,
3825 size_t n_bind_mounts) {
3826
4e677599
LP
3827 assert(context);
3828 assert(n_bind_mounts == 0 || bind_mounts);
3829
3830 /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
86b52a39 3831 * would alter the view on the file system beyond making things read-only or invisible, i.e. would
4e677599
LP
3832 * rearrange stuff in a way we cannot ignore gracefully. */
3833
3834 if (context->n_temporary_filesystems > 0)
3835 return true;
3836
3837 if (root_dir || root_image)
3838 return true;
3839
b3d13314
LB
3840 if (context->n_mount_images > 0)
3841 return true;
3842
4e677599
LP
3843 if (context->dynamic_user)
3844 return true;
3845
4355c04f
LB
3846 if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
3847 return true;
3848
4e677599
LP
3849 /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3850 * essential. */
5b10116e 3851 for (size_t i = 0; i < n_bind_mounts; i++)
4e677599
LP
3852 if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
3853 return true;
3854
91dd5f7c
LP
3855 if (context->log_namespace)
3856 return true;
3857
4e677599
LP
3858 return false;
3859}
3860
9c0c6701
DDM
3861static int setup_ephemeral(const ExecContext *context, ExecRuntime *runtime) {
3862 _cleanup_close_ int fd = -EBADF;
3863 int r;
3864
3865 if (!runtime || !runtime->ephemeral_copy)
3866 return 0;
3867
3868 r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
3869 if (r < 0)
3870 return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
3871
3872 CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
3873
3874 fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
3875 if (fd >= 0)
3876 /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3877 return 0;
3878
3879 if (fd != -EAGAIN)
3880 return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
3881
3882 log_debug("Making ephemeral snapshot of %s to %s",
3883 context->root_image ?: context->root_directory, runtime->ephemeral_copy);
3884
3885 if (context->root_image)
3886 fd = copy_file(context->root_image, runtime->ephemeral_copy, O_EXCL, 0600,
3887 COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME);
3888 else
3889 fd = btrfs_subvol_snapshot_at(AT_FDCWD, context->root_directory,
3890 AT_FDCWD, runtime->ephemeral_copy,
3891 BTRFS_SNAPSHOT_FALLBACK_COPY |
3892 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3893 BTRFS_SNAPSHOT_RECURSIVE |
3894 BTRFS_SNAPSHOT_LOCK_BSD);
3895 if (fd < 0)
3896 return log_debug_errno(fd, "Failed to snapshot %s to %s: %m",
3897 context->root_image ?: context->root_directory, runtime->ephemeral_copy);
3898
3899 if (context->root_image) {
3900 /* A root image might be subject to lots of random writes so let's try to disable COW on it
3901 * which tends to not perform well in combination with lots of random writes.
3902 *
3903 * Note: btrfs actually isn't impressed by us setting the flag after making the reflink'ed
3904 * copy, but we at least want to make the intention clear.
3905 */
3906 r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL, NULL);
3907 if (r < 0)
3908 log_debug_errno(fd, "Failed to disable copy-on-write for %s, ignoring: %m", runtime->ephemeral_copy);
3909 }
3910
3911 r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
3912 if (r < 0)
3913 return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
3914
3915 return 1;
3916}
3917
66130f0a
DDM
3918static int verity_settings_prepare(
3919 VeritySettings *verity,
3920 const char *root_image,
3921 const void *root_hash,
3922 size_t root_hash_size,
3923 const char *root_hash_path,
3924 const void *root_hash_sig,
3925 size_t root_hash_sig_size,
3926 const char *root_hash_sig_path,
3927 const char *verity_data_path) {
3928
3929 int r;
3930
3931 assert(verity);
3932
3933 if (root_hash) {
3934 void *d;
3935
3936 d = memdup(root_hash, root_hash_size);
3937 if (!d)
3938 return -ENOMEM;
3939
3940 free_and_replace(verity->root_hash, d);
3941 verity->root_hash_size = root_hash_size;
3942 verity->designator = PARTITION_ROOT;
3943 }
3944
3945 if (root_hash_sig) {
3946 void *d;
3947
3948 d = memdup(root_hash_sig, root_hash_sig_size);
3949 if (!d)
3950 return -ENOMEM;
3951
3952 free_and_replace(verity->root_hash_sig, d);
3953 verity->root_hash_sig_size = root_hash_sig_size;
3954 verity->designator = PARTITION_ROOT;
3955 }
3956
3957 if (verity_data_path) {
3958 r = free_and_strdup(&verity->data_path, verity_data_path);
3959 if (r < 0)
3960 return r;
3961 }
3962
3963 r = verity_settings_load(
3964 verity,
3965 root_image,
3966 root_hash_path,
3967 root_hash_sig_path);
3968 if (r < 0)
3969 return log_debug_errno(r, "Failed to load root hash: %m");
3970
3971 return 0;
3972}
3973
6818c54c 3974static int apply_mount_namespace(
34cf6c43 3975 const Unit *u,
9f71ba8d 3976 ExecCommandFlags command_flags,
6818c54c
LP
3977 const ExecContext *context,
3978 const ExecParameters *params,
9c0c6701 3979 ExecRuntime *runtime,
d4b6ec98 3980 const char *memory_pressure_path,
7cc5ef5f 3981 char **error_path) {
6818c54c 3982
66130f0a 3983 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
d4b6ec98
LB
3984 _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
3985 **read_write_paths_cleanup = NULL;
24759d8f 3986 _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
3f37a825 3987 *extension_dir = NULL, *host_os_release = NULL;
66130f0a 3988 const char *root_dir = NULL, *root_image = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
d4b6ec98 3989 char **read_write_paths;
228af36f 3990 NamespaceInfo ns_info;
165a31c0 3991 bool needs_sandboxing;
6c47cd7d 3992 BindMount *bind_mounts = NULL;
da6053d0 3993 size_t n_bind_mounts = 0;
6818c54c 3994 int r;
93c6bb51 3995
2b3c1b9e
DH
3996 assert(context);
3997
29933daf
DT
3998 CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
3999
915e6d16 4000 if (params->flags & EXEC_APPLY_CHROOT) {
9c0c6701
DDM
4001 r = setup_ephemeral(context, runtime);
4002 if (r < 0)
4003 return r;
915e6d16 4004
9c0c6701
DDM
4005 if (context->root_image)
4006 root_image = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_image;
4007 else
4008 root_dir = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory;
915e6d16 4009 }
93c6bb51 4010
6c47cd7d
LP
4011 r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
4012 if (r < 0)
4013 return r;
4014
211a3d87 4015 /* Symlinks for exec dirs are set up after other mounts, before they are made read-only. */
df61e79a
LB
4016 r = compile_symlinks(context, params, &symlinks);
4017 if (r < 0)
29933daf 4018 return r;
df61e79a 4019
d4b6ec98
LB
4020 /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
4021 * service will need to write to it in order to start the notifications. */
4022 if (context->protect_control_groups && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
4023 read_write_paths_cleanup = strv_copy(context->read_write_paths);
29933daf
DT
4024 if (!read_write_paths_cleanup)
4025 return -ENOMEM;
d4b6ec98
LB
4026
4027 r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
4028 if (r < 0)
29933daf 4029 return r;
d4b6ec98
LB
4030
4031 read_write_paths = read_write_paths_cleanup;
4032 } else
4033 read_write_paths = context->read_write_paths;
4034
9f71ba8d 4035 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
ecf63c91
NJ
4036 if (needs_sandboxing) {
4037 /* The runtime struct only contains the parent of the private /tmp,
4038 * which is non-accessible to world users. Inside of it there's a /tmp
56a13a49
ZJS
4039 * that is sticky, and that's the one we want to use here.
4040 * This does not apply when we are using /run/systemd/empty as fallback. */
ecf63c91 4041
28135da3
DDM
4042 if (context->private_tmp && runtime && runtime->shared) {
4043 if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
4044 tmp_dir = runtime->shared->tmp_dir;
4045 else if (runtime->shared->tmp_dir)
4046 tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
56a13a49 4047
28135da3
DDM
4048 if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
4049 var_tmp_dir = runtime->shared->var_tmp_dir;
4050 else if (runtime->shared->var_tmp_dir)
4051 var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
ecf63c91
NJ
4052 }
4053
b5a33299
YW
4054 ns_info = (NamespaceInfo) {
4055 .ignore_protect_paths = false,
4056 .private_dev = context->private_devices,
4057 .protect_control_groups = context->protect_control_groups,
4058 .protect_kernel_tunables = context->protect_kernel_tunables,
4059 .protect_kernel_modules = context->protect_kernel_modules,
94a7b275 4060 .protect_kernel_logs = context->protect_kernel_logs,
aecd5ac6 4061 .protect_hostname = context->protect_hostname,
5e98086d 4062 .mount_apivfs = exec_context_get_effective_mount_apivfs(context),
52b3d652
LP
4063 .protect_home = context->protect_home,
4064 .protect_system = context->protect_system,
4e399953
LP
4065 .protect_proc = context->protect_proc,
4066 .proc_subset = context->proc_subset,
c2da3bf2 4067 .private_network = exec_needs_network_namespace(context),
fde36d25 4068 .private_ipc = exec_needs_ipc_namespace(context),
6720e356 4069 /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
5181630f 4070 .mount_nosuid = context->no_new_privileges && !mac_selinux_use(),
b5a33299 4071 };
ecf63c91 4072 } else if (!context->dynamic_user && root_dir)
228af36f
LP
4073 /*
4074 * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed
4075 * sandbox info, otherwise enforce it, don't ignore protected paths and
4076 * fail if we are enable to apply the sandbox inside the mount namespace.
4077 */
4078 ns_info = (NamespaceInfo) {
4079 .ignore_protect_paths = true,
4080 };
4081 else
4082 ns_info = (NamespaceInfo) {};
b5a33299 4083
874cdcbc 4084 if (context->mount_propagation_flag == MS_SHARED)
37ed15d7
FB
4085 log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
4086
a631cbfa
LP
4087 if (exec_context_has_credentials(context) &&
4088 params->prefix[EXEC_DIRECTORY_RUNTIME] &&
4089 FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
bbb4e7f3 4090 creds_path = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials", u->id);
29933daf
DT
4091 if (!creds_path)
4092 return -ENOMEM;
bbb4e7f3
LP
4093 }
4094
170d978b 4095 if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
5e8deb94 4096 propagate_dir = path_join("/run/systemd/propagate/", u->id);
29933daf
DT
4097 if (!propagate_dir)
4098 return -ENOMEM;
f2550b98 4099
5e8deb94 4100 incoming_dir = strdup("/run/systemd/incoming");
29933daf
DT
4101 if (!incoming_dir)
4102 return -ENOMEM;
24759d8f
LB
4103
4104 extension_dir = strdup("/run/systemd/unit-extensions");
29933daf
DT
4105 if (!extension_dir)
4106 return -ENOMEM;
3f37a825
LB
4107
4108 /* If running under a different root filesystem, propagate the host's os-release. We make a
4109 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
4110 if (root_dir || root_image) {
4111 host_os_release = strdup("/run/systemd/propagate/os-release");
4112 if (!host_os_release)
4113 return -ENOMEM;
4114 }
170d978b
LP
4115 } else {
4116 assert(params->runtime_scope == RUNTIME_SCOPE_USER);
4117
29933daf
DT
4118 if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0)
4119 return -ENOMEM;
3f37a825
LB
4120
4121 if (root_dir || root_image) {
4122 if (asprintf(&host_os_release, "/run/user/" UID_FMT "/systemd/propagate/os-release", geteuid()) < 0)
4123 return -ENOMEM;
4124 }
170d978b 4125 }
5e8deb94 4126
66130f0a
DDM
4127 if (root_image) {
4128 r = verity_settings_prepare(
4129 &verity,
4130 root_image,
4131 context->root_hash, context->root_hash_size, context->root_hash_path,
4132 context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
4133 context->root_verity);
4134 if (r < 0)
4135 return r;
4136 }
4137
84be0c71
LP
4138 r = setup_namespace(
4139 root_dir,
4140 root_image,
4141 context->root_image_options,
4142 context->root_image_policy ?: &image_policy_service,
4143 &ns_info,
4144 read_write_paths,
4145 needs_sandboxing ? context->read_only_paths : NULL,
4146 needs_sandboxing ? context->inaccessible_paths : NULL,
4147 needs_sandboxing ? context->exec_paths : NULL,
4148 needs_sandboxing ? context->no_exec_paths : NULL,
4149 empty_directories,
4150 symlinks,
4151 bind_mounts,
4152 n_bind_mounts,
4153 context->temporary_filesystems,
4154 context->n_temporary_filesystems,
4155 context->mount_images,
4156 context->n_mount_images,
4157 context->mount_image_policy ?: &image_policy_service,
4158 tmp_dir,
4159 var_tmp_dir,
4160 creds_path,
4161 context->log_namespace,
4162 context->mount_propagation_flag,
66130f0a 4163 &verity,
84be0c71
LP
4164 context->extension_images,
4165 context->n_extension_images,
4166 context->extension_image_policy ?: &image_policy_sysext,
4167 context->extension_directories,
4168 propagate_dir,
4169 incoming_dir,
4170 extension_dir,
4171 root_dir || root_image ? params->notify_socket : NULL,
3f37a825 4172 host_os_release,
84be0c71 4173 error_path);
93c6bb51 4174
1beab8b0 4175 /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
5238e957 4176 * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
1beab8b0
LP
4177 * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
4178 * completely different execution environment. */
aca835ed 4179 if (r == -ENOANO) {
4e677599
LP
4180 if (insist_on_sandboxing(
4181 context,
4182 root_dir, root_image,
4183 bind_mounts,
29933daf
DT
4184 n_bind_mounts))
4185 return log_unit_debug_errno(u,
4186 SYNTHETIC_ERRNO(EOPNOTSUPP),
4187 "Failed to set up namespace, and refusing to continue since "
4188 "the selected namespacing options alter mount environment non-trivially.\n"
4189 "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
4190 n_bind_mounts,
4191 context->n_temporary_filesystems,
4192 yes_no(root_dir),
4193 yes_no(root_image),
4194 yes_no(context->dynamic_user));
4195
4196 log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring.");
4197 return 0;
93c6bb51
DH
4198 }
4199
4200 return r;
4201}
4202
915e6d16
LP
4203static int apply_working_directory(
4204 const ExecContext *context,
4205 const ExecParameters *params,
9c0c6701 4206 ExecRuntime *runtime,
915e6d16 4207 const char *home,
376fecf6 4208 int *exit_status) {
915e6d16 4209
6732edab 4210 const char *d, *wd;
2b3c1b9e
DH
4211
4212 assert(context);
376fecf6 4213 assert(exit_status);
2b3c1b9e 4214
6732edab
LP
4215 if (context->working_directory_home) {
4216
376fecf6
LP
4217 if (!home) {
4218 *exit_status = EXIT_CHDIR;
6732edab 4219 return -ENXIO;
376fecf6 4220 }
6732edab 4221
2b3c1b9e 4222 wd = home;
6732edab 4223
14eb3285
LP
4224 } else
4225 wd = empty_to_root(context->working_directory);
e7f1e7c6 4226
fa97f630 4227 if (params->flags & EXEC_APPLY_CHROOT)
2b3c1b9e 4228 d = wd;
fa97f630 4229 else
9c0c6701 4230 d = prefix_roota((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory, wd);
e7f1e7c6 4231
376fecf6
LP
4232 if (chdir(d) < 0 && !context->working_directory_missing_ok) {
4233 *exit_status = EXIT_CHDIR;
2b3c1b9e 4234 return -errno;
376fecf6 4235 }
e7f1e7c6
DH
4236
4237 return 0;
4238}
4239
fa97f630
JB
4240static int apply_root_directory(
4241 const ExecContext *context,
4242 const ExecParameters *params,
9c0c6701 4243 ExecRuntime *runtime,
fa97f630
JB
4244 const bool needs_mount_ns,
4245 int *exit_status) {
4246
4247 assert(context);
4248 assert(exit_status);
4249
5b10116e 4250 if (params->flags & EXEC_APPLY_CHROOT)
fa97f630 4251 if (!needs_mount_ns && context->root_directory)
9c0c6701 4252 if (chroot((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory) < 0) {
fa97f630
JB
4253 *exit_status = EXIT_CHROOT;
4254 return -errno;
4255 }
fa97f630
JB
4256
4257 return 0;
4258}
4259
b1edf445 4260static int setup_keyring(
34cf6c43 4261 const Unit *u,
b1edf445
LP
4262 const ExecContext *context,
4263 const ExecParameters *p,
4264 uid_t uid, gid_t gid) {
4265
74dd6b51 4266 key_serial_t keyring;
e64c2d0b
DJL
4267 int r = 0;
4268 uid_t saved_uid;
4269 gid_t saved_gid;
74dd6b51
LP
4270
4271 assert(u);
b1edf445 4272 assert(context);
74dd6b51
LP
4273 assert(p);
4274
4275 /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
4276 * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
4277 * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
4278 * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
4279 * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
4280 * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
4281
b1edf445
LP
4282 if (context->keyring_mode == EXEC_KEYRING_INHERIT)
4283 return 0;
4284
e64c2d0b
DJL
4285 /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
4286 * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
4287 * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
4288 * & group is just as nasty as acquiring a reference to the user keyring. */
4289
4290 saved_uid = getuid();
4291 saved_gid = getgid();
4292
4293 if (gid_is_valid(gid) && gid != saved_gid) {
4294 if (setregid(gid, -1) < 0)
4295 return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m");
4296 }
4297
4298 if (uid_is_valid(uid) && uid != saved_uid) {
4299 if (setreuid(uid, -1) < 0) {
4300 r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m");
4301 goto out;
4302 }
4303 }
4304
74dd6b51
LP
4305 keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
4306 if (keyring == -1) {
4307 if (errno == ENOSYS)
8002fb97 4308 log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring.");
065b4774 4309 else if (ERRNO_IS_PRIVILEGE(errno))
8002fb97 4310 log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring.");
74dd6b51 4311 else if (errno == EDQUOT)
8002fb97 4312 log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring.");
74dd6b51 4313 else
e64c2d0b 4314 r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m");
74dd6b51 4315
e64c2d0b 4316 goto out;
74dd6b51
LP
4317 }
4318
e64c2d0b
DJL
4319 /* When requested link the user keyring into the session keyring. */
4320 if (context->keyring_mode == EXEC_KEYRING_SHARED) {
4321
4322 if (keyctl(KEYCTL_LINK,
4323 KEY_SPEC_USER_KEYRING,
4324 KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
4325 r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m");
4326 goto out;
4327 }
4328 }
4329
4330 /* Restore uid/gid back */
4331 if (uid_is_valid(uid) && uid != saved_uid) {
4332 if (setreuid(saved_uid, -1) < 0) {
4333 r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m");
4334 goto out;
4335 }
4336 }
4337
4338 if (gid_is_valid(gid) && gid != saved_gid) {
4339 if (setregid(saved_gid, -1) < 0)
4340 return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m");
4341 }
4342
4343 /* Populate they keyring with the invocation ID by default, as original saved_uid. */
b3415f5d
LP
4344 if (!sd_id128_is_null(u->invocation_id)) {
4345 key_serial_t key;
4346
4347 key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING);
4348 if (key == -1)
8002fb97 4349 log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m");
b3415f5d
LP
4350 else {
4351 if (keyctl(KEYCTL_SETPERM, key,
4352 KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
4353 KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
e64c2d0b 4354 r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m");
b3415f5d
LP
4355 }
4356 }
4357
e64c2d0b 4358out:
37b22b3b 4359 /* Revert back uid & gid for the last time, and exit */
e64c2d0b
DJL
4360 /* no extra logging, as only the first already reported error matters */
4361 if (getuid() != saved_uid)
4362 (void) setreuid(saved_uid, -1);
b1edf445 4363
e64c2d0b
DJL
4364 if (getgid() != saved_gid)
4365 (void) setregid(saved_gid, -1);
b1edf445 4366
e64c2d0b 4367 return r;
74dd6b51
LP
4368}
4369
3042bbeb 4370static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
29206d46
LP
4371 assert(array);
4372 assert(n);
2caa38e9 4373 assert(pair);
29206d46
LP
4374
4375 if (pair[0] >= 0)
4376 array[(*n)++] = pair[0];
4377 if (pair[1] >= 0)
4378 array[(*n)++] = pair[1];
4379}
4380
a34ceba6
LP
4381static int close_remaining_fds(
4382 const ExecParameters *params,
28135da3 4383 const ExecRuntime *runtime,
00d9ef85 4384 int user_lookup_fd,
a34ceba6 4385 int socket_fd,
5b8d1f6b 4386 const int *fds, size_t n_fds) {
a34ceba6 4387
da6053d0 4388 size_t n_dont_close = 0;
9c0c6701 4389 int dont_close[n_fds + 14];
a34ceba6
LP
4390
4391 assert(params);
4392
4393 if (params->stdin_fd >= 0)
4394 dont_close[n_dont_close++] = params->stdin_fd;
4395 if (params->stdout_fd >= 0)
4396 dont_close[n_dont_close++] = params->stdout_fd;
4397 if (params->stderr_fd >= 0)
4398 dont_close[n_dont_close++] = params->stderr_fd;
4399
4400 if (socket_fd >= 0)
4401 dont_close[n_dont_close++] = socket_fd;
4402 if (n_fds > 0) {
4403 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
4404 n_dont_close += n_fds;
4405 }
4406
9c0c6701
DDM
4407 if (runtime)
4408 append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
4409
28135da3
DDM
4410 if (runtime && runtime->shared) {
4411 append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
4412 append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
a70581ff 4413 }
29206d46 4414
15220772
DDM
4415 if (runtime && runtime->dynamic_creds) {
4416 if (runtime->dynamic_creds->user)
4417 append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
4418 if (runtime->dynamic_creds->group)
4419 append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
a34ceba6
LP
4420 }
4421
00d9ef85
LP
4422 if (user_lookup_fd >= 0)
4423 dont_close[n_dont_close++] = user_lookup_fd;
4424
a34ceba6
LP
4425 return close_all_fds(dont_close, n_dont_close);
4426}
4427
00d9ef85
LP
4428static int send_user_lookup(
4429 Unit *unit,
4430 int user_lookup_fd,
4431 uid_t uid,
4432 gid_t gid) {
4433
4434 assert(unit);
4435
4436 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
4437 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
4438 * specified. */
4439
4440 if (user_lookup_fd < 0)
4441 return 0;
4442
4443 if (!uid_is_valid(uid) && !gid_is_valid(gid))
4444 return 0;
4445
4446 if (writev(user_lookup_fd,
4447 (struct iovec[]) {
ce16d177
YW
4448 IOVEC_MAKE(&uid, sizeof(uid)),
4449 IOVEC_MAKE(&gid, sizeof(gid)),
4450 IOVEC_MAKE_STRING(unit->id) }, 3) < 0)
00d9ef85
LP
4451 return -errno;
4452
4453 return 0;
4454}
4455
6732edab
LP
4456static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
4457 int r;
4458
4459 assert(c);
4460 assert(home);
4461 assert(buf);
4462
4463 /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
4464
4465 if (*home)
4466 return 0;
4467
4468 if (!c->working_directory_home)
4469 return 0;
4470
6732edab
LP
4471 r = get_home_dir(buf);
4472 if (r < 0)
4473 return r;
4474
4475 *home = *buf;
4476 return 1;
4477}
4478
da50b85a
LP
4479static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
4480 _cleanup_strv_free_ char ** list = NULL;
da50b85a
LP
4481 int r;
4482
4483 assert(c);
4484 assert(p);
4485 assert(ret);
4486
4487 assert(c->dynamic_user);
4488
4489 /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
4490 * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
4491 * directories. */
4492
5b10116e 4493 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
da50b85a
LP
4494 if (t == EXEC_DIRECTORY_CONFIGURATION)
4495 continue;
4496
4497 if (!p->prefix[t])
4498 continue;
4499
211a3d87 4500 for (size_t i = 0; i < c->directories[t].n_items; i++) {
da50b85a
LP
4501 char *e;
4502
494d0247 4503 if (exec_directory_is_private(c, t))
211a3d87 4504 e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
494d0247 4505 else
211a3d87 4506 e = path_join(p->prefix[t], c->directories[t].items[i].path);
da50b85a
LP
4507 if (!e)
4508 return -ENOMEM;
4509
4510 r = strv_consume(&list, e);
4511 if (r < 0)
4512 return r;
4513 }
4514 }
4515
ae2a15bc 4516 *ret = TAKE_PTR(list);
da50b85a
LP
4517
4518 return 0;
4519}
4520
a8b993dc
LP
4521static int exec_parameters_get_cgroup_path(
4522 const ExecParameters *params,
4523 const CGroupContext *c,
4524 char **ret) {
4525
4526 const char *subgroup = NULL;
78f93209
LP
4527 char *p;
4528
4529 assert(params);
4530 assert(ret);
4531
4532 if (!params->cgroup_path)
4533 return -EINVAL;
4534
4535 /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
4536 * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
4537 * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
4538 * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
4539 * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
4540 * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
4541 * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
4542 * flag, which is only passed for the former statements, not for the latter. */
4543
a8b993dc
LP
4544 if (FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE) && (FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP) || c->delegate_subgroup)) {
4545 if (FLAGS_SET(params->flags, EXEC_IS_CONTROL))
4546 subgroup = ".control";
4547 else
4548 subgroup = c->delegate_subgroup;
4549 }
4550
4551 if (subgroup)
4552 p = path_join(params->cgroup_path, subgroup);
78f93209
LP
4553 else
4554 p = strdup(params->cgroup_path);
4555 if (!p)
4556 return -ENOMEM;
4557
4558 *ret = p;
a8b993dc 4559 return !!subgroup;
78f93209
LP
4560}
4561
e2b2fb7f
MS
4562static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
4563 _cleanup_(cpu_set_reset) CPUSet s = {};
4564 int r;
4565
4566 assert(c);
4567 assert(ret);
4568
4569 if (!c->numa_policy.nodes.set) {
4570 log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
4571 return 0;
4572 }
4573
4574 r = numa_to_cpu_set(&c->numa_policy, &s);
4575 if (r < 0)
4576 return r;
4577
4578 cpu_set_reset(ret);
4579
4580 return cpu_set_add_all(ret, &s);
4581}
4582
4583bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
4584 assert(c);
4585
4586 return c->cpu_affinity_from_numa;
4587}
4588
1da37e58
ZJS
4589static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) {
4590 int r;
4591
4592 assert(fds);
4593 assert(n_fds);
4594 assert(*n_fds < fds_size);
4595 assert(ret_fd);
4596
4597 if (fd < 0) {
254d1313 4598 *ret_fd = -EBADF;
1da37e58
ZJS
4599 return 0;
4600 }
4601
4602 if (fd < 3 + (int) *n_fds) {
4603 /* Let's move the fd up, so that it's outside of the fd range we will use to store
4604 * the fds we pass to the process (or which are closed only during execve). */
4605
4606 r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
4607 if (r < 0)
4608 return -errno;
4609
ee3455cf 4610 close_and_replace(fd, r);
1da37e58
ZJS
4611 }
4612
4613 *ret_fd = fds[*n_fds] = fd;
4614 (*n_fds) ++;
4615 return 1;
4616}
4617
cd48e23f
RP
4618static int connect_unix_harder(Unit *u, const OpenFile *of, int ofd) {
4619 union sockaddr_union addr = {
4620 .un.sun_family = AF_UNIX,
4621 };
4622 socklen_t sa_len;
4623 static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
4624 int r;
4625
4626 assert(u);
4627 assert(of);
4628 assert(ofd >= 0);
4629
4630 r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
4631 if (r < 0)
4632 return log_unit_error_errno(u, r, "Failed to set sockaddr for %s: %m", of->path);
4633
4634 sa_len = r;
4635
4636 for (size_t i = 0; i < ELEMENTSOF(socket_types); i++) {
4637 _cleanup_close_ int fd = -EBADF;
4638
4639 fd = socket(AF_UNIX, socket_types[i] | SOCK_CLOEXEC, 0);
4640 if (fd < 0)
4641 return log_unit_error_errno(u, errno, "Failed to create socket for %s: %m", of->path);
4642
4643 r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
4644 if (r == -EPROTOTYPE)
4645 continue;
4646 if (r < 0)
4647 return log_unit_error_errno(u, r, "Failed to connect socket for %s: %m", of->path);
4648
4649 return TAKE_FD(fd);
4650 }
4651
4652 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EPROTOTYPE), "Failed to connect socket for \"%s\".", of->path);
4653}
4654
4655static int get_open_file_fd(Unit *u, const OpenFile *of) {
4656 struct stat st;
4657 _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
4658
4659 assert(u);
4660 assert(of);
4661
4662 ofd = open(of->path, O_PATH | O_CLOEXEC);
4663 if (ofd < 0)
dcebb015
DDM
4664 return log_unit_error_errno(u, errno, "Could not open \"%s\": %m", of->path);
4665
cd48e23f 4666 if (fstat(ofd, &st) < 0)
dcebb015 4667 return log_unit_error_errno(u, errno, "Failed to stat %s: %m", of->path);
cd48e23f
RP
4668
4669 if (S_ISSOCK(st.st_mode)) {
4670 fd = connect_unix_harder(u, of, ofd);
4671 if (fd < 0)
4672 return fd;
4673
4674 if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
dcebb015
DDM
4675 return log_unit_error_errno(u, errno, "Failed to shutdown send for socket %s: %m",
4676 of->path);
cd48e23f
RP
4677
4678 log_unit_debug(u, "socket %s opened (fd=%d)", of->path, fd);
4679 } else {
4680 int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
4681 if (FLAGS_SET(of->flags, OPENFILE_APPEND))
4682 flags |= O_APPEND;
4683 else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
4684 flags |= O_TRUNC;
4685
4686 fd = fd_reopen(ofd, flags | O_CLOEXEC);
4687 if (fd < 0)
4688 return log_unit_error_errno(u, fd, "Failed to open file %s: %m", of->path);
4689
4690 log_unit_debug(u, "file %s opened (fd=%d)", of->path, fd);
4691 }
4692
4693 return TAKE_FD(fd);
4694}
4695
4696static int collect_open_file_fds(
4697 Unit *u,
4698 OpenFile* open_files,
4699 int **fds,
4700 char ***fdnames,
4701 size_t *n_fds) {
4702 int r;
4703
4704 assert(u);
4705 assert(fds);
4706 assert(fdnames);
4707 assert(n_fds);
4708
4709 LIST_FOREACH(open_files, of, open_files) {
4710 _cleanup_close_ int fd = -EBADF;
4711
4712 fd = get_open_file_fd(u, of);
4713 if (fd < 0) {
4714 if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
4715 log_unit_debug_errno(u, fd, "Failed to get OpenFile= file descriptor for %s, ignoring: %m", of->path);
4716 continue;
4717 }
4718
4719 return fd;
4720 }
4721
4722 if (!GREEDY_REALLOC(*fds, *n_fds + 1))
4723 return -ENOMEM;
4724
4725 r = strv_extend(fdnames, of->fdname);
4726 if (r < 0)
4727 return r;
4728
4729 (*fds)[*n_fds] = TAKE_FD(fd);
4730
4731 (*n_fds)++;
4732 }
4733
4734 return 0;
4735}
4736
3ff67ec4
ZJS
4737static void log_command_line(Unit *unit, const char *msg, const char *executable, char **argv) {
4738 assert(unit);
4739 assert(msg);
4740 assert(executable);
4741
4742 if (!DEBUG_LOGGING)
4743 return;
4744
4745 _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
4746
4747 log_unit_struct(unit, LOG_DEBUG,
4748 "EXECUTABLE=%s", executable,
4749 LOG_UNIT_MESSAGE(unit, "%s: %s", msg, strnull(cmdline)),
4750 LOG_UNIT_INVOCATION_ID(unit));
4751}
4752
170d978b
LP
4753static bool exec_context_need_unprivileged_private_users(
4754 const ExecContext *context,
4755 const ExecParameters *params) {
4756
6ef721cb 4757 assert(context);
170d978b 4758 assert(params);
6ef721cb
LB
4759
4760 /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
4761 * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
4762 * (system manager) then we have privileges and don't need this. */
170d978b 4763 if (params->runtime_scope != RUNTIME_SCOPE_USER)
6ef721cb
LB
4764 return false;
4765
4766 return context->private_users ||
4767 context->private_tmp ||
4768 context->private_devices ||
4769 context->private_network ||
4770 context->network_namespace_path ||
4771 context->private_ipc ||
4772 context->ipc_namespace_path ||
adeff822 4773 context->private_mounts > 0 ||
6ef721cb
LB
4774 context->mount_apivfs ||
4775 context->n_bind_mounts > 0 ||
4776 context->n_temporary_filesystems > 0 ||
4777 context->root_directory ||
4778 !strv_isempty(context->extension_directories) ||
4779 context->protect_system != PROTECT_SYSTEM_NO ||
4780 context->protect_home != PROTECT_HOME_NO ||
4781 context->protect_kernel_tunables ||
4782 context->protect_kernel_modules ||
4783 context->protect_kernel_logs ||
4784 context->protect_control_groups ||
4785 context->protect_clock ||
4786 context->protect_hostname ||
4787 !strv_isempty(context->read_write_paths) ||
4788 !strv_isempty(context->read_only_paths) ||
4789 !strv_isempty(context->inaccessible_paths) ||
4790 !strv_isempty(context->exec_paths) ||
4791 !strv_isempty(context->no_exec_paths);
4792}
4793
ff0af2a1 4794static int exec_child(
f2341e0a 4795 Unit *unit,
34cf6c43 4796 const ExecCommand *command,
ff0af2a1
LP
4797 const ExecContext *context,
4798 const ExecParameters *params,
28135da3 4799 ExecRuntime *runtime,
6bb00842 4800 const CGroupContext *cgroup_context,
ff0af2a1 4801 int socket_fd,
2caa38e9 4802 const int named_iofds[static 3],
cd48e23f 4803 int *params_fds,
da6053d0 4804 size_t n_socket_fds,
25b583d7 4805 size_t n_storage_fds,
ff0af2a1 4806 char **files_env,
00d9ef85 4807 int user_lookup_fd,
12145637 4808 int *exit_status) {
d35fbf6b 4809
8c35c10d 4810 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
1da37e58 4811 int r, ngids = 0, exec_fd;
4d885bd3
DH
4812 _cleanup_free_ gid_t *supplementary_gids = NULL;
4813 const char *username = NULL, *groupname = NULL;
6bb00842 4814 _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL;
2b3c1b9e 4815 const char *home = NULL, *shell = NULL;
7ca69792 4816 char **final_argv = NULL;
7bce046b
LP
4817 dev_t journal_stream_dev = 0;
4818 ino_t journal_stream_ino = 0;
5749f855 4819 bool userns_set_up = false;
165a31c0
LP
4820 bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
4821 needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */
4822 needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */
4823 needs_ambient_hack; /* Do we need to apply the ambient capabilities hack? */
349cc4a5 4824#if HAVE_SELINUX
7f59dd35 4825 _cleanup_free_ char *mac_selinux_context_net = NULL;
43b1f709 4826 bool use_selinux = false;
ecfbc84f 4827#endif
f9fa32f0 4828#if ENABLE_SMACK
43b1f709 4829 bool use_smack = false;
ecfbc84f 4830#endif
349cc4a5 4831#if HAVE_APPARMOR
43b1f709 4832 bool use_apparmor = false;
ecfbc84f 4833#endif
5749f855
AZ
4834 uid_t saved_uid = getuid();
4835 gid_t saved_gid = getgid();
fed1e721
LP
4836 uid_t uid = UID_INVALID;
4837 gid_t gid = GID_INVALID;
1da37e58
ZJS
4838 size_t n_fds = n_socket_fds + n_storage_fds, /* fds to pass to the child */
4839 n_keep_fds; /* total number of fds not to close */
165a31c0 4840 int secure_bits;
afb11bf1
DG
4841 _cleanup_free_ gid_t *gids_after_pam = NULL;
4842 int ngids_after_pam = 0;
cd48e23f
RP
4843 _cleanup_free_ int *fds = NULL;
4844 _cleanup_strv_free_ char **fdnames = NULL;
034c6ed7 4845
f2341e0a 4846 assert(unit);
5cb5a6ff
LP
4847 assert(command);
4848 assert(context);
d35fbf6b 4849 assert(params);
ff0af2a1 4850 assert(exit_status);
d35fbf6b 4851
69339ae9
LP
4852 /* Explicitly test for CVE-2021-4034 inspired invocations */
4853 assert(command->path);
4854 assert(!strv_isempty(command->argv));
4855
d35fbf6b
DM
4856 rename_process_from_path(command->path);
4857
9c274488
LP
4858 /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4859 * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4860 * both of which will be demoted to SIG_DFL. */
ce30c8dc 4861 (void) default_signals(SIGNALS_CRASH_HANDLER,
9c274488 4862 SIGNALS_IGNORE);
d35fbf6b
DM
4863
4864 if (context->ignore_sigpipe)
9c274488 4865 (void) ignore_signals(SIGPIPE);
d35fbf6b 4866
ff0af2a1
LP
4867 r = reset_signal_mask();
4868 if (r < 0) {
4869 *exit_status = EXIT_SIGNAL_MASK;
12145637 4870 return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m");
d35fbf6b 4871 }
034c6ed7 4872
d35fbf6b
DM
4873 if (params->idle_pipe)
4874 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 4875
2c027c62
LP
4876 /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4877 * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4878 * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4879 * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
ff0af2a1 4880
d35fbf6b 4881 log_forget_fds();
2c027c62 4882 log_set_open_when_needed(true);
a3b00f91 4883 log_settle_target();
4f2d528d 4884
40a80078
LP
4885 /* In case anything used libc syslog(), close this here, too */
4886 closelog();
4887
cd48e23f
RP
4888 fds = newdup(int, params_fds, n_fds);
4889 if (!fds) {
4890 *exit_status = EXIT_MEMORY;
4891 return log_oom();
4892 }
4893
4894 fdnames = strv_copy((char**) params->fd_names);
4895 if (!fdnames) {
4896 *exit_status = EXIT_MEMORY;
4897 return log_oom();
4898 }
4899
4900 r = collect_open_file_fds(unit, params->open_files, &fds, &fdnames, &n_fds);
4901 if (r < 0) {
4902 *exit_status = EXIT_FDS;
4903 return log_unit_error_errno(unit, r, "Failed to get OpenFile= file descriptors: %m");
4904 }
4905
b1994387 4906 int keep_fds[n_fds + 3];
1da37e58
ZJS
4907 memcpy_safe(keep_fds, fds, n_fds * sizeof(int));
4908 n_keep_fds = n_fds;
4909
4910 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd);
4911 if (r < 0) {
4912 *exit_status = EXIT_FDS;
4913 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
4914 }
4915
b1994387 4916#if HAVE_LIBBPF
46004616
ZJS
4917 if (unit->manager->restrict_fs) {
4918 int bpf_map_fd = lsm_bpf_map_restrict_fs_fd(unit);
b1994387
ILG
4919 if (bpf_map_fd < 0) {
4920 *exit_status = EXIT_FDS;
46004616 4921 return log_unit_error_errno(unit, bpf_map_fd, "Failed to get restrict filesystems BPF map fd: %m");
b1994387
ILG
4922 }
4923
4924 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, bpf_map_fd, &bpf_map_fd);
4925 if (r < 0) {
4926 *exit_status = EXIT_FDS;
4927 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
4928 }
4929 }
4930#endif
4931
15220772 4932 r = close_remaining_fds(params, runtime, user_lookup_fd, socket_fd, keep_fds, n_keep_fds);
ff0af2a1
LP
4933 if (r < 0) {
4934 *exit_status = EXIT_FDS;
12145637 4935 return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m");
8c7be95e
LP
4936 }
4937
0af07108
ZJS
4938 if (!context->same_pgrp &&
4939 setsid() < 0) {
4940 *exit_status = EXIT_SETSID;
4941 return log_unit_error_errno(unit, errno, "Failed to create new process session: %m");
4942 }
9e2f7c11 4943
1e22b5cd 4944 exec_context_tty_reset(context, params);
d35fbf6b 4945
c891efaf 4946 if (unit_shall_confirm_spawn(unit)) {
3b20f877
FB
4947 _cleanup_free_ char *cmdline = NULL;
4948
4ef15008 4949 cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
3b20f877 4950 if (!cmdline) {
0460aa5c 4951 *exit_status = EXIT_MEMORY;
12145637 4952 return log_oom();
3b20f877 4953 }
d35fbf6b 4954
4ef15008 4955 r = ask_for_confirmation(context, params->confirm_spawn, unit, cmdline);
3b20f877
FB
4956 if (r != CONFIRM_EXECUTE) {
4957 if (r == CONFIRM_PRETEND_SUCCESS) {
4958 *exit_status = EXIT_SUCCESS;
4959 return 0;
4960 }
ff0af2a1 4961 *exit_status = EXIT_CONFIRM;
0af07108
ZJS
4962 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ECANCELED),
4963 "Execution cancelled by the user");
d35fbf6b
DM
4964 }
4965 }
1a63a750 4966
d521916d
LP
4967 /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4968 * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4969 * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4970 * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4971 * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4972 if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 ||
170d978b 4973 setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
d521916d
LP
4974 *exit_status = EXIT_MEMORY;
4975 return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
4976 }
4977
15220772 4978 if (context->dynamic_user && runtime && runtime->dynamic_creds) {
da50b85a 4979 _cleanup_strv_free_ char **suggested_paths = NULL;
29206d46 4980
d521916d 4981 /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
7802194a 4982 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
409093fe
LP
4983 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
4984 *exit_status = EXIT_USER;
12145637 4985 return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
409093fe
LP
4986 }
4987
da50b85a
LP
4988 r = compile_suggested_paths(context, params, &suggested_paths);
4989 if (r < 0) {
4990 *exit_status = EXIT_MEMORY;
4991 return log_oom();
4992 }
4993
15220772 4994 r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
ff0af2a1
LP
4995 if (r < 0) {
4996 *exit_status = EXIT_USER;
d85ff944
YW
4997 if (r == -EILSEQ)
4998 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
4999 "Failed to update dynamic user credentials: User or group with specified name already exists.");
12145637 5000 return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m");
524daa8c 5001 }
524daa8c 5002
70dd455c 5003 if (!uid_is_valid(uid)) {
29206d46 5004 *exit_status = EXIT_USER;
d85ff944 5005 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
70dd455c
ZJS
5006 }
5007
5008 if (!gid_is_valid(gid)) {
5009 *exit_status = EXIT_USER;
d85ff944 5010 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
29206d46 5011 }
5bc7452b 5012
15220772
DDM
5013 if (runtime->dynamic_creds->user)
5014 username = runtime->dynamic_creds->user->name;
29206d46
LP
5015
5016 } else {
4d885bd3
DH
5017 r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
5018 if (r < 0) {
5019 *exit_status = EXIT_USER;
12145637 5020 return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m");
5bc7452b 5021 }
5bc7452b 5022
4d885bd3
DH
5023 r = get_fixed_group(context, &groupname, &gid);
5024 if (r < 0) {
5025 *exit_status = EXIT_GROUP;
12145637 5026 return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m");
4d885bd3 5027 }
cdc5d5c5 5028 }
29206d46 5029
cdc5d5c5
DH
5030 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
5031 r = get_supplementary_groups(context, username, groupname, gid,
5032 &supplementary_gids, &ngids);
5033 if (r < 0) {
5034 *exit_status = EXIT_GROUP;
12145637 5035 return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m");
29206d46 5036 }
5bc7452b 5037
00d9ef85
LP
5038 r = send_user_lookup(unit, user_lookup_fd, uid, gid);
5039 if (r < 0) {
5040 *exit_status = EXIT_USER;
12145637 5041 return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m");
00d9ef85
LP
5042 }
5043
5044 user_lookup_fd = safe_close(user_lookup_fd);
5045
6732edab
LP
5046 r = acquire_home(context, uid, &home, &home_buffer);
5047 if (r < 0) {
5048 *exit_status = EXIT_CHDIR;
12145637 5049 return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m");
6732edab
LP
5050 }
5051
4a055e5a 5052 /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
d35fbf6b 5053 if (socket_fd >= 0)
a34ceba6 5054 (void) fd_nonblock(socket_fd, false);
acbb0225 5055
4c70a4a7
MS
5056 /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
5057 * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
5058 if (params->cgroup_path) {
5059 _cleanup_free_ char *p = NULL;
5060
a8b993dc 5061 r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
4c70a4a7
MS
5062 if (r < 0) {
5063 *exit_status = EXIT_CGROUP;
5064 return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
5065 }
5066
5067 r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
702cf08f
YW
5068 if (r == -EUCLEAN) {
5069 *exit_status = EXIT_CGROUP;
5070 return log_unit_error_errno(unit, r, "Failed to attach process to cgroup %s "
5071 "because the cgroup or one of its parents or "
5072 "siblings is in the threaded mode: %m", p);
5073 }
4c70a4a7
MS
5074 if (r < 0) {
5075 *exit_status = EXIT_CGROUP;
5076 return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p);
5077 }
5078 }
5079
28135da3
DDM
5080 if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
5081 r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
a8d08f39
LP
5082 if (r < 0) {
5083 *exit_status = EXIT_NETWORK;
5084 return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
5085 }
5086 }
5087
28135da3
DDM
5088 if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
5089 r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
a70581ff
XR
5090 if (r < 0) {
5091 *exit_status = EXIT_NAMESPACE;
5092 return log_unit_error_errno(unit, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
5093 }
5094 }
5095
52c239d7 5096 r = setup_input(context, params, socket_fd, named_iofds);
ff0af2a1
LP
5097 if (r < 0) {
5098 *exit_status = EXIT_STDIN;
12145637 5099 return log_unit_error_errno(unit, r, "Failed to set up standard input: %m");
d35fbf6b 5100 }
034c6ed7 5101
52c239d7 5102 r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
5103 if (r < 0) {
5104 *exit_status = EXIT_STDOUT;
12145637 5105 return log_unit_error_errno(unit, r, "Failed to set up standard output: %m");
d35fbf6b
DM
5106 }
5107
52c239d7 5108 r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
5109 if (r < 0) {
5110 *exit_status = EXIT_STDERR;
12145637 5111 return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m");
d35fbf6b
DM
5112 }
5113
d35fbf6b 5114 if (context->oom_score_adjust_set) {
bb44fd07
ZJS
5115 /* When we can't make this change due to EPERM, then let's silently skip over it. User
5116 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
9f8168eb 5117 r = set_oom_score_adjust(context->oom_score_adjust);
bb44fd07
ZJS
5118 if (ERRNO_IS_NEG_PRIVILEGE(r))
5119 log_unit_debug_errno(unit, r,
5120 "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
5121 else if (r < 0) {
5122 *exit_status = EXIT_OOM_ADJUST;
5123 return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m");
613b411c 5124 }
d35fbf6b
DM
5125 }
5126
ad21e542
ZJS
5127 if (context->coredump_filter_set) {
5128 r = set_coredump_filter(context->coredump_filter);
bb44fd07
ZJS
5129 if (ERRNO_IS_NEG_PRIVILEGE(r))
5130 log_unit_debug_errno(unit, r, "Failed to adjust coredump_filter, ignoring: %m");
5131 else if (r < 0)
5132 return log_unit_error_errno(unit, r, "Failed to adjust coredump_filter: %m");
ad21e542
ZJS
5133 }
5134
39090201
DJL
5135 if (context->nice_set) {
5136 r = setpriority_closest(context->nice);
5137 if (r < 0)
5138 return log_unit_error_errno(unit, r, "Failed to set up process scheduling priority (nice level): %m");
5139 }
613b411c 5140
d35fbf6b
DM
5141 if (context->cpu_sched_set) {
5142 struct sched_param param = {
5143 .sched_priority = context->cpu_sched_priority,
5144 };
5145
ff0af2a1
LP
5146 r = sched_setscheduler(0,
5147 context->cpu_sched_policy |
5148 (context->cpu_sched_reset_on_fork ?
5149 SCHED_RESET_ON_FORK : 0),
5150 &param);
5151 if (r < 0) {
5152 *exit_status = EXIT_SETSCHEDULER;
12145637 5153 return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m");
fc9b2a84 5154 }
d35fbf6b 5155 }
fc9b2a84 5156
e2b2fb7f
MS
5157 if (context->cpu_affinity_from_numa || context->cpu_set.set) {
5158 _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
5159 const CPUSet *cpu_set;
5160
5161 if (context->cpu_affinity_from_numa) {
5162 r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
5163 if (r < 0) {
5164 *exit_status = EXIT_CPUAFFINITY;
5165 return log_unit_error_errno(unit, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
5166 }
5167
5168 cpu_set = &converted_cpu_set;
5169 } else
5170 cpu_set = &context->cpu_set;
5171
5172 if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
ff0af2a1 5173 *exit_status = EXIT_CPUAFFINITY;
12145637 5174 return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m");
034c6ed7 5175 }
e2b2fb7f 5176 }
034c6ed7 5177
b070c7c0
MS
5178 if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
5179 r = apply_numa_policy(&context->numa_policy);
bb44fd07
ZJS
5180 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
5181 log_unit_debug_errno(unit, r, "NUMA support not available, ignoring.");
5182 else if (r < 0) {
5183 *exit_status = EXIT_NUMA_POLICY;
5184 return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m");
b070c7c0
MS
5185 }
5186 }
5187
d35fbf6b
DM
5188 if (context->ioprio_set)
5189 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 5190 *exit_status = EXIT_IOPRIO;
12145637 5191 return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m");
d35fbf6b 5192 }
da726a4d 5193
d35fbf6b
DM
5194 if (context->timer_slack_nsec != NSEC_INFINITY)
5195 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 5196 *exit_status = EXIT_TIMERSLACK;
12145637 5197 return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m");
4c2630eb 5198 }
9eba9da4 5199
21022b9d
LP
5200 if (context->personality != PERSONALITY_INVALID) {
5201 r = safe_personality(context->personality);
5202 if (r < 0) {
ff0af2a1 5203 *exit_status = EXIT_PERSONALITY;
12145637 5204 return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m");
4c2630eb 5205 }
21022b9d 5206 }
94f04347 5207
33331d11
VB
5208 if (context->utmp_id) {
5209 const char *line = context->tty_path ?
5210 (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
5211 NULL;
df0ff127 5212 utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
33331d11 5213 line,
023a4f67
LP
5214 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
5215 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
5216 USER_PROCESS,
6a93917d 5217 username);
33331d11 5218 }
d35fbf6b 5219
08f67696 5220 if (uid_is_valid(uid)) {
ff0af2a1
LP
5221 r = chown_terminal(STDIN_FILENO, uid);
5222 if (r < 0) {
5223 *exit_status = EXIT_STDIN;
12145637 5224 return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
071830ff 5225 }
d35fbf6b 5226 }
8e274523 5227
6bb00842
LP
5228 if (params->cgroup_path) {
5229 /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5230 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5231 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5232 * touch a single hierarchy too. */
5233
5234 if (params->flags & EXEC_CGROUP_DELEGATE) {
a8b993dc
LP
5235 _cleanup_free_ char *p = NULL;
5236
6bb00842
LP
5237 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
5238 if (r < 0) {
5239 *exit_status = EXIT_CGROUP;
5240 return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
5241 }
a8b993dc
LP
5242
5243 r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
5244 if (r < 0) {
5245 *exit_status = EXIT_CGROUP;
5246 return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
5247 }
5248 if (r > 0) {
bcd9b981 5249 r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
a8b993dc
LP
5250 if (r < 0) {
5251 *exit_status = EXIT_CGROUP;
5252 return log_unit_error_errno(unit, r, "Failed to adjust control subgroup access: %m");
5253 }
5254 }
6bb00842
LP
5255 }
5256
5257 if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
5258 if (cgroup_context_want_memory_pressure(cgroup_context)) {
5259 r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
5260 if (r < 0) {
5261 *exit_status = EXIT_MEMORY;
5262 return log_oom();
5263 }
5264
5265 r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
5266 if (r < 0) {
5267 log_unit_full_errno(unit, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
5268 "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
5269 memory_pressure_path = mfree(memory_pressure_path);
5270 }
5271 } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_OFF) {
5272 memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
5273 if (!memory_pressure_path) {
5274 *exit_status = EXIT_MEMORY;
5275 return log_oom();
5276 }
5277 }
034c6ed7 5278 }
d35fbf6b 5279 }
034c6ed7 5280
211a3d87
LB
5281 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
5282
5b10116e 5283 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
59dd2bbb 5284 r = setup_exec_directory(unit, context, params, uid, gid, dt, needs_mount_namespace, exit_status);
12145637
LP
5285 if (r < 0)
5286 return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
d35fbf6b 5287 }
94f04347 5288
bb0c0d6f 5289 if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
3a78b0e9 5290 r = setup_credentials(context, params, unit->id, uid, gid);
bb0c0d6f
LP
5291 if (r < 0) {
5292 *exit_status = EXIT_CREDENTIALS;
5293 return log_unit_error_errno(unit, r, "Failed to set up credentials: %m");
5294 }
5295 }
5296
7bce046b 5297 r = build_environment(
fd63e712 5298 unit,
7bce046b
LP
5299 context,
5300 params,
6bb00842 5301 cgroup_context,
7bce046b 5302 n_fds,
cd48e23f 5303 fdnames,
7bce046b
LP
5304 home,
5305 username,
5306 shell,
5307 journal_stream_dev,
5308 journal_stream_ino,
6bb00842 5309 memory_pressure_path,
7bce046b 5310 &our_env);
2065ca69
JW
5311 if (r < 0) {
5312 *exit_status = EXIT_MEMORY;
12145637 5313 return log_oom();
2065ca69
JW
5314 }
5315
5316 r = build_pass_environment(context, &pass_env);
5317 if (r < 0) {
5318 *exit_status = EXIT_MEMORY;
12145637 5319 return log_oom();
2065ca69
JW
5320 }
5321
adf769b0
ZJS
5322 /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5323 * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5324 * not specify PATH but the unit has ExecSearchPath. */
8c35c10d 5325 if (!strv_isempty(context->exec_search_path)) {
5326 _cleanup_free_ char *joined = NULL;
5327
5328 joined = strv_join(context->exec_search_path, ":");
5329 if (!joined) {
5330 *exit_status = EXIT_MEMORY;
5331 return log_oom();
5332 }
5333
5334 r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
5335 if (r < 0) {
5336 *exit_status = EXIT_MEMORY;
5337 return log_oom();
5338 }
5339 }
5340
4ab3d29f 5341 accum_env = strv_env_merge(params->environment,
2065ca69 5342 our_env,
8c35c10d 5343 joined_exec_search_path,
2065ca69
JW
5344 pass_env,
5345 context->environment,
44e5d006 5346 files_env);
2065ca69
JW
5347 if (!accum_env) {
5348 *exit_status = EXIT_MEMORY;
12145637 5349 return log_oom();
2065ca69 5350 }
1280503b 5351 accum_env = strv_env_clean(accum_env);
2065ca69 5352
096424d1 5353 (void) umask(context->umask);
b213e1c1 5354
b1edf445 5355 r = setup_keyring(unit, context, params, uid, gid);
74dd6b51
LP
5356 if (r < 0) {
5357 *exit_status = EXIT_KEYRING;
12145637 5358 return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
74dd6b51
LP
5359 }
5360
adf769b0
ZJS
5361 /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5362 * from it. */
1703fa41 5363 needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
7f18ef0a 5364
adf769b0
ZJS
5365 /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked
5366 * for it, and the kernel doesn't actually support ambient caps. */
165a31c0 5367 needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
7f18ef0a 5368
adf769b0
ZJS
5369 /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5370 * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not
5371 * desired. */
165a31c0
LP
5372 if (needs_ambient_hack)
5373 needs_setuid = false;
5374 else
5375 needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
5376
638fd8cc
LP
5377 uint64_t capability_ambient_set = context->capability_ambient_set;
5378
165a31c0 5379 if (needs_sandboxing) {
adf769b0
ZJS
5380 /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5381 * /sys being present. The actual MAC context application will happen later, as late as
5382 * possible, to avoid impacting our own code paths. */
7f18ef0a 5383
349cc4a5 5384#if HAVE_SELINUX
43b1f709 5385 use_selinux = mac_selinux_use();
7f18ef0a 5386#endif
f9fa32f0 5387#if ENABLE_SMACK
43b1f709 5388 use_smack = mac_smack_use();
7f18ef0a 5389#endif
349cc4a5 5390#if HAVE_APPARMOR
43b1f709 5391 use_apparmor = mac_apparmor_use();
7f18ef0a 5392#endif
165a31c0 5393 }
7f18ef0a 5394
ce932d2d
LP
5395 if (needs_sandboxing) {
5396 int which_failed;
5397
5398 /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5399 * is set here. (See below.) */
5400
5401 r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
5402 if (r < 0) {
5403 *exit_status = EXIT_LIMITS;
5404 return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
5405 }
5406 }
5407
0af07108 5408 if (needs_setuid && context->pam_name && username) {
ce932d2d
LP
5409 /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
5410 * wins here. (See above.) */
5411
1da37e58 5412 /* All fds passed in the fds array will be closed in the pam child process. */
0af07108
ZJS
5413 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
5414 if (r < 0) {
5415 *exit_status = EXIT_PAM;
5416 return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
165a31c0 5417 }
ac45f971 5418
638fd8cc
LP
5419 if (ambient_capabilities_supported()) {
5420 uint64_t ambient_after_pam;
5421
5422 /* PAM modules might have set some ambient caps. Query them here and merge them into
5423 * the caps we want to set in the end, so that we don't end up unsetting them. */
5424 r = capability_get_ambient(&ambient_after_pam);
5425 if (r < 0) {
5426 *exit_status = EXIT_CAPABILITIES;
5427 return log_unit_error_errno(unit, r, "Failed to query ambient caps: %m");
5428 }
5429
5430 capability_ambient_set |= ambient_after_pam;
5431 }
5432
0af07108
ZJS
5433 ngids_after_pam = getgroups_alloc(&gids_after_pam);
5434 if (ngids_after_pam < 0) {
5435 *exit_status = EXIT_MEMORY;
5436 return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
5749f855 5437 }
b213e1c1 5438 }
5749f855 5439
170d978b 5440 if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
5749f855
AZ
5441 /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5442 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5443 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
0af07108 5444
0af07108 5445 r = setup_private_users(saved_uid, saved_gid, uid, gid);
6ef721cb
LB
5446 /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5447 * the actual requested operations fail (or silently continue). */
5448 if (r < 0 && context->private_users) {
0af07108
ZJS
5449 *exit_status = EXIT_USER;
5450 return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m");
5749f855 5451 }
6ef721cb
LB
5452 if (r < 0)
5453 log_unit_info_errno(unit, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
5454 else
5455 userns_set_up = true;
5749f855
AZ
5456 }
5457
28135da3 5458 if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
a8d08f39 5459
5a3627e5
LP
5460 /* Try to enable network namespacing if network namespacing is available and we have
5461 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
5462 * new network namespace. And if we don't have that, then we could only create a network
5463 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
5464 if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
28135da3 5465 r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
bb44fd07
ZJS
5466 if (ERRNO_IS_NEG_PRIVILEGE(r))
5467 log_unit_notice_errno(unit, r,
5468 "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
5469 else if (r < 0) {
5470 *exit_status = EXIT_NETWORK;
5471 return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
6e2d7c4f 5472 }
a8d08f39
LP
5473 } else if (context->network_namespace_path) {
5474 *exit_status = EXIT_NETWORK;
ee00d1e9
ZJS
5475 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
5476 "NetworkNamespacePath= is not supported, refusing.");
6e2d7c4f 5477 } else
5a3627e5 5478 log_unit_notice(unit, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
d35fbf6b 5479 }
169c1bda 5480
28135da3 5481 if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
a70581ff
XR
5482
5483 if (ns_type_supported(NAMESPACE_IPC)) {
28135da3 5484 r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
a70581ff
XR
5485 if (r == -EPERM)
5486 log_unit_warning_errno(unit, r,
5487 "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
5488 else if (r < 0) {
5489 *exit_status = EXIT_NAMESPACE;
5490 return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m");
5491 }
5492 } else if (context->ipc_namespace_path) {
5493 *exit_status = EXIT_NAMESPACE;
5494 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
5495 "IPCNamespacePath= is not supported, refusing.");
5496 } else
5497 log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
5498 }
5499
ee818b89 5500 if (needs_mount_namespace) {
7cc5ef5f
ZJS
5501 _cleanup_free_ char *error_path = NULL;
5502
d4b6ec98 5503 r = apply_mount_namespace(unit, command->flags, context, params, runtime, memory_pressure_path, &error_path);
3fbe8dbe
LP
5504 if (r < 0) {
5505 *exit_status = EXIT_NAMESPACE;
7cc5ef5f
ZJS
5506 return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
5507 error_path ? ": " : "", strempty(error_path));
3fbe8dbe 5508 }
d35fbf6b 5509 }
81a2b7ce 5510
daf8f72b
LP
5511 if (needs_sandboxing) {
5512 r = apply_protect_hostname(unit, context, exit_status);
5513 if (r < 0)
5514 return r;
aecd5ac6
TM
5515 }
5516
85614c6e
SR
5517 if (context->memory_ksm >= 0)
5518 if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm) < 0) {
5519 if (ERRNO_IS_NOT_SUPPORTED(errno))
5520 log_unit_debug_errno(unit, errno, "KSM support not available, ignoring.");
5521 else {
5522 *exit_status = EXIT_KSM;
5523 return log_unit_error_errno(unit, errno, "Failed to set KSM: %m");
5524 }
5525 }
5526
5749f855
AZ
5527 /* Drop groups as early as possible.
5528 * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
5529 * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
165a31c0 5530 if (needs_setuid) {
afb11bf1
DG
5531 _cleanup_free_ gid_t *gids_to_enforce = NULL;
5532 int ngids_to_enforce = 0;
5533
5534 ngids_to_enforce = merge_gid_lists(supplementary_gids,
5535 ngids,
5536 gids_after_pam,
5537 ngids_after_pam,
5538 &gids_to_enforce);
5539 if (ngids_to_enforce < 0) {
5540 *exit_status = EXIT_MEMORY;
5541 return log_unit_error_errno(unit,
5542 ngids_to_enforce,
5543 "Failed to merge group lists. Group membership might be incorrect: %m");
5544 }
5545
5546 r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
096424d1
LP
5547 if (r < 0) {
5548 *exit_status = EXIT_GROUP;
12145637 5549 return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
096424d1 5550 }
165a31c0 5551 }
096424d1 5552
5749f855
AZ
5553 /* If the user namespace was not set up above, try to do it now.
5554 * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
d09df6b9 5555 * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
5749f855
AZ
5556 * case of mount namespaces being less privileged when the mount point list is copied from a
5557 * different user namespace). */
9008e1ac 5558
5749f855
AZ
5559 if (needs_sandboxing && context->private_users && !userns_set_up) {
5560 r = setup_private_users(saved_uid, saved_gid, uid, gid);
5561 if (r < 0) {
5562 *exit_status = EXIT_USER;
5563 return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
d251207d
LP
5564 }
5565 }
5566
9f71ba8d
ZJS
5567 /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
5568 * shall execute. */
5569
5570 _cleanup_free_ char *executable = NULL;
254d1313 5571 _cleanup_close_ int executable_fd = -EBADF;
8c35c10d 5572 r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9f71ba8d
ZJS
5573 if (r < 0) {
5574 if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
c2503e35
RH
5575 log_unit_struct_errno(unit, LOG_INFO, r,
5576 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
5577 LOG_UNIT_INVOCATION_ID(unit),
5578 LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
5579 command->path),
5580 "EXECUTABLE=%s", command->path);
9f71ba8d
ZJS
5581 return 0;
5582 }
5583
5584 *exit_status = EXIT_EXEC;
c2503e35
RH
5585
5586 return log_unit_struct_errno(unit, LOG_INFO, r,
5587 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
5588 LOG_UNIT_INVOCATION_ID(unit),
5589 LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m",
5590 command->path),
5591 "EXECUTABLE=%s", command->path);
9f71ba8d
ZJS
5592 }
5593
b83d5050
ZJS
5594 r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
5595 if (r < 0) {
5596 *exit_status = EXIT_FDS;
5597 return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
5598 }
5599
9f71ba8d 5600#if HAVE_SELINUX
49590d67 5601 if (needs_sandboxing && use_selinux && params->selinux_context_net) {
254d1313 5602 int fd = -EBADF;
49590d67
MS
5603
5604 if (socket_fd >= 0)
5605 fd = socket_fd;
5606 else if (params->n_socket_fds == 1)
5607 /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5608 * use context from that fd to compute the label. */
5609 fd = params->fds[0];
5610
5611 if (fd >= 0) {
5612 r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
006d1864
TM
5613 if (r < 0) {
5614 if (!context->selinux_context_ignore) {
5615 *exit_status = EXIT_SELINUX_CONTEXT;
5616 return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
5617 }
5618 log_unit_debug_errno(unit, r, "Failed to determine SELinux context, ignoring: %m");
49590d67 5619 }
9f71ba8d
ZJS
5620 }
5621 }
5622#endif
5623
4a055e5a
ZJS
5624 /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
5625 * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
5626 * more. We do keep exec_fd however, if we have it, since we need to keep it open until the final
5627 * execve(). */
5686391b 5628
1da37e58 5629 r = close_all_fds(keep_fds, n_keep_fds);
ff0af2a1
LP
5630 if (r >= 0)
5631 r = shift_fds(fds, n_fds);
5632 if (r >= 0)
cd48e23f 5633 r = flags_fds(fds, n_socket_fds, n_fds, context->non_blocking);
ff0af2a1
LP
5634 if (r < 0) {
5635 *exit_status = EXIT_FDS;
12145637 5636 return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
d35fbf6b 5637 }
e66cf1a3 5638
5686391b
LP
5639 /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
5640 * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
5641 * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
5642 * came this far. */
5643
165a31c0 5644 secure_bits = context->secure_bits;
e66cf1a3 5645
165a31c0
LP
5646 if (needs_sandboxing) {
5647 uint64_t bset;
e66cf1a3 5648
4a055e5a
ZJS
5649 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5650 * (Note this is placed after the general resource limit initialization, see above, in order
5651 * to take precedence.) */
f4170c67
LP
5652 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
5653 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
5654 *exit_status = EXIT_LIMITS;
12145637 5655 return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
f4170c67
LP
5656 }
5657 }
5658
37ac2744
JB
5659#if ENABLE_SMACK
5660 /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5661 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5662 if (use_smack) {
aa5ae971 5663 r = setup_smack(unit->manager, context, executable_fd);
29ff6247 5664 if (r < 0 && !context->smack_process_label_ignore) {
37ac2744
JB
5665 *exit_status = EXIT_SMACK_PROCESS_LABEL;
5666 return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
5667 }
5668 }
5669#endif
5670
165a31c0
LP
5671 bset = context->capability_bounding_set;
5672 /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
5673 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
5674 * instead of us doing that */
5675 if (needs_ambient_hack)
5676 bset |= (UINT64_C(1) << CAP_SETPCAP) |
5677 (UINT64_C(1) << CAP_SETUID) |
5678 (UINT64_C(1) << CAP_SETGID);
5679
5680 if (!cap_test_all(bset)) {
638fd8cc 5681 r = capability_bounding_set_drop(bset, /* right_now= */ false);
ff0af2a1
LP
5682 if (r < 0) {
5683 *exit_status = EXIT_CAPABILITIES;
12145637 5684 return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
3b8bddde 5685 }
4c2630eb 5686 }
3b8bddde 5687
16fcb191
TK
5688 /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5689 * keep-caps set.
a954b249
LP
5690 *
5691 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5692 * the inherited set and keep caps has to be set (done in enforce_user()). After setresuid()
5693 * the ambient capabilities can be raised as they are present in the permitted and
5694 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5695 * without changing the user, so we also set the ambient capabilities here.
5696 *
5697 * The requested ambient capabilities are raised in the inheritable set if the second
5698 * argument is true. */
943800f4 5699 if (!needs_ambient_hack) {
638fd8cc 5700 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
755d4b67
IP
5701 if (r < 0) {
5702 *exit_status = EXIT_CAPABILITIES;
12145637 5703 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
755d4b67 5704 }
755d4b67 5705 }
165a31c0 5706 }
755d4b67 5707
fa97f630 5708 /* chroot to root directory first, before we lose the ability to chroot */
9c0c6701 5709 r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
fa97f630
JB
5710 if (r < 0)
5711 return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");
5712
165a31c0 5713 if (needs_setuid) {
08f67696 5714 if (uid_is_valid(uid)) {
638fd8cc 5715 r = enforce_user(context, uid, capability_ambient_set);
ff0af2a1
LP
5716 if (r < 0) {
5717 *exit_status = EXIT_USER;
12145637 5718 return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
5b6319dc 5719 }
165a31c0 5720
638fd8cc 5721 if (!needs_ambient_hack && capability_ambient_set != 0) {
755d4b67 5722
16fcb191 5723 /* Raise the ambient capabilities after user change. */
638fd8cc 5724 r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
755d4b67
IP
5725 if (r < 0) {
5726 *exit_status = EXIT_CAPABILITIES;
12145637 5727 return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
755d4b67 5728 }
755d4b67 5729 }
5b6319dc 5730 }
165a31c0 5731 }
d35fbf6b 5732
56ef8db9
JB
5733 /* Apply working directory here, because the working directory might be on NFS and only the user running
5734 * this service might have the correct privilege to change to the working directory */
9c0c6701 5735 r = apply_working_directory(context, params, runtime, home, exit_status);
56ef8db9
JB
5736 if (r < 0)
5737 return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");
5738
165a31c0 5739 if (needs_sandboxing) {
37ac2744 5740 /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5cd9cd35
LP
5741 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5742 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5743 * are restricted. */
5744
349cc4a5 5745#if HAVE_SELINUX
43b1f709 5746 if (use_selinux) {
5cd9cd35
LP
5747 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5748
5749 if (exec_context) {
5750 r = setexeccon(exec_context);
006d1864
TM
5751 if (r < 0) {
5752 if (!context->selinux_context_ignore) {
5753 *exit_status = EXIT_SELINUX_CONTEXT;
5754 return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
5755 }
5756 log_unit_debug_errno(unit, r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5cd9cd35
LP
5757 }
5758 }
5759 }
5760#endif
5761
349cc4a5 5762#if HAVE_APPARMOR
43b1f709 5763 if (use_apparmor && context->apparmor_profile) {
5cd9cd35
LP
5764 r = aa_change_onexec(context->apparmor_profile);
5765 if (r < 0 && !context->apparmor_profile_ignore) {
5766 *exit_status = EXIT_APPARMOR_PROFILE;
12145637 5767 return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
5cd9cd35
LP
5768 }
5769 }
5770#endif
5771
a954b249
LP
5772 /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5773 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5774 * requires CAP_SETPCAP. */
dbdc4098 5775 if (prctl(PR_GET_SECUREBITS) != secure_bits) {
69e3234d 5776 /* CAP_SETPCAP is required to set securebits. This capability is raised into the
dbdc4098 5777 * effective set here.
a954b249
LP
5778 *
5779 * The effective set is overwritten during execve() with the following values:
5780 *
dbdc4098 5781 * - ambient set (for non-root processes)
a954b249 5782 *
dbdc4098
TK
5783 * - (inheritable | bounding) set for root processes)
5784 *
5785 * Hence there is no security impact to raise it in the effective set before execve
5786 */
a954b249 5787 r = capability_gain_cap_setpcap(/* return_caps= */ NULL);
dbdc4098
TK
5788 if (r < 0) {
5789 *exit_status = EXIT_CAPABILITIES;
5790 return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits");
5791 }
755d4b67 5792 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 5793 *exit_status = EXIT_SECUREBITS;
12145637 5794 return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
ff01d048 5795 }
dbdc4098 5796 }
5b6319dc 5797
59eeb84b 5798 if (context_has_no_new_privileges(context))
d35fbf6b 5799 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 5800 *exit_status = EXIT_NO_NEW_PRIVILEGES;
12145637 5801 return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
d35fbf6b
DM
5802 }
5803
349cc4a5 5804#if HAVE_SECCOMP
469830d1
LP
5805 r = apply_address_families(unit, context);
5806 if (r < 0) {
5807 *exit_status = EXIT_ADDRESS_FAMILIES;
12145637 5808 return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
4c2630eb 5809 }
04aa0cb9 5810
469830d1
LP
5811 r = apply_memory_deny_write_execute(unit, context);
5812 if (r < 0) {
5813 *exit_status = EXIT_SECCOMP;
12145637 5814 return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
f3e43635 5815 }
f4170c67 5816
469830d1
LP
5817 r = apply_restrict_realtime(unit, context);
5818 if (r < 0) {
5819 *exit_status = EXIT_SECCOMP;
12145637 5820 return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
f4170c67
LP
5821 }
5822
f69567cb
LP
5823 r = apply_restrict_suid_sgid(unit, context);
5824 if (r < 0) {
5825 *exit_status = EXIT_SECCOMP;
5826 return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
5827 }
5828
add00535
LP
5829 r = apply_restrict_namespaces(unit, context);
5830 if (r < 0) {
5831 *exit_status = EXIT_SECCOMP;
12145637 5832 return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
add00535
LP
5833 }
5834
469830d1
LP
5835 r = apply_protect_sysctl(unit, context);
5836 if (r < 0) {
5837 *exit_status = EXIT_SECCOMP;
12145637 5838 return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
502d704e
DH
5839 }
5840
469830d1
LP
5841 r = apply_protect_kernel_modules(unit, context);
5842 if (r < 0) {
5843 *exit_status = EXIT_SECCOMP;
12145637 5844 return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
59eeb84b
LP
5845 }
5846
84703040
KK
5847 r = apply_protect_kernel_logs(unit, context);
5848 if (r < 0) {
5849 *exit_status = EXIT_SECCOMP;
5850 return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
5851 }
5852
fc64760d
KK
5853 r = apply_protect_clock(unit, context);
5854 if (r < 0) {
5855 *exit_status = EXIT_SECCOMP;
5856 return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m");
5857 }
5858
469830d1
LP
5859 r = apply_private_devices(unit, context);
5860 if (r < 0) {
5861 *exit_status = EXIT_SECCOMP;
12145637 5862 return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
469830d1
LP
5863 }
5864
5865 r = apply_syscall_archs(unit, context);
5866 if (r < 0) {
5867 *exit_status = EXIT_SECCOMP;
12145637 5868 return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
ba128bb8
LP
5869 }
5870
78e864e5
TM
5871 r = apply_lock_personality(unit, context);
5872 if (r < 0) {
5873 *exit_status = EXIT_SECCOMP;
12145637 5874 return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
78e864e5
TM
5875 }
5876
9df2cdd8
TM
5877 r = apply_syscall_log(unit, context);
5878 if (r < 0) {
5879 *exit_status = EXIT_SECCOMP;
5880 return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m");
5881 }
5882
5cd9cd35
LP
5883 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
5884 * by the filter as little as possible. */
165a31c0 5885 r = apply_syscall_filter(unit, context, needs_ambient_hack);
469830d1
LP
5886 if (r < 0) {
5887 *exit_status = EXIT_SECCOMP;
12145637 5888 return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
d35fbf6b
DM
5889 }
5890#endif
b1994387
ILG
5891
5892#if HAVE_LIBBPF
5893 r = apply_restrict_filesystems(unit, context);
5894 if (r < 0) {
5895 *exit_status = EXIT_BPF;
5896 return log_unit_error_errno(unit, r, "Failed to restrict filesystems: %m");
5897 }
5898#endif
5899
d35fbf6b 5900 }
034c6ed7 5901
00819cc1
LP
5902 if (!strv_isempty(context->unset_environment)) {
5903 char **ee = NULL;
5904
5905 ee = strv_env_delete(accum_env, 1, context->unset_environment);
5906 if (!ee) {
5907 *exit_status = EXIT_MEMORY;
12145637 5908 return log_oom();
00819cc1
LP
5909 }
5910
130d3d22 5911 strv_free_and_replace(accum_env, ee);
00819cc1
LP
5912 }
5913
7ca69792 5914 if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
f331434d
LP
5915 _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
5916
5917 r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
5918 if (r < 0) {
7ca69792 5919 *exit_status = EXIT_MEMORY;
f331434d 5920 return log_unit_error_errno(unit, r, "Failed to replace environment variables: %m");
7ca69792
AZ
5921 }
5922 final_argv = replaced_argv;
f331434d
LP
5923
5924 if (!strv_isempty(unset_variables)) {
5925 _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
5926 log_unit_warning(unit, "Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5927 }
5928
5929 if (!strv_isempty(bad_variables)) {
5930 _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
5931 log_unit_warning(unit, "Invalid environment variable name evaluates to an empty string: %s", strna(jb));;
5932 }
7ca69792
AZ
5933 } else
5934 final_argv = command->argv;
034c6ed7 5935
3ff67ec4 5936 log_command_line(unit, "Executing", executable, final_argv);
dd305ec9 5937
5686391b
LP
5938 if (exec_fd >= 0) {
5939 uint8_t hot = 1;
5940
5941 /* We have finished with all our initializations. Let's now let the manager know that. From this point
5942 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5943
5944 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
5945 *exit_status = EXIT_EXEC;
5946 return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
5947 }
5948 }
5949
a6d9111c 5950 r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
5686391b
LP
5951
5952 if (exec_fd >= 0) {
5953 uint8_t hot = 0;
5954
5955 /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
5956 * that POLLHUP on it no longer means execve() succeeded. */
5957
5958 if (write(exec_fd, &hot, sizeof(hot)) < 0) {
5959 *exit_status = EXIT_EXEC;
5960 return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
5961 }
5962 }
12145637 5963
ff0af2a1 5964 *exit_status = EXIT_EXEC;
9f71ba8d 5965 return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable);
d35fbf6b 5966}
81a2b7ce 5967
34cf6c43 5968static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
2caa38e9 5969static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);
34cf6c43 5970
f2341e0a
LP
5971int exec_spawn(Unit *unit,
5972 ExecCommand *command,
d35fbf6b
DM
5973 const ExecContext *context,
5974 const ExecParameters *params,
28135da3 5975 ExecRuntime *runtime,
6bb00842 5976 const CGroupContext *cgroup_context,
d35fbf6b 5977 pid_t *ret) {
8351ceae 5978
ee39ca20 5979 int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
78f93209 5980 _cleanup_free_ char *subcgroup_path = NULL;
d35fbf6b 5981 _cleanup_strv_free_ char **files_env = NULL;
da6053d0 5982 size_t n_storage_fds = 0, n_socket_fds = 0;
d35fbf6b 5983 pid_t pid;
8351ceae 5984
f2341e0a 5985 assert(unit);
d35fbf6b
DM
5986 assert(command);
5987 assert(context);
5988 assert(ret);
5989 assert(params);
25b583d7 5990 assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));
4298d0b5 5991
4b2af439
DDM
5992 LOG_CONTEXT_PUSH_UNIT(unit);
5993
d35fbf6b
DM
5994 if (context->std_input == EXEC_INPUT_SOCKET ||
5995 context->std_output == EXEC_OUTPUT_SOCKET ||
5996 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 5997
d85ff944
YW
5998 if (params->n_socket_fds > 1)
5999 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
eef65bf3 6000
d85ff944
YW
6001 if (params->n_socket_fds == 0)
6002 return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
488ab41c 6003
d35fbf6b
DM
6004 socket_fd = params->fds[0];
6005 } else {
254d1313 6006 socket_fd = -EBADF;
d35fbf6b 6007 fds = params->fds;
9b141911 6008 n_socket_fds = params->n_socket_fds;
25b583d7 6009 n_storage_fds = params->n_storage_fds;
d35fbf6b 6010 }
94f04347 6011
34cf6c43 6012 r = exec_context_named_iofds(context, params, named_iofds);
52c239d7
LB
6013 if (r < 0)
6014 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
6015
f2341e0a 6016 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 6017 if (r < 0)
f2341e0a 6018 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 6019
9f71ba8d
ZJS
6020 /* Fork with up-to-date SELinux label database, so the child inherits the up-to-date db
6021 and, until the next SELinux policy changes, we save further reloads in future children. */
2df2152c
CG
6022 mac_selinux_maybe_reload();
6023
3ff67ec4
ZJS
6024 /* We won't know the real executable path until we create the mount namespace in the child, but we
6025 want to log from the parent, so we use the possibly inaccurate path here. */
6026 log_command_line(unit, "About to execute", command->path, command->argv);
12145637 6027
78f93209 6028 if (params->cgroup_path) {
a8b993dc 6029 r = exec_parameters_get_cgroup_path(params, cgroup_context, &subcgroup_path);
78f93209
LP
6030 if (r < 0)
6031 return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
18c1e481
LP
6032 if (r > 0) {
6033 /* If there's a subcgroup, then let's create it here now (the main cgroup was already
6034 * realized by the unit logic) */
6035
78f93209
LP
6036 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path);
6037 if (r < 0)
a8b993dc 6038 return log_unit_error_errno(unit, r, "Failed to create subcgroup '%s': %m", subcgroup_path);
78f93209
LP
6039 }
6040 }
6041
d35fbf6b
DM
6042 pid = fork();
6043 if (pid < 0)
74129a12 6044 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
6045
6046 if (pid == 0) {
12145637 6047 int exit_status = EXIT_SUCCESS;
ff0af2a1 6048
f2341e0a
LP
6049 r = exec_child(unit,
6050 command,
ff0af2a1
LP
6051 context,
6052 params,
6053 runtime,
6bb00842 6054 cgroup_context,
ff0af2a1 6055 socket_fd,
52c239d7 6056 named_iofds,
4c47affc 6057 fds,
9b141911 6058 n_socket_fds,
25b583d7 6059 n_storage_fds,
ff0af2a1 6060 files_env,
00d9ef85 6061 unit->manager->user_lookup_fds[1],
12145637
LP
6062 &exit_status);
6063
e1714f02
ZJS
6064 if (r < 0) {
6065 const char *status =
6066 exit_status_to_string(exit_status,
e04ed6db 6067 EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);
e1714f02 6068
c2503e35
RH
6069 log_unit_struct_errno(unit, LOG_ERR, r,
6070 "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
6071 LOG_UNIT_INVOCATION_ID(unit),
6072 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
6073 status, command->path),
6074 "EXECUTABLE=%s", command->path);
e1714f02 6075 }
4c2630eb 6076
ff0af2a1 6077 _exit(exit_status);
034c6ed7
LP
6078 }
6079
f2341e0a 6080 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 6081
78f93209
LP
6082 /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
6083 * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
6084 * process will be killed too). */
6085 if (subcgroup_path)
6086 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid);
2da3263a 6087
b58b4116 6088 exec_status_start(&command->exec_status, pid);
9fb86720 6089
034c6ed7 6090 *ret = pid;
5cb5a6ff
LP
6091 return 0;
6092}
6093
034c6ed7
LP
6094void exec_context_init(ExecContext *c) {
6095 assert(c);
6096
4c12626c 6097 c->umask = 0022;
0692548c 6098 c->ioprio = IOPRIO_DEFAULT_CLASS_AND_PRIO;
94f04347 6099 c->cpu_sched_policy = SCHED_OTHER;
071830ff 6100 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 6101 c->syslog_level_prefix = true;
353e12c2 6102 c->ignore_sigpipe = true;
3a43da28 6103 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 6104 c->personality = PERSONALITY_INVALID;
5b10116e
ZJS
6105 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
6106 c->directories[t].mode = 0755;
12213aed 6107 c->timeout_clean_usec = USEC_INFINITY;
3fd5190b 6108 c->capability_bounding_set = CAP_MASK_UNSET;
aa9d574d
YW
6109 assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
6110 c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL;
d3070fbd 6111 c->log_level_max = -1;
005bfaf1
TM
6112#if HAVE_SECCOMP
6113 c->syscall_errno = SECCOMP_ERROR_NUMBER_KILL;
6114#endif
51462135
DDM
6115 c->tty_rows = UINT_MAX;
6116 c->tty_cols = UINT_MAX;
b070c7c0 6117 numa_policy_reset(&c->numa_policy);
24002121 6118 c->private_mounts = -1;
85614c6e 6119 c->memory_ksm = -1;
034c6ed7
LP
6120}
6121
613b411c 6122void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
6123 assert(c);
6124
6796073e
LP
6125 c->environment = strv_free(c->environment);
6126 c->environment_files = strv_free(c->environment_files);
b4c14404 6127 c->pass_environment = strv_free(c->pass_environment);
00819cc1 6128 c->unset_environment = strv_free(c->unset_environment);
8c7be95e 6129
31ce987c 6130 rlimit_free_all(c->rlimit);
034c6ed7 6131
5b10116e 6132 for (size_t l = 0; l < 3; l++) {
52c239d7 6133 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
2038c3f5
LP
6134 c->stdio_file[l] = mfree(c->stdio_file[l]);
6135 }
52c239d7 6136
a1e58e8e
LP
6137 c->working_directory = mfree(c->working_directory);
6138 c->root_directory = mfree(c->root_directory);
915e6d16 6139 c->root_image = mfree(c->root_image);
18d73705 6140 c->root_image_options = mount_options_free_all(c->root_image_options);
0389f4fa
LB
6141 c->root_hash = mfree(c->root_hash);
6142 c->root_hash_size = 0;
6143 c->root_hash_path = mfree(c->root_hash_path);
d4d55b0d
LB
6144 c->root_hash_sig = mfree(c->root_hash_sig);
6145 c->root_hash_sig_size = 0;
6146 c->root_hash_sig_path = mfree(c->root_hash_sig_path);
0389f4fa 6147 c->root_verity = mfree(c->root_verity);
93f59701 6148 c->extension_images = mount_image_free_many(c->extension_images, &c->n_extension_images);
a07b9926 6149 c->extension_directories = strv_free(c->extension_directories);
a1e58e8e
LP
6150 c->tty_path = mfree(c->tty_path);
6151 c->syslog_identifier = mfree(c->syslog_identifier);
6152 c->user = mfree(c->user);
6153 c->group = mfree(c->group);
034c6ed7 6154
6796073e 6155 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 6156
a1e58e8e 6157 c->pam_name = mfree(c->pam_name);
5b6319dc 6158
2a624c36
AP
6159 c->read_only_paths = strv_free(c->read_only_paths);
6160 c->read_write_paths = strv_free(c->read_write_paths);
6161 c->inaccessible_paths = strv_free(c->inaccessible_paths);
ddc155b2
TM
6162 c->exec_paths = strv_free(c->exec_paths);
6163 c->no_exec_paths = strv_free(c->no_exec_paths);
8c35c10d 6164 c->exec_search_path = strv_free(c->exec_search_path);
82c121a4 6165
d2d6c096 6166 bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
8e06d57c
YW
6167 c->bind_mounts = NULL;
6168 c->n_bind_mounts = 0;
2abd4e38
YW
6169 temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
6170 c->temporary_filesystems = NULL;
6171 c->n_temporary_filesystems = 0;
b3d13314 6172 c->mount_images = mount_image_free_many(c->mount_images, &c->n_mount_images);
d2d6c096 6173
0985c7c4 6174 cpu_set_reset(&c->cpu_set);
b070c7c0 6175 numa_policy_reset(&c->numa_policy);
86a3475b 6176
a1e58e8e
LP
6177 c->utmp_id = mfree(c->utmp_id);
6178 c->selinux_context = mfree(c->selinux_context);
6179 c->apparmor_profile = mfree(c->apparmor_profile);
5b8e1b77 6180 c->smack_process_label = mfree(c->smack_process_label);
eef65bf3 6181
9b412709 6182 c->restrict_filesystems = set_free_free(c->restrict_filesystems);
b1994387 6183
8cfa775f 6184 c->syscall_filter = hashmap_free(c->syscall_filter);
525d3cc7
LP
6185 c->syscall_archs = set_free(c->syscall_archs);
6186 c->address_families = set_free(c->address_families);
e66cf1a3 6187
5b10116e 6188 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
211a3d87 6189 exec_directory_done(&c->directories[t]);
d3070fbd
LP
6190
6191 c->log_level_max = -1;
6192
6193 exec_context_free_log_extra_fields(c);
9b412709
FS
6194 c->log_filter_allowed_patterns = set_free_free(c->log_filter_allowed_patterns);
6195 c->log_filter_denied_patterns = set_free_free(c->log_filter_denied_patterns);
08f3be7a 6196
5ac1530e
ZJS
6197 c->log_ratelimit_interval_usec = 0;
6198 c->log_ratelimit_burst = 0;
90fc172e 6199
08f3be7a
LP
6200 c->stdin_data = mfree(c->stdin_data);
6201 c->stdin_data_size = 0;
a8d08f39
LP
6202
6203 c->network_namespace_path = mfree(c->network_namespace_path);
71d1e583 6204 c->ipc_namespace_path = mfree(c->ipc_namespace_path);
91dd5f7c
LP
6205
6206 c->log_namespace = mfree(c->log_namespace);
bb0c0d6f 6207
43144be4 6208 c->load_credentials = hashmap_free(c->load_credentials);
bb0c0d6f 6209 c->set_credentials = hashmap_free(c->set_credentials);
9b412709 6210 c->import_credentials = set_free_free(c->import_credentials);
84be0c71
LP
6211
6212 c->root_image_policy = image_policy_free(c->root_image_policy);
6213 c->mount_image_policy = image_policy_free(c->mount_image_policy);
6214 c->extension_image_policy = image_policy_free(c->extension_image_policy);
e66cf1a3
LP
6215}
6216
34cf6c43 6217int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
e66cf1a3
LP
6218 assert(c);
6219
6220 if (!runtime_prefix)
6221 return 0;
6222
211a3d87 6223 for (size_t i = 0; i < c->directories[EXEC_DIRECTORY_RUNTIME].n_items; i++) {
c2b2df60 6224 _cleanup_free_ char *p = NULL;
e66cf1a3 6225
494d0247 6226 if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
211a3d87 6227 p = path_join(runtime_prefix, "private", c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path);
494d0247 6228 else
211a3d87 6229 p = path_join(runtime_prefix, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path);
e66cf1a3
LP
6230 if (!p)
6231 return -ENOMEM;
6232
7bc4bf4a
LP
6233 /* We execute this synchronously, since we need to be sure this is gone when we start the
6234 * service next. */
c6878637 6235 (void) rm_rf(p, REMOVE_ROOT);
211a3d87 6236
211a3d87
LB
6237 STRV_FOREACH(symlink, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].symlinks) {
6238 _cleanup_free_ char *symlink_abs = NULL;
6239
6240 if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
6241 symlink_abs = path_join(runtime_prefix, "private", *symlink);
6242 else
6243 symlink_abs = path_join(runtime_prefix, *symlink);
6244 if (!symlink_abs)
6245 return -ENOMEM;
6246
6247 (void) unlink(symlink_abs);
6248 }
e66cf1a3
LP
6249 }
6250
6251 return 0;
5cb5a6ff
LP
6252}
6253
bb0c0d6f
LP
6254int exec_context_destroy_credentials(const ExecContext *c, const char *runtime_prefix, const char *unit) {
6255 _cleanup_free_ char *p = NULL;
6256
6257 assert(c);
6258
6259 if (!runtime_prefix || !unit)
6260 return 0;
6261
6262 p = path_join(runtime_prefix, "credentials", unit);
6263 if (!p)
6264 return -ENOMEM;
6265
6266 /* This is either a tmpfs/ramfs of its own, or a plain directory. Either way, let's first try to
6267 * unmount it, and afterwards remove the mount point */
6268 (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
6269 (void) rm_rf(p, REMOVE_ROOT|REMOVE_CHMOD);
6270
6271 return 0;
6272}
6273
b9f976fb
MK
6274int exec_context_destroy_mount_ns_dir(Unit *u) {
6275 _cleanup_free_ char *p = NULL;
6276
6277 if (!u || !MANAGER_IS_SYSTEM(u->manager))
6278 return 0;
6279
6280 p = path_join("/run/systemd/propagate/", u->id);
6281 if (!p)
6282 return -ENOMEM;
6283
6284 /* This is only filled transiently (see mount_in_namespace()), should be empty or even non-existent*/
6285 if (rmdir(p) < 0 && errno != ENOENT)
6286 log_unit_debug_errno(u, errno, "Unable to remove propagation dir '%s', ignoring: %m", p);
6287
6288 return 0;
6289}
6290
34cf6c43 6291static void exec_command_done(ExecCommand *c) {
43d0fcbd
LP
6292 assert(c);
6293
a1e58e8e 6294 c->path = mfree(c->path);
6796073e 6295 c->argv = strv_free(c->argv);
43d0fcbd
LP
6296}
6297
da6053d0 6298void exec_command_done_array(ExecCommand *c, size_t n) {
fe96c0f8 6299 for (size_t i = 0; i < n; i++)
43d0fcbd
LP
6300 exec_command_done(c+i);
6301}
6302
f1acf85a 6303ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
6304 ExecCommand *i;
6305
6306 while ((i = c)) {
71fda00f 6307 LIST_REMOVE(command, c, i);
43d0fcbd 6308 exec_command_done(i);
5cb5a6ff
LP
6309 free(i);
6310 }
f1acf85a
ZJS
6311
6312 return NULL;
5cb5a6ff
LP
6313}
6314
da6053d0 6315void exec_command_free_array(ExecCommand **c, size_t n) {
5b10116e 6316 for (size_t i = 0; i < n; i++)
f1acf85a 6317 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
6318}
6319
6a1d4d9f 6320void exec_command_reset_status_array(ExecCommand *c, size_t n) {
5b10116e 6321 for (size_t i = 0; i < n; i++)
6a1d4d9f
LP
6322 exec_status_reset(&c[i].exec_status);
6323}
6324
6325void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
03677889 6326 for (size_t i = 0; i < n; i++)
6a1d4d9f
LP
6327 LIST_FOREACH(command, z, c[i])
6328 exec_status_reset(&z->exec_status);
6a1d4d9f
LP
6329}
6330
039f0e70 6331typedef struct InvalidEnvInfo {
34cf6c43 6332 const Unit *unit;
039f0e70
LP
6333 const char *path;
6334} InvalidEnvInfo;
6335
6336static void invalid_env(const char *p, void *userdata) {
6337 InvalidEnvInfo *info = userdata;
6338
f2341e0a 6339 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
6340}
6341
52c239d7
LB
6342const char* exec_context_fdname(const ExecContext *c, int fd_index) {
6343 assert(c);
6344
6345 switch (fd_index) {
5073ff6b 6346
52c239d7
LB
6347 case STDIN_FILENO:
6348 if (c->std_input != EXEC_INPUT_NAMED_FD)
6349 return NULL;
5073ff6b 6350
52c239d7 6351 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
5073ff6b 6352
52c239d7
LB
6353 case STDOUT_FILENO:
6354 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
6355 return NULL;
5073ff6b 6356
52c239d7 6357 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
5073ff6b 6358
52c239d7
LB
6359 case STDERR_FILENO:
6360 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
6361 return NULL;
5073ff6b 6362
52c239d7 6363 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
5073ff6b 6364
52c239d7
LB
6365 default:
6366 return NULL;
6367 }
6368}
6369
2caa38e9
LP
6370static int exec_context_named_iofds(
6371 const ExecContext *c,
6372 const ExecParameters *p,
6373 int named_iofds[static 3]) {
6374
5b10116e 6375 size_t targets;
56fbd561 6376 const char* stdio_fdname[3];
da6053d0 6377 size_t n_fds;
52c239d7
LB
6378
6379 assert(c);
6380 assert(p);
2caa38e9 6381 assert(named_iofds);
52c239d7
LB
6382
6383 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
6384 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
6385 (c->std_error == EXEC_OUTPUT_NAMED_FD);
6386
5b10116e 6387 for (size_t i = 0; i < 3; i++)
52c239d7
LB
6388 stdio_fdname[i] = exec_context_fdname(c, i);
6389
4c47affc
FB
6390 n_fds = p->n_storage_fds + p->n_socket_fds;
6391
5b10116e 6392 for (size_t i = 0; i < n_fds && targets > 0; i++)
56fbd561
ZJS
6393 if (named_iofds[STDIN_FILENO] < 0 &&
6394 c->std_input == EXEC_INPUT_NAMED_FD &&
6395 stdio_fdname[STDIN_FILENO] &&
6396 streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
6397
52c239d7
LB
6398 named_iofds[STDIN_FILENO] = p->fds[i];
6399 targets--;
56fbd561
ZJS
6400
6401 } else if (named_iofds[STDOUT_FILENO] < 0 &&
6402 c->std_output == EXEC_OUTPUT_NAMED_FD &&
6403 stdio_fdname[STDOUT_FILENO] &&
6404 streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
6405
52c239d7
LB
6406 named_iofds[STDOUT_FILENO] = p->fds[i];
6407 targets--;
56fbd561
ZJS
6408
6409 } else if (named_iofds[STDERR_FILENO] < 0 &&
6410 c->std_error == EXEC_OUTPUT_NAMED_FD &&
6411 stdio_fdname[STDERR_FILENO] &&
6412 streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
6413
52c239d7
LB
6414 named_iofds[STDERR_FILENO] = p->fds[i];
6415 targets--;
6416 }
6417
56fbd561 6418 return targets == 0 ? 0 : -ENOENT;
52c239d7
LB
6419}
6420
398a5009
ZJS
6421static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret) {
6422 _cleanup_strv_free_ char **v = NULL;
398a5009 6423 int r;
8c7be95e
LP
6424
6425 assert(c);
398a5009 6426 assert(ret);
8c7be95e
LP
6427
6428 STRV_FOREACH(i, c->environment_files) {
7fd1b19b 6429 _cleanup_globfree_ glob_t pglob = {};
398a5009
ZJS
6430 bool ignore = false;
6431 char *fn = *i;
8c7be95e
LP
6432
6433 if (fn[0] == '-') {
6434 ignore = true;
313cefa1 6435 fn++;
8c7be95e
LP
6436 }
6437
6438 if (!path_is_absolute(fn)) {
8c7be95e
LP
6439 if (ignore)
6440 continue;
8c7be95e
LP
6441 return -EINVAL;
6442 }
6443
2bef10ab 6444 /* Filename supports globbing, take all matching files */
398a5009
ZJS
6445 r = safe_glob(fn, 0, &pglob);
6446 if (r < 0) {
2bef10ab
PL
6447 if (ignore)
6448 continue;
398a5009 6449 return r;
2bef10ab 6450 }
8c7be95e 6451
d8c92e8b
ZJS
6452 /* When we don't match anything, -ENOENT should be returned */
6453 assert(pglob.gl_pathc > 0);
6454
fcc06682 6455 for (size_t n = 0; n < pglob.gl_pathc; n++) {
398a5009
ZJS
6456 _cleanup_strv_free_ char **p = NULL;
6457
6458 r = load_env_file(NULL, pglob.gl_pathv[n], &p);
6459 if (r < 0) {
2bef10ab
PL
6460 if (ignore)
6461 continue;
398a5009 6462 return r;
e9c1ea9d 6463 }
398a5009 6464
ebc05a09 6465 /* Log invalid environment variables with filename */
039f0e70
LP
6466 if (p) {
6467 InvalidEnvInfo info = {
f2341e0a 6468 .unit = unit,
039f0e70
LP
6469 .path = pglob.gl_pathv[n]
6470 };
6471
6472 p = strv_env_clean_with_callback(p, invalid_env, &info);
6473 }
8c7be95e 6474
398a5009
ZJS
6475 if (!v)
6476 v = TAKE_PTR(p);
2bef10ab 6477 else {
398a5009 6478 char **m = strv_env_merge(v, p);
c84a9488 6479 if (!m)
2bef10ab 6480 return -ENOMEM;
2bef10ab 6481
398a5009 6482 strv_free_and_replace(v, m);
2bef10ab 6483 }
8c7be95e
LP
6484 }
6485 }
6486
398a5009 6487 *ret = TAKE_PTR(v);
8c7be95e
LP
6488
6489 return 0;
6490}
6491
6ac8fdc9 6492static bool tty_may_match_dev_console(const char *tty) {
7b912648 6493 _cleanup_free_ char *resolved = NULL;
6ac8fdc9 6494
1e22b5cd
LP
6495 if (!tty)
6496 return true;
6497
a119ec7c 6498 tty = skip_dev_prefix(tty);
6ac8fdc9
MS
6499
6500 /* trivial identity? */
6501 if (streq(tty, "console"))
6502 return true;
6503
7b912648
LP
6504 if (resolve_dev_console(&resolved) < 0)
6505 return true; /* if we could not resolve, assume it may */
6ac8fdc9
MS
6506
6507 /* "tty0" means the active VC, so it may be the same sometimes */
955f1c85 6508 return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
6509}
6510
6c0ae739
LP
6511static bool exec_context_may_touch_tty(const ExecContext *ec) {
6512 assert(ec);
1e22b5cd 6513
6c0ae739 6514 return ec->tty_reset ||
1e22b5cd
LP
6515 ec->tty_vhangup ||
6516 ec->tty_vt_disallocate ||
6ac8fdc9
MS
6517 is_terminal_input(ec->std_input) ||
6518 is_terminal_output(ec->std_output) ||
6c0ae739
LP
6519 is_terminal_output(ec->std_error);
6520}
6521
6522bool exec_context_may_touch_console(const ExecContext *ec) {
6523
6524 return exec_context_may_touch_tty(ec) &&
1e22b5cd 6525 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
6526}
6527
15ae422b 6528static void strv_fprintf(FILE *f, char **l) {
15ae422b
LP
6529 assert(f);
6530
6531 STRV_FOREACH(g, l)
6532 fprintf(f, " %s", *g);
6533}
6534
ddc155b2
TM
6535static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv) {
6536 assert(f);
6537 assert(prefix);
6538 assert(name);
6539
6540 if (!strv_isempty(strv)) {
a7bd1656 6541 fprintf(f, "%s%s:", prefix, name);
ddc155b2
TM
6542 strv_fprintf(f, strv);
6543 fputs("\n", f);
6544 }
6545}
6546
34cf6c43 6547void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
add00535 6548 int r;
9eba9da4 6549
5cb5a6ff
LP
6550 assert(c);
6551 assert(f);
6552
4ad49000 6553 prefix = strempty(prefix);
5cb5a6ff
LP
6554
6555 fprintf(f,
94f04347
LP
6556 "%sUMask: %04o\n"
6557 "%sWorkingDirectory: %s\n"
451a074f 6558 "%sRootDirectory: %s\n"
9c0c6701 6559 "%sRootEphemeral: %s\n"
15ae422b 6560 "%sNonBlocking: %s\n"
64747e2d 6561 "%sPrivateTmp: %s\n"
7f112f50 6562 "%sPrivateDevices: %s\n"
59eeb84b 6563 "%sProtectKernelTunables: %s\n"
e66a2f65 6564 "%sProtectKernelModules: %s\n"
84703040 6565 "%sProtectKernelLogs: %s\n"
fc64760d 6566 "%sProtectClock: %s\n"
59eeb84b 6567 "%sProtectControlGroups: %s\n"
d251207d
LP
6568 "%sPrivateNetwork: %s\n"
6569 "%sPrivateUsers: %s\n"
1b8689f9
LP
6570 "%sProtectHome: %s\n"
6571 "%sProtectSystem: %s\n"
5d997827 6572 "%sMountAPIVFS: %s\n"
f3e43635 6573 "%sIgnoreSIGPIPE: %s\n"
f4170c67 6574 "%sMemoryDenyWriteExecute: %s\n"
b1edf445 6575 "%sRestrictRealtime: %s\n"
f69567cb 6576 "%sRestrictSUIDSGID: %s\n"
aecd5ac6 6577 "%sKeyringMode: %s\n"
4e399953
LP
6578 "%sProtectHostname: %s\n"
6579 "%sProtectProc: %s\n"
6580 "%sProcSubset: %s\n",
5cb5a6ff 6581 prefix, c->umask,
14eb3285
LP
6582 prefix, empty_to_root(c->working_directory),
6583 prefix, empty_to_root(c->root_directory),
9c0c6701 6584 prefix, yes_no(c->root_ephemeral),
15ae422b 6585 prefix, yes_no(c->non_blocking),
64747e2d 6586 prefix, yes_no(c->private_tmp),
7f112f50 6587 prefix, yes_no(c->private_devices),
59eeb84b 6588 prefix, yes_no(c->protect_kernel_tunables),
e66a2f65 6589 prefix, yes_no(c->protect_kernel_modules),
84703040 6590 prefix, yes_no(c->protect_kernel_logs),
fc64760d 6591 prefix, yes_no(c->protect_clock),
59eeb84b 6592 prefix, yes_no(c->protect_control_groups),
d251207d
LP
6593 prefix, yes_no(c->private_network),
6594 prefix, yes_no(c->private_users),
1b8689f9
LP
6595 prefix, protect_home_to_string(c->protect_home),
6596 prefix, protect_system_to_string(c->protect_system),
5e98086d 6597 prefix, yes_no(exec_context_get_effective_mount_apivfs(c)),
f3e43635 6598 prefix, yes_no(c->ignore_sigpipe),
f4170c67 6599 prefix, yes_no(c->memory_deny_write_execute),
b1edf445 6600 prefix, yes_no(c->restrict_realtime),
f69567cb 6601 prefix, yes_no(c->restrict_suid_sgid),
aecd5ac6 6602 prefix, exec_keyring_mode_to_string(c->keyring_mode),
4e399953
LP
6603 prefix, yes_no(c->protect_hostname),
6604 prefix, protect_proc_to_string(c->protect_proc),
6605 prefix, proc_subset_to_string(c->proc_subset));
fb33a393 6606
915e6d16
LP
6607 if (c->root_image)
6608 fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);
6609
18d73705 6610 if (c->root_image_options) {
18d73705
LB
6611 fprintf(f, "%sRootImageOptions:", prefix);
6612 LIST_FOREACH(mount_options, o, c->root_image_options)
6613 if (!isempty(o->options))
9ece6444
LB
6614 fprintf(f, " %s:%s",
6615 partition_designator_to_string(o->partition_designator),
6616 o->options);
18d73705
LB
6617 fprintf(f, "\n");
6618 }
6619
0389f4fa
LB
6620 if (c->root_hash) {
6621 _cleanup_free_ char *encoded = NULL;
6622 encoded = hexmem(c->root_hash, c->root_hash_size);
6623 if (encoded)
6624 fprintf(f, "%sRootHash: %s\n", prefix, encoded);
6625 }
6626
6627 if (c->root_hash_path)
6628 fprintf(f, "%sRootHash: %s\n", prefix, c->root_hash_path);
6629
d4d55b0d
LB
6630 if (c->root_hash_sig) {
6631 _cleanup_free_ char *encoded = NULL;
6632 ssize_t len;
6633 len = base64mem(c->root_hash_sig, c->root_hash_sig_size, &encoded);
6634 if (len)
6635 fprintf(f, "%sRootHashSignature: base64:%s\n", prefix, encoded);
6636 }
6637
6638 if (c->root_hash_sig_path)
6639 fprintf(f, "%sRootHashSignature: %s\n", prefix, c->root_hash_sig_path);
6640
0389f4fa
LB
6641 if (c->root_verity)
6642 fprintf(f, "%sRootVerity: %s\n", prefix, c->root_verity);
6643
8c7be95e
LP
6644 STRV_FOREACH(e, c->environment)
6645 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
6646
6647 STRV_FOREACH(e, c->environment_files)
6648 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 6649
b4c14404
FB
6650 STRV_FOREACH(e, c->pass_environment)
6651 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
6652
00819cc1
LP
6653 STRV_FOREACH(e, c->unset_environment)
6654 fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);
6655
53f47dfc
YW
6656 fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
6657
5b10116e 6658 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
3536f49e
YW
6659 fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);
6660
211a3d87
LB
6661 for (size_t i = 0; i < c->directories[dt].n_items; i++) {
6662 fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].items[i].path);
6663
6664 STRV_FOREACH(d, c->directories[dt].items[i].symlinks)
6665 fprintf(f, "%s%s: %s:%s\n", prefix, exec_directory_type_symlink_to_string(dt), c->directories[dt].items[i].path, *d);
6666 }
3536f49e 6667 }
c2bbd90b 6668
5291f26d 6669 fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC));
12213aed 6670
fb33a393 6671 if (c->nice_set)
5291f26d 6672 fprintf(f, "%sNice: %i\n", prefix, c->nice);
fb33a393 6673
dd6c17b1 6674 if (c->oom_score_adjust_set)
5291f26d 6675 fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust);
9eba9da4 6676
ad21e542 6677 if (c->coredump_filter_set)
5291f26d 6678 fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter);
ad21e542 6679
5b10116e 6680 for (unsigned i = 0; i < RLIM_NLIMITS; i++)
3c11da9d 6681 if (c->rlimit[i]) {
4c3a2b84 6682 fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
3c11da9d 6683 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
4c3a2b84 6684 fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
3c11da9d
EV
6685 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
6686 }
94f04347 6687
f8b69d1d 6688 if (c->ioprio_set) {
1756a011 6689 _cleanup_free_ char *class_str = NULL;
f8b69d1d 6690
5bead76e 6691 r = ioprio_class_to_string_alloc(ioprio_prio_class(c->ioprio), &class_str);
837df140
YW
6692 if (r >= 0)
6693 fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);
6694
5bead76e 6695 fprintf(f, "%sIOPriority: %d\n", prefix, ioprio_prio_data(c->ioprio));
f8b69d1d 6696 }
94f04347 6697
f8b69d1d 6698 if (c->cpu_sched_set) {
1756a011 6699 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 6700
837df140
YW
6701 r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
6702 if (r >= 0)
6703 fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);
6704
94f04347 6705 fprintf(f,
38b48754
LP
6706 "%sCPUSchedulingPriority: %i\n"
6707 "%sCPUSchedulingResetOnFork: %s\n",
38b48754
LP
6708 prefix, c->cpu_sched_priority,
6709 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 6710 }
94f04347 6711
0985c7c4 6712 if (c->cpu_set.set) {
e7fca352
MS
6713 _cleanup_free_ char *affinity = NULL;
6714
6715 affinity = cpu_set_to_range_string(&c->cpu_set);
6716 fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity);
94f04347
LP
6717 }
6718
b070c7c0
MS
6719 if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
6720 _cleanup_free_ char *nodes = NULL;
6721
6722 nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
6723 fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy)));
6724 fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes));
6725 }
6726
3a43da28 6727 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 6728 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
6729
6730 fprintf(f,
80876c20
LP
6731 "%sStandardInput: %s\n"
6732 "%sStandardOutput: %s\n"
6733 "%sStandardError: %s\n",
6734 prefix, exec_input_to_string(c->std_input),
6735 prefix, exec_output_to_string(c->std_output),
6736 prefix, exec_output_to_string(c->std_error));
6737
befc4a80
LP
6738 if (c->std_input == EXEC_INPUT_NAMED_FD)
6739 fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
6740 if (c->std_output == EXEC_OUTPUT_NAMED_FD)
6741 fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
6742 if (c->std_error == EXEC_OUTPUT_NAMED_FD)
6743 fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);
6744
6745 if (c->std_input == EXEC_INPUT_FILE)
6746 fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
6747 if (c->std_output == EXEC_OUTPUT_FILE)
6748 fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
566b7d23
ZD
6749 if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
6750 fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
8d7dab1f
LW
6751 if (c->std_output == EXEC_OUTPUT_FILE_TRUNCATE)
6752 fprintf(f, "%sStandardOutputFileToTruncate: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
befc4a80
LP
6753 if (c->std_error == EXEC_OUTPUT_FILE)
6754 fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
566b7d23
ZD
6755 if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
6756 fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
8d7dab1f
LW
6757 if (c->std_error == EXEC_OUTPUT_FILE_TRUNCATE)
6758 fprintf(f, "%sStandardErrorFileToTruncate: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
befc4a80 6759
80876c20
LP
6760 if (c->tty_path)
6761 fprintf(f,
6ea832a2
LP
6762 "%sTTYPath: %s\n"
6763 "%sTTYReset: %s\n"
6764 "%sTTYVHangup: %s\n"
51462135
DDM
6765 "%sTTYVTDisallocate: %s\n"
6766 "%sTTYRows: %u\n"
6767 "%sTTYColumns: %u\n",
6ea832a2
LP
6768 prefix, c->tty_path,
6769 prefix, yes_no(c->tty_reset),
6770 prefix, yes_no(c->tty_vhangup),
51462135
DDM
6771 prefix, yes_no(c->tty_vt_disallocate),
6772 prefix, c->tty_rows,
6773 prefix, c->tty_cols);
94f04347 6774
9f6444eb 6775 if (IN_SET(c->std_output,
9f6444eb
LP
6776 EXEC_OUTPUT_KMSG,
6777 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
6778 EXEC_OUTPUT_KMSG_AND_CONSOLE,
6779 EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
6780 IN_SET(c->std_error,
9f6444eb
LP
6781 EXEC_OUTPUT_KMSG,
6782 EXEC_OUTPUT_JOURNAL,
9f6444eb
LP
6783 EXEC_OUTPUT_KMSG_AND_CONSOLE,
6784 EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {
f8b69d1d 6785
5ce70e5b 6786 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 6787
837df140
YW
6788 r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
6789 if (r >= 0)
6790 fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);
f8b69d1d 6791
837df140
YW
6792 r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
6793 if (r >= 0)
6794 fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
f8b69d1d 6795 }
94f04347 6796
d3070fbd
LP
6797 if (c->log_level_max >= 0) {
6798 _cleanup_free_ char *t = NULL;
6799
6800 (void) log_level_to_string_alloc(c->log_level_max, &t);
6801
6802 fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
6803 }
6804
5291f26d 6805 if (c->log_ratelimit_interval_usec > 0)
90fc172e
AZ
6806 fprintf(f,
6807 "%sLogRateLimitIntervalSec: %s\n",
5291f26d 6808 prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC));
90fc172e 6809
5ac1530e
ZJS
6810 if (c->log_ratelimit_burst > 0)
6811 fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);
90fc172e 6812
523ea123
QD
6813 if (!set_isempty(c->log_filter_allowed_patterns) || !set_isempty(c->log_filter_denied_patterns)) {
6814 fprintf(f, "%sLogFilterPatterns:", prefix);
6815
6816 char *pattern;
6817 SET_FOREACH(pattern, c->log_filter_allowed_patterns)
6818 fprintf(f, " %s", pattern);
6819 SET_FOREACH(pattern, c->log_filter_denied_patterns)
6820 fprintf(f, " ~%s", pattern);
6821 fputc('\n', f);
6822 }
6823
5b10116e
ZJS
6824 for (size_t j = 0; j < c->n_log_extra_fields; j++) {
6825 fprintf(f, "%sLogExtraFields: ", prefix);
6826 fwrite(c->log_extra_fields[j].iov_base,
6827 1, c->log_extra_fields[j].iov_len,
6828 f);
6829 fputc('\n', f);
d3070fbd
LP
6830 }
6831
91dd5f7c
LP
6832 if (c->log_namespace)
6833 fprintf(f, "%sLogNamespace: %s\n", prefix, c->log_namespace);
6834
07d46372
YW
6835 if (c->secure_bits) {
6836 _cleanup_free_ char *str = NULL;
6837
6838 r = secure_bits_to_string_alloc(c->secure_bits, &str);
6839 if (r >= 0)
6840 fprintf(f, "%sSecure Bits: %s\n", prefix, str);
6841 }
94f04347 6842
3fd5190b 6843 if (c->capability_bounding_set != CAP_MASK_UNSET) {
dd1f5bd0 6844 _cleanup_free_ char *str = NULL;
94f04347 6845
8142d735 6846 r = capability_set_to_string(c->capability_bounding_set, &str);
dd1f5bd0
YW
6847 if (r >= 0)
6848 fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
755d4b67
IP
6849 }
6850
6851 if (c->capability_ambient_set != 0) {
dd1f5bd0 6852 _cleanup_free_ char *str = NULL;
755d4b67 6853
8142d735 6854 r = capability_set_to_string(c->capability_ambient_set, &str);
dd1f5bd0
YW
6855 if (r >= 0)
6856 fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
94f04347
LP
6857 }
6858
6859 if (c->user)
f2d3769a 6860 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 6861 if (c->group)
f2d3769a 6862 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 6863
29206d46
LP
6864 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
6865
ddc155b2 6866 strv_dump(f, prefix, "SupplementaryGroups", c->supplementary_groups);
94f04347 6867
5b6319dc 6868 if (c->pam_name)
f2d3769a 6869 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 6870
ddc155b2
TM
6871 strv_dump(f, prefix, "ReadWritePaths", c->read_write_paths);
6872 strv_dump(f, prefix, "ReadOnlyPaths", c->read_only_paths);
6873 strv_dump(f, prefix, "InaccessiblePaths", c->inaccessible_paths);
6874 strv_dump(f, prefix, "ExecPaths", c->exec_paths);
6875 strv_dump(f, prefix, "NoExecPaths", c->no_exec_paths);
8c35c10d 6876 strv_dump(f, prefix, "ExecSearchPath", c->exec_search_path);
2e22afe9 6877
5b10116e
ZJS
6878 for (size_t i = 0; i < c->n_bind_mounts; i++)
6879 fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
6880 c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
6881 c->bind_mounts[i].ignore_enoent ? "-": "",
6882 c->bind_mounts[i].source,
6883 c->bind_mounts[i].destination,
6884 c->bind_mounts[i].recursive ? "rbind" : "norbind");
d2d6c096 6885
5b10116e
ZJS
6886 for (size_t i = 0; i < c->n_temporary_filesystems; i++) {
6887 const TemporaryFileSystem *t = c->temporary_filesystems + i;
2abd4e38 6888
5b10116e
ZJS
6889 fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
6890 t->path,
6891 isempty(t->options) ? "" : ":",
6892 strempty(t->options));
6893 }
2abd4e38 6894
169c1bda
LP
6895 if (c->utmp_id)
6896 fprintf(f,
6897 "%sUtmpIdentifier: %s\n",
6898 prefix, c->utmp_id);
7b52a628
MS
6899
6900 if (c->selinux_context)
6901 fprintf(f,
5f8640fb
LP
6902 "%sSELinuxContext: %s%s\n",
6903 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 6904
80c21aea
WC
6905 if (c->apparmor_profile)
6906 fprintf(f,
6907 "%sAppArmorProfile: %s%s\n",
6908 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
6909
6910 if (c->smack_process_label)
6911 fprintf(f,
6912 "%sSmackProcessLabel: %s%s\n",
6913 prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);
6914
050f7277 6915 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
6916 fprintf(f,
6917 "%sPersonality: %s\n",
6918 prefix, strna(personality_to_string(c->personality)));
6919
78e864e5
TM
6920 fprintf(f,
6921 "%sLockPersonality: %s\n",
6922 prefix, yes_no(c->lock_personality));
6923
17df7223 6924 if (c->syscall_filter) {
17df7223 6925 fprintf(f,
57183d11 6926 "%sSystemCallFilter: ",
17df7223
LP
6927 prefix);
6928
6b000af4 6929 if (!c->syscall_allow_list)
17df7223
LP
6930 fputc('~', f);
6931
349cc4a5 6932#if HAVE_SECCOMP
d5a99b7c
JJ
6933 void *id, *val;
6934 bool first = true;
90e74a66 6935 HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
17df7223 6936 _cleanup_free_ char *name = NULL;
8cfa775f
YW
6937 const char *errno_name = NULL;
6938 int num = PTR_TO_INT(val);
17df7223
LP
6939
6940 if (first)
6941 first = false;
6942 else
6943 fputc(' ', f);
6944
57183d11 6945 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223 6946 fputs(strna(name), f);
8cfa775f
YW
6947
6948 if (num >= 0) {
005bfaf1 6949 errno_name = seccomp_errno_or_action_to_string(num);
8cfa775f
YW
6950 if (errno_name)
6951 fprintf(f, ":%s", errno_name);
6952 else
6953 fprintf(f, ":%d", num);
6954 }
17df7223 6955 }
351a19b1 6956#endif
17df7223
LP
6957
6958 fputc('\n', f);
6959 }
6960
57183d11 6961 if (c->syscall_archs) {
57183d11
LP
6962 fprintf(f,
6963 "%sSystemCallArchitectures:",
6964 prefix);
6965
349cc4a5 6966#if HAVE_SECCOMP
d5a99b7c 6967 void *id;
90e74a66 6968 SET_FOREACH(id, c->syscall_archs)
57183d11
LP
6969 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
6970#endif
6971 fputc('\n', f);
6972 }
6973
add00535
LP
6974 if (exec_context_restrict_namespaces_set(c)) {
6975 _cleanup_free_ char *s = NULL;
6976
86c2a9f1 6977 r = namespace_flags_to_string(c->restrict_namespaces, &s);
add00535
LP
6978 if (r >= 0)
6979 fprintf(f, "%sRestrictNamespaces: %s\n",
dd0395b5 6980 prefix, strna(s));
add00535
LP
6981 }
6982
b1994387 6983#if HAVE_LIBBPF
8fe84dc8
YW
6984 if (exec_context_restrict_filesystems_set(c)) {
6985 char *fs;
6986 SET_FOREACH(fs, c->restrict_filesystems)
6987 fprintf(f, "%sRestrictFileSystems: %s\n", prefix, fs);
6988 }
b1994387
ILG
6989#endif
6990
a8d08f39
LP
6991 if (c->network_namespace_path)
6992 fprintf(f,
6993 "%sNetworkNamespacePath: %s\n",
6994 prefix, c->network_namespace_path);
6995
3df90f24 6996 if (c->syscall_errno > 0) {
3df90f24
YW
6997 fprintf(f, "%sSystemCallErrorNumber: ", prefix);
6998
005bfaf1 6999#if HAVE_SECCOMP
d5a99b7c 7000 const char *errno_name = seccomp_errno_or_action_to_string(c->syscall_errno);
3df90f24 7001 if (errno_name)
005bfaf1 7002 fputs(errno_name, f);
3df90f24 7003 else
005bfaf1
TM
7004 fprintf(f, "%d", c->syscall_errno);
7005#endif
7006 fputc('\n', f);
3df90f24 7007 }
b3d13314 7008
5b10116e 7009 for (size_t i = 0; i < c->n_mount_images; i++) {
79e20ceb 7010 fprintf(f, "%sMountImages: %s%s:%s", prefix,
b3d13314
LB
7011 c->mount_images[i].ignore_enoent ? "-": "",
7012 c->mount_images[i].source,
79e20ceb 7013 c->mount_images[i].destination);
427353f6 7014 LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options)
79e20ceb 7015 fprintf(f, ":%s:%s",
427353f6 7016 partition_designator_to_string(o->partition_designator),
79e20ceb 7017 strempty(o->options));
427353f6
LB
7018 fprintf(f, "\n");
7019 }
93f59701
LB
7020
7021 for (size_t i = 0; i < c->n_extension_images; i++) {
93f59701
LB
7022 fprintf(f, "%sExtensionImages: %s%s", prefix,
7023 c->extension_images[i].ignore_enoent ? "-": "",
7024 c->extension_images[i].source);
7025 LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options)
7026 fprintf(f, ":%s:%s",
7027 partition_designator_to_string(o->partition_designator),
7028 strempty(o->options));
7029 fprintf(f, "\n");
7030 }
a07b9926
LB
7031
7032 strv_dump(f, prefix, "ExtensionDirectories", c->extension_directories);
5cb5a6ff
LP
7033}
7034
34cf6c43 7035bool exec_context_maintains_privileges(const ExecContext *c) {
a931ad47
LP
7036 assert(c);
7037
61233823 7038 /* Returns true if the process forked off would run under
a931ad47
LP
7039 * an unchanged UID or as root. */
7040
7041 if (!c->user)
7042 return true;
7043
7044 if (streq(c->user, "root") || streq(c->user, "0"))
7045 return true;
7046
7047 return false;
7048}
7049
34cf6c43 7050int exec_context_get_effective_ioprio(const ExecContext *c) {
7f452159
LP
7051 int p;
7052
7053 assert(c);
7054
7055 if (c->ioprio_set)
7056 return c->ioprio;
7057
7058 p = ioprio_get(IOPRIO_WHO_PROCESS, 0);
7059 if (p < 0)
0692548c 7060 return IOPRIO_DEFAULT_CLASS_AND_PRIO;
7f452159 7061
8b330d7d 7062 return ioprio_normalize(p);
7f452159
LP
7063}
7064
5e98086d
ZJS
7065bool exec_context_get_effective_mount_apivfs(const ExecContext *c) {
7066 assert(c);
7067
61198784 7068 /* Explicit setting wins */
5e98086d
ZJS
7069 if (c->mount_apivfs_set)
7070 return c->mount_apivfs;
7071
61198784 7072 /* Default to "yes" if root directory or image are specified */
74e12520 7073 if (exec_context_with_rootfs(c))
61198784
ZJS
7074 return true;
7075
5e98086d
ZJS
7076 return false;
7077}
7078
d3070fbd 7079void exec_context_free_log_extra_fields(ExecContext *c) {
d3070fbd
LP
7080 assert(c);
7081
5b10116e 7082 for (size_t l = 0; l < c->n_log_extra_fields; l++)
d3070fbd
LP
7083 free(c->log_extra_fields[l].iov_base);
7084 c->log_extra_fields = mfree(c->log_extra_fields);
7085 c->n_log_extra_fields = 0;
7086}
7087
6f765baf 7088void exec_context_revert_tty(ExecContext *c) {
254d1313 7089 _cleanup_close_ int fd = -EBADF;
0ba976e8
LP
7090 const char *path;
7091 struct stat st;
6f765baf
LP
7092 int r;
7093
7094 assert(c);
7095
7096 /* First, reset the TTY (possibly kicking everybody else from the TTY) */
7097 exec_context_tty_reset(c, NULL);
7098
7099 /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path
7100 * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed
7101 * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */
0ba976e8
LP
7102 if (!exec_context_may_touch_tty(c))
7103 return;
6f765baf 7104
0ba976e8
LP
7105 path = exec_context_tty_path(c);
7106 if (!path)
7107 return;
6f765baf 7108
0ba976e8
LP
7109 fd = open(path, O_PATH|O_CLOEXEC);
7110 if (fd < 0)
7111 return (void) log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
7112 "Failed to open TTY inode of '%s' to adjust ownership/access mode, ignoring: %m",
7113 path);
7114
7115 if (fstat(fd, &st) < 0)
7116 return (void) log_warning_errno(errno, "Failed to stat TTY '%s', ignoring: %m", path);
7117
7118 /* Let's add a superficial check that we only do this for stuff that looks like a TTY. We only check
7119 * if things are a character device, since a proper check either means we'd have to open the TTY and
7120 * use isatty(), but we'd rather not do that since opening TTYs comes with all kinds of side-effects
7121 * and is slow. Or we'd have to hardcode dev_t major information, which we'd rather avoid. Why bother
7122 * with this at all? → https://github.com/systemd/systemd/issues/19213 */
7123 if (!S_ISCHR(st.st_mode))
7124 return log_warning("Configured TTY '%s' is not actually a character device, ignoring.", path);
7125
7126 r = fchmod_and_chown(fd, TTY_MODE, 0, TTY_GID);
7127 if (r < 0)
7128 log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path);
6f765baf
LP
7129}
7130
4c2f5842
LP
7131int exec_context_get_clean_directories(
7132 ExecContext *c,
7133 char **prefix,
7134 ExecCleanMask mask,
7135 char ***ret) {
7136
7137 _cleanup_strv_free_ char **l = NULL;
4c2f5842
LP
7138 int r;
7139
7140 assert(c);
7141 assert(prefix);
7142 assert(ret);
7143
5b10116e 7144 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
4c2f5842
LP
7145 if (!FLAGS_SET(mask, 1U << t))
7146 continue;
7147
7148 if (!prefix[t])
7149 continue;
7150
211a3d87 7151 for (size_t i = 0; i < c->directories[t].n_items; i++) {
4c2f5842
LP
7152 char *j;
7153
211a3d87 7154 j = path_join(prefix[t], c->directories[t].items[i].path);
4c2f5842
LP
7155 if (!j)
7156 return -ENOMEM;
7157
7158 r = strv_consume(&l, j);
7159 if (r < 0)
7160 return r;
7f622a19
YW
7161
7162 /* Also remove private directories unconditionally. */
7163 if (t != EXEC_DIRECTORY_CONFIGURATION) {
211a3d87
LB
7164 j = path_join(prefix[t], "private", c->directories[t].items[i].path);
7165 if (!j)
7166 return -ENOMEM;
7167
7168 r = strv_consume(&l, j);
7169 if (r < 0)
7170 return r;
7171 }
7172
211a3d87
LB
7173 STRV_FOREACH(symlink, c->directories[t].items[i].symlinks) {
7174 j = path_join(prefix[t], *symlink);
7f622a19
YW
7175 if (!j)
7176 return -ENOMEM;
7177
7178 r = strv_consume(&l, j);
7179 if (r < 0)
7180 return r;
7181 }
4c2f5842
LP
7182 }
7183 }
7184
7185 *ret = TAKE_PTR(l);
7186 return 0;
7187}
7188
7189int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) {
7190 ExecCleanMask mask = 0;
7191
7192 assert(c);
7193 assert(ret);
7194
7195 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
211a3d87 7196 if (c->directories[t].n_items > 0)
4c2f5842
LP
7197 mask |= 1U << t;
7198
7199 *ret = mask;
7200 return 0;
7201}
7202
50a4217b
LP
7203bool exec_context_has_encrypted_credentials(ExecContext *c) {
7204 ExecLoadCredential *load_cred;
7205 ExecSetCredential *set_cred;
7206
7207 assert(c);
7208
7209 HASHMAP_FOREACH(load_cred, c->load_credentials)
7210 if (load_cred->encrypted)
7211 return true;
7212
7213 HASHMAP_FOREACH(set_cred, c->set_credentials)
7214 if (set_cred->encrypted)
7215 return true;
7216
7217 return false;
7218}
7219
b58b4116 7220void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 7221 assert(s);
5cb5a6ff 7222
2ed26ed0
LP
7223 *s = (ExecStatus) {
7224 .pid = pid,
7225 };
7226
b58b4116
LP
7227 dual_timestamp_get(&s->start_timestamp);
7228}
7229
34cf6c43 7230void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
7231 assert(s);
7232
d46b79bb 7233 if (s->pid != pid)
2ed26ed0
LP
7234 *s = (ExecStatus) {
7235 .pid = pid,
7236 };
b58b4116 7237
63983207 7238 dual_timestamp_get(&s->exit_timestamp);
9fb86720 7239
034c6ed7
LP
7240 s->code = code;
7241 s->status = status;
169c1bda 7242
6f765baf
LP
7243 if (context && context->utmp_id)
7244 (void) utmp_put_dead_process(context->utmp_id, pid, code, status);
9fb86720
LP
7245}
7246
6a1d4d9f
LP
7247void exec_status_reset(ExecStatus *s) {
7248 assert(s);
7249
7250 *s = (ExecStatus) {};
7251}
7252
34cf6c43 7253void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
9fb86720
LP
7254 assert(s);
7255 assert(f);
7256
9fb86720
LP
7257 if (s->pid <= 0)
7258 return;
7259
4c940960
LP
7260 prefix = strempty(prefix);
7261
9fb86720 7262 fprintf(f,
ccd06097
ZJS
7263 "%sPID: "PID_FMT"\n",
7264 prefix, s->pid);
9fb86720 7265
af9d16e1 7266 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
7267 fprintf(f,
7268 "%sStart Timestamp: %s\n",
04f5c018 7269 prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime));
9fb86720 7270
af9d16e1 7271 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
7272 fprintf(f,
7273 "%sExit Timestamp: %s\n"
7274 "%sExit Code: %s\n"
7275 "%sExit Status: %i\n",
04f5c018 7276 prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime),
9fb86720
LP
7277 prefix, sigchld_code_to_string(s->code),
7278 prefix, s->status);
5cb5a6ff 7279}
44d8db9e 7280
34cf6c43 7281static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 7282 _cleanup_free_ char *cmd = NULL;
4c940960 7283 const char *prefix2;
44d8db9e
LP
7284
7285 assert(c);
7286 assert(f);
7287
4c940960 7288 prefix = strempty(prefix);
63c372cb 7289 prefix2 = strjoina(prefix, "\t");
44d8db9e 7290
4ef15008 7291 cmd = quote_command_line(c->argv, SHELL_ESCAPE_EMPTY);
38553034 7292
44d8db9e
LP
7293 fprintf(f,
7294 "%sCommand Line: %s\n",
38553034 7295 prefix, strnull(cmd));
44d8db9e 7296
9fb86720 7297 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
7298}
7299
7300void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
7301 assert(f);
7302
4c940960 7303 prefix = strempty(prefix);
44d8db9e 7304
03677889
YW
7305 LIST_FOREACH(command, i, c)
7306 exec_command_dump(i, f, prefix);
44d8db9e 7307}
94f04347 7308
a6a80b4f
LP
7309void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
7310 ExecCommand *end;
7311
7312 assert(l);
7313 assert(e);
7314
7315 if (*l) {
35b8ca3a 7316 /* It's kind of important, that we keep the order here */
cc232fa0 7317 end = LIST_FIND_TAIL(command, *l);
71fda00f 7318 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f 7319 } else
3ff67ec4 7320 *l = e;
a6a80b4f
LP
7321}
7322
26fd040d
LP
7323int exec_command_set(ExecCommand *c, const char *path, ...) {
7324 va_list ap;
7325 char **l, *p;
7326
7327 assert(c);
7328 assert(path);
7329
7330 va_start(ap, path);
7331 l = strv_new_ap(path, ap);
7332 va_end(ap);
7333
7334 if (!l)
7335 return -ENOMEM;
7336
250a918d
LP
7337 p = strdup(path);
7338 if (!p) {
26fd040d
LP
7339 strv_free(l);
7340 return -ENOMEM;
7341 }
7342
6897dfe8 7343 free_and_replace(c->path, p);
26fd040d 7344
130d3d22 7345 return strv_free_and_replace(c->argv, l);
26fd040d
LP
7346}
7347
86b23b07 7348int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 7349 _cleanup_strv_free_ char **l = NULL;
86b23b07 7350 va_list ap;
86b23b07
JS
7351 int r;
7352
7353 assert(c);
7354 assert(path);
7355
7356 va_start(ap, path);
7357 l = strv_new_ap(path, ap);
7358 va_end(ap);
7359
7360 if (!l)
7361 return -ENOMEM;
7362
e287086b 7363 r = strv_extend_strv(&c->argv, l, false);
e63ff941 7364 if (r < 0)
86b23b07 7365 return r;
86b23b07
JS
7366
7367 return 0;
7368}
7369
437f3e35
LP
7370static char *destroy_tree(char *path) {
7371 if (!path)
7372 return NULL;
9c0c6701 7373
437f3e35
LP
7374 if (!path_equal(path, RUN_SYSTEMD_EMPTY)) {
7375 log_debug("Spawning process to nuke '%s'", path);
9c0c6701 7376
437f3e35
LP
7377 (void) asynchronous_rm_rf(path, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
7378 }
9c0c6701 7379
437f3e35 7380 return mfree(path);
9c0c6701
DDM
7381}
7382
e52a696a 7383static ExecSharedRuntime* exec_shared_runtime_free(ExecSharedRuntime *rt) {
e8a565cb
YW
7384 if (!rt)
7385 return NULL;
7386
7387 if (rt->manager)
e76506b7 7388 (void) hashmap_remove(rt->manager->exec_shared_runtime_by_id, rt->id);
e8a565cb 7389
e52a696a
DDM
7390 rt->id = mfree(rt->id);
7391 rt->tmp_dir = mfree(rt->tmp_dir);
7392 rt->var_tmp_dir = mfree(rt->var_tmp_dir);
7393 safe_close_pair(rt->netns_storage_socket);
7394 safe_close_pair(rt->ipcns_storage_socket);
7395 return mfree(rt);
7396}
7397
7398DEFINE_TRIVIAL_UNREF_FUNC(ExecSharedRuntime, exec_shared_runtime, exec_shared_runtime_free);
7399DEFINE_TRIVIAL_CLEANUP_FUNC(ExecSharedRuntime*, exec_shared_runtime_free);
7400
7401ExecSharedRuntime* exec_shared_runtime_destroy(ExecSharedRuntime *rt) {
e52a696a
DDM
7402 if (!rt)
7403 return NULL;
7404
7405 assert(rt->n_ref > 0);
7406 rt->n_ref--;
7407
7408 if (rt->n_ref > 0)
7409 return NULL;
56a13a49 7410
437f3e35
LP
7411 rt->tmp_dir = destroy_tree(rt->tmp_dir);
7412 rt->var_tmp_dir = destroy_tree(rt->var_tmp_dir);
e8a565cb 7413
e52a696a 7414 return exec_shared_runtime_free(rt);
e8a565cb
YW
7415}
7416
e76506b7 7417static int exec_shared_runtime_allocate(ExecSharedRuntime **ret, const char *id) {
56a13a49 7418 _cleanup_free_ char *id_copy = NULL;
e76506b7 7419 ExecSharedRuntime *n;
613b411c 7420
8e8009dc 7421 assert(ret);
613b411c 7422
56a13a49
ZJS
7423 id_copy = strdup(id);
7424 if (!id_copy)
7425 return -ENOMEM;
7426
e76506b7 7427 n = new(ExecSharedRuntime, 1);
8e8009dc 7428 if (!n)
613b411c
LP
7429 return -ENOMEM;
7430
e76506b7 7431 *n = (ExecSharedRuntime) {
56a13a49 7432 .id = TAKE_PTR(id_copy),
19ee48a6
YW
7433 .netns_storage_socket = PIPE_EBADF,
7434 .ipcns_storage_socket = PIPE_EBADF,
8e8009dc
LP
7435 };
7436
7437 *ret = n;
613b411c
LP
7438 return 0;
7439}
7440
e76506b7 7441static int exec_shared_runtime_add(
e8a565cb
YW
7442 Manager *m,
7443 const char *id,
56a13a49
ZJS
7444 char **tmp_dir,
7445 char **var_tmp_dir,
7446 int netns_storage_socket[2],
a70581ff 7447 int ipcns_storage_socket[2],
e76506b7 7448 ExecSharedRuntime **ret) {
e8a565cb 7449
e76506b7 7450 _cleanup_(exec_shared_runtime_freep) ExecSharedRuntime *rt = NULL;
613b411c
LP
7451 int r;
7452
e8a565cb 7453 assert(m);
613b411c
LP
7454 assert(id);
7455
a70581ff 7456 /* tmp_dir, var_tmp_dir, {net,ipc}ns_storage_socket fds are donated on success */
56a13a49 7457
e76506b7 7458 r = exec_shared_runtime_allocate(&rt, id);
613b411c
LP
7459 if (r < 0)
7460 return r;
7461
e76506b7 7462 r = hashmap_ensure_put(&m->exec_shared_runtime_by_id, &string_hash_ops, rt->id, rt);
56a13a49
ZJS
7463 if (r < 0)
7464 return r;
e8a565cb 7465
56a13a49
ZJS
7466 assert(!!rt->tmp_dir == !!rt->var_tmp_dir); /* We require both to be set together */
7467 rt->tmp_dir = TAKE_PTR(*tmp_dir);
7468 rt->var_tmp_dir = TAKE_PTR(*var_tmp_dir);
e8a565cb
YW
7469
7470 if (netns_storage_socket) {
56a13a49
ZJS
7471 rt->netns_storage_socket[0] = TAKE_FD(netns_storage_socket[0]);
7472 rt->netns_storage_socket[1] = TAKE_FD(netns_storage_socket[1]);
613b411c
LP
7473 }
7474
a70581ff
XR
7475 if (ipcns_storage_socket) {
7476 rt->ipcns_storage_socket[0] = TAKE_FD(ipcns_storage_socket[0]);
7477 rt->ipcns_storage_socket[1] = TAKE_FD(ipcns_storage_socket[1]);
7478 }
7479
e8a565cb
YW
7480 rt->manager = m;
7481
7482 if (ret)
7483 *ret = rt;
e76506b7 7484 /* do not remove created ExecSharedRuntime object when the operation succeeds. */
56a13a49 7485 TAKE_PTR(rt);
e8a565cb
YW
7486 return 0;
7487}
7488
e76506b7 7489static int exec_shared_runtime_make(
74aaf59b
LP
7490 Manager *m,
7491 const ExecContext *c,
7492 const char *id,
e76506b7 7493 ExecSharedRuntime **ret) {
74aaf59b 7494
56a13a49 7495 _cleanup_(namespace_cleanup_tmpdirp) char *tmp_dir = NULL, *var_tmp_dir = NULL;
19ee48a6 7496 _cleanup_close_pair_ int netns_storage_socket[2] = PIPE_EBADF, ipcns_storage_socket[2] = PIPE_EBADF;
e8a565cb
YW
7497 int r;
7498
7499 assert(m);
7500 assert(c);
7501 assert(id);
7502
e76506b7 7503 /* It is not necessary to create ExecSharedRuntime object. */
fde36d25 7504 if (!exec_needs_network_namespace(c) && !exec_needs_ipc_namespace(c) && !c->private_tmp) {
74aaf59b 7505 *ret = NULL;
e8a565cb 7506 return 0;
74aaf59b 7507 }
e8a565cb 7508
efa2f3a1
TM
7509 if (c->private_tmp &&
7510 !(prefixed_path_strv_contains(c->inaccessible_paths, "/tmp") &&
7511 (prefixed_path_strv_contains(c->inaccessible_paths, "/var/tmp") ||
7512 prefixed_path_strv_contains(c->inaccessible_paths, "/var")))) {
e8a565cb 7513 r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir);
613b411c
LP
7514 if (r < 0)
7515 return r;
7516 }
7517
fbbb9697 7518 if (exec_needs_network_namespace(c)) {
e8a565cb
YW
7519 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0)
7520 return -errno;
7521 }
7522
fde36d25 7523 if (exec_needs_ipc_namespace(c)) {
a70581ff
XR
7524 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ipcns_storage_socket) < 0)
7525 return -errno;
7526 }
7527
e76506b7 7528 r = exec_shared_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_storage_socket, ipcns_storage_socket, ret);
e8a565cb
YW
7529 if (r < 0)
7530 return r;
7531
613b411c
LP
7532 return 1;
7533}
7534
e76506b7
DDM
7535int exec_shared_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecSharedRuntime **ret) {
7536 ExecSharedRuntime *rt;
e8a565cb 7537 int r;
613b411c 7538
e8a565cb
YW
7539 assert(m);
7540 assert(id);
7541 assert(ret);
7542
e76506b7 7543 rt = hashmap_get(m->exec_shared_runtime_by_id, id);
e8a565cb 7544 if (rt)
e76506b7 7545 /* We already have an ExecSharedRuntime object, let's increase the ref count and reuse it */
e8a565cb
YW
7546 goto ref;
7547
74aaf59b
LP
7548 if (!create) {
7549 *ret = NULL;
e8a565cb 7550 return 0;
74aaf59b 7551 }
e8a565cb
YW
7552
7553 /* If not found, then create a new object. */
e76506b7 7554 r = exec_shared_runtime_make(m, c, id, &rt);
74aaf59b 7555 if (r < 0)
e8a565cb 7556 return r;
74aaf59b 7557 if (r == 0) {
e76506b7 7558 /* When r == 0, it is not necessary to create ExecSharedRuntime object. */
74aaf59b
LP
7559 *ret = NULL;
7560 return 0;
7561 }
613b411c 7562
e8a565cb
YW
7563ref:
7564 /* increment reference counter. */
7565 rt->n_ref++;
7566 *ret = rt;
7567 return 1;
7568}
613b411c 7569
e76506b7
DDM
7570int exec_shared_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
7571 ExecSharedRuntime *rt;
e8a565cb
YW
7572
7573 assert(m);
613b411c
LP
7574 assert(f);
7575 assert(fds);
7576
e76506b7 7577 HASHMAP_FOREACH(rt, m->exec_shared_runtime_by_id) {
e8a565cb 7578 fprintf(f, "exec-runtime=%s", rt->id);
613b411c 7579
e8a565cb
YW
7580 if (rt->tmp_dir)
7581 fprintf(f, " tmp-dir=%s", rt->tmp_dir);
613b411c 7582
e8a565cb
YW
7583 if (rt->var_tmp_dir)
7584 fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir);
613b411c 7585
e8a565cb
YW
7586 if (rt->netns_storage_socket[0] >= 0) {
7587 int copy;
613b411c 7588
e8a565cb
YW
7589 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
7590 if (copy < 0)
7591 return copy;
613b411c 7592
e8a565cb
YW
7593 fprintf(f, " netns-socket-0=%i", copy);
7594 }
613b411c 7595
e8a565cb
YW
7596 if (rt->netns_storage_socket[1] >= 0) {
7597 int copy;
613b411c 7598
e8a565cb
YW
7599 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
7600 if (copy < 0)
7601 return copy;
613b411c 7602
e8a565cb
YW
7603 fprintf(f, " netns-socket-1=%i", copy);
7604 }
7605
a70581ff
XR
7606 if (rt->ipcns_storage_socket[0] >= 0) {
7607 int copy;
7608
7609 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[0]);
7610 if (copy < 0)
7611 return copy;
7612
7613 fprintf(f, " ipcns-socket-0=%i", copy);
7614 }
7615
7616 if (rt->ipcns_storage_socket[1] >= 0) {
7617 int copy;
7618
7619 copy = fdset_put_dup(fds, rt->ipcns_storage_socket[1]);
7620 if (copy < 0)
7621 return copy;
7622
7623 fprintf(f, " ipcns-socket-1=%i", copy);
7624 }
7625
e8a565cb 7626 fputc('\n', f);
613b411c
LP
7627 }
7628
7629 return 0;
7630}
7631
e76506b7
DDM
7632int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
7633 _cleanup_(exec_shared_runtime_freep) ExecSharedRuntime *rt_create = NULL;
7634 ExecSharedRuntime *rt;
613b411c
LP
7635 int r;
7636
e8a565cb
YW
7637 /* This is for the migration from old (v237 or earlier) deserialization text.
7638 * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=.
e76506b7 7639 * Even if the ExecSharedRuntime object originally created by the other unit, we cannot judge
e8a565cb
YW
7640 * so or not from the serialized text, then we always creates a new object owned by this. */
7641
7642 assert(u);
613b411c
LP
7643 assert(key);
7644 assert(value);
7645
e76506b7 7646 /* Manager manages ExecSharedRuntime objects by the unit id.
e8a565cb
YW
7647 * So, we omit the serialized text when the unit does not have id (yet?)... */
7648 if (isempty(u->id)) {
7649 log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter.");
7650 return 0;
7651 }
613b411c 7652
e76506b7 7653 if (hashmap_ensure_allocated(&u->manager->exec_shared_runtime_by_id, &string_hash_ops) < 0)
cbc165d1 7654 return log_oom();
e8a565cb 7655
e76506b7 7656 rt = hashmap_get(u->manager->exec_shared_runtime_by_id, u->id);
e8a565cb 7657 if (!rt) {
e76506b7 7658 if (exec_shared_runtime_allocate(&rt_create, u->id) < 0)
f2341e0a 7659 return log_oom();
613b411c 7660
e8a565cb
YW
7661 rt = rt_create;
7662 }
7663
7664 if (streq(key, "tmp-dir")) {
cbc165d1
ZJS
7665 if (free_and_strdup_warn(&rt->tmp_dir, value) < 0)
7666 return -ENOMEM;
613b411c
LP
7667
7668 } else if (streq(key, "var-tmp-dir")) {
cbc165d1
ZJS
7669 if (free_and_strdup_warn(&rt->var_tmp_dir, value) < 0)
7670 return -ENOMEM;
613b411c
LP
7671
7672 } else if (streq(key, "netns-socket-0")) {
7673 int fd;
7674
e652663a 7675 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 7676 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 7677 return 0;
613b411c 7678 }
e8a565cb
YW
7679
7680 safe_close(rt->netns_storage_socket[0]);
7681 rt->netns_storage_socket[0] = fdset_remove(fds, fd);
7682
613b411c
LP
7683 } else if (streq(key, "netns-socket-1")) {
7684 int fd;
7685
e652663a 7686 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 7687 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
e8a565cb 7688 return 0;
613b411c 7689 }
e8a565cb
YW
7690
7691 safe_close(rt->netns_storage_socket[1]);
7692 rt->netns_storage_socket[1] = fdset_remove(fds, fd);
a70581ff 7693
613b411c
LP
7694 } else
7695 return 0;
7696
e76506b7 7697 /* If the object is newly created, then put it to the hashmap which manages ExecSharedRuntime objects. */
e8a565cb 7698 if (rt_create) {
e76506b7 7699 r = hashmap_put(u->manager->exec_shared_runtime_by_id, rt_create->id, rt_create);
e8a565cb 7700 if (r < 0) {
3fe91079 7701 log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
e8a565cb
YW
7702 return 0;
7703 }
613b411c 7704
e8a565cb 7705 rt_create->manager = u->manager;
613b411c 7706
e8a565cb 7707 /* Avoid cleanup */
56a13a49 7708 TAKE_PTR(rt_create);
e8a565cb 7709 }
98b47d54 7710
e8a565cb
YW
7711 return 1;
7712}
613b411c 7713
e76506b7 7714int exec_shared_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) {
56a13a49
ZJS
7715 _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL;
7716 char *id = NULL;
a70581ff 7717 int r, netns_fdpair[] = {-1, -1}, ipcns_fdpair[] = {-1, -1};
99534007 7718 const char *p, *v = ASSERT_PTR(value);
e8a565cb 7719 size_t n;
613b411c 7720
e8a565cb 7721 assert(m);
e8a565cb 7722 assert(fds);
98b47d54 7723
e8a565cb 7724 n = strcspn(v, " ");
2f82562b 7725 id = strndupa_safe(v, n);
e8a565cb
YW
7726 if (v[n] != ' ')
7727 goto finalize;
7728 p = v + n + 1;
7729
7730 v = startswith(p, "tmp-dir=");
7731 if (v) {
7732 n = strcspn(v, " ");
56a13a49
ZJS
7733 tmp_dir = strndup(v, n);
7734 if (!tmp_dir)
7735 return log_oom();
e8a565cb
YW
7736 if (v[n] != ' ')
7737 goto finalize;
7738 p = v + n + 1;
7739 }
7740
7741 v = startswith(p, "var-tmp-dir=");
7742 if (v) {
7743 n = strcspn(v, " ");
56a13a49
ZJS
7744 var_tmp_dir = strndup(v, n);
7745 if (!var_tmp_dir)
7746 return log_oom();
e8a565cb
YW
7747 if (v[n] != ' ')
7748 goto finalize;
7749 p = v + n + 1;
7750 }
7751
7752 v = startswith(p, "netns-socket-0=");
7753 if (v) {
7754 char *buf;
7755
7756 n = strcspn(v, " ");
2f82562b 7757 buf = strndupa_safe(v, n);
c413bb28 7758
e652663a
DT
7759 netns_fdpair[0] = parse_fd(buf);
7760 if (netns_fdpair[0] < 0)
7761 return log_debug_errno(netns_fdpair[0], "Unable to parse exec-runtime specification netns-socket-0=%s: %m", buf);
a70581ff 7762 if (!fdset_contains(fds, netns_fdpair[0]))
c413bb28 7763 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
7764 "exec-runtime specification netns-socket-0= refers to unknown fd %d: %m", netns_fdpair[0]);
7765 netns_fdpair[0] = fdset_remove(fds, netns_fdpair[0]);
e8a565cb
YW
7766 if (v[n] != ' ')
7767 goto finalize;
7768 p = v + n + 1;
613b411c
LP
7769 }
7770
e8a565cb
YW
7771 v = startswith(p, "netns-socket-1=");
7772 if (v) {
7773 char *buf;
98b47d54 7774
e8a565cb 7775 n = strcspn(v, " ");
2f82562b 7776 buf = strndupa_safe(v, n);
a70581ff 7777
e652663a
DT
7778 netns_fdpair[1] = parse_fd(buf);
7779 if (netns_fdpair[1] < 0)
7780 return log_debug_errno(netns_fdpair[1], "Unable to parse exec-runtime specification netns-socket-1=%s: %m", buf);
a70581ff
XR
7781 if (!fdset_contains(fds, netns_fdpair[1]))
7782 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
7783 "exec-runtime specification netns-socket-1= refers to unknown fd %d: %m", netns_fdpair[1]);
7784 netns_fdpair[1] = fdset_remove(fds, netns_fdpair[1]);
7785 if (v[n] != ' ')
7786 goto finalize;
7787 p = v + n + 1;
7788 }
7789
7790 v = startswith(p, "ipcns-socket-0=");
7791 if (v) {
7792 char *buf;
7793
7794 n = strcspn(v, " ");
2f82562b 7795 buf = strndupa_safe(v, n);
a70581ff 7796
e652663a
DT
7797 ipcns_fdpair[0] = parse_fd(buf);
7798 if (ipcns_fdpair[0] < 0)
7799 return log_debug_errno(ipcns_fdpair[0], "Unable to parse exec-runtime specification ipcns-socket-0=%s: %m", buf);
a70581ff
XR
7800 if (!fdset_contains(fds, ipcns_fdpair[0]))
7801 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
7802 "exec-runtime specification ipcns-socket-0= refers to unknown fd %d: %m", ipcns_fdpair[0]);
7803 ipcns_fdpair[0] = fdset_remove(fds, ipcns_fdpair[0]);
7804 if (v[n] != ' ')
7805 goto finalize;
7806 p = v + n + 1;
7807 }
7808
7809 v = startswith(p, "ipcns-socket-1=");
7810 if (v) {
7811 char *buf;
7812
7813 n = strcspn(v, " ");
2f82562b 7814 buf = strndupa_safe(v, n);
a70581ff 7815
e652663a
DT
7816 ipcns_fdpair[1] = parse_fd(buf);
7817 if (ipcns_fdpair[1] < 0)
7818 return log_debug_errno(ipcns_fdpair[1], "Unable to parse exec-runtime specification ipcns-socket-1=%s: %m", buf);
a70581ff 7819 if (!fdset_contains(fds, ipcns_fdpair[1]))
c413bb28 7820 return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
a70581ff
XR
7821 "exec-runtime specification ipcns-socket-1= refers to unknown fd %d: %m", ipcns_fdpair[1]);
7822 ipcns_fdpair[1] = fdset_remove(fds, ipcns_fdpair[1]);
e8a565cb 7823 }
98b47d54 7824
e8a565cb 7825finalize:
e76506b7 7826 r = exec_shared_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_fdpair, ipcns_fdpair, NULL);
7d853ca6 7827 if (r < 0)
56a13a49
ZJS
7828 return log_debug_errno(r, "Failed to add exec-runtime: %m");
7829 return 0;
e8a565cb 7830}
613b411c 7831
e76506b7
DDM
7832void exec_shared_runtime_vacuum(Manager *m) {
7833 ExecSharedRuntime *rt;
e8a565cb
YW
7834
7835 assert(m);
7836
e76506b7 7837 /* Free unreferenced ExecSharedRuntime objects. This is used after manager deserialization process. */
e8a565cb 7838
e76506b7 7839 HASHMAP_FOREACH(rt, m->exec_shared_runtime_by_id) {
e8a565cb
YW
7840 if (rt->n_ref > 0)
7841 continue;
7842
e52a696a 7843 (void) exec_shared_runtime_free(rt);
e8a565cb 7844 }
613b411c
LP
7845}
7846
9c0c6701
DDM
7847int exec_runtime_make(
7848 const Unit *unit,
7849 const ExecContext *context,
7850 ExecSharedRuntime *shared,
7851 DynamicCreds *creds,
7852 ExecRuntime **ret) {
7853 _cleanup_close_pair_ int ephemeral_storage_socket[2] = PIPE_EBADF;
7854 _cleanup_free_ char *ephemeral = NULL;
28135da3 7855 _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL;
9c0c6701 7856 int r;
28135da3 7857
9c0c6701
DDM
7858 assert(unit);
7859 assert(context);
28135da3
DDM
7860 assert(ret);
7861
9c0c6701 7862 if (!shared && !creds && !exec_needs_ephemeral(context)) {
28135da3
DDM
7863 *ret = NULL;
7864 return 0;
7865 }
7866
9c0c6701
DDM
7867 if (exec_needs_ephemeral(context)) {
7868 r = mkdir_p("/var/lib/systemd/ephemeral-trees", 0755);
7869 if (r < 0)
7870 return r;
7871
7872 r = tempfn_random_child("/var/lib/systemd/ephemeral-trees", unit->id, &ephemeral);
7873 if (r < 0)
7874 return r;
7875
7876 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ephemeral_storage_socket) < 0)
7877 return -errno;
7878 }
7879
28135da3
DDM
7880 rt = new(ExecRuntime, 1);
7881 if (!rt)
7882 return -ENOMEM;
7883
7884 *rt = (ExecRuntime) {
7885 .shared = shared,
15220772 7886 .dynamic_creds = creds,
9c0c6701
DDM
7887 .ephemeral_copy = TAKE_PTR(ephemeral),
7888 .ephemeral_storage_socket[0] = TAKE_FD(ephemeral_storage_socket[0]),
7889 .ephemeral_storage_socket[1] = TAKE_FD(ephemeral_storage_socket[1]),
28135da3
DDM
7890 };
7891
7892 *ret = TAKE_PTR(rt);
7893 return 1;
7894}
7895
7896ExecRuntime* exec_runtime_free(ExecRuntime *rt) {
7897 if (!rt)
7898 return NULL;
7899
7900 exec_shared_runtime_unref(rt->shared);
15220772 7901 dynamic_creds_unref(rt->dynamic_creds);
9c0c6701 7902
437f3e35 7903 rt->ephemeral_copy = destroy_tree(rt->ephemeral_copy);
9c0c6701 7904
9c0c6701 7905 safe_close_pair(rt->ephemeral_storage_socket);
28135da3
DDM
7906 return mfree(rt);
7907}
7908
7909ExecRuntime* exec_runtime_destroy(ExecRuntime *rt) {
7910 if (!rt)
7911 return NULL;
7912
7913 rt->shared = exec_shared_runtime_destroy(rt->shared);
15220772 7914 rt->dynamic_creds = dynamic_creds_destroy(rt->dynamic_creds);
28135da3
DDM
7915 return exec_runtime_free(rt);
7916}
7917
b9c04eaf
YW
7918void exec_params_clear(ExecParameters *p) {
7919 if (!p)
7920 return;
7921
c3f8a065
LP
7922 p->environment = strv_free(p->environment);
7923 p->fd_names = strv_free(p->fd_names);
7924 p->fds = mfree(p->fds);
7925 p->exec_fd = safe_close(p->exec_fd);
b9c04eaf
YW
7926}
7927
bb0c0d6f
LP
7928ExecSetCredential *exec_set_credential_free(ExecSetCredential *sc) {
7929 if (!sc)
7930 return NULL;
7931
7932 free(sc->id);
7933 free(sc->data);
7934 return mfree(sc);
7935}
7936
43144be4
LP
7937ExecLoadCredential *exec_load_credential_free(ExecLoadCredential *lc) {
7938 if (!lc)
7939 return NULL;
7940
7941 free(lc->id);
7942 free(lc->path);
7943 return mfree(lc);
7944}
7945
211a3d87
LB
7946void exec_directory_done(ExecDirectory *d) {
7947 if (!d)
7948 return;
7949
7950 for (size_t i = 0; i < d->n_items; i++) {
7951 free(d->items[i].path);
7952 strv_free(d->items[i].symlinks);
7953 }
7954
7955 d->items = mfree(d->items);
7956 d->n_items = 0;
7957 d->mode = 0755;
7958}
7959
564e5c98
YW
7960static ExecDirectoryItem *exec_directory_find(ExecDirectory *d, const char *path) {
7961 assert(d);
7962 assert(path);
7963
7964 for (size_t i = 0; i < d->n_items; i++)
7965 if (path_equal(d->items[i].path, path))
7966 return &d->items[i];
7967
7968 return NULL;
7969}
7970
7971int exec_directory_add(ExecDirectory *d, const char *path, const char *symlink) {
211a3d87
LB
7972 _cleanup_strv_free_ char **s = NULL;
7973 _cleanup_free_ char *p = NULL;
564e5c98
YW
7974 ExecDirectoryItem *existing;
7975 int r;
211a3d87
LB
7976
7977 assert(d);
211a3d87
LB
7978 assert(path);
7979
564e5c98
YW
7980 existing = exec_directory_find(d, path);
7981 if (existing) {
7982 r = strv_extend(&existing->symlinks, symlink);
7983 if (r < 0)
7984 return r;
7985
7986 return 0; /* existing item is updated */
7987 }
7988
211a3d87
LB
7989 p = strdup(path);
7990 if (!p)
7991 return -ENOMEM;
7992
564e5c98
YW
7993 if (symlink) {
7994 s = strv_new(symlink);
211a3d87
LB
7995 if (!s)
7996 return -ENOMEM;
7997 }
7998
564e5c98 7999 if (!GREEDY_REALLOC(d->items, d->n_items + 1))
211a3d87
LB
8000 return -ENOMEM;
8001
564e5c98 8002 d->items[d->n_items++] = (ExecDirectoryItem) {
211a3d87
LB
8003 .path = TAKE_PTR(p),
8004 .symlinks = TAKE_PTR(s),
8005 };
8006
564e5c98 8007 return 1; /* new item is added */
211a3d87
LB
8008}
8009
a2ab603c
YW
8010static int exec_directory_item_compare_func(const ExecDirectoryItem *a, const ExecDirectoryItem *b) {
8011 assert(a);
8012 assert(b);
8013
8014 return path_compare(a->path, b->path);
8015}
8016
8017void exec_directory_sort(ExecDirectory *d) {
8018 assert(d);
8019
8020 /* Sort the exec directories to make always parent directories processed at first in
8021 * setup_exec_directory(), e.g., even if StateDirectory=foo/bar foo, we need to create foo at first,
8022 * then foo/bar. Also, set .only_create flag if one of the parent directories is contained in the
8023 * list. See also comments in setup_exec_directory() and issue #24783. */
8024
8025 if (d->n_items <= 1)
8026 return;
8027
8028 typesafe_qsort(d->items, d->n_items, exec_directory_item_compare_func);
8029
8030 for (size_t i = 1; i < d->n_items; i++)
8031 for (size_t j = 0; j < i; j++)
8032 if (path_startswith(d->items[i].path, d->items[j].path)) {
8033 d->items[i].only_create = true;
8034 break;
8035 }
211a3d87
LB
8036}
8037
4fb8f1e8
LP
8038ExecCleanMask exec_clean_mask_from_string(const char *s) {
8039 ExecDirectoryType t;
8040
8041 assert(s);
8042
8043 if (streq(s, "all"))
8044 return EXEC_CLEAN_ALL;
8045 if (streq(s, "fdstore"))
8046 return EXEC_CLEAN_FDSTORE;
8047
8048 t = exec_resource_type_from_string(s);
8049 if (t < 0)
8050 return (ExecCleanMask) t;
8051
8052 return 1U << t;
8053}
8054
bb0c0d6f 8055DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_set_credential_hash_ops, char, string_hash_func, string_compare_func, ExecSetCredential, exec_set_credential_free);
43144be4 8056DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_load_credential_hash_ops, char, string_hash_func, string_compare_func, ExecLoadCredential, exec_load_credential_free);
bb0c0d6f 8057
80876c20
LP
8058static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
8059 [EXEC_INPUT_NULL] = "null",
8060 [EXEC_INPUT_TTY] = "tty",
8061 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d 8062 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
52c239d7
LB
8063 [EXEC_INPUT_SOCKET] = "socket",
8064 [EXEC_INPUT_NAMED_FD] = "fd",
08f3be7a 8065 [EXEC_INPUT_DATA] = "data",
2038c3f5 8066 [EXEC_INPUT_FILE] = "file",
80876c20
LP
8067};
8068
8a0867d6
LP
8069DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
8070
94f04347 8071static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 8072 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 8073 [EXEC_OUTPUT_NULL] = "null",
80876c20 8074 [EXEC_OUTPUT_TTY] = "tty",
9a6bca7a 8075 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 8076 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
8077 [EXEC_OUTPUT_JOURNAL] = "journal",
8078 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
52c239d7
LB
8079 [EXEC_OUTPUT_SOCKET] = "socket",
8080 [EXEC_OUTPUT_NAMED_FD] = "fd",
2038c3f5 8081 [EXEC_OUTPUT_FILE] = "file",
566b7d23 8082 [EXEC_OUTPUT_FILE_APPEND] = "append",
8d7dab1f 8083 [EXEC_OUTPUT_FILE_TRUNCATE] = "truncate",
94f04347
LP
8084};
8085
8086DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
8087
8088static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
8089 [EXEC_UTMP_INIT] = "init",
8090 [EXEC_UTMP_LOGIN] = "login",
8091 [EXEC_UTMP_USER] = "user",
8092};
8093
8094DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);
53f47dfc
YW
8095
8096static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = {
8097 [EXEC_PRESERVE_NO] = "no",
8098 [EXEC_PRESERVE_YES] = "yes",
8099 [EXEC_PRESERVE_RESTART] = "restart",
8100};
8101
8102DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES);
3536f49e 8103
6b7b2ed9 8104/* This table maps ExecDirectoryType to the setting it is configured with in the unit */
72fd1768 8105static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
8106 [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory",
8107 [EXEC_DIRECTORY_STATE] = "StateDirectory",
8108 [EXEC_DIRECTORY_CACHE] = "CacheDirectory",
8109 [EXEC_DIRECTORY_LOGS] = "LogsDirectory",
8110 [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory",
8111};
8112
8113DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType);
b1edf445 8114
211a3d87
LB
8115/* This table maps ExecDirectoryType to the symlink setting it is configured with in the unit */
8116static const char* const exec_directory_type_symlink_table[_EXEC_DIRECTORY_TYPE_MAX] = {
8117 [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectorySymlink",
8118 [EXEC_DIRECTORY_STATE] = "StateDirectorySymlink",
8119 [EXEC_DIRECTORY_CACHE] = "CacheDirectorySymlink",
8120 [EXEC_DIRECTORY_LOGS] = "LogsDirectorySymlink",
8121 [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectorySymlink",
8122};
8123
8124DEFINE_STRING_TABLE_LOOKUP(exec_directory_type_symlink, ExecDirectoryType);
8125
6b7b2ed9
LP
8126/* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This
8127 * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit
8128 * directories, specifically .timer units with their timestamp touch file. */
8129static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
8130 [EXEC_DIRECTORY_RUNTIME] = "runtime",
8131 [EXEC_DIRECTORY_STATE] = "state",
8132 [EXEC_DIRECTORY_CACHE] = "cache",
8133 [EXEC_DIRECTORY_LOGS] = "logs",
8134 [EXEC_DIRECTORY_CONFIGURATION] = "configuration",
8135};
8136
8137DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);
8138
8139/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
8140 * the service payload in. */
fb2042dd
YW
8141static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
8142 [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
8143 [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
8144 [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
8145 [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
8146 [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
8147};
8148
8149DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
8150
b1edf445
LP
8151static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
8152 [EXEC_KEYRING_INHERIT] = "inherit",
8153 [EXEC_KEYRING_PRIVATE] = "private",
8154 [EXEC_KEYRING_SHARED] = "shared",
8155};
8156
8157DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode);