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