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