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